From 1c39f76f962fffd57ab8db090de4efde78ce6bef Mon Sep 17 00:00:00 2001 From: Aleop Date: Mon, 12 Oct 2026 17:04:06 +0200 Subject: [PATCH] Loksi 2026.10.0 : source correspondante des quatre applis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Export du dépôt interne d'Aleop, révision 0936ea1 (fichiers publiés identiques à e46bc12). Paquets construits depuis cette source : - Android : AAB 2026.10.0, code 4 - iPhone : archive 2026.10.0 (18) - Bureau : macOS universel build 13, Windows build 14, MSIX build 15 - Extensions Chrome, Edge et Firefox : 2026.10.0.3 --- README.md | 110 +- .../sources/OFL-Raleway.txt | 93 ++ desktop/.gitignore | 4 + desktop/after-pack.cjs | 56 + desktop/dependencies.py | 125 ++ desktop/electron-builder.cjs | 98 ++ desktop/entete.mjs | 54 + desktop/loksi.py | 1426 +++++++++++++++++ desktop/render.mjs | 78 + desktop/upstream.json | 53 + desktop/webpack-oss.cjs | 28 + extensions/.gitignore | 4 + extensions/LICENSE | 674 ++++++++ extensions/README.md | 250 +++ extensions/dependencies.py | 63 + extensions/environment.test.cjs | 60 + extensions/fonts.py | 113 ++ extensions/icons.mjs | 22 + extensions/licenses/ng-select-MIT.txt | 21 + extensions/licenses/protobuf-es-LICENSE | 201 +++ extensions/licenses/signalr-MIT.txt | 23 + extensions/loksi-coffre.test.cjs | 61 + extensions/loksi-coffre.ts | 56 + extensions/prototype.py | 976 +++++++++++ extensions/upstream.json | 19 + extensions/verify-source.py | 74 + extensions/version.json | 4 + extensions/webpack-oss.cjs | 25 + mobile/android/loksi.py | 75 +- mobile/ios/loksi.py | 30 +- mobile/ios/render.mjs | 49 + mobile/ios/swift/LoksiVault.swift | 95 ++ mobile/ios/swift/LoksiVaultTests.swift | 78 + mobile/upstream.json | 10 +- 34 files changed, 5093 insertions(+), 15 deletions(-) create mode 100644 brand/propositions/harmonisation-klepsi/sources/OFL-Raleway.txt create mode 100644 desktop/.gitignore create mode 100644 desktop/after-pack.cjs create mode 100644 desktop/dependencies.py create mode 100644 desktop/electron-builder.cjs create mode 100644 desktop/entete.mjs create mode 100644 desktop/loksi.py create mode 100644 desktop/render.mjs create mode 100644 desktop/upstream.json create mode 100644 desktop/webpack-oss.cjs create mode 100644 extensions/.gitignore create mode 100644 extensions/LICENSE create mode 100644 extensions/README.md create mode 100644 extensions/dependencies.py create mode 100644 extensions/environment.test.cjs create mode 100644 extensions/fonts.py create mode 100644 extensions/icons.mjs create mode 100644 extensions/licenses/ng-select-MIT.txt create mode 100644 extensions/licenses/protobuf-es-LICENSE create mode 100644 extensions/licenses/signalr-MIT.txt create mode 100644 extensions/loksi-coffre.test.cjs create mode 100644 extensions/loksi-coffre.ts create mode 100644 extensions/prototype.py create mode 100644 extensions/upstream.json create mode 100644 extensions/verify-source.py create mode 100644 extensions/version.json create mode 100644 extensions/webpack-oss.cjs create mode 100644 mobile/ios/render.mjs create mode 100644 mobile/ios/swift/LoksiVault.swift create mode 100644 mobile/ios/swift/LoksiVaultTests.swift diff --git a/README.md b/README.md index b182fb2..56eadc0 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,10 @@ -# Loksi pour Android : code source +# Loksi : code source des applications Loksi, par Aleop. Application Bitwarden® modifiée par Aleop, sous licence GPL v3. Aleop n'est pas affilié à Bitwarden Inc. -Ce dépôt est la source correspondante de l'application Android Loksi, au sens de la GPL v3. +Ce dépôt est la source correspondante des applications Loksi pour Android, iPhone, macOS et +Windows, et des extensions pour Chrome, Edge et Firefox, au sens de la GPL v3. Il ne contient pas une copie de l'arbre Bitwarden. Il contient les scripts qui partent des archives officielles de Bitwarden, épinglées par SHA-256, et y appliquent les adaptations Loksi. Toute modification de l'amont est faite par ces scripts, et rien d'autre. @@ -20,6 +21,13 @@ English summary at the end of this file. | `mobile/android/kotlin/` | code Kotlin ajouté par Loksi (nom ou adresse du coffre) et ses tests | | `mobile/ios/loksi.py`, `fonts.py` | textes d'accueil et police Loksi tirée de Raleway, lus par la construction Android | | `brand/` | ressources de la charte Loksi lues par la construction : icône, logos, illustrations et leurs générateurs | +| `desktop/upstream.json` | application de bureau : tag `bitwarden/clients`, commit et SHA-256 de l'archive, version Loksi et numéro de build | +| `desktop/loksi.py` | adaptation et construction du bureau : `prepare`, `changes`, `canari`, `build`, `verify` | +| `desktop/*.cjs`, `render.mjs`, `dependencies.py`, `entete.mjs` | configuration electron-builder, webpack sans code commercial, visuels, inventaire des licences, relevé de la version envoyée au serveur | +| `extensions/upstream.json`, `version.json` | extensions : tag `bitwarden/clients`, SHA-256 de l'archive, version Loksi | +| `extensions/prototype.py` | adaptation et construction des extensions : `prepare`, `build`, `paquet`. Palette, illustrations et police aussi lues par le bureau | +| `extensions/verify-source.py`, `dependencies.py`, `fonts.py`, `icons.mjs`, `webpack-oss.cjs`, `loksi-coffre.ts`, `*.test.cjs` | contrôle de la source adaptée, licences, police, icônes, construction sans code commercial, nom du coffre et ses tests | +| `extensions/README.md`, `LICENSE`, `licenses/` | détail des extensions, licence et licences des dépendances | | `LICENSE` | texte de la GPL v3, celui des dépôts Bitwarden | Chaque script refuse une archive amont dont le SHA-256 a changé. `loksi.py changes` refuse @@ -64,10 +72,83 @@ la signature finale est posée par Google. `verify-release` contrôle l'identifi l'absence des bibliothèques exclues, les textes, la signature par votre clé, et que l'AAB embarque le SDK recompilé et les mêmes dex que l'APK release. -## Application iOS +## Reconstruire l'application iPhone -L'application iOS n'est pas encore distribuée. Sa source sera publiée ici avec sa première -version. +La construction part de l'archive du tag `bitwarden/ios` et du xcframework du SDK publié par +`bitwarden/sdk-swift`, épinglés par SHA-256 dans `mobile/upstream.json`. `mobile/ios/loksi.py` +y applique les adaptations Loksi, refuse toute modification hors des fichiers prévus, et +ajoute le code Swift de `mobile/ios/swift/` (nom ou adresse du coffre, et ses tests). + +Outils : macOS avec Xcode 27, Mint (les outils du `Mintfile` amont), Python 3, Node.js, +`rsvg-convert` et poppler (`pdfinfo`, `pdfimages`). + +```bash +cd mobile +python3 ios/loksi.py prepare # archive vérifiée, adaptations, projets Xcode +python3 ios/loksi.py build # application pour le simulateur, puis verify +python3 ios/loksi.py tests # tests unitaires amont, échecs attendus listés +``` + +Pour un iPhone ou l'App Store, `device` et `archive` signent avec l'équipe Apple écrite dans +`mobile/upstream.json` (`ios.apple_team.id`). Remplacez-la par la vôtre, ainsi que +l'identifiant d'application : votre build aura le même code qu'une version Loksi, pas sa +signature. + +## Reconstruire l'application de bureau + +L'application de bureau (macOS et Windows) part de l'archive du tag `desktop-v2026.9.0` de +`bitwarden/clients`, épinglée par SHA-256 dans `desktop/upstream.json`. `desktop/loksi.py` +y applique les adaptations Loksi et refuse toute modification hors des fichiers prévus. +La construction suit la variante OSS de l'amont : `webpack-oss.cjs` refuse tout module +`bitwarden_license` et le SDK commercial. + +Poste utilisé par Aleop : Mac Apple Silicon, Node.js 26 (l'amont conseille 24), Rust 1.97.1 +par rustup, Python 3, Xcode pour `codesign`, `lipo` et `iconutil`. Pour Windows depuis un +Mac : cargo-xwin, LLVM et lld, makensis. Sous Windows natif : Visual Studio Build Tools. + +```bash +mkdir -p desktop/.cache +curl -fL https://codeload.github.com/bitwarden/clients/tar.gz/refs/tags/desktop-v2026.9.0 \ + -o desktop/.cache/upstream.tar.gz +python3 desktop/loksi.py prepare # archive vérifiée + adaptations Loksi +(cd desktop/.cache/clients-desktop-v2026.9.0 && npm ci --ignore-scripts --no-audit --no-fund) +python3 desktop/loksi.py canari # montre que les contrôles refusent les textes et dessins amont +python3 desktop/loksi.py build mac universal # ou : build win +``` + +`build` compile les modules Rust, le code de l'application, puis le paquet, et lance +`verify` : identifiant, textes, dessins, architectures de chaque binaire macOS, fusibles +Electron, numérotation, ligne « Code source » d'À propos. Il incrémente aussi le numéro +de build dans `desktop/upstream.json`. + +Ce qui n'est pas dans ce dépôt : les certificats et accès de signature. Sans identité +« Developer ID Application » de l'équipe écrite dans `desktop/upstream.json` +(`apple_team`), le paquet macOS est signé ad hoc et n'est pas notarisé : il tourne sur votre +Mac, Gatekeeper le refuse ailleurs. Sans les variables `LOKSI_AZURE_SIGN_*`, l'installateur +Windows sort non signé. Le paquet MSIX du Microsoft Store (`LOKSI_MSIX=1`) demande +l'identité de paquet donnée par Partner Center. Votre build aura le même code qu'une +version Loksi, pas sa signature. + +## Reconstruire les extensions + +Les extensions Chrome, Edge et Firefox partent de l'archive du tag `browser-v2026.9.2` de +`bitwarden/clients`, épinglée par SHA-256 dans `extensions/upstream.json`. Détail dans +`extensions/README.md`. Depuis la racine du dépôt : + +```bash +mkdir -p extensions/.cache +curl -fL https://github.com/bitwarden/clients/archive/refs/tags/browser-v2026.9.2.tar.gz \ + -o extensions/.cache/upstream.tar.gz +npm ci --prefix brand --no-audit --no-fund +python3 extensions/prototype.py prepare +(cd extensions/.cache/clients-browser-v2026.9.2 && npm ci --ignore-scripts --no-audit --no-fund) +python3 extensions/verify-source.py +python3 extensions/prototype.py build chrome # puis edge, firefox +python3 extensions/prototype.py paquet chrome # puis edge, firefox +``` + +Les magasins signent eux-mêmes les extensions : votre paquet a le même code qu'une version +Loksi, pas sa signature de magasin. ## Licences et marques @@ -88,8 +169,8 @@ Contact : loksi@aleop.eu. Loksi, by Aleop. Bitwarden® app modified by Aleop, under the GPL v3. Aleop is not affiliated with Bitwarden Inc. -This repository is the corresponding source of the Loksi Android app under the GPL v3. It -does not copy the Bitwarden tree. The scripts download the official Bitwarden archives, +This repository is the corresponding source of the Loksi apps for Android, iPhone, macOS and +Windows, and of the Loksi extensions for Chrome, Edge and Firefox, under the GPL v3. It does not copy the Bitwarden tree. The scripts download the official Bitwarden archives, pinned by SHA-256 in `mobile/upstream.json`, and apply the Loksi changes. The Bitwarden SDK is rebuilt from `bitwarden/sdk-internal` at the commit used by the tag. @@ -97,6 +178,21 @@ To rebuild the Android app, install the tools listed above and run the commands French section, from `sdk` to `release`. Signing keys are created on your machine and are not part of this repository, so your build has the same code but not the same signature. +To rebuild the iPhone app, use macOS with Xcode 27 and run `ios/loksi.py prepare`, then +`build` and `tests`. `device` and `archive` sign with the Apple team written in +`mobile/upstream.json`: put your own team and app identifier there. + +To rebuild the desktop app (macOS and Windows), download the `desktop-v2026.9.0` archive +of `bitwarden/clients` into `desktop/.cache/`, then run `desktop/loksi.py prepare`, `npm ci` +in the prepared tree, `canari`, and `build mac universal` or `build win`. Without your own +Apple Developer ID the macOS package is signed ad hoc and not notarized. Without the +`LOKSI_AZURE_SIGN_*` variables the Windows installer is not signed. + +To rebuild the browser extensions, download the `browser-v2026.9.2` archive of +`bitwarden/clients` into `extensions/.cache/`, then run the commands of the French section: +`prepare`, `npm ci` in the prepared tree, `verify-source.py`, then `build` and `paquet` for +chrome, edge and firefox. + Code is under the GPL v3. Bitwarden is a trademark of Bitwarden Inc. Loksi and its logo are trademarks of Aleop. Under section 7 e) of the GPL v3, no trademark rights are granted: a modified version you distribute must use another name and logo. diff --git a/brand/propositions/harmonisation-klepsi/sources/OFL-Raleway.txt b/brand/propositions/harmonisation-klepsi/sources/OFL-Raleway.txt new file mode 100644 index 0000000..c70fc74 --- /dev/null +++ b/brand/propositions/harmonisation-klepsi/sources/OFL-Raleway.txt @@ -0,0 +1,93 @@ +Copyright 2010 The Raleway Project Authors (impallari@gmail.com), with Reserved Font Name "Raleway". + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/desktop/.gitignore b/desktop/.gitignore new file mode 100644 index 0000000..1ebf36f --- /dev/null +++ b/desktop/.gitignore @@ -0,0 +1,4 @@ +.cache/ +dist/ +reports/ +__pycache__/ diff --git a/desktop/after-pack.cjs b/desktop/after-pack.cjs new file mode 100644 index 0000000..a94fa81 --- /dev/null +++ b/desktop/after-pack.cjs @@ -0,0 +1,56 @@ +// GPL-3.0-only. afterPack de Loksi : celui de l'amont (fusibles Electron, proxy macOS), +// puis, pour Windows construit hors de Windows, l'icône et les métadonnées de Loksi.exe. +// +// electron-builder les pose d'habitude par rcedit, qui passe par un Wine x86_64 sur +// macOS : il ne tourne pas sur Apple Silicon sans Rosetta (vu le 30/09/2026, « bad CPU +// type in executable »). resedit, en JavaScript pur, est celui qu'electron-builder +// emploie déjà pour l'intégrité asar. Sur Windows, rcedit et la signature restent ceux +// d'electron-builder (electron-builder.cjs ne coupe signAndEditExecutable qu'ailleurs). +/* eslint-disable no-console */ +const fs = require("fs"); +const path = require("path"); +const ResEdit = require("resedit"); +const upstream = require("./scripts/after-pack.js").default; + +exports.default = async function afterPack(context) { + await upstream(context); + if (context.electronPlatformName !== "win32" || process.platform === "win32") { + return; + } + const info = context.packager.appInfo; + const exe = path.join(context.appOutDir, info.productFilename + ".exe"); + const executable = ResEdit.NtExecutable.from(fs.readFileSync(exe)); + const resource = ResEdit.NtExecutableResource.from(executable); + const groups = ResEdit.Resource.IconGroupEntry.fromEntries(resource.entries); + if (groups.length !== 1) { + throw new Error("Loksi.exe : un groupe d'icônes attendu, " + groups.length + " trouvés"); + } + const icon = ResEdit.Data.IconFile.from(fs.readFileSync(path.join(__dirname, "resources/icon.ico"))); + ResEdit.Resource.IconGroupEntry.replaceIconsForResource( + resource.entries, groups[0].id, groups[0].lang, icon.icons.map((item) => item.data)); + const versions = ResEdit.Resource.VersionInfo.fromEntries(resource.entries); + if (versions.length !== 1) { + throw new Error("Loksi.exe : une ressource de version attendue"); + } + const version = versions[0]; + const [lang] = version.getAllLanguagesForStringValues(); + const parts = info.version.split(".").map(Number); + // Quatrième nombre : le numéro de build Loksi (electron-builder.cjs, buildNumber). + const build = Number(info.buildNumber); + version.setFileVersion(parts[0], parts[1], parts[2], build, lang.lang); + version.setProductVersion(parts[0], parts[1], parts[2], build, lang.lang); + version.setStringValues(lang, { + FileDescription: info.productName, + ProductName: info.productName, + InternalName: info.productName, + OriginalFilename: info.productFilename + ".exe", + CompanyName: info.companyName, + LegalCopyright: info.copyright, + FileVersion: info.version + "." + build, + ProductVersion: info.version, + }); + version.outputToResourceEntries(resource.entries); + resource.outputResource(executable); + fs.writeFileSync(exe, Buffer.from(executable.generate())); + console.log("Loksi : icône et métadonnées posées dans " + path.basename(exe) + " par resedit"); +}; diff --git a/desktop/dependencies.py b/desktop/dependencies.py new file mode 100644 index 0000000..26297d6 --- /dev/null +++ b/desktop/dependencies.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Inventaire des dépendances réellement livrées dans l'appli de bureau. + +dependencies.py mac [arm64|x64|universal] | win + +- paquets npm compilés dans main, renderer et preload, d'après les rapports de + webpack-oss.cjs, avec leurs fichiers de licence ; +- crates Rust des modules natifs (napi, proxy), d'après cargo metadata filtré sur la + cible, sans les dépendances de développement ; +- Electron et Chromium, dont les licences sont déjà livrées dans le paquet + (LICENSE, LICENSES.chromium.html). + +Écrit THIRD-PARTY.json et third-party/ dans le dossier du paquet (dist/mac, dist/mac-x64, +dist/mac-universal, dist/win). +""" +import json +from pathlib import Path +import shutil +import subprocess +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from loksi import MAC_ARCHS, NATIVE, REPORTS, SOURCE, dist_dir, tool_env # noqa: E402 + +platform = sys.argv[1] +arch = sys.argv[2] if len(sys.argv) > 2 else "arm64" +target = dist_dir(platform, arch) +TRIPLES = MAC_ARCHS[arch]["rust"] if platform == "mac" else ("x86_64-pc-windows-msvc",) + +packages = {} +reports = list(REPORTS.glob("desktop-*-modules.json")) +if not reports: + raise RuntimeError("Compiler d'abord avec webpack-oss.cjs") +third = target / "third-party" +if third.exists(): + shutil.rmtree(third) +for report in reports: + for resource in json.loads(report.read_text()): + if "node_modules/" not in resource: + continue + folder = (SOURCE / resource.split("?")[0]).resolve().parent + while folder != SOURCE: + if (folder / "package.json").is_file(): + data = json.loads((folder / "package.json").read_text()) + if data.get("name") and data.get("version"): + break + folder = folder.parent + if folder == SOURCE: + raise RuntimeError(f"Paquet non identifié : {resource}") + data = json.loads((folder / "package.json").read_text()) + key = data["name"] + "@" + data["version"] + if key in packages: + continue + license_files = [p for p in folder.iterdir() if p.is_file() and + p.name.lower().startswith(("license", "licence", "notice", "copying"))] + license = data.get("license", "UNKNOWN") + if folder.is_relative_to(SOURCE / "libs"): + # Bibliothèques du monorepo : GPL v3 par LICENSE.txt, sans champ license. + license = "GPL-3.0" + if isinstance(license, dict): + license = license.get("type", "UNKNOWN") + packages[key] = {"source": "npm", "name": data["name"], "version": data["version"], + "license": license, "license_files": [p.name for p in license_files]} + destination = third / "npm" / key.replace("/", "__") + destination.mkdir(parents=True, exist_ok=True) + for file in license_files: + shutil.copy2(file, destination / file.name) + shutil.copy2(folder / "package.json", destination / "package.json") + +metadata = json.loads(subprocess.run( + ["cargo", "metadata", "--format-version", "1", "--locked", + *[arg for triple in TRIPLES for arg in ("--filter-platform", triple)]], + cwd=NATIVE, env=tool_env(), capture_output=True, text=True, check=True).stdout) +by_id = {p["id"]: p for p in metadata["packages"]} +nodes = {n["id"]: n for n in metadata["resolve"]["nodes"]} +roots = [p["id"] for p in metadata["packages"] if p["name"] in ("desktop_napi", "desktop_proxy")] +if len(roots) != 2: + raise RuntimeError("crates racines desktop_napi et desktop_proxy introuvables") +seen, stack = set(), list(roots) +while stack: + current = stack.pop() + if current in seen: + continue + seen.add(current) + for dep in nodes[current]["deps"]: + if any(k["kind"] in (None, "build") for k in dep["dep_kinds"]): + stack.append(dep["pkg"]) +for pid in sorted(seen): + crate = by_id[pid] + key = crate["name"] + "@" + crate["version"] + local = crate["source"] is None + license = crate["license"] or ("GPL-3.0" if local else "UNKNOWN") + files_extra = [] + if license == "UNKNOWN" and crate.get("license_file") and "/sdk-internal" in crate["manifest_path"]: + # Dépôt sdk-internal : « GPL v3.0 OR BITWARDEN SOFTWARE DEVELOPMENT KIT LICENSE » hors + # des dossiers bitwarden_license (refusés plus bas). On retient la GPL v3. + root = Path(crate["manifest_path"]).parent / crate["license_file"] + license = "GPL-3.0 (au choix, LICENSE de sdk-internal)" + files_extra = [root.resolve(), root.resolve().parent / "LICENSE_GPL.txt"] + if crate["name"] == "bitwarden-russh" and license == "UNKNOWN": + # Pas de champ license ; le dépôt porte le texte Apache-2.0 (LICENSE-2.0.txt), relu le 30/09/2026. + license = "Apache-2.0" + packages["crate:" + key] = {"source": "crate", "name": crate["name"], "version": crate["version"], + "license": license} + folder = Path(crate["manifest_path"]).parent + if "bitwarden_license" in crate["manifest_path"] or "bitwarden-license" in crate["name"]: + raise RuntimeError("Crate sous licence commerciale Bitwarden : " + key) + files = [p for p in folder.iterdir() if p.is_file() and + p.name.lower().startswith(("license", "licence", "notice", "copying"))] + files += [f for f in files_extra if f.is_file()] + if files: + destination = third / "crates" / key + destination.mkdir(parents=True, exist_ok=True) + for file in files: + shutil.copy2(file, destination / file.name) + +(target / "THIRD-PARTY.json").write_text(json.dumps(list(packages.values()), indent=2) + "\n") +for name in ("LICENSE.txt", "LICENSE_GPL.txt"): + shutil.copy2(SOURCE / name, target / name) +licenses = sorted({str(p["license"]) for p in packages.values()}) +print(f"{sum(p['source'] == 'npm' for p in packages.values())} paquets npm et " + f"{sum(p['source'] == 'crate' for p in packages.values())} crates inventoriés dans {target}") +print("Licences déclarées :", licenses) +unknown = [k for k, p in packages.items() if p["license"] in ("UNKNOWN", None)] +print("Sans licence déclarée :", unknown) diff --git a/desktop/electron-builder.cjs b/desktop/electron-builder.cjs new file mode 100644 index 0000000..d9e2ba7 --- /dev/null +++ b/desktop/electron-builder.cjs @@ -0,0 +1,98 @@ +// GPL-3.0-only. Config electron-builder de Loksi : la base JSON écrite par loksi.py +// (electron-builder.loksi.json), plus ce qui dépend de l'environnement. +// +// Signature Windows par Microsoft Artifact Signing (ex Trusted Signing), décision de +// Romain du 29/09/2026. Rien n'est en dur : sans les quatre variables LOKSI_AZURE_*, +// l'installateur sort non signé et la sortie le dit. L'authentification Entra ID se +// lit à part par le module Azure (AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET), +// jamais ici. electron-builder signe par PowerShell (Invoke-TrustedSigning) : à faire +// sur un poste ou un runner Windows, pas depuis ce Mac. +// +// Paquet MSIX pour le Microsoft Store : désactivé par défaut, LOKSI_MSIX=1 l'ajoute. +// L'identité de paquet vient du Partner Center le jour venu, par les trois variables +// LOKSI_APPX_*. Sans elles, la cible refuse de partir. +/* eslint-disable no-console */ +const path = require("path"); +const config = require(path.join(__dirname, "electron-builder.loksi.json")); + +// macOS : sans Developer ID (CSC_NAME), signature ad hoc et pas de hardened runtime. +// Le framework Electron garde la signature de son éditeur (signIgnore amont) : avec le +// hardened runtime, la validation des bibliothèques refuse de le charger, vu le +// 30/09/2026 (« different Team IDs »). Le hardened runtime ne sert qu'à la notarisation. +if (!process.env.CSC_NAME) { + config.mac.hardenedRuntime = false; +} else { + // Developer ID de l'équipe Aleop (SHA-1 choisi par loksi.py), hardened runtime gardé. + config.mac.identity = process.env.CSC_NAME; +} +// Numéro de build (upstream.json, monté par loksi.py build) : CFBundleVersion sur macOS, +// quatrième nombre de la version Windows, et loksiBuild dans le package.json de l'asar +// pour « Version AAAA.M.n (build) » dans À propos. Règle de Romain du 06/10/2026. +const build = process.env.LOKSI_BUILD; +if (!/^[1-9][0-9]*$/.test(build || "")) { + throw new Error("Loksi : LOKSI_BUILD absent, passer par loksi.py build"); +} +config.buildVersion = build; +// Sous Windows natif, rcedit écrit buildVersion tel quel en version de fichier de +// Loksi.exe : « 3 » et 3.0.0.0 au premier build sur VSOP-SIG01 (09/10/2026). Hors +// Windows, after-pack.cjs recompose AAAA.M.n.build par resedit et buildVersion reste +// le CFBundleVersion du Mac. +if (process.platform === "win32") { + if (!/^\d+\.\d+\.\d+$/.test(process.env.LOKSI_VERSION || "")) { + throw new Error("Loksi : LOKSI_VERSION absent, passer par loksi.py build"); + } + config.buildVersion = process.env.LOKSI_VERSION + "." + build; +} +config.buildNumber = build; +config.extraMetadata = { ...config.extraMetadata, loksiBuild: Number(build) }; + +// Notarisation par un profil notarytool du trousseau (APPLE_KEYCHAIN_PROFILE), créé par +// Romain : ni mot de passe ni clé ne passent par ce script. +config.mac.notarize = Boolean(process.env.CSC_NAME && process.env.APPLE_KEYCHAIN_PROFILE); + +// Windows construit ailleurs que sur Windows : pas de rcedit (Wine x86_64), l'icône et +// les métadonnées de l'exe passent par after-pack.loksi.cjs. Pas de signature possible. +if (process.platform !== "win32") { + config.win.signAndEditExecutable = false; +} + +const azure = { + endpoint: process.env.LOKSI_AZURE_SIGN_ENDPOINT, + codeSigningAccountName: process.env.LOKSI_AZURE_SIGN_ACCOUNT, + certificateProfileName: process.env.LOKSI_AZURE_SIGN_PROFILE, + publisherName: process.env.LOKSI_AZURE_SIGN_PUBLISHER, +}; +const azureSet = Object.values(azure).filter(Boolean).length; +if (azureSet === 4) { + config.win.azureSignOptions = azure; + console.log("Loksi : signature Windows par Artifact Signing, compte " + azure.codeSigningAccountName); +} else if (azureSet === 0) { + console.log("Loksi : AUCUNE signature Windows (variables LOKSI_AZURE_SIGN_* absentes). Paquet de test seulement."); +} else { + throw new Error("Loksi : variables LOKSI_AZURE_SIGN_* incomplètes (" + azureSet + " sur 4)"); +} + +if (process.env.LOKSI_MSIX === "1") { + const identity = { + identityName: process.env.LOKSI_APPX_IDENTITY_NAME, + publisher: process.env.LOKSI_APPX_PUBLISHER, + publisherDisplayName: process.env.LOKSI_APPX_PUBLISHER_DISPLAY_NAME, + }; + const missing = Object.entries(identity).filter(([, value]) => !value).map(([key]) => key); + if (missing.length) { + throw new Error("Loksi : identité MSIX incomplète, manque " + missing.join(", ")); + } + // Le paquet du Store se construit sans Artifact Signing : le Store le signe lui-même + // avec le certificat du compte, dont le sujet est LOKSI_APPX_PUBLISHER. Avec + // azureSignOptions, electron-builder 26.9.0 remplace l'éditeur du manifeste par + // publisherName (computePublisherName du gestionnaire Azure), et makeappx refuse + // « ALEOP » qui n'est pas un nom distinctif : run 9 du 09/10/2026. + if (config.win.azureSignOptions) { + throw new Error("Loksi : MSIX et Artifact Signing s'excluent, lancer le paquet du Store sans LOKSI_AZURE_SIGN_*"); + } + Object.assign(config.appx, identity); + config.win.target.push({ target: "appx", arch: ["x64"] }); + console.log("Loksi : cible MSIX ajoutée pour " + identity.identityName); +} + +module.exports = config; diff --git a/desktop/entete.mjs b/desktop/entete.mjs new file mode 100644 index 0000000..40e6175 --- /dev/null +++ b/desktop/entete.mjs @@ -0,0 +1,54 @@ +// Relève l'en-tête Bitwarden-Client-Version des requêtes du paquet vers un serveur, par le +// protocole de débogage Chromium. Données dans un dossier temporaire, aucun compte, aucun +// jeton : seuls l'URL et cet en-tête sont imprimés. +// node entete.mjs +import { spawn } from "node:child_process"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const [app, base] = process.argv.slice(2); +const dir = mkdtempSync(join(tmpdir(), "loksi-entete-")); +writeFileSync(join(dir, "data.json"), JSON.stringify({ + global_environment_environment: { region: "Self-hosted", urls: { base } }, +})); +const port = 9333; +const child = spawn(join(app, "Contents/MacOS/Loksi"), [`--remote-debugging-port=${port}`], + { env: { ...process.env, BITWARDEN_APPDATA_DIR: dir }, stdio: "ignore" }); +const seen = new Map(); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +try { + let targets = []; + for (let i = 0; i < 40 && !targets.some((t) => t.type === "page"); i++) { + await sleep(500); + targets = await fetch(`http://127.0.0.1:${port}/json`).then((r) => r.json()).catch(() => []); + } + const page = targets.find((t) => t.type === "page"); + if (!page) throw new Error("aucune page de rendu"); + const ws = new WebSocket(page.webSocketDebuggerUrl); + await new Promise((r) => ws.addEventListener("open", r)); + ws.addEventListener("message", (event) => { + const msg = JSON.parse(event.data); + if (msg.method === "Network.requestWillBeSent" || msg.method === "Network.requestWillBeSentExtraInfo") { + const url = msg.params.request?.url ?? seen.get(msg.params.requestId)?.url; + const headers = msg.params.request?.headers ?? msg.params.headers ?? {}; + const key = Object.keys(headers).find((h) => h.toLowerCase() === "bitwarden-client-version"); + const entry = seen.get(msg.params.requestId) ?? {}; + if (url) entry.url = url; + if (key) entry.version = headers[key]; + seen.set(msg.params.requestId, entry); + } + }); + ws.send(JSON.stringify({ id: 1, method: "Network.enable" })); + // Recharge pour voir les requêtes du démarrage, puis laisse tourner. + ws.send(JSON.stringify({ id: 2, method: "Page.reload" })); + await sleep(15000); + ws.close(); +} finally { + child.kill("SIGKILL"); + rmSync(dir, { recursive: true, force: true }); +} +for (const { url, version } of seen.values()) { + if (url && url.startsWith(base)) console.log(new URL(url).pathname, "Bitwarden-Client-Version:", version ?? "(absent)"); +} +console.log(`requêtes vers ${base} : ${[...seen.values()].filter((e) => e.url?.startsWith(base)).length}`); diff --git a/desktop/loksi.py b/desktop/loksi.py new file mode 100644 index 0000000..4f6f8c6 --- /dev/null +++ b/desktop/loksi.py @@ -0,0 +1,1426 @@ +#!/usr/bin/env python3 +"""Application de bureau Loksi, adaptée du client desktop Bitwarden. GPL-3.0-only. + +loksi.py prepare extraction de l'archive vérifiée et adaptations +loksi.py native [win] modules Rust (napi, proxy), pour ce Mac ou pour Windows x64 +loksi.py build mac|win webpack, électron-builder, puis verify +loksi.py verify mac|win contrôles du paquet produit + mac prend une architecture en plus : arm64 (défaut), x64 ou universal. +loksi.py changes refuse toute différence avec l'archive hors des fichiers prévus +loksi.py canari montre que verify refuse les textes et dessins de l'amont + +Sources amont épinglées dans upstream.json. Ni la cryptographie, ni le SDK, ni les API, +ni la synchronisation ne sont touchés : seulement l'identité, le serveur, les textes, +les visuels et les identifiants qui feraient cohabiter Loksi avec l'appli Bitwarden. +""" +import hashlib +import json +import os +from pathlib import Path +from platform import machine as platform_machine +import plistlib +import re +import shutil +import struct +import subprocess +import sys +import tarfile +import tempfile + +ROOT = Path(__file__).resolve().parent +REPO = ROOT.parent +CONFIG = json.loads((ROOT / "upstream.json").read_text()) +CACHE = ROOT / ".cache" +ARCHIVE = CACHE / "upstream.tar.gz" +SOURCE = CACHE / ("clients-" + CONFIG["tag"]) +APP = SOURCE / "apps/desktop" +# Cache de mise à jour d'electron-builder : appInfo.updaterCacheDirName, nom du package en +# minuscules suivi de « -updater ». +UPDATER_DIR = CONFIG["executable_name"].lower() + "-updater" +NATIVE = APP / "desktop_native" +DIST = ROOT / "dist" +REPORTS = ROOT / "reports" +TOUCHED = CACHE / "touched.json" +UNSET = CONFIG["unset_server"] +HOST = CONFIG["native_messaging"]["host"] +APP_ID = CONFIG["app_id"] +TEAM_BITWARDEN = "LTZ2PFU5D6" +# Numérotation, règle de Romain du 06/10/2026 : version affichée AAAA.M.n, compteur de +# build entier dans upstream.json. La version Bitwarden de la base reste celle du tag. +BITWARDEN_VERSION = CONFIG["tag"].removeprefix("desktop-v") +VERSION = CONFIG["app_version"]["marketing"] +VERSION_RE = re.compile(r"20\d\d\.(?:[1-9]|1[0-2])\.(?:0|[1-9]\d*)") +AIDE = "https://www.aleop.eu/aide/loksi/" +CONFIDENTIALITE = "https://www.aleop.eu/loksi/confidentialite/" +CONDITIONS = "https://www.aleop.eu/cgv" +# Passkeys Windows : AAGUID propre à Loksi, tiré le 09/10/2026. Celui de l'amont fait +# afficher « Bitwarden » par les sites qui listent les fournisseurs de passkeys. +AAGUID = "4dd988f4-e397-4b27-9042-ef76ea009d6e" +AAGUID_BITWARDEN = "d548826e-79b4-db40-a3d8-11116f7e8349" +# Exécutables Windows livrés : noms Loksi à l'installation (« to » d'electron-builder). +WIN_EXE_NOMS = {"bitwarden_chromium_import_helper.exe": "loksi_chromium_import_helper.exe", + "bitwarden_plugin_authenticator.exe": "loksi_plugin_authenticator.exe"} +RUSTUP = "/opt/homebrew/opt/rustup/bin" +# Build Windows sur Windows (runner VSOP-SIG01, depuis le 08/10/2026) : MSVC natif au +# lieu de cargo-xwin, NSIS d'electron-builder au lieu de celui de brew, pas d'iconutil. +WINDOWS_HOST = sys.platform == "win32" +# Architectures macOS : cibles Rust, noms lipo exigés sur chaque binaire du paquet. +MAC_ARCHS = { + "arm64": {"rust": ("aarch64-apple-darwin",), "lipo": {"arm64"}}, + "x64": {"rust": ("x86_64-apple-darwin",), "lipo": {"x86_64"}}, + "universal": {"rust": ("aarch64-apple-darwin", "x86_64-apple-darwin"), "lipo": {"arm64", "x86_64"}}, +} +NAPI_LIPO = {"arm64": "arm64", "x64": "x86_64"} +# Fusibles Electron (V1) : sentinelle du fil dans Electron Framework, puis l'état attendu +# de ceux que after-pack.js amont pose. Index dans le fil : 0 RunAsNode, 1 chiffrement +# des cookies, 2 NODE_OPTIONS, 3 --inspect, 4 intégrité asar, 5 appli seulement en asar. +FUSE_SENTINEL = b"dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX" +FUSES = {0: "0", 1: "1", 2: "0", 3: "0", 4: "1", 5: "1"} + +# Réutilise la charte déjà portée par l'extension : palette, illustrations et leur +# table, dessins clair et sombre réunis. Lecture seule, rien n'est écrit dans extensions/. +sys.path.insert(0, str(REPO / "extensions")) +import prototype as extension # noqa: E402 +import fonts as extension_fonts # noqa: E402 + +# Textes où Bitwarden reste (brand/README.md, « Le nom Bitwarden ») : la mention +# d'origine, un produit Bitwarden réel cité comme tel, l'éditeur lui-même. +BITWARDEN_GARDE = { + "loksiAboutOrigin", "loksiBasedOn", "authenticatorAppDescV2", "newDeviceVerificationNoticeContentPage1", + "premiumPurchaseAlertV2", "bitwardenSupport", +} +# Mention d'origine validée par Romain le 30/09/2026, la même dans tous les clients +# (brand/README.md, « Le nom Bitwarden »), suivie de l'avis de copyright amont. +MENTION = { + "fr": "Loksi, par Aleop. Application de bureau Bitwarden® modifiée par Aleop, sous licence GPL v3. " + "Aleop n'est pas affilié à Bitwarden Inc.\n© Bitwarden Inc. 2015-2026", + "en": "Loksi, by Aleop. Bitwarden® desktop app modified by Aleop, under the GPL v3. " + "Aleop is not affiliated with Bitwarden Inc.\n© Bitwarden Inc. 2015-2026", +} +# Source GPL publique, citée dans À propos de chaque client avant les envois aux Stores +# (orchestration, ordre de Romain du 12/10/2026). +SOURCE_GPL = "https://sources.gitsi.dev/aleop/loksi" +TEXTES = { + "fr": { + "loksiConnectingTo": "Connexion sur", + "loksiAddressToEnter": "adresse à saisir", + "loksiAccountByAdmin": "Votre compte est créé par l'administrateur de votre entreprise.", + "loksiAboutOrigin": MENTION["fr"], + "loksiBasedOn": "Basé sur Bitwarden " + BITWARDEN_VERSION, + "loksiSourceCode": "Code source (GPL v3) : " + SOURCE_GPL, + "loksiVaultTitle": "Votre coffre Loksi", + "loksiContactUs": "Nous contacter", + "loksiContactTitle": "Écrire au support ?", + "loksiContactBody": "Votre messagerie s'ouvre avec un courriel pour loksi@aleop.eu. " + "Pour la protection des données, écrivez à dpo@aleop.eu.", + "selfHostedBaseUrlHint": "L'adresse de votre coffre Loksi vous est donnée par " + "l'administrateur de votre entreprise. Exemple : https://loksi-entreprise.aleop.eu", + }, + "en": { + "loksiConnectingTo": "Logging in to", + "loksiAddressToEnter": "address to enter", + "loksiAccountByAdmin": "Your account is created by your company's administrator.", + "loksiAboutOrigin": MENTION["en"], + "loksiBasedOn": "Based on Bitwarden " + BITWARDEN_VERSION, + "loksiSourceCode": "Source code (GPL v3): " + SOURCE_GPL, + "loksiVaultTitle": "Your Loksi vault", + "loksiContactUs": "Contact us", + "loksiContactTitle": "Email support?", + "loksiContactBody": "Your email app opens with a message to loksi@aleop.eu. " + "For data protection, write to dpo@aleop.eu.", + "selfHostedBaseUrlHint": "Your company's administrator gives you the address of your " + "Loksi vault. Example: https://loksi-company.aleop.eu", + }, +} +# Identifiants Chrome, Edge et Opera des extensions Bitwarden officielles : jamais admis. +CHROME_BITWARDEN = ("nngceckbapebfimnlniiiahkandclblb", "hccnnhgbibccigepcmlgppchkpfdophk", + "jbkfoedolllekgbhcbcoahefnbanhhlh", "ccnckbpmaceehanjmeomladnmlffdjgn") + +touched = set() + + +def rel(path): + # as_posix : sous Windows str() rend des « \ », et changes() compare aux noms de + # l'archive, en « / ». Tout passait « hors périmètre » (vu le 09/10/2026). + return Path(path).relative_to(SOURCE).as_posix() + + +def write(path, text): + Path(path).write_text(text) + touched.add(rel(path)) + + +def write_bytes(path, data): + Path(path).write_bytes(data) + touched.add(rel(path)) + + +def write_json(path, value): + write(path, json.dumps(value, indent=2, ensure_ascii=False) + "\n") + + +def replace_count(path, old, new, expected=1): + value = Path(path).read_text() + if value.count(old) != expected: + raise RuntimeError(f"Point d'adaptation amont modifié ({value.count(old)} au lieu de " + f"{expected}) : {rel(path)} : {old[:60]!r}") + write(path, value.replace(old, new)) + + +def replace_once(path, old, new): + replace_count(path, old, new, 1) + + +def run(cmd, **kwargs): + print("+", " ".join(str(c) for c in cmd), flush=True) + cmd = [str(c) for c in cmd] + if WINDOWS_HOST: + # npm et npx sont des .cmd sous Windows : CreateProcess ne les trouve pas sous + # leur nom nu. which() rend le chemin complet, extension comprise. + found = shutil.which(cmd[0], path=kwargs.get("env", os.environ).get("PATH")) + if found: + cmd[0] = found + subprocess.run(cmd, check=True, **kwargs) + + +def tool_env(): + return dict(os.environ, PATH=os.pathsep.join([RUSTUP, str(Path.home() / ".cargo/bin"), + os.environ["PATH"]])) + + +# ---------------------------------------------------------------- identité + +def identity(): + data = json.loads((APP / "src/package.json").read_text()) + data.update(name="loksi", productName=CONFIG["product_name"], desktopName="loksi.desktop", + description="Loksi, le coffre de mots de passe de votre entreprise.", + author="Aleop", homepage=CONFIG["homepage"], version=VERSION) + write_json(APP / "src/package.json", data) + # Le package.json de développement donne à electron-builder l'éditeur et la + # description des métadonnées Windows. Son nom de workspace npm reste. + data = json.loads((APP / "package.json").read_text()) + data.update(author="Aleop", homepage=CONFIG["homepage"], version=VERSION, + description="Loksi, le coffre de mots de passe de votre entreprise.") + data["keywords"] = ["loksi", "password", "vault", "password manager"] + write_json(APP / "package.json", data) + replace_once(APP / "src/index.html", "Bitwarden", "Loksi") + builder_config() + # Signature ad hoc sur ce Mac tant qu'il n'y a pas de Developer ID : l'identité vient + # de CSC_NAME, jamais de la recherche amont qui prendrait la première identité + # Apple du trousseau (celle de la Personal Team iOS, par exemple). + after_pack = APP / "scripts/after-pack.js" + text = after_pack.read_text() + start = text.index(" // Only use the Bitwarden Identities on CI\n") + end = text.index(" id = identities[0].id;\n }\n") + len(" id = identities[0].id;\n }\n") + text = (text[:start] + " // Loksi : CSC_NAME quand un Developer ID existera, signature ad hoc sinon.\n" + " id = process.env.CSC_NAME || \"-\";\n" + text[end:]) + if text.count("--timestamp") != 4: + raise RuntimeError("after-pack.js : 4 --timestamp attendus") + text = text.replace("--timestamp", "${id === \"-\" ? \"\" : \"--timestamp\"}") + # Fusibles Electron : l'amont ne les pose sur macOS que pour le paquet universel. Le + # paquet arm64 notarisé le 03/10/2026 est sorti sans aucun (RunAsNode actif, intégrité + # asar coupée), vu le 04/10. Loksi les pose aussi sur un paquet d'une seule + # architecture ; les deux moitiés d'un universel restent sans, comme l'amont. + old = "context.packager.platform.nodeName !== \"darwin\" || context.arch === builder.Arch.universal" + if text.count(old) != 1: + raise RuntimeError("after-pack.js : condition des fusibles amont modifiée") + text = text.replace(old, old + " || process.env.LOKSI_MAC_ARCH !== \"universal\"") + old = "resetAdHocDarwinSignature: platform === \"darwin\" && context.arch === builder.Arch.universal," + if text.count(old) != 1: + raise RuntimeError("after-pack.js : resetAdHocDarwinSignature amont modifié") + text = text.replace(old, "resetAdHocDarwinSignature: platform === \"darwin\",") + write(after_pack, text) + # Entitlements macOS : ceux de l'équipe Apple de Bitwarden retirés, le JIT reste. + plist = APP / "resources/entitlements.mac.plist" + data = plistlib.loads(plist.read_bytes()) + if data.pop("com.apple.application-identifier") != TEAM_BITWARDEN + ".com.bitwarden.desktop": + raise RuntimeError("entitlements.mac.plist amont modifié") + data.pop("com.apple.developer.team-identifier") + write_bytes(plist, plistlib.dumps(data)) + + +def builder_config(): + """electron-builder.loksi.json : la config amont, réduite à macOS et Windows.""" + config = json.loads((APP / "electron-builder.json").read_text()) + for key in ("afterSign", "publish", "mas", "appx", "snap", "deb", "rpm", "appImage", + "linux", "nsisWeb", "portable", "dmg"): + config.pop(key) + config["afterPack"] = "after-pack.loksi.cjs" + config.update( + extraMetadata={"name": CONFIG["executable_name"]}, productName=CONFIG["product_name"], + # Panneau À propos natif de macOS (NSHumanReadableCopyright) et LegalCopyright de + # Loksi.exe : la mention commune, en une ligne. + appId=APP_ID, copyright=MENTION["fr"].replace("\n", " "), + publish=None, protocols=config["protocols"]) + # Licence de la police Loksi (OFL) et avis de dérivation, livrés dans les ressources. + shutil.copy2(REPO / "brand/propositions/harmonisation-klepsi/sources/OFL-Raleway.txt", + APP / "resources/OFL-police-Loksi.txt") + touched.add(rel(APP / "resources/OFL-police-Loksi.txt")) + write(APP / "resources/LOKSI-NOTICE.txt", + "Loksi, application de bureau adaptée par Aleop.\n" + "Basée sur Bitwarden clients " + CONFIG["tag"] + " (" + CONFIG["commit"] + ").\n" + "Code amont et adaptations : GPL v3, licences tierces conservées.\n" + "Modifications : identité, serveur à saisir, textes, visuels, identifiants locaux.\n" + "Police Loksi : instances de Raleway renommées, SIL Open Font License 1.1\n" + "(OFL-police-Loksi.txt).\n" + "Ni affiliée ni approuvée par Bitwarden.\n") + notices = [{"from": "resources/OFL-police-Loksi.txt", "to": "OFL-police-Loksi.txt"}, + {"from": "resources/LOKSI-NOTICE.txt", "to": "LOKSI-NOTICE.txt"}] + mac = config["mac"] + mac["extraResources"] = list(notices) + config["win"]["extraResources"] = config["win"]["extraResources"] + notices + for key in ("provisioningProfile",): + mac.pop(key) + # Nom du zip avec l'architecture, x64 compris (electron-builder l'omet pour x64). + mac.update(identity="-", target=["zip"], artifactName="${productName}-${version}-${arch}-mac.${ext}") + win = config["win"] + win.pop("signtoolOptions") + # Noms Loksi des exécutables installés. Le binaire construit garde le nom de son + # crate (« from ») ; l'importeur Chromium cherche le sien sous le nouveau nom. + renommes = [f for f in win["extraFiles"] if f.get("to") in WIN_EXE_NOMS] + if len(renommes) != len(WIN_EXE_NOMS): + raise RuntimeError("Point d'adaptation amont modifié : extraFiles Windows") + for fichier in renommes: + fichier["to"] = WIN_EXE_NOMS[fichier["to"]] + # Signature et paquet Store : ajoutés par electron-builder.loksi.cjs, sur variables + # d'environnement seulement. Sans elles, un installateur NSIS non signé. + win.update(target=[{"target": "nsis", "arch": ["x64"]}], signExts=[".dll", ".node"]) + config["nsis"] = { + "oneClick": False, "perMachine": False, "allowToChangeInstallationDirectory": False, + "artifactName": "${productName}-Setup-${version}-${arch}.${ext}", + "uninstallDisplayName": "${productName}", "deleteAppDataOnUninstall": True, + "include": "installer.nsh", "installerSidebar": "installerSidebar.bmp", + "uninstallerSidebar": "installerSidebar.bmp", + # makensis 3.13 de brew : des chaînes de langue manquent dans ses fichiers + # de langue, simples avertissements que l'option -WX rendrait bloquants. + "warningsAsErrors": False, "installerLanguages": ["fr_FR", "en_US"], + "multiLanguageInstaller": True, + } + config["appx"] = { + "artifactName": "${productName}-${version}-${arch}.${ext}", "applicationId": "Loksi", + "backgroundColor": "#003087", "displayName": "Loksi", + "languages": ["fr-FR", "en-US"], + } + # Le schéma bitwarden:// reste : retour SSO du bureau (DESKTOP_SSO_CALLBACK), Duo et + # cookie SSO. Vaultwarden 1.37.3 attend ce retour, comme pour les applis mobiles. + config["protocols"] = [{"name": "Loksi", "schemes": ["bitwarden"]}] + write_json(APP / "electron-builder.loksi.json", config) + # L'installateur NSIS d'electron-builder copie l'exe d'installation dans + # %LOCALAPPDATA%\-updater\installer.exe (mises à jour différentielles), et la + # désinstallation ne le retire jamais : 115 Mo laissés sur VSOP-SIG01 le 09/10/2026. + # Loksi n'a pas de canal de mise à jour, le dossier part avec l'appli. Même + # contexte que la copie (installer.nsh d'electron-builder) : utilisateur courant. + replace_once(APP / "installer.nsh", " ${endIf}\n!macroend", f"""\ + ${{if}} $installMode == "all" + SetShellVarContext current + ${{endif}} + RMDir /r "$LOCALAPPDATA\\{UPDATER_DIR}" + ${{if}} $installMode == "all" + SetShellVarContext all + ${{endif}} + ${{endIf}} +!macroend""") + for source, target in (("electron-builder.cjs", "electron-builder.loksi.cjs"), + ("after-pack.cjs", "after-pack.loksi.cjs")): + shutil.copy2(ROOT / source, APP / target) + touched.add(rel(APP / target)) + + +# ---------------------------------------------------------------- natif (Rust) + +def native_sources(): + ipc = NATIVE / "core/src/ipc/mod.rs" + # Tuyaux et sockets propres à Loksi : sans cela l'appli Bitwarden installée sur le + # même poste répondrait aux messages de l'extension Loksi, et inversement. + replace_once(ipc, r'format!(r"\\.\pipe\{hash_b64}.s.{name}").into()', + r'format!(r"\\.\pipe\{hash_b64}.loksi.s.{name}").into()') + replace_once(ipc, 'home.join("Library/Group Containers/' + TEAM_BITWARDEN + '.com.bitwarden.desktop")', + 'home.join("Library/Group Containers/' + APP_ID + '")') + replace_once(ipc, 'let path_dir = home.join("com.bitwarden.desktop");', + 'let path_dir = home.join("' + APP_ID + '");') + # Agent SSH : socket et dossier Flatpak propres à Loksi (~/.loksi-ssh-agent.sock). + for path, count in (("core/src/ssh_agent/unix.rs", 2), ("ssh_agent/src/server/listener/unix.rs", 2)): + replace_count(NATIVE / path, ".bitwarden-ssh-agent.sock", ".loksi-ssh-agent.sock", count) + replace_once(NATIVE / path, '".var/app/com.bitwarden.desktop/data"', '".var/app/' + APP_ID + '/data"') + # Windows Hello : la clé biométrique a son propre nom dans le coffre d'identifiants. + replace_count(NATIVE / "biometric/src/windows.rs", "BitwardenBiometricsV2", "LoksiBiometricsV2", 2) + # Info.plist incrusté dans le binaire du proxy (embed_plist) : identifiant Loksi. + replace_once(APP / "resources/info.desktop_proxy.plist", "com.bitwarden.desktop", + "" + APP_ID + "") + proxy = NATIVE / "proxy/src/main.rs" + replace_once(proxy, 'path.set_extension("bitwarden.log");', 'path.set_extension("loksi.log");') + replace_once(proxy, 'info!("Starting Bitwarden IPC Proxy.");', 'info!("Starting Loksi IPC Proxy.");') + # Inventaire du 09/10/2026, décision de Romain : plus de « bitwarden » visible hors + # obligation. Variable de l'agent SSH, dossier de données et AAGUID de la passkey + # Windows, tuyau et nom de l'aide à l'import Chromium, clé de préférences macOS. + replace_count(NATIVE / "core/src/ssh_agent/unix.rs", "BITWARDEN_SSH_AUTH_SOCK", "LOKSI_SSH_AUTH_SOCK", 4) + replace_count(NATIVE / "ssh_agent/src/server/listener/unix.rs", "BITWARDEN_SSH_AUTH_SOCK", + "LOKSI_SSH_AUTH_SOCK", 7) + plugin = NATIVE / "windows_plugin_authenticator/src" + replace_once(plugin / "main.rs", 'std::env::var("BITWARDEN_APPDATA_DIR")', 'std::env::var("LOKSI_APPDATA_DIR")') + replace_once(plugin / "main.rs", ' "Bitwarden",\n', ' "Loksi",\n') + replace_once(plugin / "lib.rs", '"' + AAGUID_BITWARDEN + '"', '"' + AAGUID + '"') + importer = NATIVE / "chromium_importer/src/chromium/platform/windows" + replace_once(importer / "abe_config.rs", r"\\.\pipe\bitwarden-to-bitwarden-chromium-importer-helper", + r"\\.\pipe\loksi-chromium-importer-helper") + for amont, loksi in WIN_EXE_NOMS.items(): + if "chromium" in amont: + replace_once(importer / "mod.rs", 'const ADMIN_EXE_FILENAME: &str = "' + amont + '";', + 'const ADMIN_EXE_FILENAME: &str = "' + loksi + '";') + replace_once(NATIVE / "objc/src/native/chromium_importer/browser_access_manager.m", + '@"com.bitwarden.chromiumImporter.bookmarks"', '@"' + APP_ID + '.chromiumImporter.bookmarks"') + + +# ---------------------------------------------------------------- processus principal + +def main_process(): + main = APP / "src/main.ts" + replace_once(main, ' this.desktopCredentialStorageListener = new DesktopCredentialStorageListener(\n' + ' "Bitwarden",', + ' this.desktopCredentialStorageListener = new DesktopCredentialStorageListener(\n' + ' "Loksi",') + replace_once(main, '"bitwarden-appdata"', '"loksi-appdata"') + replace_once(APP / "src/platform/main/desktop-credential-storage-listener.ts", + 'if (serviceName == "Bitwarden_biometric") {', 'if (serviceName == "Loksi_biometric") {') + replace_once(APP / "src/key-management/biometrics/os-biometrics-mac.service.ts", + 'const SERVICE = "Bitwarden_biometric";', 'const SERVICE = "Loksi_biometric";') + # Pas de mise à jour automatique : le canal amont installerait l'appli Bitwarden. + replace_once(APP / "src/main/updater.main.ts", + " this.canUpdate =\n !this.userDisabledUpdates() &&", + " // Loksi : aucun canal de mise à jour, celui de l'amont installerait Bitwarden.\n" + " this.canUpdate =\n false &&\n !this.userDisabledUpdates() &&") + about = APP / "src/main/menu/menu.about.ts" + replace_once(about, ' "\\nArchitecture " +\n process.arch;', + ' "\\nArchitecture " +\n process.arch +\n "\\n\\n" +\n' + ' this.localize("loksiBasedOn") +\n "\\n" +\n' + ' this.localize("loksiAboutOrigin") +\n "\\n\\n" +\n' + ' this.localize("loksiSourceCode");') + # « Version AAAA.M.n (build) » (règle du 06/10/2026). Le numéro de build est posé dans + # le package.json de l'asar par electron-builder.cjs (extraMetadata.loksiBuild). + replace_once(about, 'import { BrowserWindow, clipboard, dialog, MenuItemConstructorOptions } from "electron";\n', + 'import * as fs from "fs";\nimport * as path from "path";\n\n' + 'import { app, BrowserWindow, clipboard, dialog, MenuItemConstructorOptions } from "electron";\n') + replace_once(about, "export class AboutMenu implements IMenubarMenu {", + "// Loksi : numéro de build du paquet, lu dans le package.json de l'asar.\n" + "function loksiBuild(): string {\n try {\n" + ' const file = path.join(app.getAppPath(), "package.json");\n' + ' return String(JSON.parse(fs.readFileSync(file, "utf8")).loksiBuild);\n' + ' } catch {\n return "?";\n }\n}\n\n' + "export class AboutMenu implements IMenubarMenu {") + replace_once(about, 'this.localize("version", this._version) +', + 'this.localize("version", this._version + " (" + loksiBuild() + ")") +') + # En-tête Bitwarden-Client-Version et version cliente du SDK : la version Bitwarden de + # la base de code, pas celle de Loksi. Le serveur décide de fonctionnalités selon elle, + # il doit voir ce que le code sait faire. + replace_once(APP / "src/platform/services/electron-platform-utils.service.ts", + " async getApplicationVersionNumber(): Promise {\n" + " return (await this.getApplicationVersion()).split(/[+|-]/)[0].trim();\n }\n", + " async getApplicationVersionNumber(): Promise {\n" + " // Loksi : version Bitwarden de la base, envoyée au serveur et au SDK.\n" + " return " + json.dumps(BITWARDEN_VERSION) + ";\n }\n") + # Menu Aide : l'aide et la confidentialité de Loksi. Les réseaux, magasins et + # rapports de bogue de Bitwarden sont retirés (brand/README.md). + help_menu = APP / "src/main/menu/menu.help.ts" + replace_once(help_menu, " this.helpAndFeedback,\n this.fileBugReport,\n this.legal,\n" + " this.separator,\n this.followUs,\n this.separator,\n" + " this.goToWebVault,\n this.separator,\n this.getMobileApp,\n" + " this.getBrowserExtension,\n this.separator,\n", + " this.helpAndFeedback,\n this.legal,\n this.contactUs,\n this.separator,\n" + " this.goToWebVault,\n this.separator,\n") + # « Nous contacter », comme les autres clients (demande de Romain du 30/09/2026) : + # confirmation, puis la messagerie sur loksi@aleop.eu. + replace_once(help_menu, 'import { MenuItemConstructorOptions, app } from "electron";', + 'import { MenuItemConstructorOptions, app, dialog, shell } from "electron";') + replace_once(help_menu, " private get separator(): MenuItemConstructorOptions {", + " private get contactUs(): MenuItemConstructorOptions {\n return {\n" + ' id: "loksiContactUs",\n label: this.localize("loksiContactUs"),\n' + " click: async () => {\n const result = await dialog.showMessageBox({\n" + ' type: "question",\n message: this.localize("loksiContactTitle"),\n' + ' detail: this.localize("loksiContactBody"),\n' + ' buttons: [this.localize("ok"), this.localize("cancel")],\n' + " defaultId: 0,\n cancelId: 1,\n noLink: true,\n });\n" + " if (result.response === 0) {\n" + ' void shell.openExternal("mailto:loksi@aleop.eu");\n }\n },\n' + " };\n }\n\n private get separator(): MenuItemConstructorOptions {") + replace_once(help_menu, 'this.shell.openExternal("https://bitwarden.com/help", UrlType.WebUrl)', + 'this.shell.openExternal(' + json.dumps(AIDE) + ', UrlType.WebUrl)') + replace_once(help_menu, ' visible: isMacAppStore(),\n submenu: this.legalSubmenu,', + ' visible: true || isMacAppStore(),\n submenu: this.legalSubmenu,') + text = help_menu.read_text() + start = text.index(' {\n id: "termsOfService",') + end = text.index(' {\n id: "privacyPolicy",') + write(help_menu, text[:start] + text[end:]) + replace_once(help_menu, 'this.shell.openExternal("https://bitwarden.com/privacy/", UrlType.WebUrl)', + 'this.shell.openExternal(' + json.dumps(CONFIDENTIALITE) + ', UrlType.WebUrl)') + # Variable de dossier de données (lue aussi par la passkey Windows), partition de + # session Electron, nom du rapport de diagnostic, liens de l'écran d'inscription. + replace_count(main, "BITWARDEN_APPDATA_DIR", "LOKSI_APPDATA_DIR", 2) + replace_once(APP / "src/main/window.main.ts", '"persist:bitwarden"', '"persist:loksi"') + # Barre de menus native de Windows (Fichier, Édition...) masquée, Alt l'affiche : + # demande de Romain du 09/10/2026, vue blanche et hors charte dans l'appli Store. La + # sortie du mode fenêtre réduite (popup-modal-styles) la remettait visible. + replace_once(APP / "src/main/window.main.ts", ' titleBarStyle: isMac() ? "hiddenInset" : undefined,\n', + ' titleBarStyle: isMac() ? "hiddenInset" : undefined,\n autoHideMenuBar: true,\n') + replace_once(APP / "src/platform/popup-modal-styles.ts", + " window.setWindowButtonVisibility?.(true);\n window.setMenuBarVisibility?.(true);\n", + " window.setWindowButtonVisibility?.(true);\n window.setMenuBarVisibility?.(false);\n") + replace_count(SOURCE / "libs/logging/src/flight-recorder-export.ts", "Bitwarden-diagnostic-report-", + "Loksi-diagnostic-report-", 2) + inscription = SOURCE / "libs/auth/src/angular/registration/registration-start/registration-start.component.html" + replace_once(inscription, 'href="https://bitwarden.com/terms/"', 'href="' + CONDITIONS + '"') + replace_once(inscription, 'href="https://bitwarden.com/privacy/"', 'href="' + CONFIDENTIALITE + '"') + replace_once(inscription, 'href="https://bitwarden.com/email-preferences"', 'href="' + CONFIDENTIALITE + '"') + # Liens d'aide bitwarden.com/help des écrans (réglages biométrie, création de + # compte, import, etc.) : tous vers l'aide Loksi. 34 dans les sources au 09/10/2026. + motif = re.compile(r"https?://(www\.)?bitwarden\.com/help(/[^\"'`\s)]*)?") + liens = 0 + for dossier in (APP / "src", SOURCE / "libs"): + for chemin in sorted(dossier.rglob("*")): + if chemin.suffix not in (".ts", ".html") or ".spec." in chemin.name or ".stories." in chemin.name: + continue + texte = chemin.read_text() + nouveau, n = motif.subn(AIDE, texte) + if n: + write(chemin, nouveau) + liens += n + if liens < 20: + raise RuntimeError(f"Liens d'aide Bitwarden : {liens} trouvés, l'amont a changé") + native_messaging() + + +def native_messaging(): + path = APP / "src/main/native-messaging.main.ts" + # Hôte de messagerie native propre à Loksi, clés de registre et fichiers compris. + replace_count(path, "com.8bit.bitwarden", HOST, 20) + replace_count(path, '"Bitwarden desktop <-> browser bridge"', '"Loksi desktop <-> browser bridge"', 2) + replace_once(path, '"Bitwarden desktop <-> DuckDuckGo bridge"', '"Loksi desktop <-> DuckDuckGo bridge"') + replace_once(path, 'allowed_extensions: ["{446900e4-71c2-419f-a6a7-df9c091e268b}"],', + "allowed_extensions: " + json.dumps(CONFIG["native_messaging"]["firefox_extension_ids"]) + ",") + text = path.read_text() + start = text.index(" const ids: Set = new Set([\n") + end = text.index(" ]);\n", start) + len(" ]);\n") + chrome = ["chrome-extension://" + i + "/" for i in CONFIG["native_messaging"]["chrome_extension_ids"]] + text = text[:start] + " const ids: Set = new Set(" + json.dumps(chrome) + ");\n" + text[end:] + write(path, text) + # L'extension Loksi est chargée non empaquetée : son identifiant Chromium dépend du + # poste. Le balayage des profils que l'amont réserve au développement tourne donc + # toujours, et les extensions Bitwarden officielles sont écartées du résultat. + replace_once(path, " if (!isDev()) {\n return Array.from(ids);\n }\n", "") + replace_once(path, " return Array.from(ids);\n }\n\n private binaryPath() {", + " const bitwarden = " + json.dumps(list(CHROME_BITWARDEN)) + ";\n" + " return Array.from(ids).filter((id) => !bitwarden.some((b) => id.includes(b)));\n" + " }\n\n private binaryPath() {") + + +# ---------------------------------------------------------------- serveur et connexion + +def server_entry(): + """Pas de serveur par défaut ni de choix de région : le client saisit son coffre.""" + env = SOURCE / "libs/common/src/platform/services/default-environment.service.ts" + # Sans rien de saisi, un marqueur en .invalid (RFC 6761) qui ne se résout jamais, + # comme les applis mobiles. Les régions Bitwarden restent dans le code, non proposées. + replace_count(env, " if (region == Region.SelfHosted && isEmpty(urls)) {\n region = DEFAULT_REGION;\n }\n", + " if (region == Region.SelfHosted && isEmpty(urls)) {\n" + " urls = { base: " + json.dumps(UNSET) + " };\n }\n", 2) + selector = SOURCE / "libs/angular/src/auth/environment-selector/environment-selector.component" + html = Path(str(selector) + ".html") + if html.read_text().count("toggle(ServerEnvironmentType.SelfHosted)") != 1: + raise RuntimeError("Sélecteur de région amont modifié") + write(html, '
\n
\n' + ' {{ "loksiConnectingTo" | i18n }} :\n' + ' \n
\n
\n') + ts = Path(str(selector) + ".ts") + replace_once(ts, " private destroy$ = new Subject();\n", + " // Loksi : l'adresse du coffre saisi, rien tant que c'est le marqueur.\n" + " protected loksiHost$: Observable = this.environmentService.globalEnvironment$.pipe(\n" + " map((env) => (env.getUrls().base === " + json.dumps(UNSET) + " ? null : env.getHostname())),\n" + " );\n\n private destroy$ = new Subject();\n") + dialog = SOURCE / "libs/angular/src/auth/self-hosted-env-config-dialog/self-hosted-env-config-dialog.component.ts" + replace_once(dialog, ' baseUrl: urls.base || "",', + ' baseUrl: urls.base === ' + json.dumps(UNSET) + ' ? "" : urls.base || "",') + replace_once(Path(str(SOURCE / "libs/angular/src/auth/self-hosted-env-config-dialog/" + "self-hosted-env-config-dialog.component.html")), + " Self-hosted environment", + '{{ "loksiVaultTitle" | i18n }}') + # Pas de création de compte : un compte Loksi est créé par l'administrateur. + secondary = SOURCE / "libs/auth/src/angular/login/login-secondary-content.component.ts" + text = secondary.read_text() + start = text.index(" template: `\n") + end = text.index(" `,\n", start) + len(" `,\n") + write(secondary, text[:start] + ' template: `\n
\n' + ' {{ "loksiAccountByAdmin" | i18n }}\n
\n `,\n' + text[end:]) + + +def locales(): + for path in sorted((APP / "src/locales").glob("*/messages.json")): + lang = path.parent.name + data = json.loads(path.read_text()) + for key, value in data.items(): + message = value.get("message", "") + if key in BITWARDEN_GARDE or "bitwarden" not in message.lower(): + continue + # « le coffre web de bitwarden.com » devient « le coffre web de Loksi ». + value["message"] = (message.replace("bitwarden.company.com", "loksi.company.com") + .replace("bitwarden.com", "Loksi").replace("Bitwarden", "Loksi")) + # Langues non proposées : quelques « bitwarden » en minuscules, et + # bitwarden.net (nb). Tout reste en Loksi, sans égard à la casse. + value["message"] = re.sub(r"bitwarden(\.(com|net|eu))?", "Loksi", value["message"], + flags=re.IGNORECASE) + for key, text in TEXTES["fr" if lang == "fr" else "en"].items(): + if lang in ("en", "fr") or key == "selfHostedBaseUrlHint": + data[key] = {"message": text} + write_json(path, data) + + +# ---------------------------------------------------------------- charte + +def prefixed(drawing, prefix): + """Identifiants internes d'un SVG préfixés, pour qu'un dessin n'aille pas chercher + ses dégradés ou masques dans un autre de la même page.""" + if "`" in drawing or "${" in drawing: + raise RuntimeError("Dessin Loksi inattendu") + drawing = re.sub(r'id="([^"]+)"', lambda m: 'id="' + prefix + m.group(1) + '"', drawing) + return re.sub(r"url\(#([^)]+)\)", lambda m: "url(#" + prefix + m.group(1) + ")", drawing) + + +def charte(): + svgs = SOURCE / "libs/assets/src/svg/svgs" + wordmark = extension.theme_pair(REPO / "brand/sources/loksi-logo-clair.svg", + REPO / "brand/sources/loksi-logo-sombre.svg", "logo") + for name, export in (("bitwarden-logo.icon.ts", "BitwardenLogo"), + ("bitwarden-logo-beta.icon.ts", "BitwardenLogoBeta")): + write(svgs / name, 'import { svg } from "../svg";\nexport const ' + export + ' = svg`' + wordmark + '`;\n') + # Logo de la barre latérale, toujours sur le navy de la navigation : le logo sombre. + nav = (REPO / "brand/sources/loksi-logo-sombre.svg").read_text().strip() + nav = re.sub(r'id="([^"]+)"', lambda m: 'id="loksi-nav-' + m.group(1) + '"', nav) + nav = re.sub(r"url\(#([^)]+)\)", lambda m: "url(#loksi-nav-" + m.group(1) + ")", nav) + nav = nav.replace("") + 1:mono.rindex("")] + if corps.count('fill="#0B1120"') != 1: + raise RuntimeError("loksi-icon-mono.svg inattendu") + corps = corps.replace('fill="#0B1120"', 'style="fill: rgb(var(--color-primary-600))"') + gauche = prefixed('' + '' + corps + "", "loksi-fond-") + write(svgs / "background-left-illustration.ts", + 'import { svg } from "../svg";\n\nexport const BackgroundLeftIllustration = svg`' + gauche + '`;\n') + write(svgs / "background-right-illustration.ts", + 'import { svg } from "../svg";\n\nexport const BackgroundRightIllustration = svg`' + + extension.illustration("coffre").replace('data-loksi="coffre"', 'data-loksi="fond-coffre"') + '`;\n') + (CACHE / "illustrations-amont.json").write_text(json.dumps(signatures, indent=2) + "\n") + with (APP / "src/scss/styles.scss").open("a") as scss: + scss.write("\n.loksi-illustration-sombre,\n.theme_dark .loksi-illustration-clair {\n" + " display: none;\n}\n\n.theme_dark .loksi-illustration-sombre {\n display: block;\n}\n") + touched.add(rel(APP / "src/scss/styles.scss")) + # Palette de l'extension, mêmes blocs de tw-theme.css. + theme = SOURCE / "libs/components/src/tw-theme.css" + css = theme.read_text() + for block, values in extension.PALETTE.items(): + start = css.index("\n" + block + "\n") + end = css.index("\n}\n", start) + body = css[start:end] + for name, value in values.items(): + body, count = re.subn(r"(\n " + re.escape(name) + r": )[^;]+;", lambda m: m.group(1) + value + ";", body) + if count != 1: + raise RuntimeError("Couleur amont introuvable : " + block + " " + name) + css = css[:start] + body + css[end:] + write(theme, css) + variables = APP / "src/scss/variables.scss" + replace_once(variables, "$brand-primary: #175ddc;", "$brand-primary: #003087;") + replace_once(variables, " primaryColor: #6f9df1,\n primaryAccentColor: #6f9df1,", + " primaryColor: #009cde,\n primaryAccentColor: #009cde,") + replace_once(variables, '$font-family-sans-serif: Inter, ', '$font-family-sans-serif: Loksi, Inter, ') + # Police : Raleway renommée « Loksi », mêmes fichiers que l'extension. + extension_fonts.CACHE = CACHE / "fonts" + extension_fonts.VENV = CACHE / "fonts-venv" + extension_fonts.PYTHON = extension_fonts.VENV / ("Scripts/python.exe" if WINDOWS_HOST else "bin/python") + extension_fonts.OUT = extension_fonts.CACHE / "out" + extension_fonts.WOFF2 = extension_fonts.CACHE / "woff2" + extension_fonts.main() + webfonts = SOURCE / "libs/components/src/webfonts" + faces = [] + for filename, weight, style in (("loksi-400.woff2", 400, "normal"), ("loksi-600.woff2", 600, "normal"), + ("loksi-700.woff2", 700, "normal"), ("loksi-400-italic.woff2", 400, "italic")): + shutil.copy2(extension_fonts.WOFF2 / filename, webfonts / filename) + touched.add(rel(webfonts / filename)) + faces.append('@font-face {\n font-family: Loksi;\n src: url("~@bitwarden/components/src/webfonts/' + + filename + '") format("woff2");\n font-display: swap;\n font-weight: ' + + str(weight) + ';\n font-style: ' + style + ';\n}\n') + fonts_css = SOURCE / "libs/components/src/theme.css" + replace_once(fonts_css, " --font-sans:\n Inter, ", " --font-sans:\n Loksi, Inter, ") + replace_once(fonts_css, "/**\n * CSS variables\n */", "".join(faces) + "\n/**\n * CSS variables\n */") + + +def ico(pngs): + """Fichier ICO à entrées PNG, lu par Windows depuis Vista.""" + entries, blobs = [], [] + offset = 6 + 16 * len(pngs) + for size, data in pngs: + entries.append(struct.pack(" process.stdout.write(JSON.stringify({w: info.width, h: info.height," + " c: info.channels, d: data.toString('base64')})));\n") + out = json.loads(subprocess.run(["node", "-e", code, str(png)], cwd=node, check=True, + capture_output=True, text=True).stdout) + w, h, c, raw = out["w"], out["h"], out["c"], __import__("base64").b64decode(out["d"]) + if c != 3: + raise RuntimeError("bandeau : 3 canaux attendus") + stride = (w * 3 + 3) & ~3 + rows = [] + for y in range(h - 1, -1, -1): + row = bytearray() + for x in range(w): + r, g, b = raw[(y * w + x) * 3:(y * w + x) * 3 + 3] + row += bytes((b, g, r)) + rows.append(bytes(row) + b"\0" * (stride - w * 3)) + pixels = b"".join(rows) + header = struct.pack("<2sIHHI", b"BM", 54 + len(pixels), 0, 0, 54) + info = struct.pack(" 1: + raise RuntimeError("Plusieurs Developer ID Application de l'équipe Aleop : en garder un seul") + return found[0] if found else None + + +def notary_profile(): + """Nom du profil notarytool s'il existe dans le trousseau, sinon None. Sa sortie + (liste des envois) n'est jamais affichée.""" + name = CONFIG["apple_notary_profile"]["name"] + probe = subprocess.run(["xcrun", "notarytool", "history", "--keychain-profile", name], + capture_output=True, text=True) + return name if probe.returncode == 0 else None + + +def mac_signing(env): + """Developer ID et notarisation quand ils existent, signature ad hoc sinon.""" + identity = developer_id() + if identity is None: + print("Loksi : pas de Developer ID Application de l'équipe " + + CONFIG["apple_team"]["id"] + ", signature ad hoc, paquet de test seulement.") + return + env["CSC_NAME"] = identity + profile = notary_profile() + if profile: + env["APPLE_KEYCHAIN_PROFILE"] = profile + print("Loksi : signature Developer ID de l'équipe " + CONFIG["apple_team"]["id"] + + " et notarisation par le profil " + profile) + elif os.environ.get("LOKSI_SANS_NOTARISATION") == "1": + print("Loksi : signature Developer ID SANS notarisation (LOKSI_SANS_NOTARISATION=1).") + else: + raise RuntimeError("Developer ID présent mais profil notarytool « " + + CONFIG["apple_notary_profile"]["name"] + " » absent du trousseau. " + "Le créer (README, section Signature) ou poser LOKSI_SANS_NOTARISATION=1") + + +def check_version(version, build, previous): + """Règle du 06/10/2026 : AAAA.M.n sans zéro devant, build entier qui monte. Refus.""" + refus = [] + if not isinstance(version, str) or not VERSION_RE.fullmatch(version): + refus.append(f"version {version!r} : AAAA.M.n attendu, sans zéro devant (2026.10.0)") + if not isinstance(build, int) or isinstance(build, bool) or build <= previous: + refus.append(f"build {build!r} : doit dépasser {previous}, jamais réutilisé") + return refus + + +def check_client_version(code): + """Version envoyée au serveur (Bitwarden-Client-Version) et au SDK : la version + Bitwarden de la base, en dur dans getApplicationVersionNumber. Vaultwarden décide de + fonctionnalités selon elle. Refus si une définition de la méthode ne la rend pas.""" + refus, found = [], 0 + for match in re.finditer(r"getApplicationVersionNumber\(\)(?:: Promise)?\s*\{", code): + found += 1 + body = code[match.end():match.end() + 200] + literal = re.search(r'return\s*"([^"]*)"', body) + if "split(" in body or not literal or literal.group(1) != BITWARDEN_VERSION: + refus.append("getApplicationVersionNumber ne rend pas " + BITWARDEN_VERSION + " : " + + " ".join(body.split())[:90]) + if not found: + refus.append("getApplicationVersionNumber introuvable") + return refus + + +def next_build(): + """Monte le compteur de build d'upstream.json et l'écrit. Le numéro part du plus + grand entre ce fichier et origin/main, pour qu'une branche ne reprenne pas un numéro + déjà livré depuis une autre. Un build qui échoue garde son numéro consommé.""" + current = CONFIG["app_version"]["build"] + main = subprocess.run(["git", "show", "origin/main:desktop/upstream.json"], cwd=REPO, + capture_output=True, text=True) + on_main = json.loads(main.stdout)["app_version"].get("build", 0) if main.returncode == 0 else 0 + previous = max(current, on_main) + number = previous + 1 + refus = check_version(VERSION, number, previous) + if refus: + raise RuntimeError("Numérotation : " + " ; ".join(refus)) + path = ROOT / "upstream.json" + text, count = re.subn(r'("build": )\d+', lambda m: m.group(1) + str(number), path.read_text()) + if count != 1: + raise RuntimeError("upstream.json : un seul champ build attendu") + path.write_text(text) + CONFIG["app_version"]["build"] = number + print(f"Loksi {VERSION}, build {previous} vers {number} (upstream.json, à commiter)") + return number + + +def dist_dir(platform, arch="arm64"): + """dist/mac pour arm64 (comme avant), dist/mac-x64 et dist/mac-universal sinon.""" + return DIST / (platform if platform == "win" or arch == "arm64" else platform + "-" + arch) + + +def build(platform, arch="arm64"): + if platform not in ("mac", "win") or arch not in MAC_ARCHS: + raise ValueError("Plateforme : mac [arm64|x64|universal] ou win") + changes() + number = next_build() + native(platform, arch) + webpack() + env = dict(tool_env(), CSC_IDENTITY_AUTO_DISCOVERY="false", LOKSI_MAC_ARCH=arch, + LOKSI_BUILD=str(number), LOKSI_VERSION=VERSION) + if platform == "win": + if not WINDOWS_HOST: + env["ELECTRON_BUILDER_NSIS_DIR"] = str(nsis_dir()) + else: + mac_signing(env) + target = ["--mac", "--" + arch] if platform == "mac" else ["--win", "--x64"] + out = APP / "dist" + if out.exists(): + shutil.rmtree(out) + run(["node", SOURCE / "node_modules/electron-builder/cli.js", "--config", "electron-builder.loksi.cjs", + *target, "-p", "never"], cwd=APP, env=env) + target_dir = dist_dir(platform, arch) + if target_dir.exists(): + shutil.rmtree(target_dir) + target_dir.mkdir(parents=True) + for item in out.iterdir(): + if item.is_dir() and item.name.endswith("-unpacked") or item.name.startswith("mac"): + shutil.copytree(item, target_dir / item.name, symlinks=True) + elif item.suffix in (".zip", ".exe", ".appx"): + shutil.copy2(item, target_dir / item.name) + verify(platform, arch) + run([sys.executable, ROOT / "dependencies.py", platform] + ([arch] if platform == "mac" else [])) + + +def asar_files(asar): + work = Path(tempfile.mkdtemp(prefix="loksi-asar-")) + run(["node", SOURCE / "node_modules/@electron/asar/bin/asar.js", "extract", asar, work]) + return work + + +def check_source(messages, where): + """Ligne « Code source » d'À propos : l'adresse de la source GPL publique.""" + message = messages.get("loksiSourceCode", {}).get("message", "") + if not message.endswith(SOURCE_GPL): + raise AssertionError(where + " : Code source absent d'À propos") + + +def check_texts(messages, where): + restes = [k for k, v in messages.items() + if "bitwarden" in v.get("message", "").lower() and k not in BITWARDEN_GARDE] + if restes: + raise AssertionError(where + " : Bitwarden dans " + ", ".join(restes[:8])) + + +def check_renderer(bundle): + signatures = json.loads((CACHE / "illustrations-amont.json").read_text()) + for export, signature in signatures.items(): + if signature in bundle: + raise AssertionError("Illustration Bitwarden : " + export) + # Le bureau n'importe qu'une partie des illustrations, le reste est élagué : aucune + # signature amont ne doit rester, et ces trois dessins-là doivent être présents. + for name in ("logo", "nav", "verrou", "icone", "fond", "fond-coffre"): + if 'data-loksi="' + name + '"' not in bundle: + raise AssertionError("Dessin Loksi absent : " + name) + return sorted({name for _, name in extension.ILLUSTRATION_TABLE.values() + if 'data-loksi="' + name + '"' in bundle}) + + +def macho_archs(path): + """Architectures d'un fichier Mach-O selon lipo, None si ce n'en est pas un.""" + with open(path, "rb") as handle: + magic = handle.read(4) + if magic not in (b"\xcf\xfa\xed\xfe", b"\xce\xfa\xed\xfe", b"\xca\xfe\xba\xbe", b"\xca\xfe\xba\xbf"): + return None + out = subprocess.run(["lipo", "-archs", str(path)], capture_output=True, text=True) + if out.returncode != 0: + return None # 0xcafebabe d'une classe Java, par exemple + return set(out.stdout.split()) + + +def check_archs(app, arch): + """Chaque binaire Mach-O du paquet porte toutes les architectures demandées. + + Exception, celle de l'amont (singleArchFiles, x64ArchFiles) : les modules napi sont un + fichier par architecture, desktop_napi.darwin-.node. Chacun doit porter + l'architecture de son nom, et il en faut un pour chaque architecture demandée. + Retourne le nombre de binaires vus et la liste des refus. + """ + wanted = MAC_ARCHS[arch]["lipo"] + refus, seen, napi = [], 0, set() + for path in sorted(Path(app).rglob("*")): + if path.is_symlink() or not path.is_file(): + continue + archs = macho_archs(path) + if archs is None: + continue + seen += 1 + name = str(path.relative_to(app)) + match = re.fullmatch(r"desktop_napi\.darwin-(arm64|x64)\.node", path.name) + if match: + if archs != {NAPI_LIPO[match.group(1)]}: + refus.append(name + " : " + " ".join(sorted(archs)) + " au lieu de " + NAPI_LIPO[match.group(1)]) + napi |= archs + elif not wanted <= archs: + refus.append(name + " : " + " ".join(sorted(archs)) + ", manque " + " ".join(sorted(wanted - archs))) + for missing in sorted(wanted - napi): + refus.append("module napi absent pour " + missing) + return seen, refus + + +def check_fuses(framework): + """Fusibles Electron posés dans chaque tranche de Electron Framework. Liste des refus.""" + refus, start, found = [], 0, 0 + while (index := framework.find(FUSE_SENTINEL, start)) >= 0: + found += 1 + wire = framework[index + len(FUSE_SENTINEL) + 2:index + len(FUSE_SENTINEL) + 2 + framework[index + len(FUSE_SENTINEL) + 1]] + for position, expected in FUSES.items(): + if wire[position:position + 1].decode() != expected: + refus.append(f"tranche {found} : fusible {position} à {wire[position:position + 1].decode()!r}, " + f"attendu {expected!r} (fil {wire.decode()})") + start = index + 1 + if not found: + refus.append("fil de fusibles introuvable") + return found, refus + + +def file_version(exe): + """Valeur de la chaîne FileVersion de la ressource de version, ou None. + + Chercher « AAAA.M.n.build » n'importe où dans l'exe ne suffit pas : sous Windows + natif, ProductVersion la portait et FileVersion valait « 3 », le contrôle passait + (vu le 09/10/2026). Structure String de VS_VERSIONINFO : wLength, wValueLength + (en caractères, zéro final compris), wType, la clé en UTF-16 terminée par zéro, + alignement sur 4 octets depuis le début de la structure, puis la valeur. + """ + key = "FileVersion\0".encode("utf-16-le") + at = exe.find(key) + while at >= 6: + start = at - 6 + length, chars, kind = struct.unpack_from("= 6 + len(key): + offset = start + ((6 + len(key) + 3) & ~3) + return exe[offset:offset + 2 * chars].decode("utf-16-le", "replace").rstrip("\0") + at = exe.find(key, at + 2) + return None + + +def verify(platform, arch="arm64"): + target = dist_dir(platform, arch) + if platform == "mac": + app = next(target.glob("mac*/Loksi.app")) + seen, refus = check_archs(app, arch) + assert not refus, "architectures : " + " ; ".join(refus[:8]) + print(f"Architectures : {seen} binaires Mach-O, tous {'+'.join(sorted(MAC_ARCHS[arch]['lipo']))}") + slices, refus = check_fuses((app / "Contents/Frameworks/Electron Framework.framework/Versions/A/" + "Electron Framework").read_bytes()) + assert not refus, "fusibles Electron : " + " ; ".join(refus) + print(f"Fusibles Electron posés dans {slices} tranche(s)") + info = plistlib.loads((app / "Contents/Info.plist").read_bytes()) + assert info["CFBundleIdentifier"] == APP_ID, info["CFBundleIdentifier"] + assert info["CFBundleName"] == "Loksi" and info["CFBundleExecutable"] == "Loksi" + # Le build se lit dans le paquet : un autre build a pu monter le compteur depuis. + assert info["CFBundleShortVersionString"] == VERSION, "version : " + info["CFBundleShortVersionString"] + assert info["CFBundleVersion"].isdigit(), "CFBundleVersion : " + info["CFBundleVersion"] + build_number = int(info["CFBundleVersion"]) + assert info["NSHumanReadableCopyright"] == MENTION["fr"].replace("\n", " "), "mention du panneau À propos" + signature = subprocess.run(["codesign", "-d", "--entitlements", "-", "--xml", str(app)], + capture_output=True).stdout.decode(errors="replace") + assert TEAM_BITWARDEN not in signature and "application-identifier" not in signature, "entitlements" + subprocess.run(["codesign", "--verify", "--deep", "--strict", str(app)], check=True) + for lipo in sorted(MAC_ARCHS[arch]["lipo"]): + # Signature de chaque tranche, celle que vérifiera un Mac de cette architecture. + subprocess.run(["codesign", "--verify", "--deep", "--strict", "--arch", lipo, str(app)], check=True) + details = subprocess.run(["codesign", "-dv", "--verbose=2", str(app)], + capture_output=True, text=True).stderr + team = re.search(r"^TeamIdentifier=(.*)$", details, re.M).group(1) + if team == "not set": + print("Signature ad hoc : paquet de test, refusé par Gatekeeper hors de ce Mac.") + else: + assert team == CONFIG["apple_team"]["id"], "équipe de signature inattendue : " + team + assert "Developer ID Application" in details, "pas un certificat Developer ID" + assert "runtime" in details, "hardened runtime absent" + proxy_team = subprocess.run(["codesign", "-dv", str(app / "Contents/MacOS/desktop_proxy")], + capture_output=True, text=True).stderr + assert "TeamIdentifier=" + team in proxy_team, "desktop_proxy pas signé par l'équipe" + gatekeeper = subprocess.run(["spctl", "-a", "-t", "exec", "-vv", str(app)], + capture_output=True, text=True) + if "source=Notarized Developer ID" in gatekeeper.stderr: + subprocess.run(["xcrun", "stapler", "validate", str(app)], check=True) + print("Signature Developer ID " + team + ", notarisée et agrafée, acceptée par Gatekeeper.") + else: + assert os.environ.get("LOKSI_SANS_NOTARISATION") == "1", \ + "Gatekeeper refuse le paquet : " + gatekeeper.stderr.strip()[:200] + print("Signature Developer ID " + team + " sans notarisation : Gatekeeper refusera.") + # codesign --verify accepte une appli que dyld refuse ensuite de lancer (vu le + # 30/09/2026 avec le hardened runtime) : on la lance vraiment, 10 secondes, dans + # l'architecture de ce Mac. La tranche x86_64 n'est lancée nulle part ici : pas de + # Rosetta sur ce Mac, décision de Romain du 04/10/2026. + host = platform_machine() + if host not in MAC_ARCHS[arch]["lipo"]: + print(f"Lancement : non fait, paquet {arch} et ce Mac est {host} sans Rosetta.") + else: + # Dossier de données à part (LOKSI_APPDATA_DIR, lu par main.ts) : le + # Loksi installé et ouvert sur ce Mac fait sinon quitter cette seconde instance + # (verrou d'instance unique, vu le 03/10 puis le 06/10), et le test lisait ses + # vraies données. + appdata = tempfile.mkdtemp(prefix="loksi-verify-") + process = subprocess.Popen(["arch", "-" + host, str(app / "Contents/MacOS/Loksi")], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + env=dict(os.environ, LOKSI_APPDATA_DIR=appdata)) + try: + process.wait(10) + raise AssertionError("Loksi s'arrête au lancement : " + + process.stdout.read().decode(errors="replace")[:400]) + except subprocess.TimeoutExpired: + process.terminate() + try: + process.wait(10) + except subprocess.TimeoutExpired: + # Paquet universel du 04/10 : toujours là 10 s après SIGTERM. + process.kill() + process.wait(10) + print(f"Lancement : Loksi tient 10 s en {host}, données dans {appdata}.") + finally: + shutil.rmtree(appdata, ignore_errors=True) + resources = app / "Contents/Resources" + proxy = (app / "Contents/MacOS/desktop_proxy").read_bytes() + napi = b"".join(p.read_bytes() for p in (resources / "app.asar.unpacked").rglob("desktop_napi.darwin-*.node")) + assert napi, "module napi absent" + icon = (resources / "icon.icns").read_bytes() + else: + unpacked = target / "win-unpacked" + resources = unpacked / "resources" + exe = (unpacked / "Loksi.exe").read_bytes() + assert MENTION["fr"].replace("\n", " ").encode("utf-16-le") in exe, "LegalCopyright de Loksi.exe" + for text in ("Loksi", "Aleop"): + assert ("CompanyName\0" if text == "Aleop" else "ProductName\0").encode("utf-16-le") in exe + assert text.encode("utf-16-le") in exe, "métadonnées de Loksi.exe : " + text + assert "GitHub, Inc.".encode("utf-16-le") not in exe, "métadonnées Electron dans Loksi.exe" + build_number = None # lu dans l'asar plus bas, puis cherché dans Loksi.exe + assert list(target.glob("Loksi-Setup-*-x64.exe")), "installateur NSIS absent" + assert f'RMDir /r "$LOCALAPPDATA\\{UPDATER_DIR}"' in (APP / "installer.nsh").read_text(), \ + "désinstallation : cache " + UPDATER_DIR + " non retiré" + proxy = (unpacked / "desktop_proxy.exe").read_bytes() + napi = next((resources / "app.asar.unpacked").rglob("desktop_napi.win32-x64*.node")).read_bytes() + assert b"LoksiBiometricsV2" in napi.replace(b"\0", b""), "clé Windows Hello" + config = json.loads((resources / "plugin_authenticator_config.json").read_text()) + assert config == {"clsid": CONFIG["windows_plugin_authenticator_clsid"], "name": "Loksi"} + # Inventaire du 09/10/2026 : exécutables installés sous leur nom Loksi, plus + # aucun bitwarden_*.exe ; AAGUID, dossier de données et tuyau de l'importeur. + restes = sorted(p.name for p in unpacked.rglob("*") if p.is_file() and p.name.lower().startswith("bitwarden")) + assert not restes, "fichiers Bitwarden dans le paquet : " + ", ".join(restes[:6]) + for nom in WIN_EXE_NOMS.values(): + assert (unpacked / nom).is_file(), nom + " absent" + plugin = (unpacked / WIN_EXE_NOMS["bitwarden_plugin_authenticator.exe"]).read_bytes() + # L'AAGUID est dans le napi, qui inscrit la passkey (relevé sur le build du 03/10). + assert AAGUID.encode() in napi and AAGUID_BITWARDEN.encode() not in napi, "AAGUID de la passkey" + assert b"LOKSI_APPDATA_DIR" in plugin and b"BITWARDEN_APPDATA_DIR" not in plugin, "dossier de la passkey" + helper = (unpacked / WIN_EXE_NOMS["bitwarden_chromium_import_helper.exe"]).read_bytes() + for binary, name in ((helper, "aide à l'import"), (napi, "napi")): + assert b"bitwarden-to-bitwarden" not in binary, name + " : tuyau de l'importeur Chromium" + assert b"loksi-chromium-importer-helper" in binary, name + " : tuyau Loksi absent" + icon = None + for binary, name in ((proxy, "proxy"), (napi, "napi")): + assert b"com.bitwarden.desktop" not in binary, name + " : chemin IPC Bitwarden" + assert b"BITWARDEN_SSH_AUTH_SOCK" not in napi, "napi : variable de l'agent SSH" + assert b"com.bitwarden.chromiumImporter" not in napi, "napi : préférences de l'importeur" + if platform == "mac": + assert APP_ID.encode() in proxy, "proxy : chemin IPC Loksi absent" + with tarfile.open(ARCHIVE) as tar: + upstream = tar.extractfile(tar.getmember(SOURCE.name + "/apps/desktop/resources/icon.icns")).read() + assert icon != upstream, "icône Bitwarden" + for name in ("OFL-police-Loksi.txt", "LOKSI-NOTICE.txt"): + assert (resources / name).is_file(), name + " absent du paquet" + work = asar_files(resources / "app.asar") + try: + package = json.loads((work / "package.json").read_text()) + assert package["productName"] == "Loksi" and package["name"] == CONFIG["executable_name"] + if build_number is None: + build_number = package.get("loksiBuild") + assert file_version(exe) == VERSION + "." + str(build_number), "FileVersion de Loksi.exe" + refus = check_version(package["version"], package.get("loksiBuild"), 0) + assert not refus, "numérotation : " + " ; ".join(refus) + assert package["version"] == VERSION and package["loksiBuild"] == build_number, "version de l'asar" + assert build_number <= CONFIG["app_version"]["build"], "build au-delà du compteur d'upstream.json" + print(f"Numérotation : version {VERSION}, build {build_number}") + main = (work / "main.js").read_text() + assert HOST in main and "com.8bit.bitwarden" not in main, "hôte de messagerie native" + for ident in CONFIG["native_messaging"]["chrome_extension_ids"]: + assert "chrome-extension://" + ident + "/" in main, "extension Chromium admise : " + ident + for ident in CONFIG["native_messaging"]["firefox_extension_ids"]: + assert json.dumps(ident) in main, "extension Firefox admise : " + ident + assert "Loksi_biometric" in main and "Bitwarden_biometric" not in main, "trousseau" + assert "artifacts.bitwarden.com" not in main, "canal de mise à jour" + assert "bitwarden.com/help" not in main and AIDE in main, "menu Aide" + # Décision du 03/10/2026 : support@ n'accepte que les clients connus. + assert "mailto:loksi@aleop.eu" in main and "support@aleop.eu" not in main, "Nous contacter" + assert "loksiBuild" in main and "loksiBasedOn" in main, "À propos : build et base Bitwarden" + assert 'this.localize("loksiSourceCode")' in main, "À propos : ligne Code source" + assert "LOKSI_APPDATA_DIR" in main and "BITWARDEN_APPDATA_DIR" not in main, "variable du dossier de données" + assert '"persist:loksi"' in main and "persist:bitwarden" not in main, "partition de session" + assert "autoHideMenuBar: true" in main, "barre de menus masquée" + assert not re.search(r"setMenuBarVisibility\)[^;]{0,80}call\(window, true\)", main), \ + "barre de menus réaffichée en sortie de fenêtre réduite" + # Schéma bitwarden:// gardé, obligatoire : Vaultwarden 1.37.3 impose + # bitwarden://sso-callback aux clients desktop et mobile (src/sso.rs:198), et le + # coffre web renvoie le Duo du bureau sur bitwarden://duo-callback + # (apps/web/src/connectors/duo-redirect.ts:4). Inventaire du 09/10/2026. + assert 'setAsDefaultProtocolClient("bitwarden"' in main, "schéma de retour SSO et Duo" + renderer = "".join(p.read_text() for p in (work / "app").glob("*.js")) + refus = check_client_version(renderer) + assert not refus, "version envoyée au serveur : " + " ; ".join(refus) + assert UNSET in renderer and UNSET in main, "marqueur adresse à saisir" + assert "loksi.aleop.eu" not in renderer + main, "adresse du coffre d'Aleop" + assert "Bitwarden-diagnostic-report" not in renderer + main, "rapport de diagnostic" + for lien in ("bitwarden.com/terms", "bitwarden.com/privacy", "bitwarden.com/email-preferences", + "bitwarden.com/help"): + assert lien not in renderer, "lien " + lien + print("Illustrations Loksi dans le bundle :", ", ".join(check_renderer(renderer))) + css = "".join(p.read_text() for p in (work / "app").glob("*.css")).replace(" ", "") + assert "--color-brand-700:#003087" in css and "--color-brand-700:#175ddc" not in css, "palette" + assert "font-family:Loksi" in css or "Loksi,Inter" in css, "police" + assert list((work / "app").rglob("loksi-400*.woff2")) or list(work.rglob("loksi-400*.woff2")), "police" + for chemin in sorted((work / "locales").glob("*/messages.json")): + check_texts(json.loads(chemin.read_text()), chemin.parent.name) + for lang in ("en", "fr"): + messages = json.loads((work / "locales" / lang / "messages.json").read_text()) + assert messages["loksiAboutOrigin"]["message"] == MENTION[lang], "mention d'origine " + lang + assert messages["loksiBasedOn"]["message"].endswith("Bitwarden " + BITWARDEN_VERSION), "base " + lang + check_source(messages, lang) + assert "Loksi" in (work / "index.html").read_text() + finally: + shutil.rmtree(work) + print(f"Vérifications réussies : {target}") + + +def canari_archs(): + """Mini paquet : un exécutable arm64 seul et un napi mal nommé doivent être refusés + pour x64 et universal, un exécutable universel accepté.""" + work = Path(tempfile.mkdtemp(prefix="loksi-canari-archs-")) + try: + source = work / "main.c" + source.write_text("int main(void) { return 0; }\n") + macos = work / "Canari.app/Contents/MacOS" + napi = work / "Canari.app/Contents/Resources/app.asar.unpacked" + macos.mkdir(parents=True) + napi.mkdir(parents=True) + run(["cc", "-arch", "arm64", "-o", macos / "arm64-seul", source]) + run(["cc", "-arch", "arm64", "-arch", "x86_64", "-o", macos / "universel", source]) + run(["cc", "-arch", "arm64", "-o", napi / "desktop_napi.darwin-x64.node", source]) + seen, refus = check_archs(work / "Canari.app", "x64") + ok = (seen == 3 and any("arm64-seul" in r for r in refus) and not any("universel" in r for r in refus) + and any("desktop_napi.darwin-x64.node : arm64 au lieu de x86_64" in r for r in refus)) + print("canari architectures", "OK, refus attendus :" if ok else "RATÉ :", " ; ".join(refus)) + (macos / "arm64-seul").unlink() + (napi / "desktop_napi.darwin-x64.node").unlink() + run(["cc", "-arch", "x86_64", "-o", napi / "desktop_napi.darwin-x64.node", source]) + seen, refus = check_archs(work / "Canari.app", "x64") + print("témoin architectures", "OK, accepté" if not refus else "RATÉ : " + " ; ".join(refus)) + return ok and not refus + finally: + shutil.rmtree(work) + + +def canari(): + """Les contrôles doivent refuser l'amont, sinon un contrôle muet passerait pour vert.""" + ratés = [] + # Fil de fusibles d'un Electron non modifié (relevé dans le paquet arm64 du 03/10), + # puis celui que pose after-pack.js amont. + found, refus = check_fuses(b"x" + FUSE_SENTINEL + b"\x01\x09101100011" + b"y") + print("canari fusibles", "OK, refus attendu :" if refus else "RATÉ", " ; ".join(refus[:2])) + if not refus: + ratés.append("fusibles") + if check_fuses(FUSE_SENTINEL + b"\x01\x09010011011")[1] or check_fuses(b"rien")[0]: + ratés.append("fusibles (témoin)") + if not canari_archs(): + ratés.append("architectures") + # Numérotation : un zéro devant et un build qui ne monte pas doivent être refusés. + for version, build, previous in (("2026.09.01", 8, 7), ("2026.10.0", 7, 7), ("2026.10.00", 8, 7)): + refus = check_version(version, build, previous) + print(f"canari numérotation {version} build {build} après {previous}", + "OK, refus attendu : " + " ; ".join(refus) if refus else "RATÉ, accepté") + if not refus: + ratés.append("numérotation " + version) + if check_version("2026.10.0", 8, 7) or check_version("2026.11.12", 9, 8): + ratés.append("numérotation (témoin)") + # En-tête Bitwarden-Client-Version : le code amont (version dérivée de celle de l'appli) + # et un bundle qui rendrait la version Loksi doivent être refusés. + with tarfile.open(ARCHIVE) as tar: + amont = tar.extractfile(SOURCE.name + "/apps/desktop/src/platform/services/" + "electron-platform-utils.service.ts").read().decode() + for name, code in (("amont", amont), + ("version Loksi", 'getApplicationVersionNumber(){return"' + VERSION + '"}')): + refus = check_client_version(code) + print(f"canari en-tête {name}", "OK, refus attendu : " + refus[0][:110] if refus else "RATÉ, accepté") + if not refus: + ratés.append("en-tête " + name) + if check_client_version('getApplicationVersionNumber(){return r(this,void 0,void 0,function*(){return"' + + BITWARDEN_VERSION + '"})}'): + ratés.append("en-tête (témoin)") + with tarfile.open(ARCHIVE) as tar: + en = json.loads(tar.extractfile(SOURCE.name + "/apps/desktop/src/locales/en/messages.json").read()) + logo = tar.extractfile(SOURCE.name + "/libs/assets/src/svg/svgs/lock.icon.ts").read().decode() + for name, check, value in (("textes", check_texts, en), ("dessins", check_renderer, logo), + ("code source", check_source, en)): + try: + check(value, "amont") if name != "dessins" else check(value) + ratés.append(name) + except AssertionError as error: + print(f"canari {name} OK, refus attendu : {error}") + if ratés: + sys.exit("canari raté, contrôle muet : " + ", ".join(ratés)) + + +if __name__ == "__main__": + command = sys.argv[1] if len(sys.argv) > 1 else "help" + if command in ("prepare", "changes", "canari", "webpack"): + globals()[command]() + elif command == "native": + native(sys.argv[2] if len(sys.argv) > 2 else "mac") + elif command in ("build", "verify") and sys.argv[2:3] == ["mac"] and len(sys.argv) in (3, 4): + globals()[command]("mac", sys.argv[3] if len(sys.argv) == 4 else "arm64") + elif command in ("build", "verify") and len(sys.argv) == 3: + globals()[command](sys.argv[2]) + else: + sys.exit(__doc__) diff --git a/desktop/render.mjs b/desktop/render.mjs new file mode 100644 index 0000000..24cc296 --- /dev/null +++ b/desktop/render.mjs @@ -0,0 +1,78 @@ +/** + * Visuels de l'application de bureau Loksi, rendus par Chromium depuis brand/. + * + * node render.mjs + * + * - icon-.png : l'icône d'application, maître plat de 16 px à 16, maître sculpté + * au-dessus (règle de brand/icones.mjs). Le maître sculpté garde son cadre + * transparent et ses ombres : c'est la grille des icônes macOS ; + * - mac-.png : le jeu de l'iconset macOS, au gabarit système de brand/icones.mjs + * (pleine page, opaque, angles droits). macOS 27 pose son masque ; avec icon-.png + * il enfermait l'icône dans un cadre gris et le carré bleu tombait à 480 px sur 1024 + * dans le rendu Icon Services, contre 824 pour Klepsi (mesuré le 03/10/2026) ; + * - win-.png : le jeu des .ico Windows, recadré par windows() de brand/icones.mjs + * (coins arrondis gardés, carré à 89 % au lieu de 69 %), maître plat à 16 ; + * - tray-template.png et @2x : la silhouette de loksi-icon-mono.svg en noir, que macOS + * teinte lui-même dans la barre des menus. tray-highlight : la même en blanc ; + * - installer-sidebar.png : bandeau de l'installateur Windows, 164 x 314, logo sombre + * sur fond navy. Converti en BMP 24 bits par loksi.py (NSIS ne lit que ça) ; + * - appx-*.png : visuels du paquet MSIX, aux tailles des fichiers amont. + * + * Lancé par loksi.py depuis desktop/.cache/node, où playwright est installé à la + * version de brand/package-lock.json. N'écrit que dans le dossier donné. + */ +import { readFileSync, mkdirSync } from 'fs'; +import { join, dirname, resolve } from 'path'; +import { fileURLToPath, pathToFileURL } from 'url'; +import { createRequire } from 'module'; + +const here = dirname(fileURLToPath(import.meta.url)); +const brand = resolve(here, '../brand'); +const out = process.argv[2]; +if (!out) throw new Error('dossier de sortie manquant'); +mkdirSync(out, { recursive: true }); + +const { chromium } = createRequire(join(process.cwd(), 'package.json'))('playwright'); +const { sculpte, plat16, systeme, systeme16, windows } = await import(pathToFileURL(join(brand, 'icones.mjs')).href); +// Une URL file:// et pas un chemin : sous Windows, import() refuse « C:\... » +// (ERR_UNSUPPORTED_ESM_URL_SCHEME, vu le 08/10/2026 sur VSOP-SIG01). +const mono = readFileSync(join(brand, 'sources/loksi-icon-mono.svg'), 'utf8'); +const logoSombre = readFileSync(join(brand, 'sources/loksi-logo-sombre.svg'), 'utf8'); + +// Une seule encre dans le maître mono, sinon le gabarit de barre des menus serait faux. +const encres = [...new Set([...mono.matchAll(/fill="(#[0-9A-Fa-f]{6})"/g)].map(m => m[1]))]; +if (encres.length !== 1) throw new Error(`loksi-icon-mono.svg : une encre attendue, ${encres.length} trouvées`); +const silhouette = (couleur) => mono.replaceAll(`fill="${encres[0]}"`, `fill="${couleur}"`); + +const browser = await chromium.launch(); +const page = await browser.newPage(); + +async function rendre(html, largeur, hauteur, sortie, fond = 'transparent') { + await page.setViewportSize({ width: largeur, height: hauteur }); + await page.setContent(`${html}`); + await page.screenshot({ path: join(out, sortie), omitBackground: fond === 'transparent' }); +} + +for (const t of [16, 24, 32, 48, 64, 128, 256, 512, 1024]) { + await rendre(t === 16 ? plat16 : sculpte, t, t, `icon-${t}.png`); + await rendre(t === 16 ? systeme16() : systeme(), t, t, `mac-${t}.png`); + await rendre(t === 16 ? plat16 : windows(), t, t, `win-${t}.png`); +} +for (const [suffixe, t] of [['', 16], ['@2x', 32]]) { + await rendre(silhouette('#000000'), t, t, `tray-template${suffixe}.png`); + await rendre(silhouette('#FFFFFF'), t, t, `tray-highlight${suffixe}.png`); +} +// Bandeau NSIS : le logo sombre centré dans la largeur, au premier tiers de la hauteur. +await rendre(`
${logoSombre}
`, + 164, 314, 'installer-sidebar.png', '#003087'); +// Visuels du paquet MSIX (cible Store, désactivée par défaut) aux tailles amont. +for (const [nom, t] of [['Square44x44Logo', 44], ['Square150x150Logo', 150], ['StoreLogo', 50]]) { + await rendre(sculpte, t, t, `appx-${nom}.png`); +} +for (const [nom, l, h] of [['Wide310x150Logo', 310, 150], ['SplashScreen', 620, 300]]) { + await rendre(`
${logoSombre}
`, + l, h, `appx-${nom}.png`, '#003087'); +} + +await browser.close(); +console.log(`visuels desktop rendus dans ${out}`); diff --git a/desktop/upstream.json b/desktop/upstream.json new file mode 100644 index 0000000..79f92aa --- /dev/null +++ b/desktop/upstream.json @@ -0,0 +1,53 @@ +{ + "releve": "2026-09-29", + "repository": "https://github.com/bitwarden/clients", + "tag": "desktop-v2026.9.0", + "published": "2026-09-17", + "commit": "07ac2aa903459ea8e1c18e3295b765be0bc3585f", + "archive_url": "https://codeload.github.com/bitwarden/clients/tar.gz/refs/tags/desktop-v2026.9.0", + "archive_sha256": "0ab9c0efc5622d6ea9a9558e5c6c5fb59fecaee5b49d61ad12940c2cc7f782fc", + "note_tag": "Dernier tag desktop au 29/09/2026, le plus proche de browser-v2026.9.2 de l'extension. Pas de desktop-v2026.9.1 ni 9.2.", + "app_id": "eu.aleop.loksi", + "product_name": "Loksi", + "executable_name": "loksi", + "homepage": "https://www.aleop.eu/loksi", + "app_version": { + "marketing": "2026.10.0", + "build": 15, + "note": "Règle de Romain du 06/10/2026, commune à Loksi et Klepsi. marketing : AAAA.M.n sans zéro devant, n à 0 pour la première sortie du mois. build : dernier numéro de paquet construit, monté par loksi.py build, jamais réutilisé. La version Bitwarden de la base se lit dans tag et s'affiche dans À propos." + }, + "default_server": null, + "unset_server": "https://coffre-a-renseigner.invalid", + "native_messaging": { + "host": "eu.aleop.loksi", + "firefox_extension_ids": [ + "loksi@aleop.eu", + "loksi-dev@aleop.eu" + ], + "chrome_extension_ids": [ + "gajfjinefeclihkcohkefinoainnljdc" + ], + "note": "Chrome et Edge : identifiant tiré de la clé de manifeste fixe de l'extension Loksi (branche extension-sans-bitwarden, 2c20652, vérifié le 09/10/2026 dans Chromium et Edge 154). Les magasins Chrome et Edge en attribueront d'autres, à ajouter à la publication. Le balayage des profils Chromium au démarrage reste tant que l'extension sans clé circule." + }, + "ipc_name": "loksi", + "windows_plugin_authenticator_clsid": "e2ac5ec2-a41c-4ac2-8ea1-a722a07b7e26", + "toolchain": { + "node_local": "26.3.1", + "npm_local": "11.16.0", + "rust": "1.97.1", + "electron": "43.2.0", + "electron_builder": "26.9.0", + "cargo_xwin": "0.23.0", + "mac_arch": "universal", + "windows_arch": "x64" + }, + "apple_team": { + "id": "7KKY684D37", + "name": "ALEOP", + "note": "équipe du compte Apple Developer d'Aleop, seul endroit de desktop/ où elle est écrite. Identité « Developer ID Application » de cette équipe cherchée dans le trousseau par loksi.py" + }, + "apple_notary_profile": { + "name": "loksi-notary", + "note": "profil notarytool rangé dans le trousseau par Romain (xcrun notarytool store-credentials) ; aucun secret ici" + } +} diff --git a/desktop/webpack-oss.cjs b/desktop/webpack-oss.cjs new file mode 100644 index 0000000..5ccdd61 --- /dev/null +++ b/desktop/webpack-oss.cjs @@ -0,0 +1,28 @@ +// GPL-3.0-only. Wrapper du build amont : bloque le code commercial, relève les modules réels. +// Même garde-fou que extensions/webpack-oss.cjs, pour les trois configs du bureau +// (main, renderer, preload). +const fs = require('fs'); +const path = require('path'); +const root = __dirname; +const { tag } = require('./upstream.json'); +const source = path.join(root, '.cache', `clients-${tag}`); +class OssBoundaryPlugin { + apply(compiler) { + compiler.hooks.compilation.tap('LoksiOssBoundary', compilation => { + compilation.hooks.finishModules.tap('LoksiOssBoundary', modules => { + const resources = [...modules].map(m => m.resource).filter(Boolean).sort(); + const forbidden = resources.filter(p => /[/\\]bitwarden_license[/\\]|[/\\]commercial-sdk-internal[/\\]/.test(p)); + if (forbidden.length) throw new Error(`Code commercial interdit : ${forbidden.join(', ')}`); + const name = `desktop-${compiler.options.name}`.replace(/[^a-zA-Z0-9.-]/g, '_'); + fs.mkdirSync(path.join(root, 'reports'), { recursive: true }); + fs.writeFileSync(path.join(root, 'reports', `${name}-modules.json`), + JSON.stringify(resources.map(p => path.relative(source, p)), null, 2)); + }); + }); + } +} +module.exports = (...args) => { + const configs = require(path.join(source, 'apps/desktop/webpack.config.js'))(...args); + for (const config of configs) config.plugins.push(new OssBoundaryPlugin()); + return configs; +}; diff --git a/extensions/.gitignore b/extensions/.gitignore new file mode 100644 index 0000000..1ebf36f --- /dev/null +++ b/extensions/.gitignore @@ -0,0 +1,4 @@ +.cache/ +dist/ +reports/ +__pycache__/ diff --git a/extensions/LICENSE b/extensions/LICENSE new file mode 100644 index 0000000..30ace6a --- /dev/null +++ b/extensions/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/extensions/README.md b/extensions/README.md new file mode 100644 index 0000000..58be370 --- /dev/null +++ b/extensions/README.md @@ -0,0 +1,250 @@ +# Extensions Loksi : prototype local + +Client navigateur Bitwarden **OSS 2026.9.2**, adapté à Loksi, sans coffre par défaut : +chaque client saisit l'adresse du sien. Les algorithmes cryptographiques, le SDK GPL, les API, +la synchronisation et les moteurs de remplissage sont ceux de l'amont. +Ce prototype n'est ni publié ni signé. Aucun achat ou compte de magasin n'est +nécessaire pour le compiler et le charger localement. + +## Résultat et installation + +Les répertoires `dist/chrome`, `dist/edge` et `dist/firefox` contiennent les +extensions après compilation. Utiliser un profil de test et éviter deux extensions +de remplissage actives simultanément sur la page de test. + +| Navigateur | Charger localement | +|---|---| +| Chrome 134 ou ultérieur | `chrome://extensions`, mode développeur, « Charger l'extension non empaquetée », sélectionner `extensions/dist/chrome` | +| Edge basé sur Chromium 134 ou ultérieur | `edge://extensions`, mode développeur, « Charger l'extension décompressée », sélectionner `extensions/dist/edge` | +| Firefox | `about:debugging#/runtime/this-firefox`, « Charger un module complémentaire temporaire », sélectionner `extensions/dist/firefox/manifest.json` | + +Chrome et Edge utilisent Manifest V3, Firefox le chemin Manifest V2 amont. +Firefox doit être rechargé après chaque redémarrage du navigateur. Le minimum +Firefox déclaré par l'amont est 91 ; cela ne signifie pas que cette ancienne +version a été validée ici. Tester avec une version Firefox maintenue. + +Ouvrir Loksi et contrôler le serveur affiché **avant toute connexion**. L'extension +possède son propre stockage ; elle ne migre pas les comptes de l'extension officielle. +Son identifiant Firefox est `loksi@aleop.eu` depuis le 10/10/2026 (`loksi-dev@aleop.eu` avant), distinct de Bitwarden. Chromium +attribue un identifiant au chargement local ; garder le même chemin évite les +changements inutiles d'identité. Aucun identifiant ni clé de signature officielle +n'est repris. + +## Reproduire + +Prérequis : Python 3.12+ (extraction sécurisée tar), Node.js ≥24.17.0 et npm 11, +`curl`. Validation locale effectuée avec Node 26.3.1 et npm 11.16.0. L'amont +conseille Node 24. Compter environ 2 Go de dépendances et jusqu'à 8 Go de mémoire +pour la compilation. Accès GitHub/npm nécessaire à la première préparation, +et PyPI pour le venv de `fonts.py` (fonttools épinglé dans `mobile/upstream.json`, brotli). + +Depuis la racine du dépôt : + +```sh +mkdir -p extensions/.cache +curl -fL https://github.com/bitwarden/clients/archive/refs/tags/browser-v2026.9.2.tar.gz \ + -o extensions/.cache/upstream.tar.gz +# Uniquement si les dépendances graphiques ne sont pas déjà installées : +npm ci --prefix brand --no-audit --no-fund +python3 extensions/prototype.py prepare +cd extensions/.cache/clients-browser-v2026.9.2 +npm ci --ignore-scripts --no-audit --no-fund +cd ../../.. +node --test extensions/environment.test.cjs +python3 extensions/verify-source.py +python3 extensions/prototype.py build chrome +python3 extensions/prototype.py build edge +python3 extensions/prototype.py build firefox +``` + +`prepare` vérifie le SHA-256 de l'archive avant extraction puis remet les sources +amont dans leur état initial et applique les adaptations. Il conserve +`node_modules`, mais écrase les éditions manuelles dans les sources extraites. +Ne pas le lancer pendant une compilation. Ne pas compiler deux variantes +simultanément : elles partagent la sortie intermédiaire amont. +Les versions et l'empreinte sont dans `upstream.json`. Modifier ce fichier ne suffit +pas pour changer de version : revoir les points de patch, les licences et les tests. + +Le build utilise **webpack.config.js OSS**, jamais `build:bit:*`. Le wrapper +`webpack-oss.cjs` conserve les configurations amont et refuse tout module provenant +de `bitwarden_license` ou `@bitwarden/commercial-sdk-internal`. Il produit dans +`reports/` la liste des modules réellement compilés. Les dépendances et leurs +licences présentes sont copiées dans chaque sortie (`THIRD-PARTY.json`, +`third-party/`). Voir [LICENSE-REVIEW.md](LICENSE-REVIEW.md). + +## Magasins + +Publication dans le Chrome Web Store, Edge Add-ons et Firefox Add-ons : voir +[STORES.md](STORES.md), avec les commandes `paquet` et `sources`. + +## Numérotation + +Règle de Romain du 06/10/2026, commune à Loksi et Klepsi sur tous les clients : + +- Version de sortie `AAAA.M.n`, sans zéro devant. `n` vaut 0 pour la première sortie du + mois et monte à chaque sortie du même mois : 2026.10.0, 2026.10.1, puis 2026.11.0. Une + même sortie porte le même numéro sur tous les clients du produit. Première sortie + publique : 2026.10.0. +- Numéro de build : un entier qui monte à chaque paquet, sans jamais redescendre. +- Manifeste : `version` = `AAAA.M.n.build`, `version_name` = « AAAA.M.n (build) » pour + Chrome et Edge. Firefox ne connaît pas `version_name`. +- L'appli affiche « AAAA.M.n (build) », Firefox compris, et « À propos » ajoute « Basé + sur Bitwarden 2026.9.2 ». Le serveur reçoit toujours la version amont dans + `Bitwarden-Client-Version`, puisque c'est la version réelle du code. + +Le compteur vit dans `version.json`, seul endroit. Avant chaque paquet : + +```sh +python3 extensions/prototype.py bump # build + 1 +python3 extensions/prototype.py bump 2026.11.0 # nouvelle sortie, build + 1 +``` + +`bump` refuse un zéro devant et une sortie qui ne monte pas. `verify` refuse un manifeste +qui s'écarte de `version.json`, qui porte un zéro devant ou la version amont, et vérifie à +chaque passage que ces cas fabriqués exprès sont bien refusés. + +## Adaptations limitées + +- Nom, auteur et page d'accueil des manifestes ; identifiant Firefox distinct. +- Principaux libellés d'interface et de remplissage, sans changer les clés internes. +- Actions de remplissage placées directement dans le menu natif de l'extension, + sans sous-menu de marque redondant. +- Icônes de barre d'outils, états gris/verrouillé, logo de connexion et menu de + remplissage dérivés du SVG existant `brand/loksi-icon.svg`. +- Aucun coffre par défaut (décision de Romain du 04/10/2026), comme les applis mobiles + et l'appli de bureau. Sans rien de saisi, l'extension vise `https://coffre-a-renseigner.invalid` + (`unset_server` de `upstream.json`), qui ne se résout jamais, et affiche « Connexion + sur : adresse à saisir ». Un clic ouvre la saisie, « Votre coffre Loksi », champ vide. + Tant que rien n'est saisi, « Pas encore client ? Découvrir Loksi » mène à + https://www.aleop.eu/loksi/. Une politique administrateur (GPO, MDM, `policies.json`) + reste prioritaire : `browser-environment.service.ts` n'est plus modifié. `verify` refuse + tout fichier du build qui contient encore `loksi.aleop.eu`. +- Premier lancement : sur l'écran de connexion, tant qu'aucun coffre n'est saisi, la + saisie s'ouvre d'elle-même, avec une phrase d'explication. Le champ propose + `https://societe.loksi.fr`, « societe » sélectionné, et refuse le modèle laissé tel quel. +- Nom du coffre : la saisie accepte le nom choisi à la commande (`mon-entreprise` pour + `https://mon-entreprise.loksi.fr`, même motif que le tunnel) ou une adresse complète + en https, et refuse tant qu'un Vaultwarden ne répond pas sur `/api/config` + (`loksi-coffre.ts`, tests `node --test extensions/loksi-coffre.test.cjs`). +- Accueil initial : l'aide Loksi s'ouvre à l'installation (https://www.aleop.eu/aide/loksi/). +- Carrousel d'accueil aux textes du carrousel iOS, français pour fr, anglais ailleurs. +- Nom Bitwarden : tous les textes passent en Loksi, application de bureau comprise, sauf + la liste `BITWARDEN_GARDE` (mention d'origine, produit tiers cité, textes des pages + retirées). Retirés : « Télécharger les applications Bitwarden », « Plus de Bitwarden », + et la note au magasin. `verify` refuse tout autre texte qui contient Bitwarden, + en fr et en. +- Sélecteur de serveur : plus de liste de régions, bitwarden.com et bitwarden.eu ne sont + plus proposés (voir `SELECTEUR-SERVEUR.md`). +- Pas de création de compte, comme les applis mobiles : le carrousel n'offre que « Se + connecter », la page de connexion n'a plus « Créer un compte ». Un compte Loksi est créé + par l'administrateur de l'entreprise. Le lien bitwarden.com/terms/ de l'inscription + n'est plus atteignable. +- À propos : Centre d'aide Loksi, Politique de confidentialité et Nous contacter + (confirmation, puis mailto:support@aleop.eu), comme Android et iOS. Les 38 liens + bitwarden.com/help et /privacy du code mènent aux pages Loksi, adresses www définitives. +- Pastille de l'icône verrouillée (barre d'outils et menu de remplissage) : disque cyan, + contour et barre blancs, comme la pastille d'état des illustrations. +- Illustrations de la popup : les 21 exports amont affichés (cadenas « ***__ » de + l'écran verrouillé, coffre vide, recherche vide, Send, etc.) remplacés par les + maîtres Loksi de `brand/illustrations-mobiles/sources/`, table `ILLUSTRATION_TABLE` + de `prototype.py`. Maîtres clair et sombre posés tous deux, `popup.scss` masque + l'un selon `.theme_dark`. `verify` refuse un build où reste la signature d'un + dessin amont. `Security` et `Party` ne sont pas affichés dans la popup. +- Barre d'onglets : pictogrammes Loksi des applis iOS (`brand/illustrations-mobiles/onglets/`), + couleurs passées en variables du thème. +- Palette : échelle `brand` et couleurs primaires de `tw-theme.css` remplacées. Bouton + et accents navy #003087 en clair, cyan #009CDE en sombre, comme les applis mobiles. +- Police : Raleway renommée « Loksi » (nom réservé OFL-1.1), produite par `fonts.py` + qui réutilise `mobile/ios/fonts.py`. Licence copiée dans chaque sortie + (`OFL-police-Loksi.txt`). + +Aucune modification de chiffrement, de dérivation de clés, de protocole de connexion +ou de détection/remplissage des champs. Les références aux produits tiers, à l'aide +et certains libellés secondaires Bitwarden sont conservés. + +## Ce qui garde « bitwarden », et pourquoi + +Décision de Romain du 09/10/2026 : plus de Bitwarden dans les clients Loksi, sauf +obligation. Inventaire du même jour sur le build 2026.10.0 (1) : 172 jetons distincts +dans les scripts, presque tous des noms internes. + +Retiré par `prepare`, contrôlé par `verify`. Canari : le build d'avant porte ces traces +et le contrôle les trouve. + +- Hôte de messagerie native `com.8bit.bitwarden`, devenu `eu.aleop.loksi`, celui que le + bureau Loksi écoute. Deux appels : `nativeMessaging.background.ts` et + `desktop-ipc.transport.ts`. +- Classe `com-bitwarden-browser-animated-fill` posée sur les champs remplis, que les + sites voient dans leur page : `com-loksi-browser-animated-fill`. +- Fichiers téléchargés : export `loksi_export_*`, rapport `Loksi-diagnostic-report-*.csv`. +- Auteur du manifeste : « Aleop ». Le nom Bitwarden reste dans la mention d'origine. +- Mots qui affaiblissent un mot de passe : `loksi` à la place de `bitwarden`. + +Identifiant fixe sous Chrome et Edge : `chromium_key` de `upstream.json`, clé publique +seule, la clé privée n'a jamais été écrite. Identifiant `gajfjinefeclihkcohkefinoainnljdc`, +vérifié au chargement le 09/10/2026 dans Chromium et Edge 154. Le bureau l'inscrit dans +`allowed_origins`. Les magasins Chrome et Edge attribuent leur propre identifiant à la +publication : il faudra l'ajouter aussi au bureau. + +Gardé parce qu'obligatoire : + +- L'en-tête `Bitwarden-Client-Version`, que Vaultwarden exige, avec la version amont. + `Device-Type` aussi : Vaultwarden aiguille dessus. +- Le schéma `bitwarden://` des retours SSO, Duo et WebAuthn, imposé par Vaultwarden. +- Le message `bitwarden-ipc-message` échangé avec le coffre web : c'est son protocole. +- Les attributs `data-bwignore` et apparentés que des sites posent pour Bitwarden : les + ignorer ferait remplir des champs que le site a exclus. +- La mention d'origine GPL (À propos, `LOKSI-NOTICE.txt`) et les clés de `BITWARDEN_GARDE`. +- Les formats d'import « Bitwarden (json) » et « Bitwarden (csv) » : ils nomment le + fichier d'un vrai produit, qu'un client peut vouloir importer. + +Gardé faute de gain : en-têtes `Bitwarden-Client-Name` et `Bitwarden-Package-Type` +(non lus par Vaultwarden), noms internes du code et des paquets `@bitwarden/*`, noms des +clés de traduction et leurs descriptions (jamais affichés), adresses des régions cloud +Bitwarden (jamais appelées, l'adresse se saisit), identifiants Safari (pas de build +Safari), outil de développement `map-the-web` (indicateur de développement seul). + +## Vérifications fonctionnelles à réaliser + +État au 28 septembre 2026 : Chrome, Edge et Firefox sont rapportés fonctionnels +en usage courant. L'identité et le menu Loksi ont été validés. Les parcours avancés +se testent avec la grille de [VALIDATION.md](VALIDATION.md#grille-dessais-du-28092026), +où les résultats sont consignés par navigateur. + +La compilation et les tests statiques ne prouvent pas la compatibilité effective +avec le serveur Vaultwarden 1.37.3 du projet. La grille couvre installation, +connexion par mot de passe maître et SSO Aleop, verrouillage, redémarrage, +synchronisation, remplissage, TOTP, passkeys et biométrie. Chaque bloc a un canari +qui doit échouer. + +Les pages de remplissage se servent en local, valeurs fictives uniquement : + +```sh +python3 -m http.server 8765 --bind 127.0.0.1 --directory extensions +``` + +puis `http://127.0.0.1:8765/essais/index.html`. `test-form.html` reste la connexion +simple. Les pages de `essais/` couvrent deux étapes, formulaire chargé après coup, +shadow DOM, iframes, TOTP, inscription, changement de mot de passe, identité et +carte de test. Elles n'affichent que le nombre de champs remplis, sans soumission +réseau. Noter navigateur, version, version serveur, résultats et erreurs sans secrets. + +La biométrie via l'application desktop officielle n'est pas attendue : son code +n'autorise que les identifiants officiels d'extension (essai B1 de la grille). Les parcours SSO +et passkeys peuvent aussi dépendre d'identifiants/extensions autorisés. Les +fonctionnalités commerciales absentes du build OSS ne sont pas promises. + +Les permissions amont nécessaires au remplissage sont conservées, notamment +l'accès aux sites. Les liens d'aide et certains services tiers amont peuvent +encore être contactés ; aucune promesse « zéro appel externe » n'est faite. +Pas de publication, signature, mise à jour automatique, audit de sécurité complet, +ni garantie de parité avec les extensions officielles à ce stade. + +Pour revenir en arrière, retirer Loksi du profil de test. Aucun réglage du serveur +ni installation officielle n'est modifié par les scripts de compilation. + +## Sources + +- [Sources exactes et licence](https://github.com/bitwarden/clients/tree/browser-v2026.9.2) +- [Compilation et chargement local documentés par Bitwarden](https://contributing.bitwarden.com/getting-started/clients/browser/) +- [Résultats locaux](VALIDATION.md) diff --git a/extensions/dependencies.py b/extensions/dependencies.py new file mode 100644 index 0000000..2092d63 --- /dev/null +++ b/extensions/dependencies.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Inventaire des paquets effectivement compilés, à partir des rapports Webpack.""" +import json +from pathlib import Path +import shutil +import sys +from prototype import ROOT, SOURCE + +browser = sys.argv[1] +packages = {} +reports = list((ROOT / "reports").glob(f"{browser}-*-modules.json")) +if not reports: + raise RuntimeError("Compiler d'abord avec webpack-oss.cjs") +for report in reports: + for resource in json.loads(report.read_text()): + if "node_modules/" not in resource: + continue + folder = (SOURCE / resource.split("?")[0]).resolve().parent + while folder != SOURCE: + if (folder / "package.json").is_file(): + data = json.loads((folder / "package.json").read_text()) + if data.get("name") and data.get("version"): + break + folder = folder.parent + if folder == SOURCE: + raise RuntimeError(f"Paquet non identifié : {resource}") + data = json.loads((folder / "package.json").read_text()) + name = data["name"] + key = name + "@" + data.get("version", "unknown") + if key in packages: + continue + license_files = [p for p in folder.iterdir() if p.is_file() and + p.name.lower().startswith(("license", "licence", "notice", "copying"))] + if folder.is_relative_to(SOURCE / "libs"): + data["license"] = "GPL-3.0" + license_files += [SOURCE / "LICENSE.txt", SOURCE / "LICENSE_GPL.txt"] + supplemental = { + '@microsoft/signalr': 'signalr-MIT.txt', + '@microsoft/signalr-protocol-msgpack': 'signalr-MIT.txt', + '@bufbuild/protobuf': 'protobuf-es-LICENSE', + '@ng-select/ng-select': 'ng-select-MIT.txt', + } + if name in supplemental: + license_files.append(ROOT / 'licenses' / supplemental[name]) + if name == '@bufbuild/protobuf': + # Le paquet porte aussi le BSD-3-Clause de Google dans ce fichier. + license_files.append(folder / 'dist/esm/wire/varint.js') + packages[key] = {"name": name, "version": data.get("version"), + "license": data.get("license", "UNKNOWN"), + "path": folder.relative_to(SOURCE).as_posix(), + "license_files": [p.name for p in license_files]} + destination = ROOT / "dist" / browser / "third-party" / key.replace("/", "__") + destination.mkdir(parents=True, exist_ok=True) + for file in license_files: + shutil.copy2(file, destination / file.name) + shutil.copy2(folder / "package.json", destination / "package.json") + if (folder / "README.md").is_file(): + shutil.copy2(folder / "README.md", destination / "README.md") +output = ROOT / "dist" / browser / "THIRD-PARTY.json" +output.write_text(json.dumps(list(packages.values()), indent=2) + "\n") +print(f"{len(packages)} paquets compilés inventoriés dans {output}") +print("Licences déclarées :", sorted({str(p["license"]) for p in packages.values()})) +print("Sans fichier de licence racine :", [k for k, p in packages.items() if not p["license_files"]]) diff --git a/extensions/environment.test.cjs b/extensions/environment.test.cjs new file mode 100644 index 0000000..e418709 --- /dev/null +++ b/extensions/environment.test.cjs @@ -0,0 +1,60 @@ +// GPL-3.0-only. Exécute le service adapté, sans compte ni appel réseau. +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const path = require('node:path'); +const config = require('./upstream.json'); +const root = path.join(__dirname, '.cache', `clients-${config.tag}`); +const ts = require(path.join(root, 'node_modules/typescript')); +const file = path.join(root, 'apps/browser/src/platform/services/browser-environment.service.ts'); +const compiled = ts.transpileModule(fs.readFileSync(file, 'utf8'), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } +}).outputText; +function service(managed, runtime = {}) { + const exports = {}; + class DefaultEnvironmentService { + async setEnvironment(region, urls) { this.selected = { region, urls }; } + } + vm.runInNewContext(compiled, { + exports, chrome: { storage: { managed }, runtime }, + require: id => { + if (id.endsWith('/default-environment.service')) return { DefaultEnvironmentService }; + if (id.endsWith('/environment.service')) return { Region: { SelfHosted: 'SelfHosted' } }; + if (id.endsWith('/flags')) return { devFlagEnabled: () => false }; + return {}; + } + }); + return new exports.BrowserEnvironmentService({ warning() {}, error() {} }, {}, {}); +} +// Aucun coffre par défaut depuis le 04/10/2026 : sans politique, l'amont ne règle rien +// et le client saisit l'adresse de son coffre (marqueur .invalid, voir prototype.py). +test('Firefox sans stockage géré ne prérègle aucun serveur', async () => { + const instance = service(undefined); + assert.equal(await instance.getManagedEnvironment(), null); + assert.equal(await instance.hasManagedEnvironment(), false); +}); +test('Chromium sans politique ne prérègle aucun serveur', async () => { + const instance = service({ get: (_, callback) => callback({}) }); + assert.equal(await instance.hasManagedEnvironment(), false); + assert.equal(instance.selected, undefined); +}); +test('La politique administrateur explicite reste prioritaire', async () => { + const instance = service({ get: (_, callback) => callback({ environment: { base: 'https://example.test' } }) }); + assert.equal(await instance.hasManagedEnvironment(), true); + await instance.setUrlsToManagedEnvironment(); + assert.equal(instance.selected.region, 'SelfHosted'); + assert.equal(instance.selected.urls.base, 'https://example.test'); +}); +test('Une API managed indisponible ne prérègle aucun serveur', async () => { + const instance = service({ get: (_, callback) => callback(undefined) }, { lastError: { message: 'Unavailable' } }); + assert.equal(await instance.hasManagedEnvironment(), false); +}); +test('Aucun coffre Loksi en dur dans le service', () => { + assert.equal(fs.readFileSync(file, 'utf8').includes('loksi.aleop.eu'), false); +}); +test('Le défaut amont mène au marqueur, jamais au cloud Bitwarden', () => { + const env = fs.readFileSync(path.join(root, 'libs/common/src/platform/services/default-environment.service.ts'), 'utf8'); + assert.equal(env.split(`urls = { base: "${config.unset_server}" };`).length - 1, 2); + assert.equal(env.includes('region = DEFAULT_REGION;'), false); +}); diff --git a/extensions/fonts.py b/extensions/fonts.py new file mode 100644 index 0000000..b3544e5 --- /dev/null +++ b/extensions/fonts.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Police Loksi de l'extension navigateur, dérivée de Raleway (OFL-1.1). + +fonts.py produit extensions/.cache/fonts/woff2/loksi-*.woff2 +fonts.py --canari montre que la vérification refuse un Raleway non renommé + +Réutilise mobile/ios/fonts.py tel quel (instances statiques, famille « Loksi », +chiffres alignés). Sources et empreintes lues dans mobile/upstream.json. +""" +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parent +MOBILE = ROOT.parent / "mobile" +UPSTREAM = json.loads((MOBILE / "upstream.json").read_text())["font"] +CACHE = ROOT / ".cache" / "fonts" +VENV = ROOT / ".cache" / "fonts-venv" +PYTHON = VENV / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") +OUT = CACHE / "out" +WOFF2 = CACHE / "woff2" +# Fichier produit par mobile/ios/fonts.py vers fichier WOFF2 de l'extension. +FILES = {"Loksi-Regular": "loksi-400", "Loksi-SemiBold": "loksi-600", + "Loksi-Bold": "loksi-700", "Loksi-Italic": "loksi-400-italic"} + + +# fontTools date le tableau head à l'enregistrement. Sans date figée, chaque prepare donne +# des woff2 différents, donc d'autres noms hachés dans le paquet (vu le 12/10/2026 en +# reconstruisant depuis l'export public). 1759276800 : 01/10/2025 00:00 UTC. +SOURCE_DATE_EPOCH = "1759276800" + + +def run(cmd): + subprocess.run([str(c) for c in cmd], check=True, + env={**os.environ, "SOURCE_DATE_EPOCH": SOURCE_DATE_EPOCH}) + + +def sha256(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def fetch(): + CACHE.mkdir(parents=True, exist_ok=True) + 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[key]]) + if sha256(font) != UPSTREAM[key.replace("url", "sha256")]: + raise RuntimeError(f"{name} incorrecte : SHA-256 différent") + + +def venv(): + if not PYTHON.exists(): + run([sys.executable, "-m", "venv", VENV]) + run([PYTHON, "-m", "pip", "install", "-q", f"fonttools=={UPSTREAM['fonttools']}", "brotli"]) + + +def instances(): + run([PYTHON, MOBILE / "ios" / "fonts.py", CACHE / "Raleway-wght.ttf", + CACHE / "Raleway-Italic-wght.ttf", OUT]) + + +def convert(): + """TTF vers WOFF2, dans le python du venv (fontTools et brotli y sont).""" + WOFF2.mkdir(parents=True, exist_ok=True) + code = ("import sys\nfrom fontTools.ttLib import TTFont\n" + "f = TTFont(sys.argv[1]); f.flavor = 'woff2'; f.save(sys.argv[2])\n") + for source, target in FILES.items(): + run([PYTHON, "-c", code, OUT / f"{source}.ttf", WOFF2 / f"{target}.woff2"]) + + +def check(paths): + """Famille « Loksi » et aucun enregistrement de famille contenant Raleway.""" + code = ("import sys\nfrom fontTools.ttLib import TTFont\n" + "for p in sys.argv[1:]:\n" + " n = TTFont(p)['name']\n" + " fam = n.getDebugName(16) or n.getDebugName(1)\n" + " tout = '|'.join(r.toUnicode() for r in n.names if r.nameID in (1, 16))\n" + " print(p, fam, tout, sep='\\t')\n") + out = subprocess.run([str(PYTHON), "-c", code, *map(str, paths)], check=True, + capture_output=True, text=True).stdout + for line in out.splitlines(): + path, family, records = line.split("\t") + # Le 16 (famille typographique) prime sur le 1, qui porte « Loksi SemiBold ». + if family != "Loksi": + raise RuntimeError(f"{Path(path).name} : famille « {family} », « Loksi » attendu") + if "Raleway" in records: + raise RuntimeError(f"{Path(path).name} : Raleway dans la famille") + + +def main(): + fetch() + venv() + if "--canari" in sys.argv: + try: + check([CACHE / "Raleway-wght.ttf"]) + except RuntimeError as error: + print(f"canari OK, refus attendu : {error}") + return + sys.exit("canari raté : la vérification a accepté un Raleway d'origine") + instances() + convert() + paths = [WOFF2 / f"{name}.woff2" for name in FILES.values()] + check(paths) + for path in paths: + print(f"{path.name} : famille Loksi, {path.stat().st_size} octets") + + +if __name__ == "__main__": + main() diff --git a/extensions/icons.mjs b/extensions/icons.mjs new file mode 100644 index 0000000..b8c2b78 --- /dev/null +++ b/extensions/icons.mjs @@ -0,0 +1,22 @@ +// GPL-3.0-only. Réutilise sharp verrouillé dans brand/package-lock.json. +import sharp from '../brand/node_modules/sharp/lib/index.js'; +import { readdir } from 'node:fs/promises'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +const root = fileURLToPath(new URL('.', import.meta.url)); +const { tag } = JSON.parse(readFileSync(`${root}upstream.json`)); +const dir = `${root}.cache/clients-${tag}/apps/browser/src/images`; +const source = `${root}../brand/loksi-icon.svg`; +for (const name of await readdir(dir)) { + const match = name.match(/^icon(\d+)(?:_gray|_locked)?(?:_beta)?\.png$/); + if (!match) continue; + const size = Number(match[1]); + let icon = sharp(source).resize(size, size); + if (name.includes('_gray')) icon = icon.greyscale(); + if (name.includes('_locked')) { + // Pastille d'état des illustrations : disque cyan, contour et barre blancs. Ni jaune ni rouge dans la charte. + const badge = Buffer.from(``); + icon = icon.composite([{ input: badge }]); + } + await icon.png().toFile(`${dir}/${name}`); +} diff --git a/extensions/licenses/ng-select-MIT.txt b/extensions/licenses/ng-select-MIT.txt new file mode 100644 index 0000000..97c793a --- /dev/null +++ b/extensions/licenses/ng-select-MIT.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) Andžej Maciusovič + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/extensions/licenses/protobuf-es-LICENSE b/extensions/licenses/protobuf-es-LICENSE new file mode 100644 index 0000000..0852eae --- /dev/null +++ b/extensions/licenses/protobuf-es-LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021-2026 Buf Technologies, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/extensions/licenses/signalr-MIT.txt b/extensions/licenses/signalr-MIT.txt new file mode 100644 index 0000000..984713a --- /dev/null +++ b/extensions/licenses/signalr-MIT.txt @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/extensions/loksi-coffre.test.cjs b/extensions/loksi-coffre.test.cjs new file mode 100644 index 0000000..8263a46 --- /dev/null +++ b/extensions/loksi-coffre.test.cjs @@ -0,0 +1,61 @@ +// GPL-3.0-only. Saisie du coffre Loksi : code client ou adresse complète, puis contrôle +// /api/config. *.loksi.fr n'existe pas encore : les réponses viennent de serveurs locaux. +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const http = require('node:http'); +const path = require('node:path'); +const config = require('./upstream.json'); +const ts = require(path.join(__dirname, '.cache', `clients-${config.tag}`, 'node_modules/typescript')); +const source = fs.readFileSync(path.join(__dirname, 'loksi-coffre.ts'), 'utf8'); +const compiled = ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } +}).outputText; +const mod = { exports: {} }; +new Function('module', 'exports', compiled)(mod, mod.exports); +const { loksiAdresse, loksiEstUnCoffre } = mod.exports; + +test('Un code client donne son coffre loksi.fr', () => { + assert.equal(loksiAdresse('abc'), 'https://abc.loksi.fr'); + assert.equal(loksiAdresse(' aleop '), 'https://aleop.loksi.fr'); + assert.equal(loksiAdresse('ab12cd34ef56'), 'https://ab12cd34ef56.loksi.fr'); + assert.equal(loksiAdresse('mon-entreprise'), 'https://mon-entreprise.loksi.fr'); + assert.equal(loksiAdresse('a'.repeat(20)), `https://${'a'.repeat(20)}.loksi.fr`); +}); +test('Une adresse complète en https reste acceptée', () => { + assert.equal(loksiAdresse('https://coffre.client.example/'), 'https://coffre.client.example'); + assert.equal(loksiAdresse('https://loksi.aleop.eu'), 'https://loksi.aleop.eu'); +}); +for (const refus of ['abc.evil.test', 'ABC/../x', 'http://abc.loksi.fr', 'a', 'a'.repeat(21), 'ABC', + '-abc', 'abc-', 'ab_c', 'ab c', 'é-corp', 'https://user:pw@x.example', 'https://x.example/?q=1', 'https://x.example/#a', + 'javascript:alert(1)', '', ' ']) { + test(`Canari refusé : ${JSON.stringify(refus)}`, () => { + assert.equal(loksiAdresse(refus), null); + }); +} + +function serveur(reponse) { + return new Promise((resolve) => { + const s = http.createServer((req, res) => { + if (req.url !== '/api/config') { res.statusCode = 404; return res.end(); } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(reponse)); + }); + s.listen(0, '127.0.0.1', () => resolve(s)); + }); +} +test('Un Vaultwarden local est reconnu comme coffre', async () => { + const s = await serveur({ version: '2026.6.0', server: { name: 'Vaultwarden', url: 'https://github.com/dani-garcia/vaultwarden' } }); + try { assert.equal(await loksiEstUnCoffre(`http://127.0.0.1:${s.address().port}`), true); } finally { s.close(); } +}); +test('Canari : un autre serveur qui répond du JSON est refusé', async () => { + const s = await serveur({ version: '2026.6.0', server: { name: 'Bitwarden' } }); + try { assert.equal(await loksiEstUnCoffre(`http://127.0.0.1:${s.address().port}`), false); } finally { s.close(); } +}); +test('Canari : une page sans /api/config est refusée', async () => { + const s = await serveur({}); + try { assert.equal(await loksiEstUnCoffre(`http://127.0.0.1:${s.address().port}/autre`), false); } finally { s.close(); } +}); +test('Canari : une adresse qui ne se résout pas est refusée', async () => { + assert.equal(await loksiEstUnCoffre('https://coffre-a-renseigner.invalid'), false); +}); diff --git a/extensions/loksi-coffre.ts b/extensions/loksi-coffre.ts new file mode 100644 index 0000000..eccab74 --- /dev/null +++ b/extensions/loksi-coffre.ts @@ -0,0 +1,56 @@ +// GPL-3.0-only. Adresse du coffre Loksi saisie à la connexion (décision du 04/10/2026). +// Copié par prototype.py à côté de self-hosted-env-config-dialog.component.ts. + +/** Domaine des coffres Loksi : le code client abc donne https://abc.loksi.fr. */ +export const LOKSI_DOMAINE = "loksi.fr"; + +// Le code est le nom choisi dans le tunnel de commande. Même motif que +// apps/backend/app/routers/loksi_order.py (_NOM) : 2 à 20 caractères, minuscules et +// chiffres, un tiret possible mais ni au début ni à la fin. Jamais interpolé tel quel : +// il passe ce motif ou il est refusé. Pas de point, pas de barre, pas de majuscule. +const CODE_CLIENT = /^[a-z0-9](?:[a-z0-9-]{0,18}[a-z0-9])$/; + +/** + * Adresse de base du coffre pour une saisie, ou null si la saisie est refusée. + * Un code client donne https://.loksi.fr. Sinon une adresse complète, en https, + * sans identifiant, paramètre ni ancre, pour un client qui a son propre domaine. + */ +export function loksiAdresse(saisie: string | null | undefined): string | null { + const valeur = (saisie ?? "").trim(); + if (CODE_CLIENT.test(valeur)) { + return "https://" + valeur + "." + LOKSI_DOMAINE; + } + if (!valeur.startsWith("https://")) { + return null; + } + let url: URL; + try { + url = new URL(valeur); + } catch { + return null; + } + if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) { + return null; + } + return (url.origin + url.pathname).replace(/\/+$/, ""); +} + +/** Vrai seulement si un serveur Vaultwarden répond sur /api/config à cette adresse. */ +export async function loksiEstUnCoffre( + base: string, + chercher: typeof fetch = fetch, +): Promise { + try { + const reponse = await chercher(base + "/api/config", { + headers: { Accept: "application/json" }, + credentials: "omit", + }); + if (!reponse.ok) { + return false; + } + const donnees = await reponse.json(); + return donnees?.server?.name === "Vaultwarden"; + } catch { + return false; + } +} diff --git a/extensions/prototype.py b/extensions/prototype.py new file mode 100644 index 0000000..5d925f3 --- /dev/null +++ b/extensions/prototype.py @@ -0,0 +1,976 @@ +#!/usr/bin/env python3 +"""Adaptations Loksi, GPL-3.0-only. Sources amont épinglées, jamais de patch crypto.""" +import base64 +import hashlib +import json +import os +import re +from pathlib import Path +import shutil +import subprocess +import sys +import tarfile + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "upstream.json").read_text()) +SOURCE = ROOT / ".cache" / ("clients-" + CONFIG["tag"]) +APP = SOURCE / "apps/browser" +# Premier tracé de LockIcon amont, présent dans le bundle tant que le dessin y est. +SIGNATURES = ROOT / ".cache" / "illustrations-amont.json" +LOKSI_ORIGINE = { + "fr": "Loksi, par Aleop. Extension de navigateur Bitwarden® modifiée par Aleop, sous licence " + "GPL v3. Aleop n'est pas affilié à Bitwarden Inc.", + "en": "Loksi, by Aleop. Bitwarden® browser extension modified by Aleop, under the GPL v3. " + "Aleop is not affiliated with Bitwarden Inc.", +} +LOKSI_AIDE = "https://www.aleop.eu/aide/loksi/" +LOKSI_PRODUIT = "https://www.aleop.eu/loksi/" +TEXTES_SERVEUR = { + "fr": {"loksiConnectingTo": "Connexion sur", "loksiAddressToEnter": "adresse à saisir", + "loksiVaultTitle": "Votre coffre Loksi", + "loksiNewClient": "Pas encore client ?", "loksiDiscover": "Découvrir Loksi", + "loksiVaultAddress": "Nom ou adresse de votre coffre", + "loksiVaultIntro": "Pour votre première connexion, indiquez votre coffre : remplacez « societe » " + "par le nom choisi à la commande, ou saisissez une autre adresse.", + "loksiReplaceCompany": "Remplacez « societe » par le nom de votre coffre.", + "loksiVaultAddressInvalid": "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": "Aucun coffre Loksi ne répond à cette adresse. Vérifiez le nom auprès de " + "votre administrateur.", + "selfHostedBaseUrlHint": "Vous pouvez aussi taper seulement le nom, par exemple mon-entreprise."}, + "en": {"loksiConnectingTo": "Logging in to", "loksiAddressToEnter": "address to enter", + "loksiVaultTitle": "Your Loksi vault", + "loksiNewClient": "Not a customer yet?", "loksiDiscover": "Discover Loksi", + "loksiVaultAddress": "Name or address of your vault", + "loksiVaultIntro": "For your first login, enter your vault: replace \"societe\" with the " + "name chosen when ordering, or enter another address.", + "loksiReplaceCompany": "Replace \"societe\" with the name of your vault.", + "loksiVaultAddressInvalid": "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://.", + "loksiNotAVault": "No Loksi vault answers at this address. Check the name with your " + "administrator.", + "selfHostedBaseUrlHint": "You can also type the name only, for example my-company."}, +} +UNSET = CONFIG["unset_server"] +MODELE_COFFRE = "https://societe.loksi.fr" +LOKSI_CONFIDENTIALITE = "https://www.aleop.eu/loksi/confidentialite/" +LOKSI_SUPPORT = "support@aleop.eu" +# Source GPL publiée de Loksi, citée par chaque appli avant les envois aux magasins +# (Romain, 12/10/2026). +LOKSI_SOURCE = "https://sources.gitsi.dev/aleop/loksi" +ABOUT_WEB_VAULT = """ + + + + + + + + +""" +ABOUT_METHODES = """ async launchPrivacy() { + await BrowserApi.createNewTab("https://www.aleop.eu/loksi/confidentialite/"); + } + + async launchSource() { + const confirmed = await this.dialogService.openSimpleDialog({ + title: { key: "loksiSourceTitle" }, + content: { key: "loksiSourceDesc" }, + type: "info", + acceptButtonText: { key: "continue" }, + }); + if (confirmed) { + await BrowserApi.createNewTab("https://sources.gitsi.dev/aleop/loksi"); + } + } + + async contactSupport() { + const confirmed = await this.dialogService.openSimpleDialog({ + title: { key: "loksiEmailSupport" }, + content: { key: "loksiEmailSupportDesc" }, + type: "info", + acceptButtonText: { key: "continue" }, + }); + if (confirmed) { + this.platformUtilsService.launchUri("mailto:support@aleop.eu"); + } + } + +""" +# Textes où Bitwarden reste : mention d'origine, produit tiers cité comme tel, et textes +# des seules pages « Plus de Bitwarden », « Télécharger les applications Bitwarden », +# aide et note du magasin, dont prepare retire l'accès. +BITWARDEN_GARDE = { + "loksiAboutOrigin", "loksiBasedOn", "authenticatorAppDescV2", "moreFromBitwarden", "continueToBitwardenDotCom", + "bitwardenForBusiness", "bitwardenForBusinessPageDesc", "bitwardenAuthenticator", + "continueToAuthenticatorPageDesc", "bitwardenSecretsManager", "continueToSecretsManagerPageDesc", + "continueToPasswordlessDotDevPageDesc", "freeBitwardenFamilies", "freeBitwardenFamiliesPageDesc", + "continueToBrowserExtensionStoreDesc", "downloadBitwarden", + "downloadBitwardenOnAllDevices", "getTheMobileAppDesc", "downloadFromBitwardenNow", + "downloadBitwardenApps", "premiumManageAlert", +} +CARROUSEL = { + "fr": {"introCarouselLabel": "Bienvenue sur Loksi", + "securityPrioritized": "Les accès de l'équipe, dans un coffre à vous", + "securityPrioritizedBody": "Identifiants, cartes et notes sont chiffrés sur votre appareil. " + "Le serveur ne voit jamais vos secrets en clair.", + "quickLogin": "Connexion en un geste", + "quickLoginBody": "Le déverrouillage biométrique et le remplissage automatique ouvrent vos " + "comptes sans rien taper.", + "secureUser": "Un mot de passe solide pour chaque compte", + "secureUserBody": "Le générateur les crée, Loksi les retient à votre place.", + "secureDevices": "Vos secrets, dans votre coffre, en France", + "secureDevicesBody": "Le même coffre sur votre téléphone, dans votre navigateur " + "et sur le coffre web de votre entreprise."}, + "en": {"introCarouselLabel": "Welcome to Loksi", + "securityPrioritized": "Your team's access, in a vault of your own", + "securityPrioritizedBody": "Logins, cards and notes are encrypted on your device. " + "The server never sees your secrets in clear text.", + "quickLogin": "Log in with one gesture", + "quickLoginBody": "Biometric unlock and autofill open your accounts without typing anything.", + "secureUser": "A strong password for every account", + "secureUserBody": "The generator creates them and Loksi remembers them for you.", + "secureDevices": "Your secrets, in your vault, in France", + "secureDevicesBody": "The same vault on your phone, in your browser " + "and on your company's web vault."}, +} +ONGLETS = ROOT.parent / "brand/illustrations-mobiles/onglets" +# Couleurs figées des pictogrammes d'onglets iOS (maîtres clairs), rendues aux variables +# du thème : l'actif suit le bouton (navy, cyan en sombre), le reste bascule par popup.scss. +ONGLET_COULEURS = {"#003087": "var(--color-fg-brand)", "#009CDE": "var(--loksi-onglet-accent)", + "#6B7A90": "var(--loksi-onglet-repos)"} +# Palette Bitwarden remplacée par celle de Loksi, par bloc de tw-theme.css : :root puis +# .theme_dark. Navy #003087 en clair, cyan #009CDE en sombre, comme les applis mobiles. +PALETTE = { + ":root {": { + "--color-background-alt2": "0 48 135", "--color-background-alt3": "0 38 109", + "--color-background-alt4": "0 21 64", + "--color-primary-100": "217 240 251", "--color-primary-300": "127 208 241", + "--color-primary-600": "0 48 135", "--color-primary-700": "0 38 109", + "--color-hover-default": "rgb(0 48 135 / 0.1)", + "--color-marketing-logo": "0 48 135", "--color-bw-blue": "0 48 135", + "--color-illustration-outline": "0 48 135", "--color-illustration-bg-primary": "217 240 251", + "--color-illustration-bg-secondary": "127 208 241", + "--color-illustration-tertiary": "0 156 222", "--color-illustration-logo": "0 48 135", + "--color-brand-050": "#eef8fd", "--color-brand-100": "#d9f0fb", "--color-brand-200": "#b3e2f6", + "--color-brand-300": "#7fd0f1", "--color-brand-400": "#009cde", "--color-brand-500": "#0079bd", + "--color-brand-600": "#0a55a6", "--color-brand-700": "#003087", + "--color-brand-700-rgb": "0, 48, 135", "--color-brand-800": "#00266d", + "--color-brand-900": "#001d54", "--color-brand-950": "#001540", + "--color-brand-800-rgb": "0, 38, 109", "--color-brand-950-rgb": "0, 21, 64", + }, + ".theme_dark {": { + "--color-primary-100": "0 29 84", "--color-primary-300": "0 121 189", + "--color-primary-600": "0 156 222", "--color-primary-700": "127 208 241", + "--color-hover-default": "rgb(127 208 241 / 0.1)", "--color-bw-blue": "0 48 135", + "--color-illustration-outline": "0 156 222", "--color-illustration-bg-primary": "127 208 241", + "--color-illustration-bg-secondary": "0 121 189", + "--color-illustration-tertiary": "31 191 245", + }, +} +# Fichier amont de libs/assets/src/svg/svgs : export remplacé, maître Loksi. +# Security et Party ne sont pas affichés dans la popup. +ILLUSTRATION_TABLE = { + "lock.icon.ts": ("LockIcon", "verrou"), + "user-lock.icon.ts": ("UserLockIcon", "verrou"), + "item-types.ts": ("ItemTypes", "coffre"), + "vault-open.ts": ("VaultOpen", "coffre"), + "login-cards.ts": ("LoginCards", "autofill"), + "no-credentials.icon.ts": ("NoCredentialsIcon", "generateur"), + "devices.icon.ts": ("DevicesIcon", "appareils"), + "user-verification-biometrics-fingerprint.icon.ts": ("UserVerificationBiometricsIcon", "biometrie"), + "no-folders.ts": ("NoFolders", "dossier-vide"), + "search-folder.ts": ("SearchFolder", "dossier-vide"), + "no-results.ts": ("NoResults", "recherche-vide"), + "empty-trash.ts": ("EmptyTrash", "corbeille"), + "no-send.icon.ts": ("NoSendsIcon", "send"), + "active-send.icon.ts": ("ActiveSendIcon", "send"), + "registration-check-email.icon.ts": ("RegistrationCheckEmailIcon", "email"), + "two-factor-auth-email.icon.ts": ("TwoFactorAuthEmailIcon", "email-code"), + "two-factor-timeout.icon.ts": ("TwoFactorTimeoutIcon", "delai-expire"), + "vault.icon.ts": ("VaultIcon", "securite"), + "deactivated-org.ts": ("DeactivatedOrg", "organisation"), + "account-warning.icon.ts": ("AccountWarning", "organisation"), + "domain.icon.ts": ("DomainIcon", "uri-bloquee"), +} +ILLUSTRATIONS = ROOT.parent / "brand/illustrations-mobiles/sources" + + +def write_json(path, value): + path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n") + + +def replace_once(path, old, new): + value = path.read_text() + if value.count(old) != 1: + raise RuntimeError(f"Point d'adaptation amont modifié : {path}") + path.write_text(value.replace(old, new)) + + +def replace_count(path, old, new, expected): + value = path.read_text() + if value.count(old) != expected: + raise RuntimeError(f"Point d'adaptation amont modifié : {path}") + path.write_text(value.replace(old, new)) + + +def theme_pair(clair, sombre, key): + """Dessins clair et sombre de la charte réunis en un seul SVG pour le gabarit svg`...`. + + L'amont colore ses dessins par classes que .theme_dark redéfinit ; ceux de Loksi + ont des couleurs en dur, d'où deux dessins dont popup.scss n'affiche qu'un. Les id + (g1, facestandalone...) se répètent d'un fichier à l'autre : préfixés, sinon un + dessin affiché irait chercher ses dégradés dans son jumeau masqué. + """ + parts = [] + for variant, path in (("clair", clair), ("sombre", sombre)): + drawing = path.read_text().strip() + if not drawing.startswith("") + 1] + tag = re.sub(r' (width|height|role|aria-label)="[^"]*"', "", opening) + tag = tag.replace("\n
\n' + ' {{ "loksiConnectingTo" | i18n }} :\n' + ' \n
\n' + ' @if (!(loksiHost$ | async)) {\n' + '
\n' + ' {{ "loksiNewClient" | i18n }}\n' + ' {{\n' + ' "loksiDiscover" | i18n\n }}\n' + '
\n }\n\n') + ts = Path(str(selector) + ".ts") + replace_once(ts, " private destroy$ = new Subject();\n", + " // Loksi : l'adresse du coffre saisi, rien tant que c'est le marqueur.\n" + " protected loksiHost$: Observable = this.environmentService.globalEnvironment$.pipe(\n" + " map((env) => (env.getUrls().base === " + json.dumps(UNSET) + " ? null : env.getHostname())),\n" + " );\n\n private destroy$ = new Subject();\n") + dialog = SOURCE / "libs/angular/src/auth/self-hosted-env-config-dialog/self-hosted-env-config-dialog.component.ts" + replace_once(dialog, ' baseUrl: urls.base || "",', + ' baseUrl: urls.base === ' + json.dumps(UNSET) + ' ? "" : urls.base || "",') + replace_once(SOURCE / "libs/angular/src/auth/self-hosted-env-config-dialog/self-hosted-env-config-dialog.component.html", + " Self-hosted environment", + '{{ "loksiVaultTitle" | i18n }}') + # Code client (étape 2, décision du 04/10/2026) : abc donne https://abc.loksi.fr, une + # adresse complète en https reste acceptée. Avant d'enregistrer, /api/config doit + # répondre comme un Vaultwarden. Logique dans extensions/loksi-coffre.ts, testée seule. + dialog_dir = SOURCE / "libs/angular/src/auth/self-hosted-env-config-dialog" + shutil.copy2(ROOT / "loksi-coffre.ts", dialog_dir / "loksi-coffre.ts") + dialog_ts = dialog_dir / "self-hosted-env-config-dialog.component.ts" + replace_once(dialog_ts, 'import { JslibModule } from "../../jslib.module";\n', + 'import { JslibModule } from "../../jslib.module";\n\n' + 'import { loksiAdresse, loksiEstUnCoffre } from "./loksi-coffre";\n') + replace_once(dialog_ts, + ' if (url && !url.startsWith("https://") && !platformUtilsService.isDev()) {\n' + ' return {\n onlyHttpsAllowed: {\n' + ' message: i18nService.t("selfHostedEnvMustUseHttps"),\n', + ' if (url && loksiAdresse(url) == null) {\n' + ' return {\n loksiAdresseRefusee: {\n' + ' message: i18nService.t("loksiVaultAddressInvalid"),\n') + replace_once(dialog_ts, " private destroy$ = new Subject();\n", + " private destroy$ = new Subject();\n private i18nService = inject(I18nService);\n") + replace_once(dialog_ts, + " await this.environmentService.setEnvironment(Region.SelfHosted, {\n" + " base: this.baseUrl.value,\n", + " const base = this.baseUrl.value ? loksiAdresse(this.baseUrl.value) : \"\";\n" + " if (base && !(await loksiEstUnCoffre(base))) {\n" + " this.baseUrl.setErrors({\n" + " loksiPasUnCoffre: { message: this.i18nService.t(\"loksiNotAVault\") },\n" + " });\n return;\n }\n\n" + " await this.environmentService.setEnvironment(Region.SelfHosted, {\n" + " base: base,\n") + replace_once(dialog_dir / "self-hosted-env-config-dialog.component.html", + ' {{ "baseUrl" | i18n }}', + ' {{ "loksiVaultAddress" | i18n }}') + # Premier lancement (Romain, 09/10/2026) : sur l'écran de connexion, tant qu'aucun + # coffre n'est saisi, la saisie s'ouvre d'elle-même. Le champ propose le modèle + # https://societe.loksi.fr, « societe » sélectionné : taper le nom le remplace. + replace_once(ts, 'import { Observable, Subject, map } from "rxjs";', + 'import { Observable, Subject, map, take } from "rxjs";') + replace_once(ts, " private destroy$ = new Subject();\n", + " private destroy$ = new Subject();\n\n" + " // Loksi : au premier affichage de la connexion sans coffre saisi, ouvrir la saisie.\n" + " private loksiPremiereSaisie = this.loksiHost$.pipe(take(1)).subscribe((host) => {\n" + " if (host == null && window.location.hash.startsWith(\"#/login\")) {\n" + " setTimeout(() => void this.toggle(Region.SelfHosted), 0);\n }\n });\n") + replace_once(dialog_ts, + ' baseUrl: urls.base === ' + json.dumps(UNSET) + ' ? "" : urls.base || "",', + ' baseUrl: urls.base === ' + json.dumps(UNSET) + ' ? ' + json.dumps(MODELE_COFFRE) + + ' : urls.base || "",') + replace_once(dialog_ts, " submit = async () => {\n", + " // Loksi : avec le modèle pré-rempli, « societe » est sélectionné, prêt à être remplacé.\n" + " ngAfterViewInit() {\n" + " setTimeout(() => {\n" + " const champ = document.getElementById(\"self_hosted_env_settings_form_input_base_url\");\n" + " if (champ instanceof HTMLInputElement && champ.value === " + json.dumps(MODELE_COFFRE) + ") {\n" + " champ.focus();\n" + " champ.setSelectionRange(8, 8 + \"societe\".length);\n" + " }\n }, 50);\n }\n\n" + " submit = async () => {\n") + replace_once(dialog_ts, + " const base = this.baseUrl.value ? loksiAdresse(this.baseUrl.value) : \"\";\n", + " if (this.baseUrl.value?.trim() === " + json.dumps(MODELE_COFFRE) + ") {\n" + " this.baseUrl.setErrors({\n" + " loksiModele: { message: this.i18nService.t(\"loksiReplaceCompany\") },\n" + " });\n return;\n }\n" + " const base = this.baseUrl.value ? loksiAdresse(this.baseUrl.value) : \"\";\n") + replace_once(dialog_dir / "self-hosted-env-config-dialog.component.html", + " \n {{ \"loksiVaultAddress\" | i18n }}", + "

\n" + " {{ \"loksiVaultIntro\" | i18n }}\n

\n" + " \n {{ \"loksiVaultAddress\" | i18n }}") + context_menu = APP / "src/autofill/browser/main-context-menu-handler.ts" + replace_once(context_menu, + ' {\n id: ROOT_ID,\n title: "Bitwarden",\n },\n', '') + # Edge et Chromium affichent déjà le nom natif de l'extension au-dessus de + # ces actions : supprimer le parent évite un deuxième niveau redondant. + replace_count(context_menu, ' parentId: ROOT_ID,\n', '', 12) + # Le titre de page devient le titre de la fenêtre détachée (popout) et le nom + # lu par les lecteurs d'écran sur les iframes du menu en ligne. + for page, old, new in ( + ("src/popup/index.ejs", "Bitwarden", "Loksi"), + ("src/sidepanel-disabled.html", "Bitwarden", "Loksi"), + ("src/autofill/notification/bar.html", "Bitwarden", "Loksi"), + ("src/platform/offscreen-document/index.html", "Bitwarden Offscreen Document", + "Loksi Offscreen Document"), + ("src/autofill/overlay/inline-menu/pages/button/button.html", "Bitwarden inline menu button", + "Loksi inline menu button"), + ("src/autofill/overlay/inline-menu/pages/list/list.html", "Bitwarden vault", "Loksi vault"), + ("src/autofill/overlay/inline-menu/pages/menu-container/menu-container.html", + "Bitwarden inline menu", "Loksi inline menu")): + replace_once(APP / page, "" + old + "", "" + new + "") + # Pas de création de compte : un compte Loksi est créé par l'administrateur de + # l'entreprise, et personne ne commence la relation commerciale par l'extension + # (Romain, 30/09/2026). Comme les applis mobiles. Le lien bitwarden.com/terms/ de + # l'écran d'inscription n'est plus atteignable. + carousel = APP / "src/vault/popup/components/vault/intro-carousel/intro-carousel.component.html" + html = carousel.read_text() + html, count = re.subn(r'\n', "", html, flags=re.S) + if count != 1: + raise RuntimeError("Carrousel amont modifié : navigateToSignup()") + html = html.replace(' buttonType="secondary"\n (click)="navigateToLogin()"\n class="tw-w-full tw-mt-2"', + ' buttonType="primary"\n (click)="navigateToLogin()"\n class="tw-w-full tw-mt-4"', 1) + if 'buttonType="primary"\n (click)="navigateToLogin()"' not in html: + raise RuntimeError("Carrousel amont modifié : navigateToLogin()") + carousel.write_text(html) + secondary = SOURCE / "libs/auth/src/angular/login/login-secondary-content.component.ts" + code = secondary.read_text() + code, count = re.subn(r' template: `\n
\n `,', + " template: ``,", code, flags=re.S) + if count != 1: + raise RuntimeError("Lien d'inscription amont modifié : login-secondary-content") + secondary.write_text(code) + # Sélecteur de serveur : plus de bitwarden.com ni bitwarden.eu, sans objet pour Loksi. + # Filtré dans la seule liste affichée (sélecteur, inscription) : la logique + # d'environnement garde ses régions, un état ancien sur US ne casse rien. + replace_once(SOURCE / "libs/common/src/platform/services/default-available-regions.service.ts", + ".filter((r) => r.key !== Region.Gov || govEnabled),", + ".filter((r) => r.key !== Region.Gov || govEnabled)\n" + " .filter((r) => r.key !== Region.US && r.key !== Region.EU),") + # Plus de Bitwarden sauf obligation (Romain, 09/10/2026). Inventaire et raisons dans + # README.md, « Ce qui garde bitwarden ». L'hôte de messagerie native est celui que le + # bureau Loksi écoute : sans lui, pas de déverrouillage biométrique par le bureau. + for path in ("src/background/nativeMessaging.background.ts", + "src/platform/ipc/transports/desktop-ipc.transport.ts"): + replace_once(APP / path, 'BrowserApi.connectNative("com.8bit.bitwarden")', + 'BrowserApi.connectNative(' + json.dumps(CONFIG["native_host"]) + ')') + replace_once(SOURCE / "libs/tools/export-vault-core/src/services/export-helper.ts", + 'return "bitwarden" + (prefix', 'return "loksi" + (prefix') + replace_count(SOURCE / "libs/logging/src/flight-recorder-export.ts", + "Bitwarden-diagnostic-report-", "Loksi-diagnostic-report-", 2) + # Classe posée sur les champs remplis, visible des sites dans leur propre page. + replace_count(APP / "src/autofill/content/autofill.css", "com-bitwarden-browser-animated-fill", + "com-loksi-browser-animated-fill", 3) + replace_count(APP / "src/autofill/services/insert-autofill-content.service.ts", + '"com-bitwarden-browser-animated-fill"', '"com-loksi-browser-animated-fill"', 2) + # Mots qui affaiblissent un mot de passe : le nom du produit en fait partie. + replace_once(SOURCE / "libs/common/src/tools/password-strength/password-strength.service.ts", + ' "bitwarden",\n', ' "loksi",\n') + # Tailwind ne cherche plus de classes dans bitwarden_license (code sous licence non + # libre, jamais compilé ici) : sinon le CSS en tirait 5 classes que l'archive de + # sources, qui exclut ce dossier, ne reproduisait pas (relevé le 10/10/2026). + replace_once(APP / "tailwind.config.js", + ' path.resolve(__dirname, "../../bitwarden_license/bit-browser/src/**/*.{html,ts,mdx}"),\n', "") + # Entrées qui n'ouvrent que des offres, magasins et aides Bitwarden : retirées. + settings = APP / "src/tools/popup/settings/settings-v2.component.html" + html = settings.read_text() + for route in ("/download-bitwarden", "/more-from-bitwarden"): + html, count = re.subn(r' \n \n', "", html, flags=re.S) + if count != 1: + raise RuntimeError("Entrée de paramètres amont modifiée : " + route) + settings.write_text(html) + about_page = APP / "src/tools/popup/settings/about-page/about-page-v2.component.html" + html = about_page.read_text() + for handler in ("rate()",): + html, count = re.subn(r' \n