SPB Git

Repository Public

SeedPhrase.swift 15.4 KB 353 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/SeedPhrase.swift8// Module           : Qyvora UI9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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          : None specified (no license file in this repository)33//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 SwiftUI42#if canImport(UIKit)43import UIKit44#endif4546/// Numbered recovery words. When `masked`, the words stay hidden until the grid is pressed and held.47/// When `protected` (the default), the text cannot be selected or copied and is redacted in privacy contexts.48///49/// Whatever the caller asks, the words are replaced by dots while the scene is being captured (screen recording,50/// AirPlay or cable mirroring, QYV-APP-006), with a line that says why. A screenshot cannot be prevented by an51/// application: the screens that show the phrase warn after one was taken (`ScreenshotWarning`).52public struct SeedPhraseGrid: View {53    let words: [String]54    let masked: Bool55    let protected: Bool56    @State private var revealed = false57    @State private var feedback = 058    @ScaledMetric(relativeTo: .footnote) private var cellMinimum: CGFloat = 10059    @Environment(\.redactionReasons) private var redaction60    @Environment(\.qIsSceneCaptured) private var isCaptured6162    public init(words: [String], masked: Bool = false, protected: Bool = true) {63        self.words = words64        self.masked = masked65        self.protected = protected66    }6768    var isHidden: Bool { SeedPhraseVisibility.isHidden(masked: masked, revealed: revealed, redacted: redaction.contains(.privacy), captured: isCaptured) }6970    public var body: some View {71        VStack(alignment: .leading, spacing: 12) {72            LazyVGrid(columns: [GridItem(.adaptive(minimum: cellMinimum), spacing: 8, alignment: .leading)], alignment: .leading, spacing: 8) {73                ForEach(Array(words.enumerated()), id: \.offset) { index, word in74                    cell(index: index, word: word)75                }76            }77            if isCaptured {78                Label("Hidden: the screen is being recorded or mirrored. Stop the recording, screen sharing or AirPlay to display the words.",79                      systemImage: "record.circle")80                    .font(QFont.caption)81                    .foregroundStyle(QColor.negative)82                    .fixedSize(horizontal: false, vertical: true)83            } else if masked {84                Label(revealed ? "Release to hide" : "Press and hold to reveal", systemImage: revealed ? "eye" : "eye.slash")85                    .font(QFont.caption)86                    .foregroundStyle(QColor.textSecondary)87                    .accessibilityHidden(true)88            }89        }90        .contentShape(Rectangle())91        .onLongPressGesture(minimumDuration: 0.15, maximumDistance: 80) {} onPressingChanged: { pressing in92            guard masked else { return }93            if pressing != revealed { feedback += 1 }94            revealed = pressing95        }96        .sensoryFeedback(.selection, trigger: feedback)97        .privacySensitive(protected)98        .accessibilityElement(children: .contain)99        .accessibilityLabel("Recovery phrase, \(words.count) words")100        .accessibilityActions {101            if masked {102                Button(revealed ? "Hide words" : "Reveal words") { revealed.toggle() }103            }104        }105    }106107    @ViewBuilder func cell(index: Int, word: String) -> some View {108        let label = HStack(alignment: .firstTextBaseline, spacing: 8) {109            Text("\(index + 1)")110                .font(Font.system(.caption, design: .monospaced))111                .foregroundStyle(QColor.textTertiary)112                .frame(minWidth: 18, alignment: .trailing)113            Text(isHidden ? "•••••" : word)114                .font(Font.system(.callout, design: .monospaced).weight(.medium))115                .foregroundStyle(isHidden ? QColor.textTertiary : QColor.textPrimary)116                .lineLimit(1)117                .minimumScaleFactor(0.7)118            Spacer(minLength: 0)119        }120        .padding(.horizontal, 10)121        .padding(.vertical, 10)122        .background(QColor.surface, in: RoundedRectangle(cornerRadius: 10, style: .continuous))123        .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))124        .accessibilityElement(children: .ignore)125        .accessibilityLabel(isHidden ? "Word \(index + 1), hidden" : "Word \(index + 1): \(word)")126127        if protected {128            label129        } else {130            label.textSelection(.enabled)131        }132    }133}134135public extension EnvironmentValues {136    /// True while the scene is recorded or mirrored (iOS `isSceneCaptured`); always false where the system does not137    /// report it (the macOS build of the package, used by the tests).138    var qIsSceneCaptured: Bool {139        #if os(iOS)140        return isSceneCaptured141        #else142        return false143        #endif144    }145}146147/// When the recovery words are replaced by dots. Pure, so that the rule is tested without a view.148public enum SeedPhraseVisibility {149    /// Hidden while masked and not held, in a redacted context, and always while the scene is captured.150    public static func isHidden(masked: Bool, revealed: Bool, redacted: Bool, captured: Bool) -> Bool {151        captured || redacted || (masked && !revealed)152    }153154    /// A password shown in clear by its "eye" button goes back to dots while the scene is captured.155    public static func showsPasswordInClear(revealed: Bool, captured: Bool) -> Bool {156        revealed && !captured157    }158}159160/// Banner shown on a screen that displays secret material once the user took a screenshot of it (QYV-APP-006).161/// iOS gives no way to prevent a screenshot; the notification arrives after the image was saved.162public struct ScreenshotWarning: ViewModifier {163    let isShowingSecret: Bool164    @Binding var taken: Bool165166    public func body(content: Content) -> some View {167        content168            #if canImport(UIKit)169            .onReceive(NotificationCenter.default.publisher(for: UIApplication.userDidTakeScreenshotNotification)) { _ in170                if isShowingSecret { taken = true }171            }172            #endif173    }174}175176public extension View {177    /// Sets `taken` when a screenshot is taken while `isShowingSecret` is true. Show `ScreenshotWarning.title` and178    /// `ScreenshotWarning.message` in a critical banner when `taken` is true.179    func warnsAboutScreenshots(of isShowingSecret: Bool, taken: Binding<Bool>) -> some View {180        modifier(ScreenshotWarning(isShowingSecret: isShowingSecret, taken: taken))181    }182}183184public extension ScreenshotWarning {185    nonisolated static let title = "A screenshot was taken"186    nonisolated static let message = "It contains the recovery phrase. Delete it from Photos and from Recently Deleted, and from any cloud library it may have reached."187}188189/// Recovery-phrase entry: one cell per word, validated by a caller-supplied closure, with suggestions from a190/// caller-supplied closure (prefix → candidate words). Pasting a whole phrase into any cell fills the cells.191public struct SeedPhraseEntry: View {192    @Binding var words: [String]193    let isValidWord: (String) -> Bool194    let suggestions: (String) -> [String]195    @FocusState private var focus: Int?196    @ScaledMetric(relativeTo: .footnote) private var cellMinimum: CGFloat = 132197198    /// - Parameters:199    ///   - words: the cells; its count is the phrase length (12 or 24). Use `SeedPhraseEntry.emptyWords(12)` to start.200    ///   - isValidWord: true when the word belongs to the word list.201    ///   - suggestions: candidate words for a typed prefix (the view shows at most four).202    public init(words: Binding<[String]>, isValidWord: @escaping (String) -> Bool, suggestions: @escaping (String) -> [String]) {203        self._words = words204        self.isValidWord = isValidWord205        self.suggestions = suggestions206    }207208    public static func emptyWords(_ count: Int) -> [String] { Array(repeating: "", count: count) }209210    var currentSuggestions: [String] {211        guard let i = focus, i < words.count, !words[i].isEmpty, !isValidWord(words[i]) || suggestions(words[i]).count > 1 else { return [] }212        return Array(suggestions(words[i]).prefix(4))213    }214215    public var body: some View {216        VStack(alignment: .leading, spacing: 12) {217            LazyVGrid(columns: [GridItem(.adaptive(minimum: cellMinimum), spacing: 8, alignment: .leading)], alignment: .leading, spacing: 8) {218                ForEach(words.indices, id: \.self) { index in219                    cell(index)220                }221            }222            suggestionBar223            HStack {224                let valid = SeedPhraseInput.validCount(words, isValid: isValidWord)225                Label("\(valid) of \(words.count) words recognised",226                      systemImage: valid == words.count ? "checkmark.circle" : "circle.dashed")227                    .font(QFont.caption)228                    .foregroundStyle(valid == words.count ? QColor.positive : QColor.textSecondary)229                    .contentTransition(.numericText())230                Spacer()231                if words.contains(where: { !$0.isEmpty }) {232                    Button("Clear all") {233                        words = Self.emptyWords(words.count)234                        focus = 0235                    }236                    .font(.caption.weight(.semibold))237                    .foregroundStyle(QColor.violet)238                    .frame(minHeight: 44)239                }240            }241        }242        .privacySensitive()243    }244245    @ViewBuilder var suggestionBar: some View {246        let list = currentSuggestions247        if !list.isEmpty, let i = focus {248            ScrollView(.horizontal, showsIndicators: false) {249                HStack(spacing: 8) {250                    ForEach(list, id: \.self) { word in251                        Button {252                            words[i] = word253                            advance(from: i)254                        } label: {255                            Text(word)256                                .font(Font.system(.callout, design: .monospaced).weight(.medium))257                                .foregroundStyle(QColor.textPrimary)258                                .padding(.horizontal, 14)259                                .frame(minHeight: 40)260                                .background(QColor.surfaceRaised, in: Capsule())261                                .overlay(Capsule().strokeBorder(QColor.stroke, lineWidth: 1))262                        }263                        .buttonStyle(.plain)264                        .accessibilityLabel("Use \(word) for word \(i + 1)")265                    }266                }267            }268            .transition(.opacity)269        }270    }271272    func state(_ index: Int) -> (color: Color, image: String?, spoken: String) {273        let word = words[index]274        if word.isEmpty { return (focus == index ? QColor.violet : QColor.stroke, nil, "empty") }275        if isValidWord(word) { return (QColor.positive.opacity(focus == index ? 1 : 0.55), "checkmark", "recognised") }276        if focus == index { return (QColor.violet, nil, "typing") }277        return (QColor.negative, "exclamationmark", "not in the word list")278    }279280    func cell(_ index: Int) -> some View {281        let s = state(index)282        return HStack(alignment: .firstTextBaseline, spacing: 6) {283            Text("\(index + 1)")284                .font(Font.system(.caption, design: .monospaced))285                .foregroundStyle(QColor.textTertiary)286                .frame(minWidth: 18, alignment: .trailing)287                .accessibilityHidden(true)288            TextField("", text: Binding(289                get: { words[index] },290                set: { new in291                    let parts = SeedPhraseInput.split(new)292                    if parts.count > 1 {293                        let next = SeedPhraseInput.distribute(parts, into: &words, startingAt: index)294                        focus = next295                    } else if new.last?.isWhitespace == true {296                        words[index] = SeedPhraseInput.normalizeWord(new)297                        if isValidWord(words[index]) { advance(from: index) }298                    } else {299                        words[index] = SeedPhraseInput.normalizeWord(new)300                    }301                }))302                .font(Font.system(.callout, design: .monospaced).weight(.medium))303                .foregroundStyle(QColor.textPrimary)304                .autocorrectionDisabled()305                #if os(iOS)306                .textInputAutocapitalization(.never)307                .keyboardType(.asciiCapable)308                .submitLabel(index == words.count - 1 ? .done : .next)309                #endif310                .focused($focus, equals: index)311                .onSubmit { advance(from: index) }312                .accessibilityLabel("Word \(index + 1)")313                .accessibilityValue(words[index].isEmpty ? "empty" : "\(words[index]), \(s.spoken)")314            if let image = s.image {315                Image(systemName: image)316                    .font(.caption2.weight(.bold))317                    .foregroundStyle(s.color)318                    .accessibilityHidden(true)319            }320        }321        .padding(.horizontal, 10)322        .frame(minHeight: 44)323        .background(QColor.surface, in: RoundedRectangle(cornerRadius: 10, style: .continuous))324        .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(s.color, lineWidth: focus == index ? 1.5 : 1))325    }326327    func advance(from index: Int) {328        focus = index + 1 < words.count ? index + 1 : nil329    }330}331332#if DEBUG333private struct SeedPreview: View {334    static let sample = (1...12).map { "preview\($0)" }335    @State private var words = SeedPhraseEntry.emptyWords(12)336337    var body: some View {338        ScrollView {339            VStack(alignment: .leading, spacing: 24) {340                SeedPhraseGrid(words: Self.sample)341                SeedPhraseGrid(words: Self.sample, masked: true)342                SeedPhraseEntry(words: $words, isValidWord: { Self.sample.contains($0) },343                                suggestions: { prefix in Self.sample.filter { $0.hasPrefix(prefix) } })344            }345            .padding()346        }347        .qScreen()348    }349}350351#Preview("Recovery phrase") { SeedPreview() }352#endif353
Files main
Menu

Theme