Merge pull request #5540 from jow-/wireguard-peer-gridsection
[project/luci.git] / protocols / luci-proto-wireguard / htdocs / luci-static / resources / protocol / wireguard.js
1 'use strict';
2 'require ui';
3 'require uci';
4 'require rpc';
5 'require form';
6 'require network';
7
8 var generateKey = rpc.declare({
9 object: 'luci.wireguard',
10 method: 'generateKeyPair',
11 expect: { keys: {} }
12 });
13
14 var getPublicAndPrivateKeyFromPrivate = rpc.declare({
15 object: 'luci.wireguard',
16 method: 'getPublicAndPrivateKeyFromPrivate',
17 params: ['privkey'],
18 expect: { keys: {} }
19 });
20
21 var generateQrCode = rpc.declare({
22 object: 'luci.wireguard',
23 method: 'generateQrCode',
24 params: ['privkey', 'psk', 'allowed_ips'],
25 expect: { qr_code: '' }
26 });
27
28 function validateBase64(section_id, value) {
29 if (value.length == 0)
30 return true;
31
32 if (value.length != 44 || !value.match(/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/))
33 return _('Invalid Base64 key string');
34
35 if (value[43] != "=" )
36 return _('Invalid Base64 key string');
37
38 return true;
39 }
40
41 function findSection(sections, name) {
42 for (var i = 0; i < sections.length; i++) {
43 var section = sections[i];
44 if (section['.name'] == name) return section;
45 }
46
47 return null;
48 }
49
50 function generateDescription(name, texts) {
51 return E('li', { 'style': 'color: inherit;' }, [
52 E('span', name),
53 E('ul', texts.map(function (text) {
54 return E('li', { 'style': 'color: inherit;' }, text);
55 }))
56 ]);
57 }
58
59 return network.registerProtocol('wireguard', {
60 getI18n: function() {
61 return _('WireGuard VPN');
62 },
63
64 getIfname: function() {
65 return this._ubus('l3_device') || this.sid;
66 },
67
68 getOpkgPackage: function() {
69 return 'wireguard-tools';
70 },
71
72 isFloating: function() {
73 return true;
74 },
75
76 isVirtual: function() {
77 return true;
78 },
79
80 getDevices: function() {
81 return null;
82 },
83
84 containsDevice: function(ifname) {
85 return (network.getIfnameOf(ifname) == this.getIfname());
86 },
87
88 renderFormOptions: function(s) {
89 var o, ss;
90
91 // -- general ---------------------------------------------------------------------
92
93 o = s.taboption('general', form.Value, 'private_key', _('Private Key'), _('Required. Base64-encoded private key for this interface.'));
94 o.password = true;
95 o.validate = validateBase64;
96 o.rmempty = false;
97
98 var sections = uci.sections('network');
99 var serverName = this.getIfname();
100 var server = findSection(sections, serverName);
101
102 o = s.taboption('general', form.Value, 'public_key', _('Public Key'), _('Base64-encoded public key of this interface for sharing.'));
103 o.rmempty = false;
104 o.write = function() {/* write nothing */};
105
106 o.load = function(s) {
107 return getPublicAndPrivateKeyFromPrivate(server.private_key).then(
108 function(keypair) {
109 return keypair.pub || '';
110 },
111 function(error){
112 return _('Error getting PublicKey');
113 }, this)
114 };
115
116 o = s.taboption('general', form.Button, 'generate_key', _('Generate Key'));
117 o.inputstyle = 'apply';
118 o.onclick = ui.createHandlerFn(this, function(section_id, ev) {
119 return generateKey().then(function(keypair) {
120 var keyInput = document.getElementById('widget.cbid.network.%s.private_key'.format(section_id)),
121 changeEvent = new Event('change'),
122 pubKeyInput = document.getElementById('widget.cbid.network.%s.public_key'.format(section_id));
123
124 keyInput.value = keypair.priv || '';
125 pubKeyInput.value = keypair.pub || '';
126 keyInput.dispatchEvent(changeEvent);
127 });
128 }, s.section);
129
130 o = s.taboption('general', form.Value, 'listen_port', _('Listen Port'), _('Optional. UDP port used for outgoing and incoming packets.'));
131 o.datatype = 'port';
132 o.placeholder = _('random');
133 o.optional = true;
134
135 o = s.taboption('general', form.DynamicList, 'addresses', _('IP Addresses'), _('Recommended. IP addresses of the WireGuard interface.'));
136 o.datatype = 'ipaddr';
137 o.optional = true;
138
139 o = s.taboption('general', form.Flag, 'nohostroute', _('No Host Routes'), _('Optional. Do not create host routes to peers.'));
140 o.optional = true;
141
142 // -- advanced --------------------------------------------------------------------
143
144 o = s.taboption('advanced', form.Value, 'mtu', _('MTU'), _('Optional. Maximum Transmission Unit of tunnel interface.'));
145 o.datatype = 'range(1280,1420)';
146 o.placeholder = '1420';
147 o.optional = true;
148
149 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>.'));
150 o.optional = true;
151 o.validate = function(section_id, value) {
152 if (value.length > 0 && !value.match(/^0x[a-fA-F0-9]{1,8}$/))
153 return _('Invalid hexadecimal value');
154
155 return true;
156 };
157
158
159 // -- peers -----------------------------------------------------------------------
160
161 try {
162 s.tab('peers', _('Peers'), _('Further information about WireGuard interfaces and peers at <a href=\'http://wireguard.com\'>wireguard.com</a>.'));
163 }
164 catch(e) {}
165
166 o = s.taboption('peers', form.SectionValue, '_peers', form.GridSection, 'wireguard_%s'.format(s.section));
167 o.depends('proto', 'wireguard');
168
169 ss = o.subsection;
170 ss.anonymous = true;
171 ss.addremove = true;
172 ss.addbtntitle = _('Add peer');
173 ss.nodescriptions = true;
174 ss.modaltitle = _('Edit peer');
175
176 ss.renderSectionPlaceholder = function() {
177 return E([], [
178 E('br'),
179 E('em', _('No peers defined yet'))
180 ]);
181 };
182
183 o = ss.option(form.Flag, 'disabled', _('Peer disabled'), _('Enable / Disable peer. Restart wireguard interface to apply changes.'));
184 o.optional = true;
185 o.editable = true;
186
187 o = ss.option(form.Value, 'description', _('Description'), _('Optional. Description of peer.'));
188 o.placeholder = 'My Peer';
189 o.datatype = 'string';
190 o.optional = true;
191
192 o = ss.option(form.Value, 'description', _('QR-Code'));
193 o.modalonly = true;
194 o.render = L.bind(function (view, section_id) {
195 var sections = uci.sections('network');
196 var client = findSection(sections, section_id);
197 var serverName = this.getIfname();
198 var server = findSection(sections, serverName);
199
200 var interfaceTexts = [
201 'PrivateKey: ' + _('A random, on the fly generated "PrivateKey", the key will not be saved on the router')
202 ];
203
204 var peerTexts = [
205 'PublicKey: ' + _('The "PublicKey" of that wg interface'),
206 'AllowedIPs: ' + _('The list of this client\'s "AllowedIPs" or "0.0.0.0/0, ::/0" if not configured'),
207 'PresharedKey: ' + _('If available, the client\'s "PresharedKey"')
208 ];
209
210 var description = [
211 E('span', [
212 _('If there are any unsaved changes for this client, please save the configuration before generating a QR-Code'),
213 E('br'),
214 _('The QR-Code works per wg interface, it will be refreshed with every button click and transfers the following information:')
215 ]),
216 E('ul', [
217 generateDescription('[Interface]', interfaceTexts),
218 generateDescription('[Peer]', peerTexts)
219 ])
220 ];
221
222 return E('div', { 'class': 'cbi-value' }, [
223 E('label', { 'class': 'cbi-value-title' }, _('QR-Code')),
224 E('div', {
225 'class': 'cbi-value-field',
226 'style': 'display: flex; flex-direction: column; align-items: baseline;',
227 'id': 'qr-' + section_id
228 }, [
229 E('button', {
230 'class': 'btn cbi-button cbi-button-apply',
231 'click': ui.createHandlerFn(this, function (server, client, section_id) {
232 var qrDiv = document.getElementById('qr-' + section_id);
233 var qrEl = qrDiv.querySelector('value');
234 var qrBtn = qrDiv.querySelector('button');
235 var qrencodeErr = '<b>%q</b>'.format(
236 _('For QR-Code support please install the qrencode package!'));
237
238 if (qrEl.innerHTML != '' && qrEl.innerHTML != qrencodeErr) {
239 qrEl.innerHTML = '';
240 qrBtn.innerHTML = _('Generate New QR-Code')
241 } else {
242 qrEl.innerHTML = _('Loading QR-Code...');
243
244 generateQrCode(server.private_key, client.preshared_key,
245 client.allowed_ips).then(function (qrCode) {
246 if (qrCode == '') {
247 qrEl.innerHTML = qrencodeErr;
248 } else {
249 qrEl.innerHTML = qrCode;
250 qrBtn.innerHTML = _('Hide QR-Code');
251 }
252 });
253 }
254 }, server, client, section_id)
255 }, _('Generate new QR-Code')),
256 E('value', {
257 'class': 'cbi-section',
258 'style': 'margin: 0;'
259 }),
260 E('div', { 'class': 'cbi-value-description' }, description)
261 ])
262 ]);
263 }, this);
264
265 o = ss.option(form.Value, 'public_key', _('Public Key'), _('Required. Base64-encoded public key of peer.'));
266 o.modalonly = true;
267 o.validate = validateBase64;
268 o.rmempty = false;
269
270 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.'));
271 o.modalonly = true;
272 o.password = true;
273 o.validate = validateBase64;
274 o.optional = true;
275
276 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."));
277 o.datatype = 'ipaddr';
278 o.optional = true;
279
280 o = ss.option(form.Flag, 'route_allowed_ips', _('Route Allowed IPs'), _('Optional. Create routes for Allowed IPs for this peer.'));
281 o.modalonly = true;
282
283 o = ss.option(form.Value, 'endpoint_host', _('Endpoint Host'), _('Optional. Host of peer. Names are resolved prior to bringing up the interface.'));
284 o.placeholder = 'vpn.example.com';
285 o.datatype = 'host';
286
287 o = ss.option(form.Value, 'endpoint_port', _('Endpoint Port'), _('Optional. Port of peer.'));
288 o.placeholder = '51820';
289 o.datatype = 'port';
290
291 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.'));
292 o.modalonly = true;
293 o.datatype = 'range(0,65535)';
294 o.placeholder = '0';
295 },
296
297 deleteConfiguration: function() {
298 uci.sections('network', 'wireguard_%s'.format(this.sid), function(s) {
299 uci.remove('network', s['.name']);
300 });
301 }
302 });