SPB Git

Repository Public

RelayPage.swift 16.2 KB 291 lines swift

1// SP Vault Relay: one-off encrypted copies of items, sent to an account (HPKE + signature) or by link (the key is in2// the part after #, which never reaches the server). Inbox, sent list, compose.3import SharedVaultKit4import SwiftUI56private let relayExpiries: [(label: String, seconds: Int)] = [("1 hour", 3600), ("1 day", 86_400), ("7 days", 604_800), ("30 days", 2_592_000)]78struct RelayPage: View {9    @Environment(AppModel.self) private var model10    @State private var shares: ShareList?11    @State private var error: String?12    @State private var loading = false13    @State private var opened: OpenedBox?14    @State private var picking = false15    @State private var composeFor: ItemView?16    @State private var confirm: ConfirmRequest?1718    fileprivate struct OpenedBox: Identifiable { let id: String; let share: OpenedShare }1920    var body: some View {21        ToolPage("Shared", subtitle: "One-off encrypted copies of items, sent to an account or by link. For lasting shared access, add a member to a vault instead.") {22            Button { picking = true } label: { Label("Share an item", systemImage: "square.and.arrow.up") }.buttonStyle(.vaultPrimary).accessibilityIdentifier("relay-compose")23        } content: {24            ErrorText(text: error)25            SectionCard("Received") {26                let list = (shares?.received ?? []).filter { !$0.revoked && !$0.expired }27                if list.isEmpty {28                    CardRow(last: true) { Text(loading && shares == nil ? "Loading…" : "Items other members send to your handle appear here until they expire.").font(.callout).foregroundStyle(Palette.muted) }29                }30                ForEach(Array(list.enumerated()), id: \.element.id) { i, s in31                    CardRow(last: i == list.count - 1) {32                        HStack(spacing: 10) {33                            Image(systemName: "tray.and.arrow.down").foregroundStyle(Palette.accent).accessibilityHidden(true)34                            VStack(alignment: .leading, spacing: 2) {35                                Text("From \(s.senderHandle)").foregroundStyle(Palette.text)36                                Text("Received \(ItemMeta.relative(s.createdAt)) · expires \(ItemMeta.relative(s.expiresAt))").font(.caption).foregroundStyle(Palette.muted)37                            }38                            Spacer(minLength: 8)39                            Button("Open") { open(s) }.buttonStyle(.vaultCompact).accessibilityLabel("Open the item shared by \(s.senderHandle)").accessibilityIdentifier("relay-open-\(i)")40                        }41                    }42                }43            }44            SectionCard("Sent", footer: "The server never sees what was shared — only who shared with whom, when, and how many times it was opened. Titles are not listed here for that reason.") {45                let list = shares?.sent ?? []46                if list.isEmpty {47                    CardRow(last: true) { Text("Open an item and choose Share… to send a one-off encrypted copy.").font(.callout).foregroundStyle(Palette.muted) }48                }49                ForEach(Array(list.enumerated()), id: \.element.id) { i, s in50                    CardRow(last: i == list.count - 1) {51                        HStack(spacing: 10) {52                            Image(systemName: s.kind == "link" ? "link" : "person").foregroundStyle(Palette.muted).accessibilityHidden(true)53                            VStack(alignment: .leading, spacing: 2) {54                                Text(s.kind == "link" ? "By link" : "To \(s.recipientHandle ?? "an account")").foregroundStyle(Palette.text)55                                Text("Opened \(s.views)\(s.maxViews.map { " of \($0)" } ?? "") time\(s.views == 1 && s.maxViews == nil ? "" : "s") · sent \(ItemMeta.relative(s.createdAt)) · expires \(ItemMeta.relative(s.expiresAt))")56                                    .font(.caption).foregroundStyle(Palette.muted)57                            }58                            Spacer(minLength: 8)59                            if s.revoked { Pill(text: "Revoked", tint: Palette.danger) }60                            else if s.expired { Pill(text: "Expired") }61                            else {62                                Pill(text: "Active", tint: Palette.accent)63                                Button("Revoke") { revoke(s) }.buttonStyle(.vaultDangerGhost).accessibilityIdentifier("relay-revoke-\(i)")64                            }65                        }66                    }67                }68            }69        }70        .task(id: model.sharesTick) { await load() }71        .sheet(item: $opened) { OpenedShareSheet(box: $0) }72        .sheet(isPresented: $picking) { ItemPickerSheet { picked in composeFor = picked } }73        .sheet(item: $composeFor, onDismiss: { Task { await load() } }) { ShareItemSheet(item: $0) }74        .confirmSheet($confirm)75    }7677    private func load() async {78        loading = true79        defer { loading = false }80        do { shares = try await model.engine.shares(); error = nil }81        catch { if let t = model.errorText(error) { self.error = shares == nil ? "The list of shares could not be loaded. \(t)" : t } }82    }8384    private func open(_ s: ShareInfo) {85        Task {86            error = await model.perform { opened = OpenedBox(id: s.id, share: try await model.engine.openShare(id: s.id)) }87            await load()88        }89    }9091    private func revoke(_ s: ShareInfo) {92        confirm = ConfirmRequest(title: "Revoke this share?", message: "The stored ciphertext is erased from the server. A copy that was already opened and saved cannot be taken back.", confirmLabel: "Revoke") {93            error = await model.perform("Share revoked. The stored ciphertext was erased.") { try await model.engine.revokeShare(id: s.id) }94            await load()95        }96    }97}9899// ── an opened incoming share ──100101private struct OpenedShareSheet: View {102    @Environment(AppModel.self) private var model103    @Environment(\.dismiss) private var dismiss104    let box: RelayPage.OpenedBox105    @State private var vaultId = ""106    @State private var error: String?107108    var body: some View {109        let item = box.share.item110        ToolSheet(title: "Shared by \(box.share.from)") {111            if box.share.fingerprintKnown {112                Callout(kind: .ok, text: "The signature verifies under the signing key this device already saw for this sender.")113            } else {114                Callout(kind: .warn, title: "First item from this sender on this device", text: "Their signing key is now remembered, and a later change will be refused. If you did not expect anything from \(box.share.from), do not use this item.")115            }116            HStack(spacing: 12) {117                ItemGlyph(title: item.title, symbol: ItemMeta.glyphSymbol(item), size: 40)118                VStack(alignment: .leading, spacing: 2) {119                    Text(ItemMeta.displayTitle(item)).font(.vaultHeadline).foregroundStyle(Palette.text)120                    Text("\(item.type.template.label) · \(ItemMeta.subtitle(item))").font(.callout).foregroundStyle(Palette.muted).lineLimit(2)121                }122            }123            .accessibilityElement(children: .combine)124            Text("Secrets stay hidden here. Save the item to a vault to see and use it.").font(.caption).foregroundStyle(Palette.muted)125            if model.writableVaults.isEmpty {126                Callout(kind: .info, text: "You have no vault you can write to.")127            } else {128                LabeledField(label: "Save to vault") {129                    Picker("Vault", selection: $vaultId) { ForEach(model.writableVaults) { Text($0.meta.name).tag($0.vaultId) } }.labelsHidden().accessibilityIdentifier("relay-save-vault")130                }131            }132            ErrorText(text: error)133            HStack {134                Spacer()135                Button("Close") { dismiss() }.buttonStyle(.vaultSecondary).keyboardShortcut(.cancelAction)136                Button("Save to vault", action: save).buttonStyle(.vaultPrimary).disabled(vaultId.isEmpty || model.busy).accessibilityIdentifier("relay-save")137            }138        }139        .onAppear { vaultId = model.defaultVaultId ?? "" }140    }141142    private func save() {143        Task {144            var item = box.share.item145            item.attachments = []; item.favorite = false; item.trashedAt = nil; item.conflictOf = nil146            error = await model.perform("Saved to your vault") { try await model.engine.saveItem(vaultId: vaultId, id: nil, item: item) }147            if error == nil { dismiss() }148        }149    }150}151152// ── item picker ──153154private struct ItemPickerSheet: View {155    @Environment(AppModel.self) private var model156    @Environment(\.dismiss) private var dismiss157    let onPick: (ItemView) -> Void158    @State private var query = ""159160    private var results: [ItemView] {161        model.items.filter { ($0.item.trashedAt ?? "").isEmpty && (query.isEmpty || SPV1.matchesQuery(haystack: SPV1.searchText($0.item), query: query)) }162            .sorted { ItemMeta.displayTitle($0.item).localizedCaseInsensitiveCompare(ItemMeta.displayTitle($1.item)) == .orderedAscending }163    }164165    var body: some View {166        VStack(alignment: .leading, spacing: 12) {167            HStack {168                Text("Choose an item to share").font(.vaultTitle).foregroundStyle(Palette.text)169                Spacer()170                Button("Cancel") { dismiss() }.buttonStyle(.vaultGhost).keyboardShortcut(.cancelAction)171            }172            TextField("Search", text: $query).textFieldStyle(.vault).autocorrectionDisabled().accessibilityLabel("Search items").accessibilityIdentifier("relay-pick-search")173            ScrollView {174                LazyVStack(spacing: 0) {175                    ForEach(results) { v in176                        Button {177                            dismiss()178                            onPick(v)179                        } label: {180                            HStack(spacing: 10) {181                                ItemGlyph(title: v.item.title, symbol: ItemMeta.glyphSymbol(v.item), size: 32)182                                VStack(alignment: .leading, spacing: 1) {183                                    Text(ItemMeta.displayTitle(v.item)).foregroundStyle(Palette.text).lineLimit(1)184                                    Text(ItemMeta.subtitle(v.item)).font(.caption).foregroundStyle(Palette.muted).lineLimit(1)185                                }186                                Spacer(minLength: 0)187                            }188                            .padding(.vertical, 8).contentShape(Rectangle())189                        }190                        .buttonStyle(.plain)191                        Divider().overlay(Palette.line)192                    }193                    if results.isEmpty { Text("No item matches.").font(.callout).foregroundStyle(Palette.muted).padding(.vertical, 20) }194                }195            }196        }197        .padding(22)198        .frame(minWidth: 320, idealWidth: 480, maxWidth: 560, minHeight: 380)199        .background(Palette.s1)200    }201}202203// ── compose ──204205/// Shares one item: to an account (only that account can decrypt) or by link (anyone holding the full link can read).206struct ShareItemSheet: View {207    @Environment(AppModel.self) private var model208    @Environment(\.dismiss) private var dismiss209    let item: ItemView210    private enum Mode: Hashable { case account, link }211    @State private var mode = Mode.account212    @State private var recipient: AccountLookup?213    @State private var compared = false214    @State private var expiry = 86_400215    @State private var limitViews = true216    @State private var maxViews = 1217    @State private var error: String?218    @State private var link: String?219    @State private var sentTo: String?220221    init(item: ItemView) { self.item = item }222223    var body: some View {224        ToolSheet(title: "Share “\(ItemMeta.displayTitle(item.item))”") {225            if let link { linkResult(link) }226            else if let sentTo {227                Callout(kind: .ok, title: "Shared with \(sentTo)", text: "Only \(sentTo)'s account can decrypt it. It appears in their Shared section until it expires.")228                HStack { Spacer(); Button("Done") { dismiss() }.buttonStyle(.vaultPrimary).accessibilityIdentifier("share-done") }229            } else { form }230        }231    }232233    @ViewBuilder private var form: some View {234        Picker("How", selection: $mode) { Text("To an account").tag(Mode.account); Text("By link").tag(Mode.link) }235            .pickerStyle(.segmented).labelsHidden().accessibilityIdentifier("share-mode")236        if mode == .account {237            Text("Only the recipient's account can decrypt it. The copy is signed by your account key.").font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)238            AccountLookupField(account: $recipient, testID: "share")239            if let recipient { Toggle("I compared the fingerprint with \(recipient.handle)", isOn: $compared).accessibilityIdentifier("share-compared") }240        } else {241            Callout(kind: .warn, title: "Anyone holding the full link can read this item",242                    text: "Until it expires or reaches its view limit. The key is the part after # — it never reaches the server — so send the link over a channel you trust, and prefer one view.")243        }244        LabeledField(label: "Expires after") {245            Picker("Expires after", selection: $expiry) { ForEach(relayExpiries, id: \.seconds) { Text($0.label).tag($0.seconds) } }.labelsHidden().accessibilityIdentifier("share-expiry")246        }247        if mode == .account { Toggle("Limit the number of views", isOn: $limitViews).accessibilityIdentifier("share-limit") }248        if mode == .link || limitViews {249            Stepper("Can be opened \(maxViews) time\(maxViews == 1 ? "" : "s")", value: $maxViews, in: 1...20).accessibilityIdentifier("share-max-views")250        }251        Text("Attachments and password history are not included. Sharing is a sensitive action: this device may ask to confirm your presence.")252            .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)253        ErrorText(text: error)254        HStack {255            Spacer()256            Button("Cancel") { dismiss() }.buttonStyle(.vaultSecondary).keyboardShortcut(.cancelAction)257            Button(mode == .link ? "Create link" : "Share", action: send).buttonStyle(.vaultPrimary)258                .disabled(model.busy || (mode == .account && (recipient == nil || !compared))).accessibilityIdentifier("share-send")259        }260        .onChange(of: recipient) { _, _ in compared = false }261    }262263    @ViewBuilder private func linkResult(_ link: String) -> some View {264        Callout(kind: .warn, title: "This link is shown once", text: "It carries the key. Copy it now and send it over a channel you trust. Anyone holding the full link can read this item until it expires or is used.")265        Text(link).font(.system(.caption, design: .monospaced)).foregroundStyle(Palette.text).textSelection(.enabled).lineLimit(5)266            .padding(10).frame(maxWidth: .infinity, alignment: .leading)267            .background(Palette.bg, in: RoundedRectangle(cornerRadius: 8, style: .continuous))268            .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.lineStrong, lineWidth: 1))269            .accessibilityLabel("Share link").accessibilityIdentifier("share-link")270        HStack(spacing: 8) {271            Button { model.copy(link, label: "Link") } label: { Label("Copy link", systemImage: "doc.on.doc") }.buttonStyle(.vaultSecondary).accessibilityIdentifier("share-link-copy")272            if let url = URL(string: link) { ShareLink(item: url) { Label("Send…", systemImage: "square.and.arrow.up") }.buttonStyle(.vaultSecondary) }273            Spacer()274            Button("Done") { dismiss() }.buttonStyle(.vaultPrimary).accessibilityIdentifier("share-done")275        }276    }277278    private func send() {279        Task {280            error = await model.perform {281                if mode == .link {282                    link = try await model.engine.shareByLink(item: item.item, origin: AppEnvironment.origin, expiresInSec: expiry, maxViews: maxViews)283                } else if let recipient {284                    try await model.engine.shareWithAccount(item: item.item, recipient: recipient, expiresInSec: expiry, maxViews: limitViews ? maxViews : nil)285                    sentTo = recipient.handle286                }287            }288        }289    }290}291
Files main
Menu

Theme