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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
|
// @flow
import JsonRpcTransport from './jsonrpc-transport';
import {
object,
maybe,
string,
number,
boolean,
enumeration,
arrayOf,
oneOf,
} from 'validated/schema';
import { validate } from 'validated/object';
import type { Node as SchemaNode } from 'validated/schema';
export type AccountData = { expiry: string };
export type AccountToken = string;
export type Ip = string;
export type Location = {
ip: Ip,
country: string,
city: ?string,
latitude: number,
longitude: number,
mullvad_exit_ip: boolean,
};
const LocationSchema = object({
ip: string,
country: string,
city: maybe(string),
latitude: number,
longitude: number,
mullvad_exit_ip: boolean,
});
export type SecurityState = 'secured' | 'unsecured';
export type BackendState = {
state: SecurityState,
target_state: SecurityState,
};
export type RelayProtocol = 'tcp' | 'udp';
export type RelayLocation = {| city: [string, string] |} | {| country: string |};
type OpenVpnParameters = {
port: 'any' | { only: number },
protocol: 'any' | { only: RelayProtocol },
};
type TunnelOptions<TOpenVpnParameters> = {
openvpn: TOpenVpnParameters,
};
type RelaySettingsNormal<TTunnelOptions> = {
location:
| 'any'
| {
only: RelayLocation,
},
tunnel:
| 'any'
| {
only: TTunnelOptions,
},
};
// types describing the structure of RelaySettings
export type RelaySettingsCustom = {
host: string,
tunnel: {
openvpn: {
port: number,
protocol: RelayProtocol,
},
},
};
export type RelaySettings =
| {|
normal: RelaySettingsNormal<TunnelOptions<OpenVpnParameters>>,
|}
| {|
custom_tunnel_endpoint: RelaySettingsCustom,
|};
// types describing the partial update of RelaySettings
export type RelaySettingsNormalUpdate = $Shape<
RelaySettingsNormal<TunnelOptions<$Shape<OpenVpnParameters>>>,
>;
export type RelaySettingsUpdate =
| {|
normal: RelaySettingsNormalUpdate,
|}
| {|
custom_tunnel_endpoint: RelaySettingsCustom,
|};
const constraint = <T>(constraintValue: SchemaNode<T>) => {
return oneOf(
string, // any
object({
only: constraintValue,
}),
);
};
const RelaySettingsSchema = oneOf(
object({
normal: object({
location: constraint(
oneOf(
object({
city: arrayOf(string),
}),
object({
country: string,
}),
),
),
tunnel: constraint(
object({
openvpn: object({
port: constraint(number),
protocol: constraint(enumeration('udp', 'tcp')),
}),
}),
),
}),
}),
object({
custom_tunnel_endpoint: object({
host: string,
tunnel: object({
openvpn: object({
port: number,
protocol: enumeration('udp', 'tcp'),
}),
}),
}),
}),
);
export type RelayList = {
countries: Array<RelayListCountry>,
};
export type RelayListCountry = {
name: string,
code: string,
cities: Array<RelayListCity>,
};
export type RelayListCity = {
name: string,
code: string,
latitude: number,
longitude: number,
has_active_relays: boolean,
};
const RelayListSchema = object({
countries: arrayOf(
object({
name: string,
code: string,
cities: arrayOf(
object({
name: string,
code: string,
latitude: number,
longitude: number,
has_active_relays: boolean,
}),
),
}),
),
});
const AccountDataSchema = object({
expiry: string,
});
const allSecurityStates: Array<SecurityState> = ['secured', 'unsecured'];
const BackendStateSchema = object({
state: enumeration(...allSecurityStates),
target_state: enumeration(...allSecurityStates),
});
export interface DaemonRpcProtocol {
connect(string): void;
disconnect(): void;
getAccountData(AccountToken): Promise<AccountData>;
getRelayLocations(): Promise<RelayList>;
getAccount(): Promise<?AccountToken>;
setAccount(accountToken: ?AccountToken): Promise<void>;
updateRelaySettings(RelaySettingsUpdate): Promise<void>;
getRelaySettings(): Promise<RelaySettings>;
setAllowLan(boolean): Promise<void>;
getAllowLan(): Promise<boolean>;
connectTunnel(): Promise<void>;
disconnectTunnel(): Promise<void>;
getLocation(): Promise<Location>;
getState(): Promise<BackendState>;
subscribeStateListener((state: ?BackendState, error: ?Error) => void): Promise<void>;
addOpenConnectionObserver(() => void): ConnectionObserver;
addCloseConnectionObserver((error: ?Error) => void): ConnectionObserver;
authenticate(sharedSecret: string): Promise<void>;
getAccountHistory(): Promise<Array<AccountToken>>;
removeAccountFromHistory(accountToken: AccountToken): Promise<void>;
}
export class ResponseParseError extends Error {
_validationError: ?Error;
constructor(message: string, validationError: ?Error) {
super(message);
this._validationError = validationError;
}
get validationError(): ?Error {
return this._validationError;
}
}
export type ConnectionObserver = {
unsubscribe: () => void,
};
export class DaemonRpc implements DaemonRpcProtocol {
_transport = new JsonRpcTransport();
async authenticate(sharedSecret: string): Promise<void> {
await this._transport.send('auth', sharedSecret);
}
connect(connectionString: string) {
this._transport.connect(connectionString);
}
disconnect() {
this._transport.disconnect();
}
addOpenConnectionObserver(handler: () => void): ConnectionObserver {
this._transport.on('open', handler);
return {
unsubscribe: () => {
this._transport.off('open', handler);
},
};
}
addCloseConnectionObserver(handler: (error: ?Error) => void): ConnectionObserver {
this._transport.on('close', handler);
return {
unsubscribe: () => {
this._transport.off('close', handler);
},
};
}
async getAccountData(accountToken: AccountToken): Promise<AccountData> {
// send the IPC with 30s timeout since the backend will wait
// for a HTTP request before replying
const response = await this._transport.send('get_account_data', accountToken, 30000);
try {
return validate(AccountDataSchema, response);
} catch (error) {
throw new ResponseParseError('Invalid response from get_account_data', error);
}
}
async getRelayLocations(): Promise<RelayList> {
const response = await this._transport.send('get_relay_locations');
try {
return validate(RelayListSchema, response);
} catch (error) {
throw new ResponseParseError('Invalid response from get_relay_locations', error);
}
}
async getAccount(): Promise<?AccountToken> {
const response = await this._transport.send('get_account');
if (response === null || typeof response === 'string') {
return response;
} else {
throw new ResponseParseError('Invalid response from get_account', null);
}
}
async setAccount(accountToken: ?AccountToken): Promise<void> {
await this._transport.send('set_account', accountToken);
}
async updateRelaySettings(relaySettings: RelaySettingsUpdate): Promise<void> {
await this._transport.send('update_relay_settings', [relaySettings]);
}
async getRelaySettings(): Promise<RelaySettings> {
const response = await this._transport.send('get_relay_settings');
try {
const validatedObject = validate(RelaySettingsSchema, response);
/* $FlowFixMe:
There is no way to express the constraints with string literals, i.e:
RelaySettingsSchema constraint:
oneOf(string, object)
RelaySettings constraint:
'any' | object
These two are incompatible so we simply enforce the type for now.
*/
return ((validatedObject: any): RelaySettings);
} catch (e) {
throw new ResponseParseError('Invalid response from get_relay_settings', e);
}
}
async setAllowLan(allowLan: boolean): Promise<void> {
await this._transport.send('set_allow_lan', [allowLan]);
}
async getAllowLan(): Promise<boolean> {
const response = await this._transport.send('get_allow_lan');
if (typeof response === 'boolean') {
return response;
} else {
throw new ResponseParseError('Invalid response from get_allow_lan', null);
}
}
async connectTunnel(): Promise<void> {
await this._transport.send('connect');
}
async disconnectTunnel(): Promise<void> {
await this._transport.send('disconnect');
}
async getLocation(): Promise<Location> {
// send the IPC with 30s timeout since the backend will wait
// for a HTTP request before replying
const response = await this._transport.send('get_current_location', [], 30000);
try {
return validate(LocationSchema, response);
} catch (error) {
throw new ResponseParseError('Invalid response from get_current_location', error);
}
}
async getState(): Promise<BackendState> {
const response = await this._transport.send('get_state');
try {
return validate(BackendStateSchema, response);
} catch (error) {
throw new ResponseParseError('Invalid response from get_state', error);
}
}
subscribeStateListener(listener: (state: ?BackendState, error: ?Error) => void): Promise<void> {
return this._transport.subscribe('new_state', (payload) => {
try {
const newState = validate(BackendStateSchema, payload);
listener(newState, null);
} catch (error) {
listener(null, new ResponseParseError('Invalid payload from new_state', error));
}
});
}
async getAccountHistory(): Promise<Array<AccountToken>> {
const response = await this._transport.send('get_account_history');
try {
return validate(arrayOf(string), response);
} catch (error) {
throw new ResponseParseError('Invalid response from get_account_history', null);
}
}
async removeAccountFromHistory(accountToken: AccountToken): Promise<void> {
await this._transport.send('remove_account_from_history', accountToken);
}
}
|