52 lines · 2.8 KB · SwiftRaw
// One Copy for secret columns. Persist consumption before putting bytes on// the clipboard, so a refused write never releases a credential.import CottonValuesimport Foundationimport CottonKit@MainActorenum SecretCopy { private struct Key: Hashable { let store: ObjectIdentifier; let table: String; let record: String } private static var copying: Set<Key> = [] static func problem(_ error: Error) -> String { if let refused = error as? ActionRefused { return refused.sentence } if let refused = error as? CottonCallError { return refused.message } return ShellLines.line("record", "copy.failed", ["reason": "\(error.localizedDescription)"]) } @discardableResult static func copy( _ value: RevealedValue, definition: TableDefinition, store: any Records, clipboard: any Clipboard = SystemClipboard(), now: Date = Date() ) async throws -> ChangeRecord? { guard let key = value.column else { guard clipboard.put(value.value, expiringAfter: SecretClipboard.seconds) else { throw ActionRefused(ShellLines.line("record", "copy.no_expiry")) } return nil } guard let column = definition.column(key), column.isSecret, column.type == .text, let policy = column.reveal, (1...86400).contains(policy.expires), definition.column(ColumnReveal.countColumn)?.type == .number, definition.column(ColumnReveal.lastRevealedColumn)?.type == .date, let id = value.record else { throw ActionRefused(ShellLines.line("record", "copy_no_expiry")) } let lock = Key(store: ObjectIdentifier(store), table: definition.id, record: id) guard copying.insert(lock).inserted else { throw ActionRefused(ShellLines.line("record", "copy.in_progress")) } defer { copying.remove(lock) } guard let record = try await store.get(table: definition.id, id: id) else { throw RecordsError.unknownRecord(id) } let count: Double switch record[ColumnReveal.countColumn] { case .null: count = 0 case .number(let number) where number >= 0 && number.rounded() == number: count = number default: throw ActionRefused(ShellLines.line("record", "copy.history_unreadable")) } guard !policy.once || count == 0 else { throw ActionRefused(ShellLines.line("record", "copy.once")) } let timestamp = CottonDate.format(now) let change = try await store.update(table: definition.id, id: id, patch: [ ColumnReveal.countColumn: .number(count + 1), ColumnReveal.lastRevealedColumn: .text(timestamp) ]) guard clipboard.put(value.value, expiringAfter: SecretClipboard.seconds(policy: TimeInterval(policy.expires))) else { throw ActionRefused(ShellLines.line("record", "copy.refused")) } return change }}