Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/APIConfiguration.swift3// Description: Where the backend lives and how the native apps present themselves to it (origin, User-Agent, cookie4// names, timeouts).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// Static description of one backend: its base URL, the `Origin` the server expects on mutating requests, the11/// `User-Agent` that labels the session ("SP Notes · iPhone|iPad|Mac") and the transport timeouts.12public struct APIConfiguration: Sendable, Equatable {13 /// The device family announced in the User-Agent. The server derives the session label from it.14 public enum DeviceFamily: String, Sendable, Equatable, CaseIterable {15 case iPhone16 case iPad17 case mac = "Macintosh"1819 /// The family of the device this code runs on (no UIKit: the hardware identifier is read with `uname`).20 public static var current: DeviceFamily {21 #if os(macOS)22 return .mac23 #else24 if ProcessInfo.processInfo.isiOSAppOnMac || ProcessInfo.processInfo.isMacCatalystApp { return .mac }25 let model = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? hardwareIdentifier()26 return model.hasPrefix("iPad") ? .iPad : .iPhone27 #endif28 }2930 var osName: String {31 switch self {32 case .iPhone: return "iOS"33 case .iPad: return "iPadOS"34 case .mac: return "macOS"35 }36 }37 }3839 /// Base URL of the backend, without a trailing slash (`https://note.spboucher.ai`).40 public var baseURL: URL41 /// Exact value of the `Origin` header sent on POST, PATCH, PUT and DELETE (`scheme://host[:port]`).42 public var origin: String43 /// `SPNotes/<x.y.z> (iPhone|iPad|Macintosh; <os>) native`.44 public var userAgent: String45 /// Idle timeout of an ordinary request, in seconds.46 public var requestTimeout: TimeInterval47 /// Total time allowed for one resource (uploads and downloads of 200 MB, long AI streams), in seconds.48 public var resourceTimeout: TimeInterval49 /// Idle timeout between two chunks of a server-sent event stream, in seconds.50 public var streamIdleTimeout: TimeInterval51 /// Name of the session cookie.52 public var sessionCookieName: String53 /// Name of the short-lived WebAuthn ceremony cookie.54 public var ceremonyCookieName: String5556 public init(57 baseURL: URL,58 userAgent: String = APIConfiguration.userAgent(appVersion: "1.0.0"),59 requestTimeout: TimeInterval = 30,60 resourceTimeout: TimeInterval = 60 * 60,61 streamIdleTimeout: TimeInterval = 120,62 sessionCookieName: String = "__Host-note_session",63 ceremonyCookieName: String = "__Host-note_wa"64 ) {65 self.baseURL = APIConfiguration.normalized(baseURL)66 self.origin = APIConfiguration.origin(of: baseURL)67 self.userAgent = userAgent68 self.requestTimeout = requestTimeout69 self.resourceTimeout = resourceTimeout70 self.streamIdleTimeout = streamIdleTimeout71 self.sessionCookieName = sessionCookieName72 self.ceremonyCookieName = ceremonyCookieName73 }7475 /// The production backend.76 public static let production = APIConfiguration(baseURL: URL(string: "https://note.spboucher.ai")!)7778 /// The production backend, announcing the given application version.79 public static func production(appVersion: String) -> APIConfiguration {80 APIConfiguration(baseURL: URL(string: "https://note.spboucher.ai")!, userAgent: userAgent(appVersion: appVersion))81 }8283 /// The relying party identifier the backend uses for passkeys: the host of the origin.84 public var relyingPartyID: String { baseURL.host ?? "" }8586 // MARK: User-Agent8788 /// Builds `SPNotes/<version> (<iPhone|iPad|Macintosh>; <os version>) native`.89 /// - Parameters:90 /// - appVersion: marketing version of the app (`1.2.0`).91 /// - device: device family; defaults to the current device.92 /// - osVersion: operating system and version (`iOS 18.1`); defaults to the running system.93 public static func userAgent(appVersion: String, device: DeviceFamily = .current, osVersion: String? = nil) -> String {94 let os = osVersion ?? currentOSVersion(for: device)95 return "SPNotes/\(sanitized(appVersion)) (\(device.rawValue); \(sanitized(os))) native"96 }9798 /// `iOS 18.1`, `iPadOS 18.1.1`, `macOS 15.2`.99 public static func currentOSVersion(for device: DeviceFamily = .current) -> String {100 let v = ProcessInfo.processInfo.operatingSystemVersion101 let number = v.patchVersion > 0 ? "\(v.majorVersion).\(v.minorVersion).\(v.patchVersion)" : "\(v.majorVersion).\(v.minorVersion)"102 return "\(device.osName) \(number)"103 }104105 /// `scheme://host[:port]` — the port is omitted when it is the default one of the scheme.106 public static func origin(of url: URL) -> String {107 let scheme = (url.scheme ?? "https").lowercased()108 let host = (url.host ?? "").lowercased()109 let bracketed = host.contains(":") ? "[\(host)]" : host110 guard let port = url.port, !(scheme == "https" && port == 443), !(scheme == "http" && port == 80) else {111 return "\(scheme)://\(bracketed)"112 }113 return "\(scheme)://\(bracketed):\(port)"114 }115116 // MARK: private117118 private static func normalized(_ url: URL) -> URL {119 var text = url.absoluteString120 while text.hasSuffix("/") { text.removeLast() }121 return URL(string: text) ?? url122 }123124 /// Header values must stay on one line and free of parentheses that would break the server's parsing.125 private static func sanitized(_ text: String) -> String {126 String(text.unicodeScalars.filter { $0.isASCII && $0.value >= 0x20 && $0.value != 0x7F && $0 != "(" && $0 != ")" && $0 != ";" }.map(Character.init))127 }128129 private static func hardwareIdentifier() -> String {130 var info = utsname()131 uname(&info)132 return withUnsafeBytes(of: &info.machine) { raw in133 String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)134 }135 }136}137