Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/SecureStorage/SharedSettingsStore.swift10// Description : Non-sensitive settings shared through the App Group:11// versioned Codable blobs with a safe fallback when the12// group is unavailable (keyboard without Full Access) or the13// stored data is corrupted.14// Module : SecureStorage15// Repository : https://git.spboucher.ai/sp-keyboard16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293/// Identifiers of the shared container. Entitlements must list the same group.94public enum SharedContainer {95 public static let appGroup = "group.ai.spboucher.keyboard"9697 /// Directory of the App Group, `nil` when the entitlement is missing or the extension has no Full Access.98 public static var directory: URL? {99 FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup)100 }101}102103/// Raw blob storage. Never used for secrets.104public protocol SettingsBlobStoring: Sendable {105 func data(forKey key: String) -> Data?106 func set(_ data: Data?, forKey key: String)107 /// False when writes cannot reach the shared container.108 var isShared: Bool { get }109}110111/// A settings type that knows its schema version and how to repair itself after decoding.112public protocol VersionedSettings: Codable, Sendable {113 static var currentSchemaVersion: Int { get }114 static var storageKey: String { get }115 static var fallback: Self { get }116 var schemaVersion: Int { get set }117 /// Clamp values, drop unknown entries, upgrade from older schema versions.118 func migrated() -> Self119}120121public enum SettingsLoadOutcome: String, Sendable {122 case stored, missing, corrupted, newerSchema123}124125public extension SettingsBlobStoring {126 /// Never throws: missing, corrupted or too-new data yields the embedded fallback and says why.127 func load<T: VersionedSettings>(_ type: T.Type = T.self) -> (value: T, outcome: SettingsLoadOutcome) {128 guard let data = data(forKey: T.storageKey) else { return (T.fallback, .missing) }129 guard data.count <= 512 * 1024, let decoded = try? JSONDecoder().decode(T.self, from: data) else {130 return (T.fallback, .corrupted)131 }132 guard decoded.schemaVersion <= T.currentSchemaVersion else { return (T.fallback, .newerSchema) }133 var value = decoded.migrated()134 value.schemaVersion = T.currentSchemaVersion135 return (value, .stored)136 }137138 /// `notify: false` stores without bumping the revision (measurements nobody needs to reload for).139 func save<T: VersionedSettings>(_ value: T, notify: Bool = true) {140 var copy = value.migrated()141 copy.schemaVersion = T.currentSchemaVersion142 guard let data = try? JSONEncoder().encode(copy) else { return }143 set(data, forKey: T.storageKey)144 if notify { bumpRevision() }145 }146147 func remove<T: VersionedSettings>(_ type: T.Type) {148 set(nil, forKey: T.storageKey)149 bumpRevision()150 }151152 /// Monotonic counter the extension compares to know that the app changed something.153 var revision: Int {154 guard let data = data(forKey: "revision"), let text = String(data: data, encoding: .utf8) else { return 0 }155 return Int(text) ?? 0156 }157158 func bumpRevision() {159 set(Data(String(revision &+ 1).utf8), forKey: "revision")160 }161}162163/// `UserDefaults` suite of the App Group, falling back to the process's own defaults when the group is164/// unreachable (the caller can tell through `isShared`).165public final class AppGroupSettingsStore: SettingsBlobStoring, @unchecked Sendable {166 private let defaults: UserDefaults167 public let isShared: Bool168 private let prefix = "spk."169170 public init(appGroup: String = SharedContainer.appGroup) {171 if FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) != nil,172 let suite = UserDefaults(suiteName: appGroup) {173 defaults = suite174 isShared = true175 } else {176 defaults = .standard177 isShared = false178 }179 }180181 public func data(forKey key: String) -> Data? { defaults.data(forKey: prefix + key) }182183 public func set(_ data: Data?, forKey key: String) {184 if let data { defaults.set(data, forKey: prefix + key) } else { defaults.removeObject(forKey: prefix + key) }185 }186187 /// Removes every SP Keyboard key of the suite.188 public func eraseAll() {189 for key in defaults.dictionaryRepresentation().keys where key.hasPrefix(prefix) {190 defaults.removeObject(forKey: key)191 }192 }193}194195public final class InMemorySettingsStore: SettingsBlobStoring, @unchecked Sendable {196 private let lock = NSLock()197 private var blobs: [String: Data] = [:]198 public let isShared: Bool199200 public init(isShared: Bool = true) { self.isShared = isShared }201202 public func data(forKey key: String) -> Data? { lock.withLock { blobs[key] } }203 public func set(_ data: Data?, forKey key: String) { lock.withLock { blobs[key] = data } }204}205