Commit dd63f0e9 authored by Kourser's avatar Kourser
Browse files

Vaults: sync with OneDrive, iCloud Drive or a synced folder

Steps 2 to 5 of docs/coffres-multiples.md. Instead of rewriting the sync
engine around a new protocol, each new service is a gateway behind the
HTTPClient port that answers the engine's WebDAV requests with the same
meaning (207 multistatus, 412 on a failed precondition, 405 for an existing
folder, 415/501 for what the service cannot do). The engine, its checksums,
immutable revisions, conditional writes and conflict copies stay unchanged.

- OneDriveGateway (EnvorennCore): Microsoft Graph in the app folder only
  (Files.ReadWrite.AppFolder), conditional writes, upload sessions in
  10 MiB chunks, paging, Retry-After, one token renewal on 401. Uploads are
  verified by reading back; folders announce no ETag, so the listing cache
  does not apply.
- OneDriveAuthorization and OneDriveTokenSession: OAuth 2 with PKCE, no SDK
  and no client secret; the rotating refresh token is kept in the vault's
  keychain entry. The app signs in through ASWebAuthenticationSession.
  OneDrive stays disabled until ENVORENN_ONEDRIVE_CLIENT_ID is set in
  project.yml (steps in the doc).
- FolderGateway (EnvorennCore): a folder synced by the system. The vault
  stays on the device, so recordings in progress, drafts and sync state are
  never shared. ETag from size and nanosecond mtime, atomic replace, SHA-256
  computed in place, service files ignored, pending .icloud files listed
  under their real name.
- iCloud Drive (Apple): FolderGateway on the Documents folder of the
  iCloud.eu.cythin.envorenn container, visible as "Envorenn" in Files and the
  Finder. Files are downloaded before reading; concurrent versions are
  merged (memo metadata), kept beside (Markdown) or stored on the device,
  never dropped. iOS gets its own entitlements file; the container is
  declared for iOS and macOS and the export options set the production
  iCloud environment.
- Pairing and sync settings offer Nextcloud, OneDrive and iCloud Drive;
  certificate pinning is hidden for the two new services.
- Linux: "Dossier synchronisé…" syncs the open vault with a chosen folder
  (Syncthing, desktop OneDrive or Nextcloud client) through FolderGateway.
- Android: VaultRegistry ported to the Kotlin core, with a test over the
  shared conformance/vaults cases.
- Translations: 16 new strings in the 24 languages; button labels written by
  hand, "vault" terminology corrected. generate_translations.py now protects
  "iCloud Drive", "OneDrive" and "Microsoft", which Google translated.

Checks: 643 core tests (17 new: gateways and OAuth, including two-device
syncs through each gateway), 20 integration tests against Nextcloud and the
Python tests pass; signed macOS and iOS builds succeed. Not verified: the
Kotlin and Linux bridge code (no JDK or libcrypto on the build machine),
OneDrive against a real account, iCloud Drive on a real account.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 7950d2fc
Loading
Loading
Loading
Loading
+165
Changes for Android/core/src/main/kotlin/eu/cythin/envorenn/core/VaultRegistry.kt: 165 added lines, 0 removed lines.
Original line number Diff line number Diff line
package eu.cythin.envorenn.core

import java.io.File
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.UUID

/**
 * Registre des coffres de l'appareil (docs/coffres-multiples.md, section « Registre »).
 *
 * Local, jamais synchronisé. Les mêmes fichiers sont acceptés et refusés par Swift
 * (VaultRegistryTests), Python (Linux/test_vaults.py) et ce client (conformance/vaults).
 * Un registre mal formé est refusé en entier : jamais deviné, jamais écrasé.
 */
class VaultRegistryException(message: String) : IllegalArgumentException(message)

data class VaultEntry(val id: UUID, val name: String, val path: String, val createdAt: String)

class VaultRegistry private constructor(val active: UUID, val vaults: List<VaultEntry>) {

