Loksi 2026.10.0 (Android 3) : source correspondante

Export du dépôt interne d'Aleop, révision 5fbb921.
Cette révision appartient à :
Aleop a révisé 2026-10-09 22:14:30 +02:00
révision c3608b3938
91 fichiers modifiés
+7297

Aucun fichier ne correspond à votre recherche

+385
Voir le fichier
@@ -0,0 +1,385 @@
#!/usr/bin/env python3
"""Ressources vectorielles Loksi pour Android, GPL-3.0-only.
Tout part des fichiers de la charte adoptée le 28/09/2026 :
- brand/loksi-icon.svg, l'icône sculptée ;
- brand/sources/loksi-logo-{clair,sombre}.svg, icône et mot déjà en tracés ;
- brand/sources/loksi-icon-mono.svg, pour la couche monochrome.
Les SVG sont convertis en VectorDrawable par un convertisseur limité à ce que la
charte emploie : groupes translate et scale, rect arrondi, path, circle, dégradés
linéaires et radiaux. Tout autre élément ou attribut le fait échouer : c'est le
canari de structure. Les filtres (ombres floues) n'existent pas en VectorDrawable,
ils sont retirés et comptés. La géométrie des ombres dures (socle décalé, copie
foncée du symbole) reste. L'icône du lanceur, qui garde ses ombres, est en PNG par
densité, rendue par Chromium (render.mjs).
"""
import re
import xml.etree.ElementTree as ET
from pathlib import Path
NAVY = "#003087"
SVG = "{http://www.w3.org/2000/svg}"
HEADER = ('xmlns:android="http://schemas.android.com/apk/res/android"\n'
' xmlns:aapt="http://schemas.android.com/aapt"')
TRANSFORM = re.compile(r"(?:translate\(([-\d.]+)[ ,]+([-\d.]+)\))?\s*(?:scale\(([-\d.]+)(?:[ ,]+([-\d.]+))?\))?")
# Rotation autour d'un point, seule forme employée par les illustrations de la charte.
ROTATE = re.compile(r"rotate\(([-\d.]+)[ ,]+([-\d.]+)[ ,]+([-\d.]+)\)")
# Attributs admis par élément. Un attribut inconnu est un changement de la charte.
ALLOWED = {
"svg": {"viewBox", "role", "aria-label", "width", "height"},
"g": {"transform", "fill", "filter"},
"rect": {"x", "y", "width", "height", "rx", "fill", "stroke", "stroke-width", "filter", "mask"},
"path": {"d", "fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap",
"stroke-linejoin", "transform"},
"circle": {"cx", "cy", "r", "fill"},
}
def number(value):
value = float(value)
return f"{0.0 if abs(value) < 5e-5 else value:.4f}".rstrip("0").rstrip(".")
def argb(color, opacity=1.0):
color = color.strip().upper()
if not re.fullmatch(r"#[0-9A-F]{3}|#[0-9A-F]{6}", color):
raise RuntimeError(f"Couleur SVG non prise en charge : {color}")
if len(color) == 4:
color = "#" + "".join(c * 2 for c in color[1:])
return "#%02X%s" % (round(float(opacity) * 255), color[1:])
def percent(value, default):
value = default if value is None else value
return float(value[:-1]) / 100 if value.endswith("%") else float(value)
def path_bounds(d):
from fontTools.pens.boundsPen import BoundsPen
from fontTools.svgLib.path import parse_path
pen = BoundsPen(None)
parse_path(d, pen)
return pen.bounds
class Converter:
def __init__(self, svg_text, white=False):
self.root = ET.fromstring(svg_text)
self.white = white
self.dropped_filters = 0
self.gradients = {}
for tag in ("linearGradient", "radialGradient"):
for node in self.root.iter(SVG + tag):
stops = [(float(s.get("offset", "0")), argb(s.get("stop-color"), s.get("stop-opacity", "1")))
for s in node.findall(SVG + "stop")]
self.gradients[node.get("id")] = (tag, node.attrib, stops)
def paint(self, attribute, value, bounds):
"""Couleur ou dégradé VectorDrawable pour fillColor ou strokeColor."""
if value.startswith("url(#"):
if self.white:
return f'android:{attribute}="#FFFFFFFF"', ""
tag, attrib, stops = self.gradients[value[5:-1]]
x0, y0, x1, y1 = bounds
w, h = x1 - x0, y1 - y0
if attrib.get("gradientUnits") == "userSpaceOnUse":
# Coordonnées absolues dans le repère de la forme, comme en VectorDrawable.
if tag != "linearGradient":
raise RuntimeError("Dégradé radial en userSpaceOnUse non pris en charge")
geometry = " ".join(f'android:{a}="{number(attrib[k])}"' for a, k in
(("startX", "x1"), ("startY", "y1"), ("endX", "x2"), ("endY", "y2")))
items = "".join(f'\n <item android:offset="{number(o)}" android:color="{c}"/>'
for o, c in stops)
return "", (f'\n <aapt:attr name="android:{attribute}">\n'
f' <gradient android:type="linear" {geometry}>{items}\n </gradient>\n'
f' </aapt:attr>')
elif attrib.get("gradientUnits") not in (None, "objectBoundingBox"):
raise RuntimeError(f"gradientUnits non pris en charge : {attrib.get('gradientUnits')}")
if tag == "linearGradient":
geometry = (f'android:type="linear" android:startX="{number(x0 + w * percent(attrib.get("x1"), "0%"))}" '
f'android:startY="{number(y0 + h * percent(attrib.get("y1"), "0%"))}" '
f'android:endX="{number(x0 + w * percent(attrib.get("x2"), "100%"))}" '
f'android:endY="{number(y0 + h * percent(attrib.get("y2"), "0%"))}"')
else:
if "fx" in attrib or "fy" in attrib or abs(w - h) > 0.01:
raise RuntimeError("Dégradé radial non pris en charge (foyer ou boîte non carrée)")
geometry = (f'android:type="radial" android:centerX="{number(x0 + w * percent(attrib.get("cx"), "50%"))}" '
f'android:centerY="{number(y0 + h * percent(attrib.get("cy"), "50%"))}" '
f'android:gradientRadius="{number(w * percent(attrib.get("r"), "50%"))}"')
items = "".join(f'\n <item android:offset="{number(o)}" android:color="{c}"/>' for o, c in stops)
return "", (f'\n <aapt:attr name="android:{attribute}">\n'
f' <gradient {geometry}>{items}\n </gradient>\n </aapt:attr>')
return f'android:{attribute}="{"#FFFFFFFF" if self.white else argb(value)}"', ""
def group(self, transform, children):
if not transform:
return children
rotation = ROTATE.fullmatch(transform.strip())
if rotation:
angle, px, py = rotation.groups()
return ([f'<group android:rotation="{number(angle)}" android:pivotX="{number(px)}" android:pivotY="{number(py)}">']
+ [" " + line for line in children] + ["</group>"])
match = TRANSFORM.fullmatch(transform.strip())
if not match:
raise RuntimeError(f"Transformation SVG non prise en charge : {transform}")
tx, ty, sx, sy = match.groups()
attributes = []
if tx is not None:
attributes += [f'android:translateX="{number(tx)}"', f'android:translateY="{number(ty)}"']
if sx is not None:
attributes += [f'android:scaleX="{number(sx)}"', f'android:scaleY="{number(sy if sy is not None else sx)}"']
return [f'<group {" ".join(attributes)}>'] + [" " + line for line in children] + ["</group>"]
def shape(self, d, bounds, attrib, fill):
attributes, inner = [], ""
if fill != "none":
a, i = self.paint("fillColor", fill, bounds)
attributes.append(a)
inner += i
if "fill-opacity" in attrib:
attributes.append(f'android:fillAlpha="{number(attrib["fill-opacity"])}"')
if "fill-rule" in attrib:
if attrib["fill-rule"] != "evenodd":
raise RuntimeError(f"fill-rule non pris en charge : {attrib['fill-rule']}")
attributes.append('android:fillType="evenOdd"')
stroke = attrib.get("stroke")
if stroke and stroke != "none":
a, i = self.paint("strokeColor", stroke, bounds)
attributes.append(a)
inner += i
attributes.append(f'android:strokeWidth="{number(attrib.get("stroke-width", "1"))}"')
if "stroke-opacity" in attrib:
attributes.append(f'android:strokeAlpha="{number(attrib["stroke-opacity"])}"')
if "stroke-linecap" in attrib:
attributes.append(f'android:strokeLineCap="{attrib["stroke-linecap"]}"')
if "stroke-linejoin" in attrib:
attributes.append(f'android:strokeLineJoin="{attrib["stroke-linejoin"]}"')
attributes = " ".join(a for a in attributes if a)
if inner:
return [f'<path android:pathData="{d}" {attributes}>{inner}\n </path>']
return [f'<path android:pathData="{d}" {attributes}/>']
def walk(self, node, fill):
tag = node.tag.replace(SVG, "")
if tag == "defs":
return []
if tag not in ALLOWED:
raise RuntimeError(f"Élément SVG non pris en charge : {tag}")
unknown = set(node.attrib) - ALLOWED[tag]
if unknown or "mask" in node.attrib:
raise RuntimeError(f"Attributs SVG non pris en charge sur {tag} : {sorted(unknown) or ['mask']}")
if "filter" in node.attrib:
self.dropped_filters += 1
fill = node.get("fill", fill)
if tag in ("svg", "g"):
children = [line for child in node for line in self.walk(child, fill)]
return self.group(node.get("transform"), children)
if tag == "rect":
x, y = float(node.get("x", 0)), float(node.get("y", 0))
w, h, r = float(node.get("width")), float(node.get("height")), float(node.get("rx", 0))
d = (f"M{number(x + r)},{number(y)}H{number(x + w - r)}A{number(r)},{number(r)} 0 0 1 {number(x + w)},{number(y + r)}"
f"V{number(y + h - r)}A{number(r)},{number(r)} 0 0 1 {number(x + w - r)},{number(y + h)}"
f"H{number(x + r)}A{number(r)},{number(r)} 0 0 1 {number(x)},{number(y + h - r)}"
f"V{number(y + r)}A{number(r)},{number(r)} 0 0 1 {number(x + r)},{number(y)}Z")
return self.shape(d, (x, y, x + w, y + h), node.attrib, fill)
if tag == "circle":
cx, cy, r = (float(node.get(k)) for k in ("cx", "cy", "r"))
d = (f"M{number(cx - r)},{number(cy)}A{number(r)},{number(r)} 0 1 0 {number(cx + r)},{number(cy)}"
f"A{number(r)},{number(r)} 0 1 0 {number(cx - r)},{number(cy)}Z")
return self.shape(d, (cx - r, cy - r, cx + r, cy + r), node.attrib, fill)
d = node.get("d")
return self.group(node.get("transform"), self.shape(d, path_bounds(d), node.attrib, fill))
def vector(self, width_dp, height_dp, viewbox=None, subtree=None):
"""VectorDrawable du SVG entier, ou du seul sous-arbre dont le transform est donné,
ancêtres compris. viewbox (x, y, largeur, hauteur) remplace celui du SVG."""
if viewbox is None:
viewbox = tuple(float(v) for v in self.root.get("viewBox").split())
if subtree is not None:
parents = {child: parent for parent in self.root.iter() for child in parent}
found = [n for n in self.root.iter() if n.get("transform") == subtree]
if len(found) != 1:
raise RuntimeError(f"Sous-arbre « {subtree} » : {len(found)} trouvés, 1 attendu")
keep, node = found[0], found[0]
while node is not self.root:
node = parents[node]
for sibling in list(node):
if sibling is not keep and sibling.tag != SVG + "defs":
node.remove(sibling)
keep = node
body = self.walk(self.root, "#000")
if not body:
raise RuntimeError("SVG vide après conversion")
x, y, w, h = viewbox
lines = "\n ".join(body)
return (f'<vector {HEADER}\n android:width="{number(width_dp)}dp"\n android:height="{number(height_dp)}dp"\n'
f' android:viewportWidth="{number(w)}"\n android:viewportHeight="{number(h)}">\n'
f' <group android:translateX="{number(-x)}" android:translateY="{number(-y)}">\n'
f' {lines}\n </group>\n</vector>\n')
# Carré de l'icône dans le repère de brand/loksi-icon.svg : translate(7 2) scale(.86).
SQUARE = (7.0, 2.0, 86.0)
SYMBOL = "translate(3 0) scale(.94)"
def adaptive(square):
"""Repère 108 dp d'une icône adaptative : le carré occupe les 72 dp visibles du centre."""
x, y, side = square
return (x - side / 4, y - side / 4, side * 1.5, side * 1.5)
def monochrome(mono_text):
"""Couche monochrome : le symbole seul, pris dans le masque de loksi-icon-mono.svg,
en blanc plein. Le système pose son fond et teinte la couche."""
root = ET.fromstring(mono_text)
masks = root.findall(f".//{SVG}mask")
if len(masks) != 1:
raise RuntimeError("loksi-icon-mono.svg : un masque attendu")
groups = masks[0].findall(SVG + "g")
if len(groups) != 1 or len(list(groups[0])) != 3:
raise RuntimeError("loksi-icon-mono.svg : le masque doit porter un groupe de 3 tracés")
ET.register_namespace("", SVG[1:-1])
symbol = ET.tostring(groups[0], encoding="unicode")
svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">{symbol}</svg>'
return Converter(svg, white=True).vector(108, 108, viewbox=adaptive((0.0, 0.0, 100.0)))
def write_all(src, brand):
"""Écrit les ressources vectorielles. Chaque cible existe déjà en amont, sauf le logo sombre."""
brand = Path(brand)
icon = (brand / "loksi-icon.svg").read_text()
written, dropped = [], 0
def put(relative, content, must_exist=True):
path = src / relative
if must_exist and not path.is_file():
raise RuntimeError(f"Ressource amont absente : {relative}")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
written.append(relative)
def convert(svg_text, *args, **kwargs):
nonlocal dropped
converter = Converter(svg_text)
result = converter.vector(*args, **kwargs)
dropped += converter.dropped_filters
return result
mono = monochrome((brand / "sources/loksi-icon-mono.svg").read_text())
for variant in ("main", "beta", "release"):
# Premier plan du lanceur : PNG par densité (render.mjs), enveloppé ici.
put(f"app/src/{variant}/res/drawable/ic_launcher_foreground.xml",
'<?xml version="1.0" encoding="utf-8"?>\n'
'<!-- Loksi : symbole sculpté, PNG par densité rendu par mobile/android/render.mjs. -->\n'
'<bitmap xmlns:android="http://schemas.android.com/apk/res/android"\n'
' android:src="@drawable/loksi_launcher_foreground" />\n')
put(f"app/src/{variant}/res/drawable/ic_launcher_monochrome.xml", mono)
# Écran de démarrage : le symbole seul sur le fond navy, repère de l'icône adaptative.
put("ui/src/main/res/drawable/logo_shield_icon.xml",
convert(icon, 108, 108, viewbox=adaptive(SQUARE), subtree=SYMBOL))
# Remplissage automatique et échange d'identifiants : le carré, sans marge d'ombre.
put("ui/src/main/res/drawable/logo_bitwarden_icon.xml",
convert(icon, 64, 64, viewbox=(SQUARE[0], SQUARE[1], SQUARE[2], SQUARE[2])))
# Logo complet : 44 dp de haut comme sur iOS, cadre de la charte (marges d'ombre comprises).
for variant, relative, must_exist in (("clair", "drawable", True), ("sombre", "drawable-night", False)):
svg_text = (brand / f"sources/loksi-logo-{variant}.svg").read_text()
_, _, w, h = (float(v) for v in re.search(r'viewBox="([^"]+)"', svg_text).group(1).split())
put(f"ui/src/main/res/{relative}/logo_bitwarden.xml", convert(svg_text, round(44 * w / h), 44), must_exist)
background = src / "app/src/main/res/values/ic_launcher_background.xml"
value = background.read_text()
if value.count("#FF175DDC") != 1:
raise RuntimeError("Couleur de fond d'icône amont modifiée")
background.write_text(value.replace("#FF175DDC", "#FF" + NAVY[1:]))
written.append("app/src/main/res/values/ic_launcher_background.xml")
# Canari : icône et deux logos portent chacun deux filtres (socle et symbole) ; le
# symbole seul en porte un. Un autre compte veut dire que la charte a changé.
if dropped != 7:
raise RuntimeError(f"Filtres retirés : {dropped}, 7 attendus")
return written
# Illustrations de la charte (brand/illustrations-mobiles/, style validé par Romain le
# 29/09/2026). Chaque ill_* amont est remplacé sous le même nom par le maître clair, et un
# ill_* du même nom dans drawable-night reçoit le maître sombre : l'amont n'a qu'une
# variante, recolorée par des chemins nommés, les maîtres Loksi ont leurs couleurs en dur.
# La correspondance vient de brand/illustrations-mobiles/correspondance.mjs, colonne Android.
# Hors jeu : Premium (ill_celebration) et ill_vault, que le code amont n'affiche pas.
OUT_OF_SET = {"ill_celebration", "ill_vault"}
def android_set(brand):
"""{drawable amont: maître Loksi}, lu dans la colonne Android de correspondance.mjs."""
text = (Path(brand) / "illustrations-mobiles/correspondance.mjs").read_text()
quoted = r"'((?:[^'\\]|\\.)*)'"
rows = re.findall(r"\[\s*" + r",\s*".join([quoted] * 5) + r"\s*\]", text)
if len(rows) < 20:
raise RuntimeError(f"correspondance.mjs illisible : {len(rows)} lignes")
mapping = {}
for name, _, _, android, _ in rows:
for drawable in re.findall(r"ill_\w+", android):
if drawable in mapping:
raise RuntimeError(f"{drawable} attribué deux fois dans correspondance.mjs")
mapping[drawable] = name
return mapping
def write_illustrations(src, brand):
brand = Path(brand)
res = src / "ui/src/main/res"
upstream = {p.stem for p in (res / "drawable").glob("ill_*.xml")}
mapping = android_set(brand)
# Toute illustration amont est remplacée ou écartée exprès ; toute cible existe en amont.
if set(mapping) | OUT_OF_SET != upstream or set(mapping) & OUT_OF_SET:
raise RuntimeError(f"Illustrations amont non couvertes : {sorted(upstream - set(mapping) - OUT_OF_SET)}, "
f"absentes de l'amont : {sorted(set(mapping) - upstream)}")
written, evenodd = [], 0
for drawable, name in sorted(mapping.items()):
size = float(re.search(r'android:width="([\d.]+)dp"', (res / f"drawable/{drawable}.xml").read_text()).group(1))
for variant, folder in (("clair", "drawable"), ("sombre", "drawable-night")):
svg_text = (brand / f"illustrations-mobiles/sources/{name}-{variant}.svg").read_text()
converter = Converter(svg_text)
vector = converter.vector(size, size)
if converter.dropped_filters:
raise RuntimeError(f"{name}-{variant}.svg : filtre dans un maître d'illustration")
if vector.count('android:fillType="evenOdd"') != svg_text.count('fill-rule="evenodd"'):
raise RuntimeError(f"{name}-{variant}.svg : évidement perdu à la conversion")
evenodd += svg_text.count('fill-rule="evenodd"')
(res / folder).mkdir(exist_ok=True)
(res / folder / f"{drawable}.xml").write_text(vector)
written.append(f"{folder}/{drawable}.xml")
return written, evenodd
# Barre d'onglets : pictogrammes de la charte (brand/illustrations-mobiles/onglets/). Actif :
# formes pleines aux couleurs de la charte, clair dans drawable, sombre dans drawable-night,
# affichées sans teinte par l'amont (icônes multitons). Inactif : au trait, teinté par le
# thème (icon.primary), la variante claire suffit.
TABS = {"vault": "ic_vault", "generator": "ic_generator", "send": "ic_send", "settings": "ic_settings"}
def write_tab_icons(src, brand):
res = src / "ui/src/main/res"
sources = Path(brand) / "illustrations-mobiles/onglets"
written, evenodd = [], 0
for tab, drawable in TABS.items():
for state, name, variants in (("idle", drawable, (("light", "drawable"),)),
("active", drawable + "_filled", (("light", "drawable"), ("dark", "drawable-night")))):
if not (res / f"drawable/{name}.xml").is_file():
raise RuntimeError(f"Pictogramme amont absent : {name}")
for theme, folder in variants:
svg_text = (sources / f"{tab}-{state}-{theme}.svg").read_text()
vector = Converter(svg_text).vector(24, 24)
if vector.count('android:fillType="evenOdd"') != svg_text.count('fill-rule="evenodd"'):
raise RuntimeError(f"{tab}-{state}-{theme}.svg : évidement perdu à la conversion")
evenodd += svg_text.count('fill-rule="evenodd"')
(res / folder / f"{name}.xml").write_text(vector)
written.append(f"{folder}/{name}.xml")
if len(written) != 12:
raise RuntimeError(f"12 pictogrammes attendus, {len(written)}")
# Canari : la roue et le coffre ont des évidements (fill-rule evenodd). Sans aucun,
# le contrôle de conversion ci-dessus ne prouve rien.
if not evenodd:
raise RuntimeError("Canari muet : aucun évidement dans les pictogrammes")
return written, evenodd
+86
Voir le fichier
@@ -0,0 +1,86 @@
// GPL-3.0-only. Loksi: vault name or address entered at login (decision of 04/10/2026).
// Copied by mobile/android/loksi.py next to EnvironmentUrlDataJsonExtensions.kt. Same rule
// as the Loksi browser extension (extensions/loksi-coffre.ts).
package com.bitwarden.data.repository.util
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
/**
* Loksi: domain of the Loksi vaults. The vault name "abc" gives https://abc.loksi.fr.
*/
const val LOKSI_DOMAIN: String = "loksi.fr"
// The name chosen in the order funnel: same pattern as the order backend (_NOM), 2 to 20
// lowercase letters or digits, a hyphen allowed but neither first nor last. Never
// interpolated as typed: it matches this pattern or it is refused.
private val LOKSI_VAULT_NAME = Regex("^[a-z0-9](?:[a-z0-9-]{0,18}[a-z0-9])$")
private const val LOKSI_TIMEOUT_MS: Int = 10_000
/**
* Loksi: base address of the vault for what was typed, or null if it is refused.
* A vault name gives https://<name>.loksi.fr. Otherwise a full https address without
* credentials, query or fragment, for a customer with their own domain.
*/
fun loksiVaultAddress(input: String?): String? {
val value = input.orEmpty().trim()
if (LOKSI_VAULT_NAME.matches(value)) {
return "https://$value.$LOKSI_DOMAIN"
}
if (!value.startsWith("https://")) {
return null
}
val uri = try {
URI(value)
} catch (_: Exception) {
return null
}
if (uri.scheme != "https" || uri.host.isNullOrEmpty() || uri.rawUserInfo != null ||
uri.rawQuery != null || uri.rawFragment != null
) {
return null
}
val port = if (uri.port == -1) "" else ":${uri.port}"
return "https://${uri.host}$port${uri.rawPath.orEmpty()}".trimEnd('/')
}
/**
* Loksi: true only if a Vaultwarden server answers on /api/config at [base].
* [fetch] returns the body of a successful GET, or null.
*/
suspend fun isLoksiVault(
base: String,
fetch: suspend (String) -> String? = ::loksiGet,
): Boolean =
try {
val body = fetch("$base/api/config")
body != null &&
Json.parseToJsonElement(body).jsonObject["server"]
?.jsonObject?.get("name")?.jsonPrimitive?.content == "Vaultwarden"
} catch (_: Exception) {
false
}
private suspend fun loksiGet(url: String): String? = withContext(Dispatchers.IO) {
val connection = URL(url).openConnection() as HttpURLConnection
try {
connection.connectTimeout = LOKSI_TIMEOUT_MS
connection.readTimeout = LOKSI_TIMEOUT_MS
connection.instanceFollowRedirects = false
connection.setRequestProperty("Accept", "application/json")
if (connection.responseCode == HttpURLConnection.HTTP_OK) {
connection.inputStream.bufferedReader().use { it.readText() }
} else {
null
}
} finally {
connection.disconnect()
}
}
+93
Voir le fichier
@@ -0,0 +1,93 @@
// GPL-3.0-only. Loksi: vault name or address, then /api/config. *.loksi.fr does not exist
// yet: the answers come from local servers, as for the browser extension.
package com.bitwarden.data.repository.util
import com.sun.net.httpserver.HttpServer
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.net.InetSocketAddress
class LoksiVaultTest {
@Test
fun `a vault name gives its loksi fr vault`() {
assertEquals("https://abc.loksi.fr", loksiVaultAddress("abc"))
assertEquals("https://aleop.loksi.fr", loksiVaultAddress(" aleop "))
assertEquals("https://ab12cd34ef56.loksi.fr", loksiVaultAddress("ab12cd34ef56"))
assertEquals("https://mon-entreprise.loksi.fr", loksiVaultAddress("mon-entreprise"))
assertEquals("https://${"a".repeat(20)}.loksi.fr", loksiVaultAddress("a".repeat(20)))
}
@Test
fun `a full https address is still accepted`() {
assertEquals("https://coffre.client.example", loksiVaultAddress("https://coffre.client.example/"))
assertEquals("https://loksi.aleop.eu", loksiVaultAddress("https://loksi.aleop.eu"))
assertEquals("https://x.example:8443/coffre", loksiVaultAddress("https://x.example:8443/coffre/"))
}
@Test
fun `canaries are refused`() {
listOf(
"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)", "",
" ", "https://", null,
).forEach { refused ->
assertNull(loksiVaultAddress(refused), "accepted: $refused")
}
}
private fun server(body: String?): HttpServer =
HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
createContext("/") { exchange ->
val answer = body?.takeIf { exchange.requestURI.path == "/api/config" }
if (answer == null) {
exchange.sendResponseHeaders(404, -1)
} else {
val bytes = answer.toByteArray()
exchange.responseHeaders.add("Content-Type", "application/json")
exchange.sendResponseHeaders(200, bytes.size.toLong())
exchange.responseBody.use { it.write(bytes) }
}
exchange.close()
}
start()
}
private fun <T> withServer(body: String?, block: suspend (String) -> T): T {
val running = server(body)
return try {
runBlocking { block("http://127.0.0.1:${running.address.port}") }
} finally {
running.stop(0)
}
}
@Test
fun `a local Vaultwarden is recognised as a vault`() {
assertTrue(withServer("""{"version":"2026.6.0","server":{"name":"Vaultwarden"}}""") { isLoksiVault(it) })
}
@Test
fun `canary, another server answering JSON is refused`() {
assertFalse(withServer("""{"version":"2026.6.0","server":{"name":"Bitwarden"}}""") { isLoksiVault(it) })
}
@Test
fun `canary, a page without api config is refused`() {
assertFalse(withServer(null) { isLoksiVault(it) })
}
@Test
fun `canary, a body that is not JSON is refused`() {
assertFalse(withServer("<html>Vaultwarden</html>") { isLoksiVault(it) })
}
@Test
fun `canary, an address that does not resolve is refused`() {
assertFalse(runBlocking { isLoksiVault("https://coffre-a-renseigner.invalid") })
}
}
+1645
Voir le fichier
Diff désactivé car ce fichier est trop long. Voir la Diff
+73
Voir le fichier
@@ -0,0 +1,73 @@
/**
* Icône adaptative de l'application Android Loksi, rendue par Chromium depuis brand/.
*
* node render.mjs <dossier de sortie>
*
* Deux couches de 108 dp par densité (mdpi à xxxhdpi), tirées de l'icône sculptée
* (brand/icones.mjs, export `sculpte`) :
* - loksi_launcher_background.png : la face, dégradé et lumière, pleine page. Le
* liseré et le reflet d'angle suivent l'arrondi de la charte et sont laissés : le
* lanceur pose sa propre forme ;
* - loksi_launcher_foreground.png : le symbole avec son ombre portée (feDropShadow),
* ce qu'un VectorDrawable ne sait pas dessiner.
* Le carré 100 de la charte occupe les 72 dp visibles du centre, le symbole tient dans
* le cercle sûr de 66 dp.
*
* Chaque retouche du maître doit tomber exactement une fois : sinon la charte a
* changé de forme et le rendu s'arrête. Lancé par loksi.py depuis mobile/.cache/node,
* où playwright est installé à la version de brand/package-lock.json.
*/
import { mkdirSync } from 'fs';
import { join, dirname, resolve } from 'path';
import { fileURLToPath } 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');
const { chromium } = createRequire(join(process.cwd(), 'package.json'))('playwright');
const { sculpte } = await import(join(brand, 'icones.mjs'));
const une = (s, motif, quoi) => {
const trouves = s.match(new RegExp(motif, 'g')) ?? [];
if (trouves.length !== 1) throw new Error(`icône Android : « ${quoi} » trouvé ${trouves.length} fois, 1 attendu`);
return trouves[0];
};
const defs = une(sculpte, '<defs>[\\s\\S]*?</defs>', 'defs');
// La face et sa lumière passent en coordonnées utilisateur, sur le carré 0 à 100 :
// le dégradé reste celui du carré et se prolonge (pad) jusqu'aux bords du calque.
let fondDefs = defs;
for (const id of ['facestandalone', 'lightstandalone']) {
const balise = une(fondDefs, `<(linear|radial)Gradient id="${id}"[^>]*>`, id);
fondDefs = fondDefs.replace(balise, balise.replace(/="(-?[\d.]+)%"/g, '="$1"').replace('>', ' gradientUnits="userSpaceOnUse">'));
}
une(sculpte, '<rect width="100" height="100" rx="24" fill="url\\(#facestandalone\\)"/>', 'face');
une(sculpte, '<rect width="100" height="100" rx="24" fill="url\\(#lightstandalone\\)"/>', 'lumière');
const debut = sculpte.indexOf('<g transform="translate(3 0) scale(.94)" filter="url(#caststandalone)">');
if (debut < 0 || sculpte.indexOf('<g transform="translate(3 0) scale(.94)"', debut + 1) >= 0) throw new Error('icône Android : symbole introuvable');
const symbole = sculpte.slice(debut, sculpte.lastIndexOf('</g></svg>'));
if ((symbole.match(/<g[ >]/g) ?? []).length !== (symbole.match(/<\/g>/g) ?? []).length) throw new Error('icône Android : symbole mal découpé');
const cadre = 'viewBox="-25 -25 150 150" xmlns="http://www.w3.org/2000/svg"';
const couches = {
loksi_launcher_background: `<svg ${cadre}>${fondDefs}<rect x="-25" y="-25" width="150" height="150" fill="url(#facestandalone)"/><rect x="-25" y="-25" width="150" height="150" fill="url(#lightstandalone)"/></svg>`,
loksi_launcher_foreground: `<svg ${cadre}>${defs}${symbole}</svg>`,
};
const densites = { mdpi: 1, hdpi: 1.5, xhdpi: 2, xxhdpi: 3, xxxhdpi: 4 };
const browser = await chromium.launch();
const page = await browser.newPage();
for (const [densite, echelle] of Object.entries(densites)) {
const cote = 108 * echelle;
mkdirSync(join(out, `drawable-${densite}`), { recursive: true });
for (const [nom, svg] of Object.entries(couches)) {
await page.setViewportSize({ width: cote, height: cote });
await page.setContent(`<style>html,body{margin:0;width:100%;height:100%;background:transparent}svg{width:100%;height:100%;display:block}</style>${svg}`);
await page.screenshot({ path: join(out, `drawable-${densite}`, `${nom}.png`), omitBackground: true });
}
}
await browser.close();
console.log('Icône adaptative rendue dans', out);