Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 177 additions & 0 deletions apps/sylo-ios/SyloKit/Sources/SyloKit/Access/ModeratorView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import Foundation

// The focused moderator view (Sylo 5.3, `moderator-view` in `GET /api/mobile/info`). A person whose level in a
// server is Inbox lands on the inbox and sees only the moderation tools their level allows, instead of the full
// app with its settings locked. View keeps the full read-only app (observers need the whole picture) and Edit is
// unchanged. An Inbox person can choose "Show everything" to get the full, still locked, app back. Nothing changes
// on the server: the level is `access` of each server in `GET /api/v2/guilds`, and the server enforces it on every
// route. The rules here follow the web dashboard's (web-v2/src/overviewModel.js, `navModel` with `focused`):
// the inboxes whose module is on (Tickets, Appeals, Applications, Suggestions), the Moderation hub and Member
// data. The audit log, the leaderboard, the insights, the module settings and the server settings are not in it.
// A server that does not announce `moderator-view` (Sylo 5.2 and older, self-hosted ones) keeps the full app.

extension ServerFeature {
/// The web dashboard's focused view for Inbox-level people; the app follows the same rules.
public static let moderatorView = ServerFeature(rawValue: "moderator-view")
}

public enum ModeratorView {
/// The device's choice to see everything instead of the focused view (one choice for the device, as the
/// web keeps one for the browser).
public static let showEverythingKey = "moderatorView.showEverything"

/// What a server screen shows the signed-in person.
public enum Mode: Equatable, Sendable {
/// The whole app (Edit, View, an unknown level, Inbox who chose "Show everything", or a server that
/// has no focused view).
case full
/// Only the moderation tools.
case focused
/// An Inbox person on a server whose features are not known yet: wait before drawing the app, so it
/// does not show the full app and then narrow it.
case undecided
}

/// - Parameters:
/// - access: The person's level in the server; nil from a server without levels (that is Edit).
/// - supports: Whether the server announces ``ServerFeature/moderatorView``; nil while that is not known.
/// - showEverything: The person's choice to see everything.
public static func mode(access: DashboardAccess?, supports: Bool?, showEverything: Bool) -> Mode {
guard access == DashboardAccess.inbox else { return .full }
switch supports {
case .some(true): return showEverything ? .full : .focused
case .some(false): return .full
case .none: return .undecided
}
}

/// How long an Inbox person waits for the server's features before the app draws as it would without them.
public static let featureWait: Duration = .seconds(3)

/// Whether the server announces ``ServerFeature/moderatorView``; nil only while that is really not known. An
/// Inbox person on a server that does not announce it (Sylo 5.2, self-hosted) never waits: the sign-in's own
/// read of the server already says so (`serverInfoKnown`), a finished read of the features says so
/// (`featuresRead`, whether it worked or not), and after ``featureWait`` the app stops waiting.
public static func supports(hasFeature: Bool, featuresRead: Bool, serverInfoKnown: Bool, waited: Bool) -> Bool? {
if hasFeature { return true }
if featuresRead || serverInfoKnown || waited { return false }
return nil
}

/// Whether the person may switch between the focused and the full app (an Inbox person on a server that
/// has the focused view): the switch is shown only then.
public static func canChoose(access: DashboardAccess?, supports: Bool?) -> Bool {
access == DashboardAccess.inbox && supports == true
}

// MARK: - What the focused view lists

/// The tabs of a server screen in the focused view, in the order they are shown.
public enum Tab: Hashable, Sendable {
/// The ticket conversations (when the Tickets module is on).
case tickets
/// The rest of the queues (applications, suggestions) and Member data.
case tools
/// The Moderation hub: infractions, and ban appeals when that module is on.
case moderation
}

/// The pages the Tools tab lists.
public enum Tool: Hashable, Sendable {
case applications
case suggestions
case memberData
}

/// Where a server opens for an Inbox person: the first inbox that is switched on, in the order of the web
/// dashboard (tickets, appeals, applications, suggestions), else the Moderation hub.
public enum Landing: Hashable, Sendable {
case tickets
/// The Moderation tab, on its Appeals part.
case appeals
case applications
case moderationHub

/// The tab this lands on.
public var tab: Tab {
switch self {
case .tickets: .tickets
case .appeals, .moderationHub: .moderation
case .applications: .tools
}
}
}

/// Whether a module is on. A card the overview does not list counts as on (as on the web), and so does every
/// module while the overview is not known.
public static func isModuleOn(_ id: String, in overview: ServerOverview?) -> Bool {
guard let card = overview?.groups.lazy.flatMap(\.cards).first(where: { $0.id == id }) else { return true }
return !(card.hasToggle && card.isEnabled != true)
}

public static func tabs(overview: ServerOverview?) -> [Tab] {
var tabs: [Tab] = []
if isModuleOn("tickets", in: overview) { tabs.append(.tickets) }
tabs.append(.tools)
tabs.append(.moderation)
return tabs
}

public static func tools(overview: ServerOverview?) -> [Tool] {
var tools: [Tool] = []
if isModuleOn("applications", in: overview) { tools.append(.applications) }
if isModuleOn("suggestions", in: overview) { tools.append(.suggestions) }
tools.append(.memberData)
return tools
}

/// Whether the Moderation tab offers the Appeals part.
public static func showsAppeals(overview: ServerOverview?) -> Bool {
isModuleOn("appeals", in: overview)
}

public static func landing(overview: ServerOverview?) -> Landing {
if isModuleOn("tickets", in: overview) { return .tickets }
if isModuleOn("appeals", in: overview) { return .appeals }
if isModuleOn("applications", in: overview) || isModuleOn("suggestions", in: overview) {
return .applications
}
return .moderationHub
}

/// Which part of the Moderation tab opens first in the focused view.
public enum ModerationStart: Hashable, Sendable {
case infractions
case appeals
}

/// The Moderation tab opens on Appeals when that is where the server lands (Tickets off, Appeals on). The
/// view applies it again when the overview arrives, so it holds also when the first draw had no overview.
public static func moderationStart(overview: ServerOverview?) -> ModerationStart {
landing(overview: overview) == .appeals ? .appeals : .infractions
}

/// The pages the search offers in the focused view (not the settings, the audit log or the insights).
public static func searchPages(overview: ServerOverview?) -> [SearchPage] {
var pages: [SearchPage] = []
if isModuleOn("tickets", in: overview) { pages.append(.tickets) }
if showsAppeals(overview: overview) { pages.append(.appeals) }
pages.append(.moderation)
pages.append(.memberData)
return pages
}

/// The overview the search sees in the focused view: only the two queues that are modules (the
/// applications and the suggestions), so module settings and the rest are not offered.
public static func searchOverview(_ overview: ServerOverview?) -> ServerOverview? {
guard let overview else { return nil }
let queues: Set<String> = ["applications", "suggestions"]
let groups = overview.groups.compactMap { group -> OverviewGroup? in
let cards = group.cards.filter { queues.contains($0.id) }
return cards.isEmpty ? nil : OverviewGroup(title: group.title, cards: cards)
}
return ServerOverview(
server: overview.server, openTickets: overview.openTickets, openAppeals: overview.openAppeals,
groups: groups, attention: nil)
}
}
17 changes: 15 additions & 2 deletions apps/sylo-ios/SyloKit/Sources/SyloKit/Health/HealthModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,30 @@ public struct HealthReport: Decodable, Sendable, Equatable {
public let backupsKept: Int?
/// Where off-site copies go ("WebDAV"), or nil when there are none.
public let offsite: String?
/// Rights of the Postgres role Sylo connects as that are more than it needs ("SUPERUSER", ...); empty when
/// the role is fine or the database is SQLite. nil when the server did not send the list (Sylo 5.2 and
/// older), which is also how the app tells that a restore must not be sent a ``RestoreConfirmation``.
public let roleRisks: [String]?
/// The docs on setting up a role with few rights, when the server sent them.
public let roleDocsURL: URL?

public init(
size: String? = nil, wal: String? = nil, isPostgres: Bool = false, backupIntervalHours: Double? = nil,
backupsKept: Int? = nil, offsite: String? = nil
backupsKept: Int? = nil, offsite: String? = nil, roleRisks: [String]? = nil, roleDocsURL: URL? = nil
) {
self.size = size
self.wal = wal
self.isPostgres = isPostgres
self.backupIntervalHours = backupIntervalHours
self.backupsKept = backupsKept
self.offsite = offsite
self.roleRisks = roleRisks
self.roleDocsURL = roleDocsURL
}

private enum CodingKeys: String, CodingKey { case size, wal, postgres, intervalHours, retention, offsite }
private enum CodingKeys: String, CodingKey {
case size, wal, postgres, intervalHours, retention, offsite, roleRisks, roleDocsUrl
}

public init(from decoder: any Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
Expand All @@ -55,6 +65,9 @@ public struct HealthReport: Decodable, Sendable, Equatable {
backupIntervalHours = try c.decodeIfPresent(Double.self, forKey: .intervalHours)
backupsKept = try c.decodeIfPresent(Int.self, forKey: .retention)
offsite = try c.decodeIfPresent(String.self, forKey: .offsite)
// `try?`: a list of an odd shape reads as not sent.
roleRisks = (try? c.decodeIfPresent([String].self, forKey: .roleRisks)) ?? nil
roleDocsURL = ServerMarkdown.openable((try? c.decodeURLIfPresent(forKey: .roleDocsUrl)) ?? nil)
}
}

Expand Down
76 changes: 72 additions & 4 deletions apps/sylo-ios/SyloKit/Sources/SyloKit/Operator/Backups.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,20 @@ extension Endpoints {
}

/// `POST /api/v2/health/backups/:name/restore`: replaces the live database with the backup and
/// restarts the bot (the server answers first, then exits).
/// restarts the bot (the server answers first, then exits). A Sylo 5.3 server wants the snapshot's name
/// as `confirm`, and `acknowledgeSql` for an uploaded Postgres dump (see ``RestorePlan``); an older server
/// takes no body, and gets none.
public struct RestoreBackup: APIEndpoint {
public typealias Response = OKResponse
public let name: String
public init(name: String) { self.name = name }
public let confirmation: RestoreConfirmation?
public init(name: String, confirmation: RestoreConfirmation? = nil) {
self.name = name
self.confirmation = confirmation
}
public var path: String { "/api/v2/health/backups/\(name.encodedPathSegment)/restore" }
public var method: HTTPMethod { .post }
public var body: (any Encodable & Sendable)? { confirmation }
}

/// `POST /api/v2/health/backups/import`: a raw body, sent as `application/octet-stream` and streamed
Expand Down Expand Up @@ -76,6 +83,61 @@ extension Endpoints {
}
}