    val activeEntry: VaultEntry get() = vaults.first { it.id == active }

    fun entry(id: UUID): VaultEntry? = vaults.firstOrNull { it.id == id }

    /** Ajoute un coffre sans l'ouvrir. */
    fun adding(name: String, path: String, id: UUID = UUID.randomUUID(), createdAt: Instant = Instant.now()): VaultRegistry =
        validated(active, vaults + VaultEntry(id, normalizedName(name), path, isoDate(createdAt)))

    fun renaming(id: UUID, name: String): VaultRegistry {
        if (entry(id) == null) throw VaultRegistryException("Coffre inconnu.")
        return validated(active, vaults.map { if (it.id == id) it.copy(name = normalizedName(name)) else it })
    }

    fun activating(id: UUID): VaultRegistry {
        if (entry(id) == null) throw VaultRegistryException("Coffre inconnu.")
        return validated(id, vaults)
    }

    /** Retire un coffre de la liste ; le coffre ouvert ne se retire pas. */
    fun removing(id: UUID): VaultRegistry {
        if (entry(id) == null) throw VaultRegistryException("Coffre inconnu.")
        if (id == active) throw VaultRegistryException("Ouvrez un autre coffre avant de retirer celui-ci.")
        return validated(active, vaults.filter { it.id != id })
    }

    fun toJson(): Json.Obj {
        val root = Json.Obj()
        root.set("schemaVersion", SCHEMA_VERSION)
        root.set("active", active.toString())
        val list = Json.Arr()
        for (vault in vaults) {
            val item = Json.Obj()
            item.set("id", vault.id.toString())
            item.set("name", vault.name)
            item.set("path", vault.path)
            item.set("createdAt", vault.createdAt)
            list.items.add(item)
        }
        root["vaults"] = list
        return root
    }

    companion object {
        const val SCHEMA_VERSION = 1
        const val MAXIMUM_VAULTS = 100
        const val MAXIMUM_NAME_LENGTH = 80

        fun first(name: String, path: String, id: UUID = UUID.randomUUID(), createdAt: Instant = Instant.now()): VaultRegistry =
            validated(id, listOf(VaultEntry(id, normalizedName(name), path, isoDate(createdAt))))

        fun fromJson(json: Json): VaultRegistry {
            val root = json as? Json.Obj ?: throw VaultRegistryException("Registre invalide.")
            if (root.int("schemaVersion") != SCHEMA_VERSION.toLong()) throw VaultRegistryException("Version du registre non prise en charge.")
            val list = root.arr("vaults")?.items ?: throw VaultRegistryException("Registre invalide.")
            val vaults = list.map { item ->
                val obj = item as? Json.Obj ?: throw VaultRegistryException("Registre invalide.")
                val id = uuid(obj.str("id"))
                val createdAt = obj.str("createdAt") ?: throw VaultRegistryException("Registre invalide.")
                try { Instant.parse(createdAt) } catch (e: Exception) { throw VaultRegistryException("Registre invalide.") }
                VaultEntry(id, obj.str("name") ?: throw VaultRegistryException("Nom de coffre invalide."),
                           obj.str("path") ?: throw VaultRegistryException("Chemin de coffre invalide."), createdAt)
            }
            return validated(uuid(root.str("active")), vaults)
        }

        fun normalizedName(raw: String): String {
            val name = raw.trim()
            if (name.isEmpty() || name.codePointCount(0, name.length) > MAXIMUM_NAME_LENGTH ||
                name.any { Character.getType(it) == Character.CONTROL.toInt() }) {
                throw VaultRegistryException("Nom de coffre invalide.")
            }
            return name
        }

        private fun uuid(raw: String?): UUID = try {
            UUID.fromString(raw ?: throw VaultRegistryException("Registre invalide."))
        } catch (e: IllegalArgumentException) {
            throw VaultRegistryException("Registre invalide.")
        }

        private fun validatePath(path: String) {
            if (path.isEmpty() || path.toByteArray(Charsets.UTF_8).size > 4096 ||
                path.any { Character.getType(it) == Character.CONTROL.toInt() } ||
                path.split("/").contains("..") || path.startsWith("~")) {
                throw VaultRegistryException("Chemin de coffre invalide.")
            }
        }

        private fun normalizedPath(path: String): String =
            (if (path.startsWith("/")) "/" else "") + path.split("/").filter { it.isNotEmpty() && it != "." }.joinToString("/")

        private fun validated(active: UUID, vaults: List<VaultEntry>): VaultRegistry {
            if (vaults.isEmpty() || vaults.size > MAXIMUM_VAULTS) throw VaultRegistryException("Registre invalide.")
            if (vaults.map { it.id }.toSet().size != vaults.size || vaults.none { it.id == active }) {
                throw VaultRegistryException("Registre invalide.")
            }
            for (vault in vaults) {
                if (normalizedName(vault.name) != vault.name) throw VaultRegistryException("Nom de coffre invalide.")
                validatePath(vault.path)
            }
            if (vaults.map { normalizedPath(it.path) }.toSet().size != vaults.size) {
                throw VaultRegistryException("Deux coffres partagent un dossier.")
            }
            return VaultRegistry(active, vaults)
        }

        private fun isoDate(instant: Instant): String =
            DateTimeFormatter.ISO_INSTANT.format(instant.truncatedTo(ChronoUnit.SECONDS))
    }
}

