diff --git a/Packaging/webconsole/console.js b/Packaging/webconsole/console.js
index 1049ae1..9a27986 100644
--- a/Packaging/webconsole/console.js
+++ b/Packaging/webconsole/console.js
@@ -4,7 +4,7 @@ const element = (id) => document.getElementById(id);
const routes = ["overview", "storage", "security", "audit"];
const nav = [...document.querySelectorAll("nav button")];
const dateFormat = new Intl.DateTimeFormat("ru", { dateStyle: "short", timeStyle: "short" });
-const labels = { LOGIN: "Вход", LOGOUT: "Выход" };
+const labels = { LOGIN: "Вход", LOGOUT: "Выход", SETTINGS: "Настройки" };
const pageSize = 20;
let token = "";
let revision = 0;
@@ -149,6 +149,54 @@ function definitions(target, entries) {
}
const yesNo = (value) => value === "true" ? "Да" : value === "false" ? "Нет" : "—";
+const policyForm = element("policy");
+const policyInputs = [...policyForm.querySelectorAll("input[name], select[name]")];
+for (const [name, options] of Object.entries({
+ minimumLength: Array.from({ length: 13 }, (_, index) => index + 8),
+ expirationDaysAfter: [30, 60, 90, 120, 150, 180],
+ expirationReminderDaysBefore: Array.from({ length: 10 }, (_, index) => index + 1)
+})) {
+ policyForm.elements[name].replaceChildren(...options.map((value) => new Option(value, value)));
+}
+
+function updateExpirationFields() {
+ const enabled = policyForm.elements.isExpirationEnabled.checked;
+ policyForm.elements.expirationDaysAfter.disabled = !enabled;
+ policyForm.elements.expirationReminderDaysBefore.disabled = !enabled;
+}
+
+policyForm.elements.isExpirationEnabled.addEventListener("change", updateExpirationFields);
+policyForm.addEventListener("input", () => message("policy-feedback", ""));
+policyForm.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ const feedback = element("policy-feedback");
+ feedback.dataset.error = "true";
+ if (policyInputs.filter((field) => field.name.endsWith("Enabled") &&
+ field.name !== "isExpirationEnabled" && field.checked).length < 2) {
+ message("policy-feedback", "Выберите не менее двух типов символов.");
+ return;
+ }
+ const data = policyInputs.map((field) => ({
+ section: "PasswordPolicy",
+ key: field.name,
+ value: field.type === "checkbox" ? String(field.checked) : field.value
+ }));
+ const fields = element("policy-fields");
+ const requestToken = token;
+ fields.disabled = true;
+ message("policy-feedback", "");
+ try {
+ await api("/api/v1/settings/settingvalues", { data });
+ if (requestToken !== token) return;
+ feedback.dataset.error = "false";
+ message("policy-feedback", "Политика сохранена.");
+ } catch (error) {
+ if (requestToken === token) message("policy-feedback", error.message);
+ } finally {
+ if (requestToken === token) fields.disabled = false;
+ }
+});
+
const loaders = {
async overview(active) {
const [health, result] = await Promise.all([api("/health"), api("/api/v1/info/versions")]);
@@ -169,6 +217,8 @@ const loaders = {
element("copy-path").disabled = !storagePath;
},
async security(active) {
+ element("policy-fields").disabled = true;
+ message("policy-feedback", "");
const [policy, protection, counts] = await Promise.all([
api("/api/v1/settings/settingvalues/section/PasswordPolicy"),
api("/api/v1/settings/settingvaluesp2/section/ProtectPatientSocialIDs/key/isEnabled"),
@@ -176,14 +226,12 @@ const loaders = {
]);
if (!active()) return;
const values = Object.fromEntries(policy.data.map(({ key, value }) => [key, value]));
- definitions("policy", [
- ["Минимальная длина", values.minimumLength],
- ["Прописные буквы", yesNo(values.isUpperAlphabetsEnabled)],
- ["Строчные буквы", yesNo(values.isLowerAlphabetsEnabled)],
- ["Цифры", yesNo(values.isNumericDigitsEnabled)],
- ["Специальные символы", yesNo(values.isSpecialCharactersEnabled)],
- ["Срок действия", yesNo(values.isExpirationEnabled)]
- ]);
+ for (const field of policyInputs) {
+ if (field.type === "checkbox") field.checked = values[field.name] === "true";
+ else field.value = values[field.name];
+ }
+ element("policy-fields").disabled = false;
+ updateExpirationFields();
definitions("privacy", [
["Защита включена", yesNo(protection.data[0]?.value)],
["Защищено", counts.protectedSocialIDs],
diff --git a/Packaging/webconsole/index.html b/Packaging/webconsole/index.html
index 1ee7b1f..7a6e661 100644
--- a/Packaging/webconsole/index.html
+++ b/Packaging/webconsole/index.html
@@ -66,7 +66,25 @@
Безопасность
Политика паролей
Требования оригинального EzServer к новым паролям
-
+
Защита идентификаторов
diff --git a/Packaging/webconsole/material.css b/Packaging/webconsole/material.css
index aee9153..93a8b9e 100644
--- a/Packaging/webconsole/material.css
+++ b/Packaging/webconsole/material.css
@@ -115,3 +115,14 @@ dd { margin: 0; font-weight: 600; text-align: end; }
.filters label { flex: 1 1 9rem; }
.topbar { font-size: .9rem; }
}
+
+.policy fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
+.policy > fieldset { display: grid; gap: 16px; }
+.policy .policy-toggles { display: grid; gap: 8px; }
+.policy legend { color: var(--muted); font-size: .875rem; margin-bottom: 8px; }
+.policy .policy-switch, .policy-toggles label { display: flex; align-items: center; gap: 10px; }
+.policy input[type="checkbox"] { width: 18px; height: 18px; min-height: 0; margin: 0; accent-color: var(--primary); }
+.policy-period { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
+.policy button { justify-self: start; }
+#policy-feedback { margin: 12px 0 0; color: var(--ok); }
+#policy-feedback[data-error="true"] { color: var(--error); }
diff --git a/README.md b/README.md
index fc7a539..e2ba662 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
В строке меню доступны запуск и остановка, выбор порта, выбор папки снимков и кнопка для открытия `/webconsole`. Путь и порт меняются при остановленной службе. При выборе папки EzServer копирует снимки в новый подкаталог `Files` и сохраняет прежнюю копию. По умолчанию SQLite и снимки находятся в `~/Library/Application Support/EzServerMac`. Для командной строки отдельную папку снимков можно задать абсолютным путём в `EZSERVER_IMAGES_PARENT`.
-Web Console приложения использует Material Design 3 и входит в каждую сборку. Локальный вход выполняется под `Master Admin` с паролем `0000` по умолчанию. Для запуска с другим паролем задайте `EZSERVER_CONSOLE_PASSWORD`. В консоли доступны обзор API, путь снимков, сведения о защите и журнал входов и выходов текущего процесса. Порт и папка меняются из строки меню. Отдельный PHP-режим раздаёт оригинальные статические ресурсы из установщика.
+Web Console приложения использует Material Design 3 и входит в каждую сборку. Локальный вход выполняется под `Master Admin` с паролем `0000` по умолчанию. Для запуска с другим паролем задайте `EZSERVER_CONSOLE_PASSWORD`. В консоли доступны обзор API, путь снимков, сведения о защите и журнал входов и выходов текущего процесса. Политику для новых паролей можно изменить во вкладке «Безопасность». Настройки хранятся в SQLite. Порт и папка меняются из строки меню. Отдельный PHP-режим раздаёт оригинальные статические ресурсы из установщика.
## Импорт из EzDent
diff --git a/Sources/EzServerMac/ServerStore.swift b/Sources/EzServerMac/ServerStore.swift
index cd01630..615320f 100644
--- a/Sources/EzServerMac/ServerStore.swift
+++ b/Sources/EzServerMac/ServerStore.swift
@@ -55,12 +55,69 @@ final class ServerStore {
PRAGMA user_version = 1;
""")
}
+ try execute("""
+ CREATE TABLE IF NOT EXISTS password_policy (
+ key TEXT PRIMARY KEY NOT NULL,
+ value TEXT NOT NULL
+ );
+ """)
try recoverPendingDeletes()
}
}
deinit { sqlite3_close(db) }
+ private static let passwordPolicyDefaults = [
+ "minimumLength": "10",
+ "isUpperAlphabetsEnabled": "true",
+ "isLowerAlphabetsEnabled": "true",
+ "isNumericDigitsEnabled": "true",
+ "isSpecialCharactersEnabled": "true",
+ "isExpirationEnabled": "false",
+ "expirationDaysAfter": "180",
+ "expirationReminderDaysBefore": "10",
+ ]
+
+ private static let characterClasses = [
+ "isUpperAlphabetsEnabled", "isLowerAlphabetsEnabled",
+ "isNumericDigitsEnabled", "isSpecialCharactersEnabled",
+ ]
+
+ func passwordPolicy() throws -> [String: String] {
+ lock.lock()
+ defer { lock.unlock() }
+ let rows = try query("SELECT key, value FROM password_policy") { row in
+ (self.text(row, 0), self.text(row, 1))
+ }
+ let saved = Dictionary(uniqueKeysWithValues: rows)
+ return Self.passwordPolicyDefaults.merging(saved) { _, value in value }
+ }
+
+ func updatePasswordPolicy(_ changes: [String: String]) throws {
+ lock.lock()
+ defer { lock.unlock() }
+ guard !changes.isEmpty, changes.keys.allSatisfy({ Self.passwordPolicyDefaults[$0] != nil }) else {
+ throw StoreError.invalid
+ }
+ try transaction {
+ let policy = try passwordPolicy().merging(changes) { _, value in value }
+ let booleanKeys = Self.characterClasses + ["isExpirationEnabled"]
+ guard let length = policy["minimumLength"].flatMap(Int.init), (8...20).contains(length),
+ let days = policy["expirationDaysAfter"].flatMap(Int.init), (30...180).contains(days), days % 30 == 0,
+ let reminder = policy["expirationReminderDaysBefore"].flatMap(Int.init), (1...10).contains(reminder),
+ booleanKeys.allSatisfy({ policy[$0] == "true" || policy[$0] == "false" }),
+ Self.characterClasses.filter({ policy[$0] == "true" }).count >= 2 else {
+ throw StoreError.invalid
+ }
+ for (key, value) in changes {
+ try run("""
+ INSERT INTO password_policy(key, value) VALUES (?, ?)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
+ """, [.text(key), .text(value)])
+ }
+ }
+ }
+
func copyImages(to parent: URL) throws {
lock.lock()
defer { lock.unlock() }
diff --git a/Sources/EzServerMac/WebConsoleAPI.swift b/Sources/EzServerMac/WebConsoleAPI.swift
index 400adc7..56102ed 100644
--- a/Sources/EzServerMac/WebConsoleAPI.swift
+++ b/Sources/EzServerMac/WebConsoleAPI.swift
@@ -87,20 +87,35 @@ final class WebConsoleAPI {
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]
- }])
+ 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)