/// What a restore request says besides the snapshot in its address (Sylo 5.3, src/db/backup.js
/// `restoreConfirmationError`). `confirm` is the snapshot's name. `acknowledgeSql` is `true` for a Postgres dump
/// that was uploaded (its name starts with `sylo-imported-`): restoring it runs the SQL in the file with the rights
/// of the database role Sylo connects as, and the server refuses it (400) unless the request says the person knows.
/// A key that is not set is not sent.
public struct RestoreConfirmation: Encodable, Sendable, Equatable {
public let confirm: String
public let acknowledgeSql: Bool?

public init(confirm: String, acknowledgeSql: Bool? = nil) {
self.confirm = confirm
self.acknowledgeSql = acknowledgeSql
}
}

/// What the app asks and sends for a restore of one snapshot.
public struct RestorePlan: Sendable, Equatable {
/// The snapshot is an uploaded Postgres dump: restoring it runs the SQL in the file. The app explains that and
/// wants the person to say they know, whatever the server's version.
public let isUploadedSqlDump: Bool
/// The body to send; nil for a server that did not say it wants one (Sylo 5.2 and older, which take none).
public let confirmation: RestoreConfirmation?

public init(isUploadedSqlDump: Bool, confirmation: RestoreConfirmation?) {
self.isUploadedSqlDump = isUploadedSqlDump
self.confirmation = confirmation
}

/// The name an uploaded snapshot is stored under (`sylo-imported-...`).
public static func isImported(_ name: String) -> Bool { name.hasPrefix("sylo-imported-") }

/// The plan for `name` on a server whose health report has this `database`. The 5.3 server sends `roleRisks`
/// (an empty list when the role is fine); a server without it is not sent the new keys.
public static func make(name: String, database: HealthReport.Database?) -> RestorePlan {
let sql = database?.isPostgres == true && isImported(name)
let wantsConfirmation = database?.roleRisks != nil
return RestorePlan(
isUploadedSqlDump: sql,
confirmation: wantsConfirmation ? RestoreConfirmation(confirm: name, acknowledgeSql: sql ? true : nil) : nil)
}
}