/** Lecture et écriture du registre, à côté des dossiers qu'il désigne. */
class VaultRegistryStore(val file: File) {

    fun load(): VaultRegistry? {
        if (!file.isFile) return null
        if (file.length() > 1_000_000) throw VaultRegistryException("Registre invalide.")
        return VaultRegistry.fromJson(JsonParser.parse(file.readBytes()))
    }

    fun save(registry: VaultRegistry) {
        file.parentFile?.mkdirs()
        val staged = File(file.parentFile, ".${file.name}.tmp")
        staged.writeBytes(JsonWriter.writeBytes(registry.toJson()))
        if (!staged.renameTo(file)) {
            file.delete()
            if (!staged.renameTo(file)) throw VaultRegistryException("Le registre n'a pas pu être enregistré.")
        }
    }

    /** Le registre, ou un registre d'un seul coffre : celui qu'on utilisait déjà, à sa place. */
    fun loadOrCreate(currentPath: String, name: String): VaultRegistry {
        load()?.let { return it }
        val registry = VaultRegistry.first(name, currentPath)
        save(registry)
        return registry
    }

    /** Racine d'un coffre : relative au dossier du registre, ou absolue. Sur Android, un
     * coffre choisi par l'accès aux documents (SAF) s'inscrit sous son URI `content://`. */
    fun root(entry: VaultEntry): String =
        if (entry.path.startsWith("/") || entry.path.contains("://")) entry.path
        else File(file.parentFile, entry.path).path
}
+71
Changes for Android/core/src/test/kotlin/eu/cythin/envorenn/core/VaultRegistryTest.kt: 71 added lines, 0 removed lines.
Original line number Diff line number Diff line
package eu.cythin.envorenn.core

import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import java.io.File
import java.nio.file.Files

/**
 * Registre des coffres : mêmes cas que Swift (VaultRegistryTests) et Python
 * (Linux/test_vaults.py), lus dans conformance/vaults.
 */
class VaultRegistryTest {

    private val repoRoot = File("..").canonicalFile // Android/
    private val cases = File(repoRoot, "../conformance/vaults")

