Remove the non-original Mac HTTP API

This commit is contained in:
SantaSpeen committed 2026-11-23 17:11:05 +03:00
1 parent 9487744f33
commit 69f70d0325
6 files changed
+22 -244

No files matched your search

+16 -105
View File
@@ -1,3 +1,4 @@
import CryptoKit
import Foundation
import Network
import OSLog
@@ -29,7 +30,8 @@ final class LocalServer {
private let queue = DispatchQueue(label: "ezserver.http")
private let maxHeaderSize = 8192
private let diagnostics = Logger(subsystem: "EzServerMac", category: "HTTP")
private let library: LibraryAPI
private let store: ServerStore
private let diskSpaceToken: SHA256.Digest
private let webConsole = WebConsoleAPI()
private var connections: [ObjectIdentifier: NWConnection] = [:]
private var diagnosticRoutes: [ObjectIdentifier: String] = [:]
@@ -38,8 +40,9 @@ final class LocalServer {
"implantds", "iosensor", "orthods", "thirdparty", "device", "pay",
]
init(port: UInt16, library: LibraryAPI) throws {
self.library = library
init(port: UInt16, configuration: ServerConfiguration) throws {
store = configuration.store
diskSpaceToken = SHA256.hash(data: Data(configuration.token.utf8))
let parameters = NWParameters.tcp
(parameters.defaultProtocolStack.internetProtocol as? NWProtocolIP.Options)?.version = .v4
parameters.requiredLocalEndpoint = .hostPort(host: "0.0.0.0", port: NWEndpoint.Port(rawValue: port)!)
@@ -150,7 +153,7 @@ final class LocalServer {
let reply: (Data) -> Void = { [self] body in
let response = webConsole.reply(path: route, method: method, body: body,
authorization: bearer, query: target.queryItems ?? [],
queryPathLast: segments.last, store: library.store)
queryPathLast: segments.last, store: store)
guard let json = try? JSONSerialization.data(withJSONObject: response.body) else {
connection.cancel()
return
@@ -172,16 +175,6 @@ final class LocalServer {
return
}
}
if segments.starts(with: ["mac", "v1", "patients"]) {
let path = Array(segments.dropFirst(3))
if method == "GET" {
serveLibrary(path: path, query: target.queryItems ?? [], authorization: bearer, on: connection)
} else {
mutateLibrary(method: method, path: path, query: target.queryItems ?? [], authorization: bearer,
headers: headers, initialBody: initialBody, on: connection)
}
return
}
guard method == "GET" else {
send(["error": "Only GET is supported"], status: "405 Method Not Allowed",
extraHeaders: "Allow: GET\r\n", on: connection)
@@ -216,8 +209,8 @@ final class LocalServer {
case "api/v1/auth/ping", "api/index.php/v1/auth/ping":
send(LegacyPing(), on: connection)
case "api/v1/fs/sysinfofordiskspace", "api/index.php/v1/fs/sysinfofordiskspace":
guard library.isAuthorized(bearer) else { sendUnauthorized(on: connection); return }
let values = try? library.store.directory.resourceValues(forKeys: [
guard isAuthorizedForDiskSpace(bearer) else { sendUnauthorized(on: connection); return }
let values = try? store.directory.resourceValues(forKeys: [
.volumeTotalCapacityKey, .volumeAvailableCapacityKey
])
guard let total = values?.volumeTotalCapacity, let free = values?.volumeAvailableCapacity else {
@@ -280,42 +273,15 @@ final class LocalServer {
})
}
private func serveLibrary(path: [String], query: [URLQueryItem], authorization: String?,
on connection: NWConnection) {
switch library.response(path: path, query: query, authorization: authorization) {
case let .listing(listing):
send(listing, on: connection)
case let .patient(patient):
send(patient, on: connection)
case let .file(file):
let safeName = file.filename.addingPercentEncoding(withAllowedCharacters: CharacterSet(
charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
)) ?? "image"
let headers = responseHeaders(status: "200 OK", type: file.contentType, bytes: file.bytes,
extra: "Content-Disposition: attachment; filename*=UTF-8''\(safeName)\r\n")
connection.send(content: headers, completion: .contentProcessed { [weak self] error in
guard let self, error == nil else { connection.cancel(); return }
self.stream(file.handle, remaining: file.bytes, on: connection)
})
case .unauthorized:
sendUnauthorized(on: connection)
case .invalidRequest:
send(["error": "Invalid limit, offset or search query"], status: "400 Bad Request", on: connection)
case .notFound:
send(["error": "Patient or image not found"], status: "404 Not Found", on: connection)
case .unavailable:
send(["error": "Could not read patient library"], status: "503 Service Unavailable", on: connection)
}
}
private struct LegacyPing: Encodable {
let errorCode = 0
let message = "Pong"
}
private struct PatientInput: Decodable {
let name: String
let chartNumber: String
private func isAuthorizedForDiskSpace(_ authorization: String?) -> Bool {
guard let authorization, authorization.hasPrefix("Bearer ") else { return false }
let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8))
return zip(candidate, diskSpaceToken).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0
}
private func sendUnauthorized(on connection: NWConnection) {
@@ -323,61 +289,6 @@ final class LocalServer {
extraHeaders: "WWW-Authenticate: Bearer\r\n", on: connection)
}
private func mutateLibrary(method: String, path: [String], query: [URLQueryItem], authorization: String?,
headers: [String: [String]], initialBody: Data, on connection: NWConnection) {
guard library.isAuthorized(authorization) else { sendUnauthorized(on: connection); return }
if method == "POST", path.isEmpty {
acceptBody(headers, initial: initialBody, maximum: 32 * 1024, on: connection) { url in
guard let input = try? JSONDecoder().decode(PatientInput.self, from: Data(contentsOf: url)) else {
throw StoreError.invalid
}
let patient = try self.library.store.createPatient(name: input.name, chartNumber: input.chartNumber)
self.send(patient, status: "201 Created", on: connection)
}
return
}
guard path.count == 3, path[1] == "images", let patient = UUID(uuidString: path[0]),
let image = UUID(uuidString: path[2]) else {
send(["error": "Route or method unavailable"], status: "404 Not Found", on: connection)
return
}
if method == "DELETE" {
do {
try library.store.deleteFile(patient: patient, imageID: image)
send(["status": "deleted"], on: connection)
} catch {
sendMutationError(error, on: connection)
}
} else if method == "PUT" {
guard let name = query.first(where: { $0.name == "name" })?.value, !name.isEmpty else {
sendMutationError(StoreError.invalid, on: connection)
return
}
let dicom = headers["content-type"]?.first?.lowercased() == "application/dicom"
acceptBody(headers, initial: initialBody, maximum: 2 * 1024 * 1024 * 1024, on: connection) { url in
let item = try self.library.store.addFile(from: url, patient: patient, imageID: image,
name: name, dicom: dicom)
self.send(item, status: "201 Created", on: connection)
}
} else {
send(["error": "Method unavailable"], status: "405 Method Not Allowed",
extraHeaders: "Allow: GET, PUT, DELETE\r\n", on: connection)
}
}
private func sendMutationError(_ error: Error, on connection: NWConnection) {
switch error {
case StoreError.invalid:
send(["error": "Invalid patient or file"], status: "400 Bad Request", on: connection)
case StoreError.notFound:
send(["error": "Patient or file not found"], status: "404 Not Found", on: connection)
case StoreError.conflict:
send(["error": "Duplicate chart number or file identifier"], status: "409 Conflict", on: connection)
default:
send(["error": "Could not update storage"], status: "503 Service Unavailable", on: connection)
}
}
private func acceptBody(_ headers: [String: [String]], initial: Data, maximum: Int, on connection: NWConnection,
finish: @escaping (URL) throws -> Void) {
guard headers["transfer-encoding"] == nil, let lengths = headers["content-length"],
@@ -390,7 +301,7 @@ final class LocalServer {
return
}
do {
let upload = try IncomingFile(in: library.store.directory)
let upload = try IncomingFile(in: store.directory)
let timeout = DispatchWorkItem { [weak connection] in connection?.cancel() }
queue.asyncAfter(deadline: .now() + 300, execute: timeout)
if headers["expect"]?.first?.lowercased() == "100-continue" {
@@ -399,7 +310,7 @@ final class LocalServer {
}
receiveBody(upload, chunk: initial, remaining: length, on: connection, timeout: timeout, finish: finish)
} catch {
sendMutationError(error, on: connection)
send(["error": "Could not read request body"], status: "503 Service Unavailable", on: connection)
}
}
@@ -426,7 +337,7 @@ final class LocalServer {
}
} catch {
timeout.cancel()
sendMutationError(error, on: connection)
send(["error": "Could not read request body"], status: "503 Service Unavailable", on: connection)
}
}