SPB Git

Repository Public MIT

RegistryClient.swift 5.9 KB 124 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/GlassCLICore/RegistryClient.swift8// Module           : Glass CLICore9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SPGlassRegistry43import SPGlassThemes4445/// Reads a registry and checks everything it returns: signature, schema, checksums and sizes.46public struct RegistryClient: Sendable {47    public let source: any RegistrySource48    public let publicKey: String?4950    public init(source: any RegistrySource, publicKey: String?) {51        self.source = source52        self.publicKey = publicKey53    }5455    public var identity: String { source.identity }56    /// True when a public key is configured, so the index is authenticated and not only checksummed.57    public var isAuthenticated: Bool { publicKey != nil }5859    public func index() async throws -> RegistryIndex {60        let data = try await source.fetch(RegistrySchema.indexFileName, limit: RegistryJSON.maximumDocumentBytes)61        if let publicKey {62            let signature: Data63            do {64                signature = try await source.fetch(RegistrySchema.signatureFileName, limit: 1024)65            } catch let error as CLIError where error.exitCode == .notFound {66                throw CLIError(RegistryError.signatureMissing)67            }68            try RegistrySignature.verify(data, signature: String(decoding: signature, as: UTF8.self), publicKey: publicKey)69        }70        let index = try RegistryJSON.decode(RegistryIndex.self, from: data, what: "The registry index")71        try RegistryValidator.validate(index)72        return index73    }7475    public func manifest(id: String, version: String?, index: RegistryIndex) async throws -> ComponentManifest {76        try RegistryPath.validateIdentifier(id)77        guard let entry = index.item(id) else { throw RegistryError.unknownItem(id) }78        let wanted = version ?? entry.latest79        guard let published = entry.version(wanted) else { throw RegistryError.unknownVersion(id: id, version: wanted) }80        let data = try await verified(path: published.path, sha256: published.sha256, limit: RegistryJSON.maximumDocumentBytes)81        let manifest = try RegistryJSON.decode(ComponentManifest.self, from: data, what: "Manifest \"\(id)\"")82        try RegistryValidator.validate(manifest)83        guard manifest.id == id, manifest.version == wanted else {84            throw RegistryError.invalidManifest(id: id, detail: "it describes \(RegistryText.clip(manifest.id)) \(RegistryText.clip(manifest.version)) instead of \(id) \(wanted).")85        }86        return manifest87    }8889    public func file(_ file: ManifestFile, of manifest: ComponentManifest) async throws -> Data {90        let path = manifest.registryPath(of: file)91        let data = try await verified(path: path, sha256: file.sha256, limit: RegistryJSON.maximumFileBytes)92        try RegistryHash.verify(data, against: file)93        return data94    }9596    public func theme(id: String, version: String?, index: RegistryIndex) async throws -> (theme: GlassTheme, data: Data, version: RegistryIndexVersion) {97        try RegistryPath.validateIdentifier(id)98        guard let entry = index.theme(id) else { throw RegistryError.unknownItem(id) }99        let wanted = version ?? entry.latest100        guard let published = entry.version(wanted) else { throw RegistryError.unknownVersion(id: id, version: wanted) }101        let data = try await verified(path: published.path, sha256: published.sha256, limit: GlassThemeCodec.maximumBytes)102        do {103            return (try GlassThemeCodec.decode(data), data, published)104        } catch {105            throw CLIError(code: "invalid_theme", message: "Theme \"\(id)\": \(error.description)", exitCode: .invalidData)106        }107    }108109    /// Fetches a file and compares its checksum. A mismatch coming from the cache is retried once from the registry.110    private func verified(path: String, sha256: String, limit: Int) async throws -> Data {111        var data = try await source.fetch(path, limit: limit)112        if RegistryHash.sha256(data) != sha256, let caching = source as? CachingRegistrySource, !caching.offline {113            caching.invalidate(path)114            data = try await source.fetch(path, limit: limit)115        }116        let actual = RegistryHash.sha256(data)117        guard actual == sha256 else {118            (source as? CachingRegistrySource)?.invalidate(path)119            throw RegistryError.hashMismatch(path: path, expected: sha256, actual: actual)120        }121        return data122    }123}124
Files main
Menu

Theme