    @Test
    fun casCommuns() {
        val manifest = (JsonParser.parse(File(cases, "manifest.json").readBytes()) as Json.Obj).obj("cases")!!
        assertTrue(manifest.map.size >= 10)
        for ((name, value) in manifest.map.toSortedMap()) {
            val expected = value as Json.Obj
            val store = VaultRegistryStore(File(cases, name))
            if (expected.bool("accept") == true) {
                val registry = store.load()!!
                assertEquals(name, expected.str("active"), registry.activeEntry.name)
                assertEquals(name, expected.arr("paths")!!.items.map { (it as Json.Str).value }, registry.vaults.map { it.path })
            } else {
                try {
                    store.load()
                    fail("$name devait être refusé")
                } catch (expectedError: VaultRegistryException) {
                }
            }
        }
    }

    @Test
    fun premierLancementPuisAjoutOuvertureEtRetrait() {
        val directory = Files.createTempDirectory("registre").toFile()
        try {
            val store = VaultRegistryStore(File(directory, "vaults.json"))
            val first = store.loadOrCreate("content://documents/tree/Envorenn", " Mon coffre ")
            assertEquals("Mon coffre", first.activeEntry.name)
            assertEquals(first.active, store.loadOrCreate("ailleurs", "Autre").active)

            val withWork = first.adding("Travail", "content://documents/tree/Travail")
            val work = withWork.vaults.last()
            assertEquals(first.active, withWork.active)
            val opened = withWork.activating(work.id).renaming(work.id, "Bureau")
            try {
                opened.removing(work.id)
                fail("Le coffre ouvert ne se retire pas.")
            } catch (expected: VaultRegistryException) {
            }
            val alone = opened.removing(first.active)
            store.save(alone)
            assertEquals(listOf("Bureau"), store.load()!!.vaults.map { it.name })

            try {
                alone.adding("Doublon", "content://documents/tree/Travail")
                fail("Deux coffres ne partagent pas un dossier.")
            } catch (expected: VaultRegistryException) {
            }
        } finally {
            directory.deleteRecursively()
        }
    }
}
+105 −2
Changes for App/Features/Sync/PairingView.swift: 105 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -34,6 +34,8 @@ struct PairingView: View {
    /// SEC-15 : certificat inconnu, présenté à l'utilisateur plutôt que refusé
    /// en silence ou accepté en douce.
    @State private var untrusted: ServerTrust.UntrustedCertificate?
    @State private var connectingOneDrive = false
    @State private var connectingICloud = false

    var body: some View {
        NavigationStack {
@@ -78,6 +80,68 @@ struct PairingView: View {

    @ViewBuilder
    private var addressStep: some View {
        if reconnecting?.isOneDrive == true {
            oneDriveSection
        } else if reconnecting?.isICloud == true {
            iCloudSection
        } else {
            nextcloudSections
            if reconnecting == nil {
                oneDriveSection
                iCloudSection
            }
        }
    }

    /// iCloud Drive : le dossier `Envorenn` du compte iCloud de l'appareil,
    /// sans rien à saisir.
    @ViewBuilder
    private var iCloudSection: some View {
        Section {
            if connectingICloud {
                HStack(spacing: 12) {
                    ProgressView()
                    Text("Préparation du dossier iCloud Drive…")
                }
            } else {
                Button("Utiliser iCloud Drive", action: connectICloud)
                    .disabled(isWorking)
            }
        } header: {
            Text(verbatim: "iCloud Drive")
        } footer: {
            Text("Le coffre est copié dans le dossier Envorenn d'iCloud Drive, puis iCloud le porte sur vos autres appareils Apple. Disponible sur iPhone, iPad et Mac uniquement.").foregroundStyle(Color.secondaryText)
        }
    }

    /// OneDrive : une page de connexion Microsoft, puis le dossier
    /// `Applications/Envorenn` du compte, et rien d'autre.
    @ViewBuilder
    private var oneDriveSection: some View {
        Section {
            if connectingOneDrive {
                HStack(spacing: 12) {
                    ProgressView()
                    Text("Validez l'accès sur la page de Microsoft…")
                }
                Button("Arrêter", role: .cancel) { work?.cancel() }
            } else {
                Button("Se connecter à OneDrive", action: connectOneDrive)
                    .disabled(isWorking || !OneDriveSignIn.isAvailable)
            }
        } header: {
            Text(verbatim: "OneDrive")
        } footer: {
            if OneDriveSignIn.isAvailable {
                Text("Envorenn n'accède qu'au dossier Applications › Envorenn de votre OneDrive. Votre mot de passe Microsoft se saisit sur la page de Microsoft, jamais dans Envorenn.").foregroundStyle(Color.secondaryText)
            } else {
                Text("OneDrive n'est pas encore activé dans cette version d'Envorenn.").foregroundStyle(Color.secondaryText)
            }
        }
    }

    @ViewBuilder
    private var nextcloudSections: some View {
        Section {
            addressField
                .submitLabel(.continue)
@@ -283,6 +347,40 @@ struct PairingView: View {
        }
    }

    private func connectOneDrive() {
        guard !isWorking else { return }
        errorMessage = nil
        untrusted = nil
        isWorking = true
        connectingOneDrive = true
        work = Task {
            defer { isWorking = false; connectingOneDrive = false }
            do {
                let folder = reconnecting?.remoteRoot ?? RemoteFolder.defaultPath
                try await sync.connectOneDrive(remoteRoot: folder)
                dismiss()
            } catch {
                errorMessage = Self.describe(error)
            }
        }
    }

    private func connectICloud() {
        guard !isWorking else { return }
        errorMessage = nil
        isWorking = true
        connectingICloud = true
        work = Task {
            defer { isWorking = false; connectingICloud = false }
            do {
                try await sync.connectICloud(folder: reconnecting?.remoteRoot ?? RemoteFolder.defaultPath)
                dismiss()
            } catch {
                errorMessage = Self.describe(error)
            }
        }
    }

    private func connectManually() {
        guard !isWorking else { return }
        errorMessage = nil
@@ -358,7 +456,7 @@ struct PairingView: View {

    private var title: String {
        switch step {
        case .address: reconnecting == nil ? String(localized: "Connecter Nextcloud", bundle: AppLanguage.bundle, locale: AppLanguage.locale) : String(localized: "Se reconnecter", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        case .address: reconnecting == nil ? String(localized: "Relier le coffre", bundle: AppLanguage.bundle, locale: AppLanguage.locale) : String(localized: "Se reconnecter", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        case .manual: String(localized: "Mot de passe d'application", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        case .folder: String(localized: "Dossier du coffre", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        }
@@ -371,8 +469,13 @@ struct PairingView: View {
    /// Message d'erreur, ou `nil` pour un arrêt voulu par l'utilisateur.
    private static func describe(_ error: any Error) -> String? {
        switch error {
        case SyncError.cancelled, is CancellationError, LoginFlowSession.LoginError.cancelled:
        case SyncError.cancelled, is CancellationError, LoginFlowSession.LoginError.cancelled,
             OneDriveAuthorization.AuthorizationError.cancelled:
            nil
        case OneDriveAuthorization.AuthorizationError.refused(let detail):
            String(localized: "Microsoft a refusé la connexion : \(detail)", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        case OneDriveAuthorization.AuthorizationError.stateMismatch, OneDriveAuthorization.AuthorizationError.malformedResponse:
            String(localized: "La réponse de Microsoft n'a pas pu être vérifiée. Réessayez.", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        case SyncError.insecureServerURL:
            String(localized: "Adresse refusée : la connexion doit être chiffrée (https).", bundle: AppLanguage.bundle, locale: AppLanguage.locale)
        case SyncError.invalidServerURL:
+15 −3
Changes for App/Features/Sync/SyncSettingsView.swift: 15 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -82,9 +82,9 @@ struct SyncSettingsView: View {

    private var unpairedSection: some View {
        Section {
            Button("Connecter un Nextcloud") { showPairing = true }
            Button("Relier à Nextcloud, OneDrive ou iCloud Drive") { showPairing = true }
        } footer: {
            Text("Envorenn fonctionne entièrement sans serveur. Pour sauvegarder vos souvenirs, connectez un dossier de votre propre Nextcloud : ils y sont envoyés, vérifiés, et restent aussi sur cet appareil.").foregroundStyle(Color.secondaryText)
            Text("Envorenn fonctionne entièrement sans serveur. Pour sauvegarder ce coffre, reliez-le à un dossier de votre Nextcloud, de votre OneDrive ou d'iCloud Drive : vos souvenirs y sont envoyés, vérifiés, et restent aussi sur cet appareil.").foregroundStyle(Color.secondaryText)
        }
    }

@@ -92,7 +92,11 @@ struct SyncSettingsView: View {
    private var pairedSections: some View {
        if sync.phase == .needsReconnection {
            Section {
                if sync.account?.isOneDrive == true {
                    WarningRow(message: String(localized: "OneDrive refuse l'accès de cet appareil : la connexion a expiré ou a été retirée. Vos souvenirs restent ici, rien n'est perdu.", bundle: AppLanguage.bundle, locale: AppLanguage.locale))
                } else {
                    WarningRow(message: String(localized: "Nextcloud refuse l'accès de cet appareil : le mot de passe d'application a sans doute été révoqué. Vos souvenirs restent ici, rien n'est perdu.", bundle: AppLanguage.bundle, locale: AppLanguage.locale))
                }
                Button("Se reconnecter") { showPairing = true }
            }
        } else if sync.certificateRefused {
@@ -160,11 +164,17 @@ struct SyncSettingsView: View {

        if let account = sync.account {
            Section {
                if account.isOneDrive {
                    LabeledContent("Dossier", value: "Applications › Envorenn" + account.remoteRoot.replacingOccurrences(of: "/", with: " › "))
                } else if account.isICloud {
                    LabeledContent("Dossier", value: "iCloud Drive › Envorenn" + account.remoteRoot.replacingOccurrences(of: "/", with: " › "))
                } else {
                    LabeledContent("Serveur", value: account.serverLabel)
                    LabeledContent("Compte", value: account.loginName)
                    LabeledContent("Dossier", value: account.remoteRoot)
                }
            } header: {
                Text("Nextcloud")
                Text(verbatim: account.serverLabel == "OneDrive" || account.isICloud ? account.serverLabel : "Nextcloud")
            }

            #if !os(macOS)
@@ -197,6 +207,7 @@ struct SyncSettingsView: View {

            #endif

            if !account.isOneDrive && !account.isICloud {
            Section {
                DisclosureGroup("Sécurité de la connexion", isExpanded: $advanced) {
                ForEach(account.trust?.acceptedAuthorities ?? [], id: \.self) { fingerprint in
@@ -219,6 +230,7 @@ struct SyncSettingsView: View {
            } footer: {
                Text("Option avancée. Épinglée, la clé que présente aujourd'hui le serveur est la seule acceptée : si un renouvellement de certificat en change, la synchronisation s'arrête jusqu'à ce que l'épinglage soit retiré.").foregroundStyle(Color.secondaryText)
            }
            }

            Section {
                Button("Déconnecter cet appareil", role: .destructive) {
+1 −1
Changes for App/Features/VaultSwitcher.swift: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -134,7 +134,7 @@ struct VaultManagerView: View {
            VStack(alignment: .leading, spacing: 2) {
                Text(entry.name).journalFont(.body, weight: isActive ? .semibold : .regular)
                Group {
                    if let account { Text("Nextcloud · \(account.serverLabel)") } else { Text("Sur cet appareil") }
                    if let account, account.isOneDrive || account.isICloud { Text(verbatim: account.serverLabel) } else if let account { Text("Nextcloud · \(account.serverLabel)") } else { Text("Sur cet appareil") }
                }
                .journalFont(.caption).foregroundStyle(Color.secondaryText)
            }
Loading