/// What the app says before it restores an uploaded Postgres dump, in the dashboard's words.
public enum UploadedDumpNotice {
public static let title = "This file was uploaded"
public static let message = "A Postgres dump holds SQL, and restoring it runs that SQL with the rights of the database role Sylo connects as. Inside Sylo's own database that adds nothing an operator cannot already do, because a restore replaces the whole database. A role with more rights can also reach the database server's own system. Restore only a file you made or trust."
public static let acknowledgement = "I made this file or I trust it"

/// The role's extra rights as a sentence, nil when there are none.
public static func roleSentence(_ risks: [String]?) -> String? {
guard let risks, !risks.isEmpty else { return nil }
return "The database role Sylo connects as has more rights than it needs: \(risks.joined(separator: ", ")). A restored dump runs its SQL with those rights."
}
}

/// The Backups screen: the list, and creating, deleting and restoring.
@MainActor
@Observable
Expand Down Expand Up @@ -162,13 +224,19 @@ public final class BackupsModel {
/// it had), which the session handles like any other 401.
/// - Returns: Whether the server took the restore.
@discardableResult
public func restore(_ name: String, typed: String) async -> Bool {
public func restore(_ name: String, typed: String, acknowledgedSql: Bool = false) async -> Bool {
guard confirmed(.restore(backup: name), typed) else { return false }
// An uploaded Postgres dump runs its SQL with the database role's rights: the person has to say they know.
let plan = RestorePlan.make(name: name, database: report?.database)
if plan.isUploadedSqlDump, !acknowledgedSql {
actionError = "Confirm that you made this file or trust it before it is restored."
return false
}
// Where the old process stands, to tell it from a restarted one afterwards.
let before = await uptimeBeforeRestore()
let logBaseline = await newestErrorID()
let started = await change { generation in
_ = try await self.session.send(Endpoints.RestoreBackup(name: name))
_ = try await self.session.send(Endpoints.RestoreBackup(name: name, confirmation: plan.confirmation))
guard self.session.generation == generation else { return }
self.restoring = name
}
Expand Down
Loading
Loading