import CommonCrypto import CryptoKit import Foundation // Runs on LocalServer's serial request queue. final class WebConsoleAPI { struct Reply { let status: String let body: [String: Any] init(_ values: [String: Any] = [:], status: String = "200 OK", errorCode: Int = 0) { self.status = status body = values.merging(["errorCode": errorCode]) { _, code in code } } } private static let admin = "Master Admin" private static let legacyPatientFields = [ "strLastName", "strFirstName", "strMiddleName", "strGender", "strAge", "dtBirthdate", "strEmail", "strSocialID", "strPhone", "strPhotoIDName", "dtRegisteredDateTime", "strZipCode", "strAddress", "strMobile", "strRace", "strClassification", "strJob", "eSourceType", ] private static let wireKey = Data(base64Encoded: "fCVpkpDy3QII1bJ0uklkvQ==")! private static let wireIV = Data(base64Encoded: "p+O8XWH7eWQw1xifYtxx5Q==")! private let passwordDigest = SHA256.hash(data: Data( (ProcessInfo.processInfo.environment["EZSERVER_CONSOLE_PASSWORD"] ?? "0000").utf8 )) private static let applicationFingerprint = Data(base64Encoded: "7dH5qqbP4LiANpOsC28VFALLLHuZyhWZjON7NKoO7T8=")! private struct Session { let expiry: Date let administrator: Bool } private let signingKey = SymmetricKey(size: .bits256) private var sessions: [String: Session] = [:] private var events: [[String: Any]] = [] private var failures = 0 private var lockedUntil = Date.distantPast func handles(_ path: [String], method: String) -> Bool { guard path.count >= 2 else { return false } switch (path[0], path[1], method) { case ("auth", "apploginr2", "POST"), ("auth", "applogin", "POST"), ("e2ds", "useraccountsbynamer2", "GET"), ("e2ds", "useraccountsfornames", "GET"), ("e2ds", "patientsbychartno", "GET"), ("e2ds", "patients", "POST"), ("e2ds", "patientsbychartnoforimage", "POST"), ("e2ds", "reportsbychartno", "GET"), ("e2ds", "trresultbychartno", "GET"), ("e2ds", "doctors", "GET"), ("e2ds", "smartpayaccountsbyidandqueryuserid", "GET"), ("e2ds", "patientsbynumlistforrecentlyacquired", "POST"), ("analytics", "eventsforsearch", "POST"), ("analytics", "eventsr2", "POST"), ("settings", "fileserversettings", "GET"), ("settings", "dbserversettings", "GET"), ("settings", "checkvaliddbconnection", "POST"), ("settings", "dirsforaccessible", "POST"), ("settings", "settingvaluesp2", "GET"), ("settings", "settingvalues", "GET"), ("e2ds", "patientsocialids", "GET"), ("settings", "fileserversettings", "PUT"), ("settings", "dbserversettings", "PUT"), ("settings", "settingvalues", "POST"), ("e2ds", "patientsocialids", "PUT"): return true default: return false } } func allowsNetworkAccess(_ path: [String], method: String) -> Bool { switch (path, method) { case (["auth", "apploginr2"], "POST"), (["auth", "applogin"], "POST"), (["e2ds", "patientsbynumlistforrecentlyacquired"], "POST"), (["e2ds", "patients"], "POST"), (["e2ds", "patientsbychartnoforimage"], "POST"): return true case (let route, "GET"): return route.starts(with: ["e2ds", "patientsbychartno"]) || isBootstrapRead(route) default: return false } } private func isBootstrapRead(_ path: [String]) -> Bool { path.starts(with: ["e2ds", "useraccountsbynamer2"]) || path.starts(with: ["e2ds", "smartpayaccountsbyidandqueryuserid"]) || path.starts(with: ["e2ds", "reportsbychartno"]) || path.starts(with: ["e2ds", "trresultbychartno"]) || path == ["e2ds", "doctors"] } func reply(path: [String], method: String, body: Data, authorization: String?, query: [URLQueryItem], queryPathLast: String?, store: ServerStore) -> Reply { if path == ["auth", "apploginr2"] || path == ["auth", "applogin"] { return login(body) } let now = Date() guard let authorization, authorization.hasPrefix("Bearer "), let session = sessions[String(authorization.dropFirst(7))], session.expiry > now else { return Reply(["errorMessage": "Auth token has expired"], status: "401 Unauthorized", errorCode: -8001511) } let applicationBootstrap = (method == "GET" && isBootstrapRead(path)) || (method == "GET" && path.starts(with: ["e2ds", "patientsbychartno"])) || (method == "POST" && (path == ["e2ds", "patientsbynumlistforrecentlyacquired"] || path == ["e2ds", "patients"] || path == ["e2ds", "patientsbychartnoforimage"])) guard session.administrator || applicationBootstrap else { return Reply(["errorMessage": "Administrator login required"], status: "403 Forbidden", errorCode: -1013) } let input = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:] switch (path[0], path[1], method) { case ("e2ds", "useraccountsbynamer2", "GET"): let queryName = query.first(where: { $0.name == "name" })?.value?.lowercased() let pathName = path.count == 4 && path[2] == "name" ? path[3] : nil guard let name = pathName ?? queryName, !name.isEmpty else { return Reply(status: "400 Bad Request", errorCode: -1021) } guard name == Self.admin.lowercased() else { return Reply(errorCode: -100037) } return Reply(["accountInfo": [ "nAccountId": 1, "strAccountName": Self.admin, "strAccountPasswd": "", "strGrade": "M", "bDataDel": true, "bDataTransfer": true, "bDataExport": true, "bDataAddModify": true, "bPatientAddModify": true, "bUserAccountEdit": true, "bSharedContentsEdit": true, "strAccountStatus": "eActive", "nFailedLoginCount": 0, "dtPasswordUpdated": "", ]]) case ("e2ds", "doctors", "GET"): return Reply(["doctorNameList": [String]()], errorCode: -100037) case ("e2ds", "smartpayaccountsbyidandqueryuserid", "GET"): return Reply(["strUserID": "", "strPassword": ""], errorCode: -100037) case ("e2ds", "patientsbynumlistforrecentlyacquired", "POST"): guard let doctor = input["DoctorNameAccountTypePair"] as? [String: String], doctor["first"] != nil, let selection = doctor["second"], ["eDoctorAccountAll", "eDoctorAccountNone", "eDoctorAccountName"].contains(selection) else { return Reply(status: "400 Bad Request", errorCode: -1021) } let page = input["pageNum"] as? Int ?? (input["pageNum"] as? String).flatMap(Int.init) ?? 0 let limit = input["numItems"] as? Int ?? (input["numItems"] as? String).flatMap(Int.init) ?? 50 guard page >= 0, limit > 0, limit <= 1000, page <= Int.max / limit else { return Reply(status: "400 Bad Request", errorCode: -1021) } do { let patients = selection == "eDoctorAccountName" ? [] : try store.recentlyAcquiredPatients(offset: page * limit, limit: limit) let items = patients.map { ["strChartNo": $0.chartNumber, "strLastName": $0.name, "strFirstName": "", "strMiddleName": "", "dtBirthdate": "", "strGender": ""] } return Reply(["searchedPatientList": items], errorCode: items.isEmpty ? -100037 : 0) } catch { return Reply(status: "503 Service Unavailable", errorCode: -1005) } case ("e2ds", "patients", "POST") where path.count == 2: guard let chartNumber = input["strChartNo"] as? String, !chartNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return Reply(status: "400 Bad Request", errorCode: -1021) } var fields: [String: String] = [:] for field in Self.legacyPatientFields { guard let raw = input[field], !(raw is NSNull) else { continue } guard let value = raw as? String, value.utf8.count <= 4096, !value.contains("\0") else { return Reply(status: "400 Bad Request", errorCode: -1021) } fields[field] = value } let gender = fields["strGender"]?.prefix(1).uppercased() ?? "" guard ["", "O", "M", "F"].contains(gender) else { return Reply(status: "400 Bad Request", errorCode: -1021) } fields["strGender"] = gender.isEmpty ? "O" : gender let displayName = ["strLastName", "strFirstName", "strMiddleName"].compactMap { fields[$0] } .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }.joined(separator: " ") do { _ = try store.createPatient(name: displayName.isEmpty ? chartNumber : displayName, chartNumber: chartNumber, legacyFields: fields) return Reply() } catch StoreError.conflict { return Reply(errorCode: -100029) } catch StoreError.invalid { return Reply(status: "400 Bad Request", errorCode: -1021) } catch { return Reply(status: "503 Service Unavailable", errorCode: -1005) } case ("e2ds", "patientsbychartnoforimage", "POST") where path.count == 2: guard let chartNumber = input["strChartNo"] as? String, !chartNumber.isEmpty else { return Reply(status: "400 Bad Request", errorCode: -1021) } do { guard let patient = try store.patient(chartNumber: chartNumber), try store.imageCount(patient.record.id) > 0 else { return Reply(errorCode: -100037) } return Reply() } catch { return Reply(status: "503 Service Unavailable", errorCode: -1005) } case ("e2ds", "reportsbychartno", "GET"), ("e2ds", "trresultbychartno", "GET"): guard !Self.chartNumber(query: query, path: path, last: queryPathLast).isEmpty else { return Reply(status: "400 Bad Request", errorCode: -1021) } if path[1] == "reportsbychartno" { return Reply(["vecReport": [String]()], errorCode: -100037) } return Reply(["errorMessage": "No such data in DB"], errorCode: -100037) case ("e2ds", "patientsbychartno", "GET"): let chartNumber = Self.chartNumber(query: query, path: path, last: queryPathLast) do { guard !chartNumber.isEmpty, let patient = try store.patient(chartNumber: chartNumber) else { return Reply(["patientInfo": []], errorCode: -100037) } var info: [String: Any] = Dictionary(uniqueKeysWithValues: Self.legacyPatientFields.map { ($0, "") }) info["strChartNo"] = patient.record.chartNumber info["strLastName"] = patient.record.name info["strlDoctor"] = [String]() info["eSourceType"] = "eUnknownSourceType" for (field, value) in patient.fields { info[field] = value } return Reply(["patientInfo": info]) } catch { return Reply(status: "503 Service Unavailable", errorCode: -1005) } case ("e2ds", "useraccountsfornames", "GET"): return Reply(["strlUserName": [Self.admin]]) case ("settings", "fileserversettings", "GET"): return Reply(["FileServerSettings": ["dataFilePath": store.files.path, "subDataFilePath": "", "linkFilePath": "", "ioSensorFilePath": "", "useFileManagerSettings": false]]) case ("settings", "dbserversettings", "GET"): return Reply(["DBServerSettings": ["hostname": "SQLite", "port": 0]]) case ("settings", "checkvaliddbconnection", "POST"): return Reply(["ValidDBConnection": false]) case ("settings", "dirsforaccessible", "POST"): let dirs = (input["dirs"] as? [[String: Any]] ?? []).map { item -> [String: Any] in var checked = item checked["errorCode"] = (item["dir"] as? String) == store.files.path ? 0 : -1002 return checked } return Reply(["dirs": dirs]) case ("settings", "settingvalues", "GET"): guard path == ["settings", "settingvalues", "section", "passwordpolicy"] else { return Reply(["data": []], errorCode: -100037) } do { let policy = try store.passwordPolicy() return Reply(["data": policy.sorted { $0.key < $1.key }.map { ["section": "PasswordPolicy", "key": $0.key, "value": $0.value] }]) } catch { return Reply(status: "503 Service Unavailable", errorCode: -1005) } case ("settings", "settingvalues", "POST") where path.count == 2: guard let rows = input["data"] as? [[String: String]], (1...8).contains(rows.count) else { return Reply(status: "400 Bad Request", errorCode: -1021) } var changes: [String: String] = [:] for row in rows { guard row["section"] == "PasswordPolicy", let key = row["key"], let value = row["value"], changes[key] == nil else { return Reply(status: "400 Bad Request", errorCode: -1021) } changes[key] = value } do { try store.updatePasswordPolicy(changes) event(type: "SETTINGS", message: "Updated password policy.") return Reply() } catch StoreError.invalid { return Reply(status: "400 Bad Request", errorCode: -1021) } catch { return Reply(status: "503 Service Unavailable", errorCode: -1005) } case ("settings", "settingvaluesp2", "GET"): guard path == ["settings", "settingvaluesp2", "section", "protectpatientsocialids", "key", "isenabled"] else { return Reply(["data": []], errorCode: -100037) } return Reply(["data": [["section": "ProtectPatientSocialIDs", "key": "isEnabled", "value": "false"]]]) case ("e2ds", "patientsocialids", "GET"): return Reply(["protectedSocialIDs": 0, "unprotectedSocialIDs": 0]) case ("analytics", "eventsforsearch", "POST"): return search(input) case ("analytics", "eventsr2", "POST"): guard input["eventType"] as? String == "LOGOUT" else { return Reply(status: "400 Bad Request", errorCode: -1021) } sessions.removeValue(forKey: String(authorization.dropFirst(7))) event(type: "LOGOUT", message: "Logged out of EzServer Web Console.") return Reply() case ("settings", "fileserversettings", "PUT"): return Reply(["errorMessage": "Change the images folder in the EzServer menu."], status: "409 Conflict", errorCode: -1017) default: return Reply(["errorMessage": "This setting is unavailable for the local SQLite server."], status: "409 Conflict", errorCode: -1017) } } private static func chartNumber(query: [URLQueryItem], path: [String], last: String?) -> String { let value = query.first(where: { $0.name == "chartno" })?.value ?? (path.count == 4 && path[2] == "chartno" ? last : nil) ?? "" // The original controller URL-decodes the value again after CodeIgniter parses it. let normalized = value.replacingOccurrences(of: "+", with: " ") return normalized.removingPercentEncoding ?? normalized } private func login(_ body: Data) -> Reply { let now = Date() guard now >= lockedUntil else { return Reply(["errorMessage": "Too many attempts. Try again in one minute.", "accountLockoutThreshold": 8, "failedLoginCount": failures], status: "429 Too Many Requests", errorCode: -8001001) } guard let request = try? JSONDecoder().decode(LoginRequest.self, from: body), let login = Self.decrypt(request.data), login.auth.exp >= now.timeIntervalSince1970, login.auth.exp < Double(Int32.max), let administrator = role(for: login.auth) else { failures += 1 if failures >= 8 { lockedUntil = now.addingTimeInterval(60) failures = 0 } return Reply(["errorMessage": "Invalid user name or password", "accountLockoutThreshold": 8, "failedLoginCount": failures], status: "401 Unauthorized", errorCode: -8001001) } failures = 0 sessions = sessions.filter { $0.value.expiry > now } if sessions.count >= 32, let oldest = sessions.min(by: { $0.value.expiry < $1.value.expiry }) { sessions.removeValue(forKey: oldest.key) } let expiry = Int(login.auth.exp) guard let token = try? makeToken(login, issuedAt: Int(now.timeIntervalSince1970), expiry: expiry) else { return Reply(status: "503 Service Unavailable", errorCode: -1005) } sessions[token] = Session(expiry: Date(timeIntervalSince1970: Double(expiry)), administrator: administrator) if administrator { event(type: "LOGIN", message: "Logged in to EzServer Web Console.") } return Reply(["token": token]) } private func role(for auth: Login.Auth) -> Bool? { guard let username = auth.decoded(auth.usr), let password = auth.decoded(auth.sec) else { return nil } if username == Data(Self.admin.utf8) { return Self.matches(SHA256.hash(data: password), passwordDigest) ? true : nil } // The bundled client uses the original temporary application account before user login. let fingerprint = SHA256.hash(data: username + Data([0]) + password) return Self.matches(fingerprint, Self.applicationFingerprint) ? false : nil } private static func matches(_ lhs: A, _ rhs: B) -> Bool where A.Element == UInt8, B.Element == UInt8 { zip(lhs, rhs).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0 } private func makeToken(_ login: Login, issuedAt: Int, expiry: Int) throws -> String { func base64URL(_ bytes: Data) -> String { bytes.base64EncodedString().replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") } let header = try JSONSerialization.data(withJSONObject: ["typ": "JWT", "alg": "HS256"], options: .sortedKeys) let payload = try JSONSerialization.data(withJSONObject: [ "enc": login.auth.enc, "iss": login.auth.usr, "aud": "http://www.ewoosoft.com", "iat": issuedAt, "exp": expiry, "clientName": login.client?.name ?? "Legacy", "clientVersion": login.client?.ver ?? "0.0.0", ], options: .sortedKeys) let message = base64URL(header) + "." + base64URL(payload) let signature = HMAC.authenticationCode(for: Data(message.utf8), using: signingKey) return message + "." + base64URL(Data(signature)) } private func event(type: String, message: String) { events.append(["id": UUID().uuidString, "eventType": String(type.prefix(100)), "appName": "EzServer Web Console", "userName": Self.admin, "message": String(message.prefix(512)), "created": ISO8601DateFormatter().string(from: Date())]) if events.count > 250 { events.removeFirst() } } private func search(_ input: [String: Any]) -> Reply { let from = input["startDate"] as? String ?? "" let through = input["endDate"] as? String ?? "" let user = input["userName"] as? String ?? "" let type = input["eventType"] as? String ?? "" let matches = events.reversed().filter { item in let day = (item["created"] as? String ?? "").prefix(10) return (from.isEmpty || day >= from.prefix(10)) && (through.isEmpty || day <= through.prefix(10)) && (user.isEmpty || item["userName"] as? String == user) && (type.isEmpty || item["eventType"] as? String == type) } let size = min(100, max(1, input["numRows"] as? Int ?? 20)) let page = min(matches.count, max(0, input["pageNum"] as? Int ?? 0)) return Reply(["numTotalEvents": matches.count, "pagedEvents": Array(matches.dropFirst(page * size).prefix(size))]) } private struct LoginRequest: Decodable { let data: String } private struct Login: Decodable { struct Auth: Decodable { let enc: String let usr: String let sec: String let exp: Double private enum CodingKeys: String, CodingKey { case enc, usr, sec, exp } init(from decoder: Decoder) throws { let fields = try decoder.container(keyedBy: CodingKeys.self) enc = try fields.decode(String.self, forKey: .enc) usr = try fields.decode(String.self, forKey: .usr) sec = try fields.decode(String.self, forKey: .sec) if let numeric = try? fields.decode(Double.self, forKey: .exp) { exp = numeric } else { exp = Double(try fields.decode(String.self, forKey: .exp)) ?? 0 } } func decoded(_ value: String) -> Data? { switch enc { case "raw": return Data(value.utf8) case "b64": return Data(base64Encoded: value) case "hex": let digits = Array(value.utf8) guard digits.count.isMultiple(of: 2) else { return nil } var bytes: [UInt8] = [] for index in stride(from: 0, to: digits.count, by: 2) { guard let byte = UInt8(String(decoding: digits[index...index + 1], as: UTF8.self), radix: 16) else { return nil } bytes.append(byte) } return Data(bytes) default: return nil } } } struct Client: Decodable { let name: String let ver: String } let auth: Auth let client: Client? } private static func decrypt(_ encoded: String) -> Login? { // The original Web Console uses AES-CBC with ISO/IEC 9797-1 method 2 padding. guard let ciphertext = Data(base64Encoded: encoded), !ciphertext.isEmpty, ciphertext.count.isMultiple(of: kCCBlockSizeAES128) else { return nil } var output = Data(count: ciphertext.count) let capacity = output.count var length = 0 let result = output.withUnsafeMutableBytes { plain in ciphertext.withUnsafeBytes { cipher in wireKey.withUnsafeBytes { key in wireIV.withUnsafeBytes { iv in CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES), 0, key.baseAddress, wireKey.count, iv.baseAddress, cipher.baseAddress, ciphertext.count, plain.baseAddress, capacity, &length) } } } } guard result == kCCSuccess, length == ciphertext.count, let marker = output.lastIndex(where: { $0 != 0 }), output[marker] == 0x80, output.count - marker <= kCCBlockSizeAES128 else { return nil } return try? JSONDecoder().decode(Login.self, from: output.prefix(upTo: marker)) } }