luci-proto-wireguard: grammar fixes
[project/luci.git] / protocols / luci-proto-wireguard / htdocs / luci-static / resources / protocol / wireguard.js
1 'use strict';
2 'require fs';
3 'require ui';
4 'require dom';
5 'require uci';
6 'require rpc';
7 'require form';
8 'require network';
9 'require validation';
10
11 var generateKey = rpc.declare({
12 object: 'luci.wireguard',
13 method: 'generateKeyPair',
14 expect: { keys: {} }
15 });
16
17 var getPublicAndPrivateKeyFromPrivate = rpc.declare({
18 object: 'luci.wireguard',
19 method: 'getPublicAndPrivateKeyFromPrivate',
20 params: ['privkey'],
21 expect: { keys: {} }
22 });
23
24 var generatePsk = rpc.declare({
25 object: 'luci.wireguard',
26 method: 'generatePsk',
27 expect: { psk: '' }
28 });
29
30 var qrIcon = '<svg viewBox="0 0 29 29" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M0 0h29v29H0z"/><path d="M4 4h1v1H4zM5 4h1v1H5zM6 4h1v1H6zM7 4h1v1H7zM8 4h1v1H8zM9 4h1v1H9zM10 4h1v1h-1zM12 4h1v1h-1zM13 4h1v1h-1zM14 4h1v1h-1zM15 4h1v1h-1zM16 4h1v1h-1zM18 4h1v1h-1zM19 4h1v1h-1zM20 4h1v1h-1zM21 4h1v1h-1zM22 4h1v1h-1zM23 4h1v1h-1zM24 4h1v1h-1zM4 5h1v1H4zM10 5h1v1h-1zM12 5h1v1h-1zM14 5h1v1h-1zM16 5h1v1h-1zM18 5h1v1h-1zM24 5h1v1h-1zM4 6h1v1H4zM6 6h1v1H6zM7 6h1v1H7zM8 6h1v1H8zM10 6h1v1h-1zM12 6h1v1h-1zM18 6h1v1h-1zM20 6h1v1h-1zM21 6h1v1h-1zM22 6h1v1h-1zM24 6h1v1h-1zM4 7h1v1H4zM6 7h1v1H6zM7 7h1v1H7zM8 7h1v1H8zM10 7h1v1h-1zM12 7h1v1h-1zM13 7h1v1h-1zM14 7h1v1h-1zM15 7h1v1h-1zM18 7h1v1h-1zM20 7h1v1h-1zM21 7h1v1h-1zM22 7h1v1h-1zM24 7h1v1h-1zM4 8h1v1H4zM6 8h1v1H6zM7 8h1v1H7zM8 8h1v1H8zM10 8h1v1h-1zM16 8h1v1h-1zM18 8h1v1h-1zM20 8h1v1h-1zM21 8h1v1h-1zM22 8h1v1h-1zM24 8h1v1h-1zM4 9h1v1H4zM10 9h1v1h-1zM12 9h1v1h-1zM13 9h1v1h-1zM15 9h1v1h-1zM18 9h1v1h-1zM24 9h1v1h-1zM4 10h1v1H4zM5 10h1v1H5zM6 10h1v1H6zM7 10h1v1H7zM8 10h1v1H8zM9 10h1v1H9zM10 10h1v1h-1zM12 10h1v1h-1zM14 10h1v1h-1zM16 10h1v1h-1zM18 10h1v1h-1zM19 10h1v1h-1zM20 10h1v1h-1zM21 10h1v1h-1zM22 10h1v1h-1zM23 10h1v1h-1zM24 10h1v1h-1zM13 11h1v1h-1zM14 11h1v1h-1zM15 11h1v1h-1zM16 11h1v1h-1zM4 12h1v1H4zM5 12h1v1H5zM8 12h1v1H8zM9 12h1v1H9zM10 12h1v1h-1zM13 12h1v1h-1zM15 12h1v1h-1zM19 12h1v1h-1zM21 12h1v1h-1zM22 12h1v1h-1zM23 12h1v1h-1zM24 12h1v1h-1zM5 13h1v1H5zM6 13h1v1H6zM8 13h1v1H8zM11 13h1v1h-1zM13 13h1v1h-1zM14 13h1v1h-1zM15 13h1v1h-1zM16 13h1v1h-1zM19 13h1v1h-1zM22 13h1v1h-1zM4 14h1v1H4zM5 14h1v1H5zM9 14h1v1H9zM10 14h1v1h-1zM11 14h1v1h-1zM15 14h1v1h-1zM18 14h1v1h-1zM19 14h1v1h-1zM20 14h1v1h-1zM21 14h1v1h-1zM22 14h1v1h-1zM23 14h1v1h-1zM7 15h1v1H7zM8 15h1v1H8zM9 15h1v1H9zM11 15h1v1h-1zM12 15h1v1h-1zM13 15h1v1h-1zM17 15h1v1h-1zM18 15h1v1h-1zM20 15h1v1h-1zM21 15h1v1h-1zM23 15h1v1h-1zM4 16h1v1H4zM6 16h1v1H6zM10 16h1v1h-1zM11 16h1v1h-1zM13 16h1v1h-1zM14 16h1v1h-1zM16 16h1v1h-1zM17 16h1v1h-1zM18 16h1v1h-1zM22 16h1v1h-1zM23 16h1v1h-1zM24 16h1v1h-1zM12 17h1v1h-1zM16 17h1v1h-1zM17 17h1v1h-1zM18 17h1v1h-1zM4 18h1v1H4zM5 18h1v1H5zM6 18h1v1H6zM7 18h1v1H7zM8 18h1v1H8zM9 18h1v1H9zM10 18h1v1h-1zM14 18h1v1h-1zM16 18h1v1h-1zM17 18h1v1h-1zM21 18h1v1h-1zM22 18h1v1h-1zM23 18h1v1h-1zM4 19h1v1H4zM10 19h1v1h-1zM12 19h1v1h-1zM13 19h1v1h-1zM15 19h1v1h-1zM16 19h1v1h-1zM19 19h1v1h-1zM21 19h1v1h-1zM23 19h1v1h-1zM24 19h1v1h-1zM4 20h1v1H4zM6 20h1v1H6zM7 20h1v1H7zM8 20h1v1H8zM10 20h1v1h-1zM12 20h1v1h-1zM13 20h1v1h-1zM15 20h1v1h-1zM18 20h1v1h-1zM19 20h1v1h-1zM20 20h1v1h-1zM22 20h1v1h-1zM23 20h1v1h-1zM24 20h1v1h-1zM4 21h1v1H4zM6 21h1v1H6zM7 21h1v1H7zM8 21h1v1H8zM10 21h1v1h-1zM13 21h1v1h-1zM15 21h1v1h-1zM16 21h1v1h-1zM19 21h1v1h-1zM21 21h1v1h-1zM23 21h1v1h-1zM24 21h1v1h-1zM4 22h1v1H4zM6 22h1v1H6zM7 22h1v1H7zM8 22h1v1H8zM10 22h1v1h-1zM13 22h1v1h-1zM15 22h1v1h-1zM18 22h1v1h-1zM19 22h1v1h-1zM20 22h1v1h-1zM21 22h1v1h-1zM22 22h1v1h-1zM4 23h1v1H4zM10 23h1v1h-1zM12 23h1v1h-1zM13 23h1v1h-1zM14 23h1v1h-1zM17 23h1v1h-1zM18 23h1v1h-1zM20 23h1v1h-1zM22 23h1v1h-1zM4 24h1v1H4zM5 24h1v1H5zM6 24h1v1H6zM7 24h1v1H7zM8 24h1v1H8zM9 24h1v1H9zM10 24h1v1h-1zM12 24h1v1h-1zM13 24h1v1h-1zM14 24h1v1h-1zM16 24h1v1h-1zM17 24h1v1h-1zM18 24h1v1h-1zM22 24h1v1h-1zM24 24h1v1h-1z"/></svg>';
31
32 function validateBase64(section_id, value) {
33 if (value.length == 0)
34 return true;
35
36 if (value.length != 44 || !value.match(/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/))
37 return _('Invalid Base64 key string');
38
39 if (value[43] != "=" )
40 return _('Invalid Base64 key string');
41
42 return true;
43 }
44
45 var stubValidator = {
46 factory: validation,
47 apply: function(type, value, args) {
48 if (value != null)
49 this.value = value;
50
51 return validation.types[type].apply(this, args);
52 },
53 assert: function(condition) {
54 return !!condition;
55 }
56 };
57
58 function generateDescription(name, texts) {
59 return E('li', { 'style': 'color: inherit;' }, [
60 E('span', name),
61 E('ul', texts.map(function (text) {
62 return E('li', { 'style': 'color: inherit;' }, text);
63 }))
64 ]);
65 }
66
67 function invokeQREncode(data, code) {
68 return fs.exec_direct('/usr/bin/qrencode', [
69 '--inline', '--8bit', '--type=SVG',
70 '--output=-', '--', data
71 ]).then(function(svg) {
72 code.style.opacity = '';
73 dom.content(code, Object.assign(E(svg), { style: 'width:100%;height:auto' }));
74 }).catch(function(error) {
75 code.style.opacity = '';
76
77 if (L.isObject(error) && error.name == 'NotFoundError') {
78 dom.content(code, [
79 Object.assign(E(qrIcon), { style: 'width:32px;height:32px;opacity:.2' }),
80 E('p', _('The <em>qrencode</em> package is required for generating an QR code image of the configuration.'))
81 ]);
82 }
83 else {
84 dom.content(code, [
85 _('Unable to generate QR code: %s').format(L.isObject(error) ? error.message : error)
86 ]);
87 }
88 });
89 }
90
91 var cbiKeyPairGenerate = form.DummyValue.extend({
92 cfgvalue: function(section_id, value) {
93 return E('button', {
94 'class': 'btn',
95 'click': ui.createHandlerFn(this, function(section_id, ev) {
96 var prv = this.section.getUIElement(section_id, 'private_key'),
97 pub = this.section.getUIElement(section_id, 'public_key'),
98 map = this.map;
99
100 if ((prv.getValue() || pub.getValue()) && !confirm(_('Do you want to replace the current keys?')))
101 return;
102
103 return generateKey().then(function(keypair) {
104 prv.setValue(keypair.priv);
105 pub.setValue(keypair.pub);
106 map.save(null, true);
107 });
108 }, section_id)
109 }, [ _('Generate new key pair') ]);
110 }
111 });
112
113 function handleWindowDragDropIgnore(ev) {
114 ev.preventDefault()
115 }
116
117 return network.registerProtocol('wireguard', {
118 getI18n: function() {
119 return _('WireGuard VPN');
120 },
121
122 getIfname: function() {
123 return this._ubus('l3_device') || this.sid;
124 },
125
126 getOpkgPackage: function() {
127 return 'wireguard-tools';
128 },
129
130 isFloating: function() {
131 return true;
132 },
133
134 isVirtual: function() {
135 return true;
136 },
137
138 getDevices: function() {
139 return null;
140 },
141
142 containsDevice: function(ifname) {
143 return (network.getIfnameOf(ifname) == this.getIfname());
144 },
145
146 renderFormOptions: function(s) {
147 var o, ss, ss2;
148
149 // -- general ---------------------------------------------------------------------
150
151 o = s.taboption('general', form.Value, 'private_key', _('Private Key'), _('Required. Base64-encoded private key for this interface.'));
152 o.password = true;
153 o.validate = validateBase64;
154 o.rmempty = false;
155
156 var serverName = this.getIfname();
157
158 o = s.taboption('general', form.Value, 'public_key', _('Public Key'), _('Base64-encoded public key of this interface for sharing.'));
159 o.rmempty = false;
160 o.write = function() {/* write nothing */};
161
162 o.load = function(section_id) {
163 var privKey = s.formvalue(section_id, 'private_key') || uci.get('network', section_id, 'private_key');
164
165 return getPublicAndPrivateKeyFromPrivate(privKey).then(
166 function(keypair) {
167 return keypair.pub || '';
168 },
169 function(error) {
170 return _('Error getting PublicKey');
171 }, this)
172 };
173
174 s.taboption('general', cbiKeyPairGenerate, '_gen_server_keypair', ' ');
175
176 o = s.taboption('general', form.Value, 'listen_port', _('Listen Port'), _('Optional. UDP port used for outgoing and incoming packets.'));
177 o.datatype = 'port';
178 o.placeholder = _('random');
179 o.optional = true;
180
181 o = s.taboption('general', form.DynamicList, 'addresses', _('IP Addresses'), _('Recommended. IP addresses of the WireGuard interface.'));
182 o.datatype = 'ipaddr';
183 o.optional = true;
184
185 o = s.taboption('general', form.Flag, 'nohostroute', _('No Host Routes'), _('Optional. Do not create host routes to peers.'));
186 o.optional = true;
187
188 o = s.taboption('general', form.Button, '_import', _('Import configuration'), _('Imports settings from an existing WireGuard configuration file'));
189 o.inputtitle = _('Load configuration…');
190 o.onclick = function() {
191 return ss.handleConfigImport('full');
192 };
193
194 // -- advanced --------------------------------------------------------------------
195
196 o = s.taboption('advanced', form.Value, 'mtu', _('MTU'), _('Optional. Maximum Transmission Unit of tunnel interface.'));
197 o.datatype = 'range(0,8940)';
198 o.placeholder = '1420';
199 o.optional = true;
200
201 o = s.taboption('advanced', form.Value, 'fwmark', _('Firewall Mark'), _('Optional. 32-bit mark for outgoing encrypted packets. Enter value in hex, starting with <code>0x</code>.'));
202 o.optional = true;
203 o.validate = function(section_id, value) {
204 if (value.length > 0 && !value.match(/^0x[a-fA-F0-9]{1,8}$/))
205 return _('Invalid hexadecimal value');
206
207 return true;
208 };
209
210
211 // -- peers -----------------------------------------------------------------------
212
213 try {
214 s.tab('peers', _('Peers'), _('Further information about WireGuard interfaces and peers at <a href=\'http://wireguard.com\'>wireguard.com</a>.'));
215 }
216 catch(e) {}
217
218 o = s.taboption('peers', form.SectionValue, '_peers', form.GridSection, 'wireguard_%s'.format(s.section));
219 o.depends('proto', 'wireguard');
220
221 ss = o.subsection;
222 ss.anonymous = true;
223 ss.addremove = true;
224 ss.addbtntitle = _('Add peer');
225 ss.nodescriptions = true;
226 ss.modaltitle = _('Edit peer');
227
228 ss.handleDragConfig = function(ev) {
229 ev.stopPropagation();
230 ev.preventDefault();
231 ev.dataTransfer.dropEffect = 'copy';
232 };
233
234 ss.handleDropConfig = function(mode, ev) {
235 var file = ev.dataTransfer.files[0],
236 nodes = ev.currentTarget,
237 input = nodes.querySelector('textarea'),
238 reader = new FileReader();
239
240 if (file) {
241 reader.onload = function(rev) {
242 input.value = rev.target.result.trim();
243 ss.handleApplyConfig(mode, nodes, file.name, ev);
244 };
245
246 reader.readAsText(file);
247 }
248
249 ev.stopPropagation();
250 ev.preventDefault();
251 };
252
253 ss.parseConfig = function(data) {
254 var lines = String(data).split(/(\r?\n)+/),
255 section = null,
256 config = { peers: [] },
257 s;
258
259 for (var i = 0; i < lines.length; i++) {
260 var line = lines[i].replace(/#.*$/, '').trim();
261
262 if (line.match(/^\[(\w+)\]$/)) {
263 section = RegExp.$1.toLowerCase();
264
265 if (section == 'peer')
266 config.peers.push(s = {});
267 else
268 s = config;
269 }
270 else if (section && line.match(/^(\w+)\s*=\s*(.+)$/)) {
271 var key = RegExp.$1,
272 val = RegExp.$2.trim();
273
274 if (val.length)
275 s[section + '_' + key.toLowerCase()] = val;
276 }
277 }
278
279 if (config.interface_address) {
280 config.interface_address = config.interface_address.split(/[, ]+/);
281
282 for (var i = 0; i < config.interface_address.length; i++)
283 if (!stubValidator.apply('ipaddr', config.interface_address[i]))
284 return _('Address setting is invalid');
285 }
286
287 if (config.interface_dns) {
288 config.interface_dns = config.interface_dns.split(/[, ]+/);
289
290 for (var i = 0; i < config.interface_dns.length; i++)
291 if (!stubValidator.apply('ipaddr', config.interface_dns[i], ['nomask']))
292 return _('DNS setting is invalid');
293 }
294
295 if (!config.interface_privatekey || validateBase64(null, config.interface_privatekey) !== true)
296 return _('PrivateKey setting is missing or invalid');
297
298 if (!stubValidator.apply('port', config.interface_listenport || '0'))
299 return _('ListenPort setting is invalid');
300
301 for (var i = 0; i < config.peers.length; i++) {
302 var pconf = config.peers[i];
303
304 if (pconf.peer_publickey != null && validateBase64(null, pconf.peer_publickey) !== true)
305 return _('PublicKey setting is invalid');
306
307 if (pconf.peer_presharedkey != null && validateBase64(null, pconf.peer_presharedkey) !== true)
308 return _('PresharedKey setting is invalid');
309
310 if (pconf.peer_allowedips) {
311 pconf.peer_allowedips = pconf.peer_allowedips.split(/[, ]+/);
312
313 for (var j = 0; j < pconf.peer_allowedips.length; j++)
314 if (!stubValidator.apply('ipaddr', pconf.peer_allowedips[j]))
315 return _('AllowedIPs setting is invalid');
316 }
317 else {
318 pconf.peer_allowedips = [ '0.0.0.0/0', '::/0' ];
319 }
320
321 if (pconf.peer_endpoint) {
322 var host_port = pconf.peer_endpoint.match(/^\[([a-fA-F0-9:]+)\]:(\d+)$/) || pconf.peer_endpoint.match(/^(.+):(\d+)$/);
323
324 if (!host_port || !stubValidator.apply('host', host_port[1]) || !stubValidator.apply('port', host_port[2]))
325 return _('Endpoint setting is invalid');
326
327 pconf.peer_endpoint = [ host_port[1], host_port[2] ];
328 }
329
330 if (pconf.peer_persistentkeepalive == 'off' || pconf.peer_persistentkeepalive == '0')
331 delete pconf.peer_persistentkeepalive;
332
333 if (!stubValidator.apply('port', pconf.peer_persistentkeepalive || '0'))
334 return _('PersistentKeepAlive setting is invalid');
335 }
336
337 return config;
338 };
339
340 ss.handleApplyConfig = function(mode, nodes, comment, ev) {
341 var input = nodes.querySelector('textarea').value,
342 error = nodes.querySelector('.alert-message'),
343 cancel = nodes.nextElementSibling.querySelector('.btn'),
344 config = this.parseConfig(input);
345
346 if (typeof(config) == 'string') {
347 error.firstChild.data = _('Cannot parse configuration: %s').format(config);
348 error.style.display = 'block';
349 return;
350 }
351
352 if (mode == 'full') {
353 var prv = s.formvalue(s.section, 'private_key');
354
355 if (prv && prv != config.interface_privatekey && !confirm(_('Overwrite the current settings with the imported configuration?')))
356 return;
357
358 return getPublicAndPrivateKeyFromPrivate(config.interface_privatekey).then(function(keypair) {
359 s.getOption('private_key').getUIElement(s.section).setValue(keypair.priv);
360 s.getOption('public_key').getUIElement(s.section).setValue(keypair.pub);
361 s.getOption('listen_port').getUIElement(s.section).setValue(config.interface_listenport || '');
362 s.getOption('addresses').getUIElement(s.section).setValue(config.interface_address);
363
364 if (config.interface_dns)
365 s.getOption('dns').getUIElement(s.section).setValue(config.interface_dns);
366
367 for (var i = 0; i < config.peers.length; i++) {
368 var pconf = config.peers[i];
369 var sid = uci.add('network', 'wireguard_' + s.section);
370
371 uci.sections('network', 'wireguard_' + s.section, function(peer) {
372 if (peer.public_key == pconf.peer_publickey)
373 uci.remove('network', peer['.name']);
374 });
375
376 uci.set('network', sid, 'description', comment || _('Imported peer configuration'));
377 uci.set('network', sid, 'public_key', pconf.peer_publickey);
378 uci.set('network', sid, 'preshared_key', pconf.peer_presharedkey);
379 uci.set('network', sid, 'allowed_ips', pconf.peer_allowedips);
380 uci.set('network', sid, 'persistent_keepalive', pconf.peer_persistentkeepalive);
381
382 if (pconf.peer_endpoint) {
383 uci.set('network', sid, 'endpoint_host', pconf.peer_endpoint[0]);
384 uci.set('network', sid, 'endpoint_port', pconf.peer_endpoint[1]);
385 }
386 }
387
388 return s.map.save(null, true);
389 }).then(function() {
390 cancel.click();
391 });
392 }
393 else {
394 return getPublicAndPrivateKeyFromPrivate(config.interface_privatekey).then(function(keypair) {
395 var sid = uci.add('network', 'wireguard_' + s.section);
396 var pub = s.formvalue(s.section, 'public_key');
397
398 uci.sections('network', 'wireguard_' + s.section, function(peer) {
399 if (peer.public_key == keypair.pub)
400 uci.remove('network', peer['.name']);
401 });
402
403 uci.set('network', sid, 'description', comment || _('Imported peer configuration'));
404 uci.set('network', sid, 'public_key', keypair.pub);
405 uci.set('network', sid, 'private_key', keypair.priv);
406
407 for (var i = 0; i < config.peers.length; i++) {
408 var pconf = config.peers[i];
409
410 if (pconf.peer_publickey == pub) {
411 uci.set('network', sid, 'preshared_key', pconf.peer_presharedkey);
412 uci.set('network', sid, 'allowed_ips', pconf.peer_allowedips);
413 uci.set('network', sid, 'persistent_keepalive', pconf.peer_persistentkeepalive);
414 break;
415 }
416 }
417
418 return s.map.save(null, true);
419 }).then(function() {
420 cancel.click();
421 });
422 }
423 };
424
425 ss.handleConfigImport = function(mode) {
426 var mapNode = ss.getActiveModalMap(),
427 headNode = mapNode.parentNode.querySelector('h4'),
428 parent = this.map;
429
430 var nodes = E('div', {
431 'dragover': this.handleDragConfig,
432 'drop': this.handleDropConfig.bind(this, mode)
433 }, [
434 E([], (mode == 'full') ? [
435 E('p', _('Drag or paste a valid <em>*.conf</em> file below to configure the local WireGuard interface.'))
436 ] : [
437 E('p', _('Paste or drag a WireGuard configuration (commonly <em>wg0.conf</em>) from another system below to create a matching peer entry allowing that system to connect to the local WireGuard interface.')),
438 E('p', _('To fully configure the local WireGuard interface from an existing (e.g. provider supplied) configuration file, use the <strong><a class="full-import" href="#">configuration import</a></strong> instead.'))
439 ]),
440 E('p', [
441 E('textarea', {
442 'placeholder': (mode == 'full')
443 ? _('Paste or drag supplied WireGuard configuration file…')
444 : _('Paste or drag WireGuard peer configuration (wg0.conf) file…'),
445 'style': 'height:5em;width:100%; white-space:pre'
446 })
447 ]),
448 E('div', {
449 'class': 'alert-message',
450 'style': 'display:none'
451 }, [''])
452 ]);
453
454 var cancelFn = function() {
455 nodes.parentNode.removeChild(nodes.nextSibling);
456 nodes.parentNode.removeChild(nodes);
457 mapNode.classList.remove('hidden');
458 mapNode.nextSibling.classList.remove('hidden');
459 headNode.removeChild(headNode.lastChild);
460 window.removeEventListener('dragover', handleWindowDragDropIgnore);
461 window.removeEventListener('drop', handleWindowDragDropIgnore);
462 };
463
464 var a = nodes.querySelector('a.full-import');
465
466 if (a) {
467 a.addEventListener('click', ui.createHandlerFn(this, function(mode) {
468 cancelFn();
469 this.handleConfigImport('full');
470 }));
471 }
472
473 mapNode.classList.add('hidden');
474 mapNode.nextElementSibling.classList.add('hidden');
475
476 headNode.appendChild(E('span', [ ' » ', (mode == 'full') ? _('Import configuration') : _('Import as peer') ]));
477 mapNode.parentNode.appendChild(E([], [
478 nodes,
479 E('div', {
480 'class': 'right'
481 }, [
482 E('button', {
483 'class': 'btn',
484 'click': cancelFn
485 }, [ _('Cancel') ]),
486 ' ',
487 E('button', {
488 'class': 'btn primary',
489 'click': ui.createHandlerFn(this, 'handleApplyConfig', mode, nodes, null)
490 }, [ _('Import settings') ])
491 ])
492 ]));
493
494 window.addEventListener('dragover', handleWindowDragDropIgnore);
495 window.addEventListener('drop', handleWindowDragDropIgnore);
496 };
497
498 ss.renderSectionAdd = function(/* ... */) {
499 var nodes = this.super('renderSectionAdd', arguments);
500
501 nodes.appendChild(E('button', {
502 'class': 'btn',
503 'click': ui.createHandlerFn(this, 'handleConfigImport', 'peer')
504 }, [ _('Import configuration as peer…') ]));
505
506 return nodes;
507 };
508
509 ss.renderSectionPlaceholder = function() {
510 return E('em', _('No peers defined yet.'));
511 };
512
513 o = ss.option(form.Flag, 'disabled', _('Peer disabled'), _('Enable / Disable peer. Restart wireguard interface to apply changes.'));
514 o.modalonly = true;
515 o.optional = true;
516
517 o = ss.option(form.Value, 'description', _('Description'), _('Optional. Description of peer.'));
518 o.placeholder = 'My Peer';
519 o.datatype = 'string';
520 o.optional = true;
521 o.width = '30%';
522 o.textvalue = function(section_id) {
523 var dis = ss.getOption('disabled'),
524 pub = ss.getOption('public_key'),
525 prv = ss.getOption('private_key'),
526 psk = ss.getOption('preshared_key'),
527 name = this.cfgvalue(section_id),
528 key = pub.cfgvalue(section_id);
529
530 var desc = [
531 E('p', [
532 name ? E('span', [ name ]) : E('em', [ _('Untitled peer') ])
533 ])
534 ];
535
536 if (dis.cfgvalue(section_id) == '1')
537 desc.push(E('span', {
538 'class': 'ifacebadge',
539 'data-tooltip': _('WireGuard peer is disabled')
540 }, [
541 E('em', [ _('Disabled', 'Label indicating that WireGuard peer is disabled') ])
542 ]), ' ');
543
544 if (!key || !pub.isValid(section_id)) {
545 desc.push(E('span', {
546 'class': 'ifacebadge',
547 'data-tooltip': _('Public key is missing')
548 }, [
549 E('em', [ _('Key missing', 'Label indicating that WireGuard peer lacks public key') ])
550 ]));
551 }
552 else {
553 desc.push(
554 E('span', {
555 'class': 'ifacebadge',
556 'data-tooltip': _('Public key: %h', 'Tooltip displaying full WireGuard peer public key').format(key)
557 }, [
558 E('code', [ key.replace(/^(.{5}).+(.{6})$/, '$1…$2') ])
559 ]),
560 ' ',
561 (prv.cfgvalue(section_id) && prv.isValid(section_id))
562 ? E('span', {
563 'class': 'ifacebadge',
564 'data-tooltip': _('Private key present')
565 }, [ _('Private', 'Label indicating that WireGuard peer private key is stored') ]) : '',
566 ' ',
567 (psk.cfgvalue(section_id) && psk.isValid(section_id))
568 ? E('span', {
569 'class': 'ifacebadge',
570 'data-tooltip': _('Preshared key in use')
571 }, [ _('PSK', 'Label indicating that WireGuard peer uses a PSK') ]) : ''
572 );
573 }
574
575 return E([], desc);
576 };
577
578 function handleKeyChange(ev, section_id, value) {
579 var prv = this.section.getUIElement(section_id, 'private_key'),
580 btn = this.map.findElement('.btn.qr-code');
581
582 btn.disabled = (!prv.isValid() || !prv.getValue());
583 }
584
585 o = ss.option(form.Value, 'public_key', _('Public Key'), _('Required. Public key of the WireGuard peer.'));
586 o.modalonly = true;
587 o.validate = validateBase64;
588 o.onchange = handleKeyChange;
589
590 o = ss.option(form.Value, 'private_key', _('Private Key'), _('Optional. Private key of the WireGuard peer. The key is not required for establishing a connection but allows generating a peer configuration or QR code if available. It can be removed after the configuration has been exported.'));
591 o.modalonly = true;
592 o.validate = validateBase64;
593 o.onchange = handleKeyChange;
594 o.password = true;
595
596 o = ss.option(cbiKeyPairGenerate, '_gen_peer_keypair', ' ');
597 o.modalonly = true;
598
599 o = ss.option(form.Value, 'preshared_key', _('Preshared Key'), _('Optional. Base64-encoded preshared key. Adds in an additional layer of symmetric-key cryptography for post-quantum resistance.'));
600 o.modalonly = true;
601 o.validate = validateBase64;
602 o.password = true;
603
604 o = ss.option(form.DummyValue, '_gen_psk', ' ');
605 o.modalonly = true;
606 o.cfgvalue = function(section_id, value) {
607 return E('button', {
608 'class': 'btn',
609 'click': ui.createHandlerFn(this, function(section_id, ev) {
610 var psk = this.section.getUIElement(section_id, 'preshared_key'),
611 map = this.map;
612
613 if (psk.getValue() && !confirm(_('Do you want to replace the current PSK?')))
614 return;
615
616 return generatePsk().then(function(key) {
617 psk.setValue(key);
618 map.save(null, true);
619 });
620 }, section_id)
621 }, [ _('Generate preshared key') ]);
622 };
623
624 o = ss.option(form.DynamicList, 'allowed_ips', _('Allowed IPs'), _("Optional. IP addresses and prefixes that this peer is allowed to use inside the tunnel. Usually the peer's tunnel IP addresses and the networks the peer routes through the tunnel."));
625 o.datatype = 'ipaddr';
626 o.textvalue = function(section_id) {
627 var ips = L.toArray(this.cfgvalue(section_id)),
628 list = [];
629
630 for (var i = 0; i < ips.length; i++) {
631 if (i > 7) {
632 list.push(E('em', {
633 'class': 'ifacebadge cbi-tooltip-container'
634 }, [
635 _('+ %d more', 'Label indicating further amount of allowed ips').format(ips.length - i),
636 E('span', {
637 'class': 'cbi-tooltip'
638 }, [
639 E('ul', ips.map(function(ip) {
640 return E('li', [
641 E('span', { 'class': 'ifacebadge' }, [ ip ])
642 ]);
643 }))
644 ])
645 ]));
646
647 break;
648 }
649
650 list.push(E('span', { 'class': 'ifacebadge' }, [ ips[i] ]));
651 }
652
653 if (!list.length)
654 list.push('*');
655
656 return E('span', { 'style': 'display:inline-flex;flex-wrap:wrap;gap:.125em' }, list);
657 };
658
659 o = ss.option(form.Flag, 'route_allowed_ips', _('Route Allowed IPs'), _('Optional. Create routes for Allowed IPs for this peer.'));
660 o.modalonly = true;
661
662 o = ss.option(form.Value, 'endpoint_host', _('Endpoint Host'), _('Optional. Host of peer. Names are resolved prior to bringing up the interface.'));
663 o.placeholder = 'vpn.example.com';
664 o.datatype = 'host';
665 o.textvalue = function(section_id) {
666 var host = this.cfgvalue(section_id),
667 port = this.section.cfgvalue(section_id, 'endpoint_port');
668
669 return (host && port)
670 ? '%h:%d'.format(host, port)
671 : (host
672 ? '%h:*'.format(host)
673 : (port
674 ? '*:%d'.format(port)
675 : '*'));
676 };
677
678 o = ss.option(form.Value, 'endpoint_port', _('Endpoint Port'), _('Optional. Port of peer.'));
679 o.modalonly = true;
680 o.placeholder = '51820';
681 o.datatype = 'port';
682
683 o = ss.option(form.Value, 'persistent_keepalive', _('Persistent Keep Alive'), _('Optional. Seconds between keep alive messages. Default is 0 (disabled). Recommended value if this device is behind a NAT is 25.'));
684 o.modalonly = true;
685 o.datatype = 'range(0,65535)';
686 o.placeholder = '0';
687
688
689
690 o = ss.option(form.DummyValue, '_keyops', _('Configuration Export'),
691 _('Generates a configuration suitable for import on a WireGuard peer'));
692
693 o.modalonly = true;
694
695 o.createPeerConfig = function(section_id, endpoint, ips) {
696 var pub = s.formvalue(s.section, 'public_key'),
697 port = s.formvalue(s.section, 'listen_port') || '51820',
698 prv = this.section.formvalue(section_id, 'private_key'),
699 psk = this.section.formvalue(section_id, 'preshared_key'),
700 eport = this.section.formvalue(section_id, 'endpoint_port'),
701 keep = this.section.formvalue(section_id, 'persistent_keepalive');
702
703 return [
704 '[Interface]',
705 'PrivateKey = ' + prv,
706 eport ? 'ListenPort = ' + eport : '# ListenPort not defined',
707 '',
708 '[Peer]',
709 'PublicKey = ' + pub,
710 psk ? 'PresharedKey = ' + psk : '# PresharedKey not used',
711 ips && ips.length ? 'AllowedIPs = ' + ips.join(', ') : '# AllowedIPs not defined',
712 endpoint ? 'Endpoint = ' + endpoint + ':' + port : '# Endpoint not defined',
713 keep ? 'PersistentKeepAlive = ' + keep : '# PersistentKeepAlive not defined'
714 ].join('\n');
715 };
716
717 o.handleGenerateQR = function(section_id, ev) {
718 var mapNode = ss.getActiveModalMap(),
719 headNode = mapNode.parentNode.querySelector('h4'),
720 configGenerator = this.createPeerConfig.bind(this, section_id),
721 parent = this.map;
722
723 return Promise.all([
724 network.getWANNetworks(),
725 network.getWAN6Networks(),
726 L.resolveDefault(uci.load('ddns')),
727 L.resolveDefault(uci.load('system')),
728 parent.save(null, true)
729 ]).then(function(data) {
730 var hostnames = [];
731
732 uci.sections('ddns', 'service', function(s) {
733 if (typeof(s.lookup_host) == 'string' && s.enabled == '1')
734 hostnames.push(s.lookup_host);
735 });
736
737 uci.sections('system', 'system', function(s) {
738 if (typeof(s.hostname) == 'string' && s.hostname.indexOf('.') > 0)
739 hostnames.push(s.hostname);
740 });
741
742 for (var i = 0; i < data[0].length; i++)
743 hostnames.push.apply(hostnames, data[0][i].getIPAddrs().map(function(ip) { return ip.split('/')[0] }));
744
745 for (var i = 0; i < data[1].length; i++)
746 hostnames.push.apply(hostnames, data[1][i].getIP6Addrs().map(function(ip) { return ip.split('/')[0] }));
747
748 var ips = [ '0.0.0.0/0', '::/0' ];
749
750 var qrm, qrs, qro;
751
752 qrm = new form.JSONMap({ config: { endpoint: hostnames[0], allowed_ips: ips } }, null, _('The generated configuration can be imported into a WireGuard client application to set up a connection towards this device.'));
753 qrm.parent = parent;
754
755 qrs = qrm.section(form.NamedSection, 'config');
756
757 function handleConfigChange(ev, section_id, value) {
758 var code = this.map.findElement('.qr-code'),
759 conf = this.map.findElement('.client-config'),
760 endpoint = this.section.getUIElement(section_id, 'endpoint'),
761 ips = this.section.getUIElement(section_id, 'allowed_ips');
762
763 if (this.isValid(section_id)) {
764 conf.firstChild.data = configGenerator(endpoint.getValue(), ips.getValue());
765 code.style.opacity = '.5';
766
767 invokeQREncode(conf.firstChild.data, code);
768 }
769 };
770
771 qro = qrs.option(form.Value, 'endpoint', _('Connection endpoint'), _('The public hostname or IP address of this system the peer should connect to. This usually is a static public IP address, a static hostname or a DDNS domain.'));
772 qro.datatype = 'or(ipaddr,hostname)';
773 hostnames.forEach(function(hostname) { qro.value(hostname) });
774 qro.onchange = handleConfigChange;
775
776 qro = qrs.option(form.DynamicList, 'allowed_ips', _('Allowed IPs'), _('IP addresses that are allowed inside the tunnel. The peer will accept tunnelled packets with source IP addresses matching this list and route back packets with matching destination IP.'));
777 qro.datatype = 'ipaddr';
778 qro.default = ips;
779 ips.forEach(function(ip) { qro.value(ip) });
780 qro.onchange = handleConfigChange;
781
782 qro = qrs.option(form.DummyValue, 'output');
783 qro.renderWidget = function() {
784 var peer_config = configGenerator(hostnames[0], ips);
785
786 var node = E('div', {
787 'style': 'display:flex;flex-wrap:wrap;align-items:center;gap:.5em;width:100%'
788 }, [
789 E('div', {
790 'class': 'qr-code',
791 'style': 'width:320px;flex:0 1 320px;text-align:center'
792 }, [
793 E('em', { 'class': 'spinning' }, [ _('Generating QR code…') ])
794 ]),
795 E('pre', {
796 'class': 'client-config',
797 'style': 'flex:1;white-space:pre;overflow:auto',
798 'click': function(ev) {
799 var sel = window.getSelection(),
800 range = document.createRange();
801
802 range.selectNodeContents(ev.currentTarget);
803
804 sel.removeAllRanges();
805 sel.addRange(range);
806 }
807 }, [ peer_config ])
808 ]);
809
810 invokeQREncode(peer_config, node.firstChild);
811
812 return node;
813 };
814
815 return qrm.render().then(function(nodes) {
816 mapNode.classList.add('hidden');
817 mapNode.nextElementSibling.classList.add('hidden');
818
819 headNode.appendChild(E('span', [ ' » ', _('Generate configuration') ]));
820 mapNode.parentNode.appendChild(E([], [
821 nodes,
822 E('div', {
823 'class': 'right'
824 }, [
825 E('button', {
826 'class': 'btn',
827 'click': function() {
828 nodes.parentNode.removeChild(nodes.nextSibling);
829 nodes.parentNode.removeChild(nodes);
830 mapNode.classList.remove('hidden');
831 mapNode.nextSibling.classList.remove('hidden');
832 headNode.removeChild(headNode.lastChild);
833 }
834 }, [ _('Back to peer configuration') ])
835 ])
836 ]));
837
838 if (!s.formvalue(s.section, 'listen_port')) {
839 nodes.appendChild(E('div', { 'class': 'alert-message' }, [
840 E('p', [
841 _('No fixed interface listening port defined, peers might not be able to initiate connections to this WireGuard instance!')
842 ])
843 ]));
844 }
845 });
846 });
847 };
848
849 o.cfgvalue = function(section_id, value) {
850 var privkey = this.section.cfgvalue(section_id, 'private_key');
851
852 return E('button', {
853 'class': 'btn qr-code',
854 'style': 'display:inline-flex;align-items:center;gap:.5em',
855 'click': ui.createHandlerFn(this, 'handleGenerateQR', section_id),
856 'disabled': privkey ? null : ''
857 }, [
858 Object.assign(E(qrIcon), { style: 'width:22px;height:22px' }),
859 _('Generate configuration…')
860 ]);
861 };
862 },
863
864 deleteConfiguration: function() {
865 uci.sections('network', 'wireguard_%s'.format(this.sid), function(s) {
866 uci.remove('network', s['.name']);
867 });
868 }
869 });