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