Restore original Web Console login and navigation
This commit is contained in:
1 parent
d748f7cc69
commit
81a86d0e6c
5 files changed
+290
-7
No files matched your search
@@ -4,7 +4,7 @@
|
||||
|
||||
В строке меню доступны запуск и остановка, выбор порта, выбор папки снимков и кнопка для открытия `/webconsole`. Путь и порт меняются при остановленной службе. При выборе папки EzServer копирует снимки в новый подкаталог `Files` и сохраняет прежнюю копию. По умолчанию SQLite и снимки находятся в `~/Library/Application Support/EzServerMac`. Для командной строки отдельную папку снимков можно задать абсолютным путём в `EZSERVER_IMAGES_PARENT`.
|
||||
|
||||
Оригинальная Web Console извлекается из `webapps/webconsole` установщика. Её HTML, JavaScript и CSS входят в сборку, если ресурсы подготовлены через `server/prepare.sh`. Консоль оригинала использует PHP API для входа и настроек сервера. Эти операции ещё требуют переноса, поэтому доступна загрузка самой консоли.
|
||||
Оригинальная Web Console извлекается из `webapps/webconsole` установщика. Её HTML, JavaScript и CSS входят в сборку, если ресурсы подготовлены через `server/prepare.sh`. В приложении вход выполняется под `Master Admin` с паролем `0000` по умолчанию. Для запуска с другим паролем задайте `EZSERVER_CONSOLE_PASSWORD`. Консоль доступна через loopback и показывает версию API, параметры SQLite, фактический путь снимков и журнал входов и выходов текущего процесса. Порт и папка меняются из строки меню. Поля оригинала для внешнего PostgreSQL и управления защитой идентификаторов пациентов в локальном режиме доступны для просмотра.
|
||||
|
||||
## Импорт из EzDent
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ final class LocalServer {
|
||||
private let queue = DispatchQueue(label: "ezserver.loopback")
|
||||
private let maxHeaderSize = 8192
|
||||
private let library: LibraryAPI
|
||||
private let webConsole = WebConsoleAPI()
|
||||
private var connections: [ObjectIdentifier: NWConnection] = [:]
|
||||
|
||||
init(port: UInt16, library: LibraryAPI) throws {
|
||||
@@ -123,6 +124,35 @@ final class LocalServer {
|
||||
let segments = target.path.split(separator: "/").map(String.init)
|
||||
let authorization = headers["authorization"] ?? []
|
||||
let bearer = authorization.count == 1 ? authorization[0] : nil
|
||||
let lower = segments.map { $0.lowercased() }
|
||||
let apiPrefix = lower.starts(with: ["api", "index.php", "v1"]) ? 3 : 2
|
||||
if lower.starts(with: ["api", "v1"]) || apiPrefix == 3 {
|
||||
let route = Array(lower.dropFirst(apiPrefix))
|
||||
if webConsole.handles(route, method: method) {
|
||||
let reply: (Data) -> Void = { [self] body in
|
||||
let response = webConsole.reply(path: route, method: method, body: body,
|
||||
authorization: bearer, store: library.store)
|
||||
guard let json = try? JSONSerialization.data(withJSONObject: response.body) else {
|
||||
connection.cancel()
|
||||
return
|
||||
}
|
||||
sendBody(json, status: response.status, on: connection)
|
||||
}
|
||||
if method == "GET" {
|
||||
reply(Data())
|
||||
} else {
|
||||
guard headers["content-type"]?.first?.lowercased().hasPrefix("application/json") == true else {
|
||||
send(["errorMessage": "Expected application/json"],
|
||||
status: "415 Unsupported Media Type", on: connection)
|
||||
return
|
||||
}
|
||||
acceptBody(headers, initial: initialBody, maximum: 32 * 1024, on: connection) { url in
|
||||
reply(try Data(contentsOf: url))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
if segments.starts(with: ["mac", "v1", "patients"]) {
|
||||
let path = Array(segments.dropFirst(3))
|
||||
if method == "GET" {
|
||||
@@ -193,7 +223,8 @@ final class LocalServer {
|
||||
return
|
||||
}
|
||||
let type = UTType(filenameExtension: file.pathExtension)?.preferredMIMEType ?? "application/octet-stream"
|
||||
let headers = responseHeaders(status: "200 OK", type: type, bytes: bytes, extra: "")
|
||||
let policy = "Content-Security-Policy: connect-src 'self'; frame-ancestors 'none'; object-src 'none'\r\n"
|
||||
let headers = responseHeaders(status: "200 OK", type: type, bytes: bytes, extra: policy)
|
||||
connection.send(content: headers, completion: .contentProcessed { [weak self] error in
|
||||
guard let self, error == nil else { connection.cancel(); return }
|
||||
self.stream(handle, remaining: bytes, on: connection)
|
||||
@@ -377,6 +408,10 @@ final class LocalServer {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dateEncodingStrategy = .iso8601
|
||||
guard let body = try? encoder.encode(response) else { connection.cancel(); return }
|
||||
sendBody(body, status: status, extraHeaders: extraHeaders, on: connection)
|
||||
}
|
||||
|
||||
private func sendBody(_ body: Data, status: String, extraHeaders: String = "", on connection: NWConnection) {
|
||||
let headers = responseHeaders(status: status, type: "application/json; charset=utf-8",
|
||||
bytes: body.count, extra: extraHeaders)
|
||||
connection.send(content: headers + body, completion: .contentProcessed { _ in
|
||||
|
||||
@@ -9,7 +9,8 @@ struct MenuBarServer: App {
|
||||
MenuBarExtra {
|
||||
ServerPanel(model: model)
|
||||
} label: {
|
||||
Label("EzServer", systemImage: model.running ? "externaldrive.fill.badge.checkmark" : "externaldrive")
|
||||
Label("ezServer", systemImage: "externaldrive")
|
||||
.labelStyle(.titleAndIcon)
|
||||
}
|
||||
.menuBarExtraStyle(.window)
|
||||
}
|
||||
@@ -134,7 +135,22 @@ private struct ServerPanel: View {
|
||||
@ObservedObject var model: ServerControl
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: "externaldrive.fill")
|
||||
.font(.system(size: 17, weight: .medium))
|
||||
.foregroundStyle(Color.accentColor)
|
||||
.frame(width: 34, height: 34)
|
||||
.background(Color.accentColor.opacity(0.12), in: RoundedRectangle(cornerRadius: 8))
|
||||
Text("ezServer")
|
||||
.font(.title3.weight(.semibold))
|
||||
.accessibilityAddTraits(.isHeader)
|
||||
Spacer()
|
||||
Label(serverStatus, systemImage: "circle.fill")
|
||||
.font(.caption.weight(.medium))
|
||||
.foregroundStyle(model.running ? Color.green : Color.secondary)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
Text("Порт")
|
||||
TextField("55005", text: $model.port)
|
||||
@@ -161,10 +177,22 @@ private struct ServerPanel: View {
|
||||
if let notice = model.notice {
|
||||
Text(notice).font(.caption).foregroundStyle(.secondary).textSelection(.enabled)
|
||||
}
|
||||
Button("Открыть Web Console", action: model.openConsole)
|
||||
.disabled(!model.running)
|
||||
Divider()
|
||||
Button(action: model.openConsole) {
|
||||
Label("Открыть Web Console", systemImage: "arrow.up.right.square")
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.controlSize(.large)
|
||||
.disabled(!model.running)
|
||||
}
|
||||
.padding(16)
|
||||
.frame(width: 360)
|
||||
}
|
||||
|
||||
private var serverStatus: String {
|
||||
if model.starting { return "Запускается" }
|
||||
if model.stopping { return "Останавливается" }
|
||||
return model.running ? "Работает" : "Остановлен"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
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 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 var sessions: [String: Date] = [:]
|
||||
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"),
|
||||
("e2ds", "useraccountsbynamer2", "GET"),
|
||||
("e2ds", "useraccountsfornames", "GET"),
|
||||
("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 reply(path: [String], method: String, body: Data, authorization: String?, store: ServerStore) -> Reply {
|
||||
if path == ["auth", "apploginr2"] {
|
||||
return login(body)
|
||||
}
|
||||
let now = Date()
|
||||
guard let authorization, authorization.hasPrefix("Bearer "),
|
||||
let expires = sessions[String(authorization.dropFirst(7))], expires > now else {
|
||||
return Reply(["errorMessage": "Auth token has expired"], status: "401 Unauthorized", errorCode: -8001511)
|
||||
}
|
||||
let input = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
|
||||
switch (path[0], path[1], method) {
|
||||
case ("e2ds", "useraccountsbynamer2", "GET"):
|
||||
guard path == ["e2ds", "useraccountsbynamer2", "name", Self.admin.lowercased()] else {
|
||||
return Reply(status: "404 Not Found", errorCode: -100037)
|
||||
}
|
||||
return Reply(["accountInfo": ["strAccountName": Self.admin, "strGrade": "M"]])
|
||||
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)
|
||||
}
|
||||
// Display the defaults from CreateSETTINGDBTable.sql.
|
||||
let policy = [
|
||||
"minimumLength": "10",
|
||||
"isUpperAlphabetsEnabled": "true",
|
||||
"isLowerAlphabetsEnabled": "true",
|
||||
"isNumericDigitsEnabled": "true",
|
||||
"isSpecialCharactersEnabled": "true",
|
||||
"isExpirationEnabled": "false",
|
||||
"expirationDaysAfter": "180",
|
||||
"expirationReminderDaysBefore": "10",
|
||||
]
|
||||
return Reply(["data": policy.sorted { $0.key < $1.key }.map {
|
||||
["section": "PasswordPolicy", "key": $0.key, "value": $0.value]
|
||||
}])
|
||||
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 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.enc == "raw", login.auth.usr == Self.admin,
|
||||
login.auth.exp >= now.timeIntervalSince1970,
|
||||
zip(SHA256.hash(data: Data(login.auth.sec.utf8)), passwordDigest)
|
||||
.reduce(UInt8(0), { $0 | ($1.0 ^ $1.1) }) == 0 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 > now }
|
||||
if sessions.count >= 32, let oldest = sessions.min(by: { $0.value < $1.value }) {
|
||||
sessions.removeValue(forKey: oldest.key)
|
||||
}
|
||||
let token = UUID().uuidString + UUID().uuidString
|
||||
sessions[token] = now.addingTimeInterval(600)
|
||||
event(type: "LOGIN", message: "Logged in to EzServer Web Console.")
|
||||
return Reply(["token": token])
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
let auth: Auth
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -22,7 +22,7 @@
|
||||
|
||||
Относительно извлечённого `www/ezwebserver/src`:
|
||||
|
||||
- Оригинальные статические ресурсы Web Console находятся в `webapps/webconsole` установщика. Они используют API входа и настроек.
|
||||
- Оригинальные статические ресурсы Web Console находятся в `webapps/webconsole` установщика. Swift-режим обслуживает её оригинальный AES-вход (Master Admin / 0000 по умолчанию), настройки SQLite и файлов, версии и журнал сеанса. PHP-режим пока раздаёт статические ресурсы консоли.
|
||||
- `public/api/index.php` — точка входа, `application/config/routes.php` — маршруты. Версия API в комплекте — 3.0.6.
|
||||
- `application/controllers/v1/E2Ds.php` — оригинальные операции с карточками, включая `POST /api/v1/e2ds/patients` с полем `strChartNo` и `GET /api/v1/e2ds/patientsByChartNo?chartno=…`.
|
||||
- `application/config/database.php` — конфигурация групп БД. В `vendor/codeigniter/framework/system/database/drivers/` есть драйверы SQLite3 и PDO SQLite. При переносе проверить модели пациентов и групп данных на PostgreSQL-специфичные запросы. Схема текущего Swift-хранилища и схема оригинала требуют отдельного сопоставления.
|
||||
|
||||
Reference in new issue
Block a user