Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraUI/Security.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 SwiftUI4243/// Numeric PIN entry. The caller owns the PIN text, decides whether it is right, and reports a wrong entry by44/// incrementing `errorCount` (the pad shakes, vibrates and shows `message`). During a lock-out the keys are45/// disabled and the remaining time counts down.46public struct PINPad: View {47 public enum Biometry: Sendable {48 case faceID, touchID, opticID4950 var systemImage: String {51 switch self {52 case .faceID: return "faceid"53 case .touchID: return "touchid"54 case .opticID: return "opticid"55 }56 }5758 var label: String {59 switch self {60 case .faceID: return "Unlock with Face ID"61 case .touchID: return "Unlock with Touch ID"62 case .opticID: return "Unlock with Optic ID"63 }64 }65 }6667 @Binding var pin: String68 let length: Int69 let title: String70 let message: String?71 let errorCount: Int72 let lockedUntil: Date?73 let biometry: Biometry?74 let onBiometry: (() -> Void)?75 let onComplete: (String) -> Void7677 @State private var shake: CGFloat = 078 @State private var keyFeedback = 079 @Environment(\.accessibilityReduceMotion) private var reduceMotion80 @ScaledMetric(relativeTo: .title) private var keyHeight: CGFloat = 648182 /// - Parameters:83 /// - pin: digits entered so far; clear it after a wrong entry.84 /// - message: line under the dots (error text, attempts left); announced when it changes.85 /// - errorCount: increment to signal a wrong PIN.86 /// - lockedUntil: end of the lock-out, or nil.87 /// - biometry / onBiometry: shows the biometric key when both are given.88 /// - onComplete: called once when `length` digits are entered.89 public init(pin: Binding<String>, length: Int = 6, title: String = "Enter your PIN", message: String? = nil, errorCount: Int = 0,90 lockedUntil: Date? = nil, biometry: Biometry? = nil, onBiometry: (() -> Void)? = nil,91 onComplete: @escaping (String) -> Void) {92 self._pin = pin93 self.length = length94 self.title = title95 self.message = message96 self.errorCount = errorCount97 self.lockedUntil = lockedUntil98 self.biometry = biometry99 self.onBiometry = onBiometry100 self.onComplete = onComplete101 }102103 public var body: some View {104 if let lockedUntil {105 TimelineView(.periodic(from: .now, by: 1)) { timeline in106 let remaining = lockedUntil.timeIntervalSince(timeline.date)107 content(locked: remaining > 0, remaining: remaining)108 }109 } else {110 content(locked: false, remaining: 0)111 }112 }113114 func content(locked: Bool, remaining: TimeInterval) -> some View {115 VStack(spacing: 28) {116 VStack(spacing: 16) {117 Text(title).font(QFont.title).foregroundStyle(QColor.textPrimary).multilineTextAlignment(.center)118 HStack(spacing: 16) {119 ForEach(0..<length, id: \.self) { i in120 Circle()121 .fill(i < pin.count ? QColor.textPrimary : Color.clear)122 .overlay(Circle().strokeBorder(i < pin.count ? QColor.textPrimary : QColor.textTertiary, lineWidth: 1.5))123 .frame(width: 14, height: 14)124 .scaleEffect(i < pin.count ? 1 : 0.86)125 .animation(reduceMotion ? nil : .spring(duration: 0.22, bounce: 0.4), value: pin.count)126 }127 }128 .modifier(ShakeEffect(travel: shake))129 .accessibilityElement(children: .ignore)130 .accessibilityLabel("PIN")131 .accessibilityValue("\(pin.count) of \(length) digits entered")132 Group {133 if locked {134 Label("Locked. Try again in \(CountdownFormat.text(remaining))", systemImage: "lock")135 .foregroundStyle(QColor.warning)136 .monospacedDigit()137 .contentTransition(.numericText(countsDown: true))138 } else if let message {139 Label(message, systemImage: "exclamationmark.circle").foregroundStyle(QColor.negative)140 } else {141 Text(" ")142 }143 }144 .font(QFont.callout)145 .multilineTextAlignment(.center)146 .fixedSize(horizontal: false, vertical: true)147 }148 Grid(horizontalSpacing: 14, verticalSpacing: 12) {149 ForEach(0..<3, id: \.self) { row in150 GridRow {151 ForEach(1...3, id: \.self) { column in digitKey(row * 3 + column) }152 }153 }154 GridRow {155 if let biometry, let onBiometry {156 key(label: biometry.label, action: onBiometry) {157 Image(systemName: biometry.systemImage).font(.title2).foregroundStyle(QColor.violet)158 }159 } else {160 Color.clear.frame(height: keyHeight).accessibilityHidden(true)161 }162 digitKey(0)163 key(label: "Delete", action: { if !pin.isEmpty { pin.removeLast(); keyFeedback += 1 } }) {164 Image(systemName: "delete.left").font(.title3).foregroundStyle(QColor.textPrimary)165 }166 .disabled(pin.isEmpty)167 }168 }169 .frame(maxWidth: 340)170 .disabled(locked)171 .opacity(locked ? 0.4 : 1)172 }173 .sensoryFeedback(.selection, trigger: keyFeedback)174 .sensoryFeedback(.error, trigger: errorCount)175 .onChange(of: errorCount) { _, _ in176 guard !reduceMotion else { return }177 shake = 0178 withAnimation(.linear(duration: 0.4)) { shake = 1 }179 }180 }181182 func digitKey(_ digit: Int) -> some View {183 key(label: "\(digit)", action: { append(digit) }) {184 Text("\(digit)")185 .font(Font.system(.title, design: .rounded, weight: .medium).monospacedDigit())186 .foregroundStyle(QColor.textPrimary)187 }188 }189190 func key<Label: View>(label: String, action: @escaping () -> Void, @ViewBuilder content: () -> Label) -> some View {191 Button(action: action) {192 content()193 .frame(maxWidth: .infinity, minHeight: keyHeight)194 .contentShape(Rectangle())195 }196 .buttonStyle(PINKeyStyle())197 .accessibilityLabel(label)198 }199200 func append(_ digit: Int) {201 guard pin.count < length else { return }202 pin.append(String(digit))203 keyFeedback += 1204 if pin.count == length { onComplete(pin) }205 }206}207208struct PINKeyStyle: ButtonStyle {209 func makeBody(configuration: Configuration) -> some View {210 configuration.label211 .background(configuration.isPressed ? QColor.surfaceRaised : QColor.surface,212 in: RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous))213 .overlay(RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))214 .animation(.snappy(duration: 0.12), value: configuration.isPressed)215 }216}217218/// Horizontal shake: `travel` animates from 0 to 1 and the content oscillates three times.219struct ShakeEffect: GeometryEffect {220 var travel: CGFloat221 var animatableData: CGFloat {222 get { travel }223 set { travel = newValue }224 }225226 func effectValue(size: CGSize) -> ProjectionTransform {227 ProjectionTransform(CGAffineTransform(translationX: 9 * sin(travel * .pi * 6) * (1 - travel), y: 0))228 }229}230231/// Strength of a password as estimated by the caller (`level` 0 = very weak … 4 = very strong).232public struct PasswordStrength: Sendable, Equatable {233 public let level: Int234 public let entropyBits: Double?235 public let advice: String?236237 public init(level: Int, entropyBits: Double? = nil, advice: String? = nil) {238 self.level = min(4, max(0, level))239 self.entropyBits = entropyBits240 self.advice = advice241 }242243 public var label: String {244 ["Very weak", "Weak", "Fair", "Strong", "Very strong"][level]245 }246247 var color: Color {248 switch level {249 case 0, 1: return QColor.negative250 case 2: return QColor.warning251 default: return QColor.positive252 }253 }254}255256/// Password entry with a reveal toggle and, when a strength is supplied, a five-step meter with its label,257/// the estimated entropy and one line of advice.258public struct PasswordField: View {259 let title: String260 @Binding var text: String261 let strength: PasswordStrength?262 let isNewPassword: Bool263 let onSubmit: (() -> Void)?264 @State private var revealed = false265 @FocusState private var focused: Bool266 @Environment(\.qIsSceneCaptured) private var isCaptured267268 public init(_ title: String = "Password", text: Binding<String>, strength: PasswordStrength? = nil, isNewPassword: Bool = false,269 onSubmit: (() -> Void)? = nil) {270 self.title = title271 self._text = text272 self.strength = strength273 self.isNewPassword = isNewPassword274 self.onSubmit = onSubmit275 }276277 public var body: some View {278 VStack(alignment: .leading, spacing: 10) {279 HStack(spacing: 4) {280 Group {281 // shown in clear only on request, and never while the screen is recorded or mirrored (QYV-APP-006)282 if SeedPhraseVisibility.showsPasswordInClear(revealed: revealed, captured: isCaptured) {283 TextField(title, text: $text)284 .font(Font.system(.body, design: .monospaced))285 } else {286 SecureField(title, text: $text)287 }288 }289 .foregroundStyle(QColor.textPrimary)290 .autocorrectionDisabled()291 #if os(iOS)292 .textInputAutocapitalization(.never)293 .textContentType(isNewPassword ? .newPassword : .password)294 #endif295 .focused($focused)296 .onSubmit { onSubmit?() }297 .privacySensitive()298 Button {299 revealed.toggle()300 } label: {301 Image(systemName: revealed ? "eye.slash" : "eye")302 .foregroundStyle(QColor.textSecondary)303 .frame(minWidth: 44, minHeight: 44)304 .contentShape(Rectangle())305 }306 .buttonStyle(.plain)307 .accessibilityLabel(revealed ? "Hide password" : "Show password")308 }309 .padding(.leading, 14)310 .padding(.trailing, 4)311 .frame(minHeight: 52)312 .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))313 .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous)314 .strokeBorder(focused ? QColor.violet : QColor.stroke, lineWidth: focused ? 1.5 : 1))315316 if let strength, !text.isEmpty {317 VStack(alignment: .leading, spacing: 6) {318 HStack(spacing: 4) {319 ForEach(0..<5, id: \.self) { i in320 Capsule()321 .fill(i <= strength.level ? strength.color : QColor.stroke)322 .frame(height: 4)323 }324 }325 .animation(.snappy(duration: 0.2), value: strength.level)326 .accessibilityHidden(true)327 HStack(alignment: .firstTextBaseline) {328 Text(strength.label).font(.caption.weight(.semibold)).foregroundStyle(strength.color)329 Spacer()330 if let bits = strength.entropyBits {331 Text("≈ \(Int(bits.rounded())) bits (estimate)")332 .font(QFont.caption.monospacedDigit())333 .foregroundStyle(QColor.textSecondary)334 .contentTransition(.numericText())335 }336 }337 if let advice = strength.advice {338 Text(advice).font(QFont.caption).foregroundStyle(QColor.textSecondary)339 .fixedSize(horizontal: false, vertical: true)340 }341 }342 .accessibilityElement(children: .ignore)343 .accessibilityLabel("Password strength: \(strength.label), step \(strength.level + 1) of 5"344 + (strength.entropyBits.map { ", about \(Int($0.rounded())) bits" } ?? "")345 + (strength.advice.map { ". " + $0 } ?? ""))346 }347 }348 }349}350351#if DEBUG352private struct SecurityPreview: View {353 @State private var pin = ""354 @State private var errors = 0355 @State private var password = ""356357 var body: some View {358 ScrollView {359 VStack(spacing: 32) {360 PINPad(pin: $pin, message: errors > 0 ? "Preview: wrong PIN" : nil, errorCount: errors, biometry: .faceID, onBiometry: {}) { _ in361 errors += 1362 pin = ""363 }364 PasswordField("Preview password", text: $password,365 strength: PasswordStrength(level: min(4, password.count / 4), entropyBits: Double(password.count) * 4,366 advice: "Preview advice supplied by the caller."), isNewPassword: true)367 }368 .padding()369 }370 .qScreen()371 }372}373374#Preview("PIN and password") { SecurityPreview() }375#endif376