1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
|
//
// WireguardKeysViewController.swift
// MullvadVPN
//
// Created by pronebird on 04/12/2019.
// Copyright © 2019 Mullvad VPN AB. All rights reserved.
//
import Combine
import Foundation
import UIKit
import os
/// A UI refresh interval for the public key creation date (in seconds)
private let kCreationDateRefreshInterval = TimeInterval(60)
/// A maximum number of characters to display out of the entire public key representation
private let kDisplayPublicKeyMaxLength = 20
private enum WireguardKeysViewState {
case `default`
case verifyingKey
case verifiedKey(Bool)
case regeneratingKey
}
private struct VerifyWireguardPublicKeyError: Error {
var underlyingError: MullvadRpc.Error
init(_ error: MullvadRpc.Error) {
self.underlyingError = error
}
}
extension VerifyWireguardPublicKeyError: LocalizedError {
var errorDescription: String? {
return NSLocalizedString("Cannot verify the public key", comment: "")
}
var failureReason: String? {
switch underlyingError {
case .network(let urlError):
return urlError.localizedDescription
case .server(let serverError):
return serverError.errorDescription
case .decoding, .encoding:
return NSLocalizedString("Internal error", comment: "")
}
}
}
class WireguardKeysViewController: UIViewController {
@IBOutlet var publicKeyButton: UIButton!
@IBOutlet var creationDateLabel: UILabel!
@IBOutlet var regenerateKeyButton: UIButton!
@IBOutlet var verifyKeyButton: UIButton!
@IBOutlet var wireguardKeyStatusView: WireguardKeyStatusView!
private var publicKeySubscriber: AnyCancellable?
private var loadKeySubscriber: AnyCancellable?
private var verifyKeySubscriber: AnyCancellable?
private var regenerateKeySubscriber: AnyCancellable?
private var creationDateTimerSubscriber: AnyCancellable?
private var copyToPasteboardSubscriber: AnyCancellable?
private let rpc = MullvadRpc.withEphemeralURLSession()
private var state: WireguardKeysViewState = .default {
didSet {
updateViewState(state)
}
}
override func viewDidLoad() {
super.viewDidLoad()
creationDateTimerSubscriber = Timer.publish(every: kCreationDateRefreshInterval, on: .main, in: .common)
.autoconnect()
.sink { [weak self] _ in
let publicKey = TunnelManager.shared.publicKey
self?.updatePublicKey(publicKey: publicKey, animated: true)
}
publicKeySubscriber = TunnelManager.shared.$publicKey
.dropFirst()
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] (publicKey) in
self?.updatePublicKey(publicKey: publicKey, animated: true)
})
// Set public key title without animation
updatePublicKey(publicKey: TunnelManager.shared.publicKey, animated: false)
}
// MARK: - IBActions
@IBAction func copyPublicKey(_ sender: Any) {
guard let publicKey = TunnelManager.shared.publicKey else { return }
UIPasteboard.general.string = publicKey.stringRepresentation()
setPublicKeyTitle(
string: NSLocalizedString("COPIED TO PASTEBOARD!", comment: ""),
animated: true)
copyToPasteboardSubscriber =
Just(()).cancellableDelay(for: .seconds(3), scheduler: DispatchQueue.main)
.sink(receiveValue: { [weak self] () in
guard let self = self else { return }
let publicKey = TunnelManager.shared.publicKey
self.updatePublicKey(publicKey: publicKey, animated: true)
})
}
@IBAction func handleRegenerateKey(_ sender: Any) {
regeneratePrivateKey()
}
@IBAction func handleVerifyKey(_ sender: Any) {
guard let accountToken = Account.shared.token,
let publicKey = TunnelManager.shared.publicKey else { return }
verifyKey(accountToken: accountToken, publicKey: publicKey)
}
// MARK: - Private
private func formatKeyGenerationElapsedTime(with creationDate: Date) -> String? {
return CustomDateComponentsFormatting.localizedString(
from: creationDate,
to: Date(),
unitsStyle: .full
).map { (formattedInterval) -> String in
return String(format: NSLocalizedString("%@ ago", comment: ""), formattedInterval)
}
}
private func updateCreationDateLabel(with creationDate: Date) {
creationDateLabel.text = formatKeyGenerationElapsedTime(with: creationDate) ?? "-"
}
private func updatePublicKey(publicKey: WireguardPublicKey?, animated: Bool) {
if let publicKey = publicKey {
let displayKey = publicKey
.stringRepresentation(maxLength: kDisplayPublicKeyMaxLength)
setPublicKeyTitle(string: displayKey, animated: animated)
updateCreationDateLabel(with: publicKey.creationDate)
} else {
setPublicKeyTitle(string: "-", animated: animated)
creationDateLabel.text = "-"
}
}
private func updateViewState(_ state: WireguardKeysViewState) {
switch state {
case .default:
setKeyActionButtonsEnabled(true)
wireguardKeyStatusView.status = .default
case .verifyingKey:
setKeyActionButtonsEnabled(false)
wireguardKeyStatusView.status = .verifying
case .verifiedKey(let isValid):
setKeyActionButtonsEnabled(true)
wireguardKeyStatusView.status = .verified(isValid)
case .regeneratingKey:
setKeyActionButtonsEnabled(false)
wireguardKeyStatusView.status = .verifying
}
}
private func setKeyActionButtonsEnabled(_ enabled: Bool) {
regenerateKeyButton.isEnabled = enabled
verifyKeyButton.isEnabled = enabled
}
private func verifyKey(accountToken: String, publicKey: WireguardPublicKey) {
verifyKeySubscriber = rpc.checkWireguardKey(
accountToken: accountToken,
publicKey: publicKey.rawRepresentation
)
.retry(1)
.receive(on: DispatchQueue.main)
.mapError { VerifyWireguardPublicKeyError($0) }
.handleEvents(receiveSubscription: { _ in
self.updateViewState(.verifyingKey)
})
.sink(receiveCompletion: { (completion) in
switch completion {
case .finished:
break
case .failure(let error):
self.presentError(error, preferredStyle: .alert)
self.updateViewState(.default)
}
}) { (isValid) in
self.updateViewState(.verifiedKey(isValid))
}
}
private func regeneratePrivateKey() {
regenerateKeySubscriber = TunnelManager.shared.regeneratePrivateKey()
.receive(on: DispatchQueue.main)
.handleEvents(receiveSubscription: { (_) in
self.updateViewState(.regeneratingKey)
}, receiveCompletion: { (completion) in
self.updateViewState(.default)
})
.sink { (completion) in
switch completion {
case .finished:
break
case .failure(let error):
os_log(.error, "Failed to re-generate the private key: %{public}s",
error.errorDescription ?? "")
self.presentError(error, preferredStyle: .alert)
}
}
}
private func setPublicKeyTitle(string: String, animated: Bool) {
let updateTitle = {
self.publicKeyButton.setTitle(string, for: .normal)
}
if animated {
updateTitle()
} else {
UIView.performWithoutAnimation {
updateTitle()
publicKeyButton.layoutIfNeeded()
}
}
}
}
class WireguardKeyStatusView: UIView {
enum Status {
case `default`, verifying, verified(Bool)
}
@IBOutlet var textLabel: UILabel!
@IBOutlet var activityIndicator: SpinnerActivityIndicatorView!
var status: Status = .default {
didSet {
updateView()
}
}
override func awakeFromNib() {
super.awakeFromNib()
updateView()
}
private func updateView() {
switch status {
case .default:
textLabel.isHidden = true
activityIndicator.stopAnimating()
case .verifying:
textLabel.isHidden = true
activityIndicator.startAnimating()
case .verified(let isValid):
textLabel.isHidden = false
activityIndicator.stopAnimating()
if isValid {
textLabel.textColor = .successColor
textLabel.text = NSLocalizedString("Key is valid", comment: "")
} else {
textLabel.textColor = .dangerColor
textLabel.text = NSLocalizedString("Key is invalid", comment: "")
}
}
}
}
|