hopwire 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/settings.js CHANGED
@@ -1,30 +1,110 @@
1
1
  import { readFile, writeFile } from 'node:fs/promises';
2
2
  import { isMap, isNode, isScalar, parseDocument } from 'yaml';
3
- import { parseConfig } from './config.js';
3
+ import { isPublicKeyHex, isReservableSubdomain } from '@hopwire/protocol';
4
+ import { isServiceName, parseConfig } from './config.js';
4
5
  import { renderConfig } from './config-template.js';
5
6
  import { HopwireError, errorCode } from './errors.js';
6
- /** The value of one setting. */
7
+ import { defaultLogName } from './log-follow.js';
8
+ function serviceField(id) {
9
+ const match = /^(\d+):(public|name|subdomain|auth|logs)$/.exec(id);
10
+ return match === null ? null : { index: Number(match[1]), field: match[2] };
11
+ }
12
+ export function settingKind(id) {
13
+ const field = serviceField(id)?.field;
14
+ if (id === 'allow' || field === 'logs') {
15
+ return 'list';
16
+ }
17
+ if (field === 'auth') {
18
+ return 'auth';
19
+ }
20
+ return field === 'name' || field === 'subdomain' ? 'text' : 'switch';
21
+ }
22
+ /** The value of one setting. Log files are their paths; Basic Auth is `user:password`. */
7
23
  export function settingValue(settings, id) {
8
- if (id.startsWith('public:')) {
9
- return settings.services.find((service) => `public:${service.name}` === id)?.public ?? false;
24
+ const of = serviceField(id);
25
+ if (of !== null) {
26
+ const service = settings.services[of.index];
27
+ if (service === undefined) {
28
+ return null;
29
+ }
30
+ switch (of.field) {
31
+ case 'public':
32
+ return service.public;
33
+ case 'name':
34
+ return service.name;
35
+ case 'subdomain':
36
+ return service.subdomain;
37
+ case 'auth':
38
+ return service.basicAuth;
39
+ default:
40
+ return service.logs.map((log) => log.path);
41
+ }
42
+ }
43
+ return id === 'allow' ? settings.allow : settings[id];
44
+ }
45
+ /** Whether a switch is on; false for anything that is none. */
46
+ export function isOn(settings, id) {
47
+ return settingValue(settings, id) === true;
48
+ }
49
+ /** The user of a `user:password`. */
50
+ export function authUser(basicAuth) {
51
+ return basicAuth.split(':')[0] ?? '';
52
+ }
53
+ /** A name for a log file that no other of the service has. */
54
+ function logName(path, taken) {
55
+ const base = defaultLogName(path);
56
+ let name = base;
57
+ for (let count = 2; taken.some((log) => log.name === name); count += 1) {
58
+ name = `${base}-${count}`;
10
59
  }
11
- return settings[id];
60
+ return name;
12
61
  }
13
62
  /**
14
- * The settings with one of them changed, and what follows from it: without sharing there is no team and no relay,
15
- * the relay is for the team only.
63
+ * The settings with one of them changed, and what follows from it: without sharing there is no team, no relay and
64
+ * no list of keys; the relay is for the team only; the team is its own list.
16
65
  */
17
66
  export function withSetting(settings, id, value) {
18
- const next = { ...settings, services: settings.services.map((service) => ({ ...service })) };
19
- if (id.startsWith('public:')) {
20
- const service = next.services.find((entry) => `public:${entry.name}` === id);
21
- if (service !== undefined) {
67
+ const next = {
68
+ ...settings,
69
+ allow: [...settings.allow],
70
+ services: settings.services.map((service) => ({ ...service, logs: [...service.logs] })),
71
+ };
72
+ const of = serviceField(id);
73
+ if (of !== null) {
74
+ const service = next.services[of.index];
75
+ if (service === undefined) {
76
+ return next;
77
+ }
78
+ if (of.field === 'public' && typeof value === 'boolean') {
22
79
  service.public = value;
23
80
  }
81
+ else if (of.field === 'name' && typeof value === 'string') {
82
+ service.name = value;
83
+ }
84
+ else if (of.field === 'subdomain' && !Array.isArray(value) && typeof value !== 'boolean') {
85
+ service.subdomain = value === '' ? null : value;
86
+ }
87
+ else if (of.field === 'auth' && !Array.isArray(value) && typeof value !== 'boolean') {
88
+ service.basicAuth = value;
89
+ }
90
+ else if (of.field === 'logs' && Array.isArray(value)) {
91
+ const kept = service.logs.filter((log) => value.includes(log.path));
92
+ for (const path of value) {
93
+ if (!kept.some((log) => log.path === path)) {
94
+ kept.push({ path, name: logName(path, kept) });
95
+ }
96
+ }
97
+ service.logs = kept;
98
+ }
24
99
  return next;
25
100
  }
26
- next[id] = value;
27
- if (id === 'relay' && value) {
101
+ if (id === 'allow') {
102
+ next.allow = Array.isArray(value) ? value.map((key) => key.toLowerCase()) : next.allow;
103
+ }
104
+ else if (typeof value === 'boolean') {
105
+ next[id] = value;
106
+ }
107
+ if (id === 'relay' && value === true) {
28
108
  next.team = true;
29
109
  }
30
110
  if (!next.share) {
@@ -34,26 +114,93 @@ export function withSetting(settings, id, value) {
34
114
  if (!next.team) {
35
115
  next.relay = false;
36
116
  }
117
+ if (next.team && id !== 'allow') {
118
+ next.allow = [];
119
+ }
37
120
  return next;
38
121
  }
39
- /** Why a setting cannot be turned on as things are; null when it can. */
122
+ /** Why a setting cannot be changed as things are; null when it can. */
40
123
  export function unavailable(settings, id) {
41
- if ((id === 'team' || id === 'relay') && !settings.share) {
124
+ if ((id === 'team' || id === 'relay' || id === 'allow') && !settings.share) {
42
125
  return 'needs sharing';
43
126
  }
127
+ if (id === 'allow' && settings.team) {
128
+ return 'with Team only the team is the list';
129
+ }
130
+ const of = serviceField(id);
131
+ if (of !== null &&
132
+ (of.field === 'subdomain' || of.field === 'auth') &&
133
+ settings.services[of.index]?.public !== true) {
134
+ return 'needs the public URL';
135
+ }
44
136
  return null;
45
137
  }
46
- /** The settings that differ between two states, as the ids of the page. */
47
- export function changedSettings(before, after) {
48
- const ids = [
49
- ...after.services.map((service) => `public:${service.name}`),
138
+ /** Why a typed value cannot be taken, as a sentence; null when it can. */
139
+ export function invalidValue(settings, id, value) {
140
+ const of = serviceField(id);
141
+ if (id === 'allow') {
142
+ if (!isPublicKeyHex(value)) {
143
+ return "A key is 64 hexadecimal characters: what hopwire id prints on the teammate's machine.";
144
+ }
145
+ return settings.allow.includes(value.toLowerCase()) ? 'That key is on the list already.' : null;
146
+ }
147
+ if (of === null) {
148
+ return null;
149
+ }
150
+ switch (of.field) {
151
+ case 'name':
152
+ if (!isServiceName(value)) {
153
+ return 'A service name is 1 to 255 bytes without control characters.';
154
+ }
155
+ return settings.services.some((service, index) => index !== of.index && service.name === value)
156
+ ? 'Another service has that name.'
157
+ : null;
158
+ case 'subdomain':
159
+ return value === '' || isReservableSubdomain(value)
160
+ ? null
161
+ : '3 to 63 lowercase letters, digits or hyphens; not starting or ending with a hyphen, not starting with t-.';
162
+ case 'logs':
163
+ if (value.trim() === '') {
164
+ return 'Give the path of a log file.';
165
+ }
166
+ return settings.services[of.index]?.logs.some((log) => log.path === value)
167
+ ? 'That file is followed already.'
168
+ : null;
169
+ default:
170
+ return null;
171
+ }
172
+ }
173
+ /** Why a user and a password cannot be taken for Basic Auth; null when they can. */
174
+ export function invalidAuth(user, password) {
175
+ if (user === '' || /[:\s\p{Cc}]/u.test(user)) {
176
+ return 'The user must not be empty and holds no colon or space.';
177
+ }
178
+ if (password === '' || /\p{Cc}/u.test(password)) {
179
+ return 'The password must not be empty.';
180
+ }
181
+ return null;
182
+ }
183
+ /** Every setting of these settings, in the order of the page. */
184
+ export function settingIds(settings) {
185
+ return [
186
+ ...settings.services.flatMap((_, index) => [
187
+ `${index}:name`,
188
+ `${index}:public`,
189
+ `${index}:subdomain`,
190
+ `${index}:auth`,
191
+ `${index}:logs`,
192
+ ]),
50
193
  'share',
51
194
  'team',
52
195
  'relay',
196
+ 'allow',
53
197
  'websocket',
54
198
  'agent',
55
199
  ];
56
- return ids.filter((id) => settingValue(before, id) !== settingValue(after, id));
200
+ }
201
+ /** The settings that differ between two states. */
202
+ export function changedSettings(before, after) {
203
+ return settingIds(after).filter((id) => JSON.stringify(settingValue(before, id)) !== JSON.stringify(settingValue(after, id)));
57
204
  }
58
205
  /** The settings a hopwire.yaml has. */
59
206
  export function settingsOfConfig(config, agent) {
@@ -61,47 +208,48 @@ export function settingsOfConfig(config, agent) {
61
208
  share: config.share,
62
209
  team: config.team,
63
210
  relay: config.relay,
211
+ allow: config.allow ?? [],
64
212
  websocket: config.captureWebSocket,
65
213
  agent: agent ?? config.agent ?? true,
66
- services: config.services.map((service) => ({ name: service.name, public: service.public })),
214
+ services: config.services.map((service) => ({
215
+ name: service.name,
216
+ target: service.local.origin,
217
+ public: service.public,
218
+ subdomain: service.subdomain,
219
+ basicAuth: service.basicAuth,
220
+ logs: service.logs.map((log) => ({ ...log })),
221
+ })),
67
222
  };
68
223
  }
69
- /** A config with the settings of the page in place of its own. */
224
+ /** A config with the settings of the page in place of its own. Services are matched by their position. */
70
225
  export function configWithSettings(config, settings) {
71
226
  return {
72
227
  ...config,
73
228
  share: settings.share,
74
229
  team: settings.team,
75
230
  relay: settings.relay,
231
+ allow: settings.share && !settings.team && settings.allow.length > 0 ? settings.allow : null,
76
232
  captureWebSocket: settings.websocket,
77
233
  agent: settings.agent,
78
234
  // Without sharing there is nothing these could apply to
79
235
  allowAgents: settings.share && config.allowAgents,
80
- shareLogs: settings.share && config.shareLogs,
81
- services: config.services.map((service) => ({
82
- ...service,
83
- public: settings.services.find((entry) => entry.name === service.name)?.public ?? service.public,
84
- })),
236
+ shareLogs: settings.share && config.shareLogs && settings.services.some((service) => service.logs.length > 0),
237
+ services: config.services.map((service, index) => {
238
+ const wanted = settings.services[index];
239
+ return wanted === undefined
240
+ ? service
241
+ : {
242
+ ...service,
243
+ name: wanted.name,
244
+ public: wanted.public,
245
+ subdomain: wanted.public ? wanted.subdomain : service.subdomain,
246
+ basicAuth: wanted.public ? wanted.basicAuth : service.basicAuth,
247
+ logs: wanted.logs.map((log) => ({ ...log })),
248
+ };
249
+ }),
85
250
  };
86
251
  }
87
- /** Where a setting stands in hopwire.yaml, and its value when the file leaves it out. */
88
- function fileKey(id) {
89
- if (id.startsWith('public:')) {
90
- return { path: ['services', id.slice('public:'.length), 'public'], fallback: false };
91
- }
92
- switch (id) {
93
- case 'share':
94
- return { path: ['p2p', 'share'], fallback: false };
95
- case 'team':
96
- return { path: ['p2p', 'team'], fallback: false };
97
- case 'relay':
98
- return { path: ['p2p', 'relay'], fallback: false };
99
- case 'websocket':
100
- return { path: ['capture', 'websocket'], fallback: true };
101
- default:
102
- return { path: ['agent'], fallback: true };
103
- }
104
- }
252
+ // --- the file ---
105
253
  /** Where a line starts that holds this position of a text. */
106
254
  function lineStart(text, at) {
107
255
  return text.lastIndexOf('\n', at - 1) + 1;
@@ -115,90 +263,253 @@ function afterLine(text, at) {
115
263
  function indentUnit(text) {
116
264
  return /^( +)[^\s#]/m.exec(text)?.[1] ?? ' ';
117
265
  }
118
- /**
119
- * A text of YAML with one true or false set, by changing that word alone or adding one line: nothing else of the
120
- * file is written anew, so comments, order, quotes and indentation stay exactly as they are. The YAML library is
121
- * only asked where things stand.
122
- */
123
- export function setBoolean(text, path, value, shown) {
124
- const document = parseDocument(text, { uniqueKeys: true, logLevel: 'error' });
125
- const refuse = () => {
126
- throw new HopwireError(`${path.join('.')} in ${shown} cannot be changed from here; change it in the file.`);
127
- };
128
- const word = value ? 'true' : 'false';
129
- const unit = indentUnit(text);
266
+ /** A text as a YAML value: plain when nothing in it could be read as something else, in double quotes otherwise. */
267
+ export function yamlText(value) {
268
+ return /^[A-Za-z0-9_/][A-Za-z0-9_./*~ -]*$/.test(value) &&
269
+ !/^(true|false|null|yes|no|on|off|~|-?[\d.]+)$/i.test(value) &&
270
+ !value.endsWith(' ')
271
+ ? value
272
+ : JSON.stringify(value);
273
+ }
274
+ function refuse(path, shown) {
275
+ throw new HopwireError(`${path.join('.')} in ${shown} cannot be changed from here; change it in the file.`);
276
+ }
277
+ function pairOf(map, key) {
278
+ return map.items.find((item) => isScalar(item.key) && item.key.value === key);
279
+ }
280
+ /** The mapping a path leads through, as far as the file has it. */
281
+ function locate(document, path) {
130
282
  let map = document.contents;
131
283
  for (let depth = 0; depth < path.length; depth += 1) {
132
284
  if (!isMap(map)) {
133
- return refuse();
285
+ return null;
134
286
  }
135
- const key = path[depth] ?? '';
136
- const pair = map.items.find((item) => isScalar(item.key) && item.key.value === key);
137
- const rest = path.slice(depth);
138
- // The lines for what is missing from here on: sections first, the value last
139
- const lines = (from, names) => names
140
- .map((name, index) => `${from}${unit.repeat(index)}${name}:${index === names.length - 1 ? ` ${word}` : ''}\n`)
141
- .join('');
142
- if (pair === undefined) {
143
- // After the last entry of this mapping, at its indent
144
- const last = map.items[map.items.length - 1];
145
- const first = map.items[0];
146
- if (last === undefined || first === undefined || !isScalar(first.key) || first.key.range == null) {
147
- return refuse();
148
- }
149
- const column = first.key.range[0] - lineStart(text, first.key.range[0]);
150
- const end = (isNode(last.value) ? last.value.range?.[1] : undefined) ??
151
- (isNode(last.key) ? last.key.range?.[1] : undefined);
152
- if (end === undefined) {
153
- return refuse();
154
- }
155
- const place = afterLine(text, Math.max(end - 1, 0));
156
- return `${place.text.slice(0, place.at)}${lines(' '.repeat(column), rest)}${place.text.slice(place.at)}`;
287
+ const pair = pairOf(map, path[depth] ?? '');
288
+ if (pair === undefined || depth === path.length - 1) {
289
+ return { map, depth, pair };
157
290
  }
158
- const last = depth === path.length - 1;
159
- if (isScalar(pair.value) && pair.value.value === null && isScalar(pair.key) && pair.key.range != null) {
160
- // A name with nothing under it (every key commented, or left empty): the value, or the section, goes there
161
- const keyStart = pair.key.range[0];
162
- if (last) {
163
- const colon = text.indexOf(':', pair.key.range[1]);
164
- return `${text.slice(0, colon + 1)} ${word}${text.slice(colon + 1)}`;
165
- }
166
- const place = afterLine(text, keyStart);
167
- const column = keyStart - lineStart(text, keyStart);
168
- return `${place.text.slice(0, place.at)}${lines(' '.repeat(column) + unit, rest.slice(1))}${place.text.slice(place.at)}`;
169
- }
170
- if (last) {
171
- if (!isScalar(pair.value) || typeof pair.value.value !== 'boolean' || pair.value.range == null) {
172
- return refuse();
173
- }
174
- const [start, end] = pair.value.range;
175
- return `${text.slice(0, start)}${word}${text.slice(end)}`;
291
+ // A name with nothing under it stops the way: what is missing goes under it
292
+ if (isScalar(pair.value) && pair.value.value === null) {
293
+ return { map, depth, pair };
176
294
  }
177
295
  map = pair.value;
178
296
  }
179
- return refuse();
297
+ return null;
298
+ }
299
+ /** The lines for keys that are missing, the entry at the last of them. */
300
+ function newLines(from, unit, names, entry) {
301
+ return names
302
+ .map((name, index) => {
303
+ const indent = `${from}${unit.repeat(index)}`;
304
+ const key = yamlText(name);
305
+ if (index < names.length - 1) {
306
+ return `${indent}${key}:\n`;
307
+ }
308
+ return typeof entry === 'string'
309
+ ? `${indent}${key}: ${entry}\n`
310
+ : `${indent}${key}:\n${entry.map((line) => `${indent}${unit}${line}\n`).join('')}`;
311
+ })
312
+ .join('');
313
+ }
314
+ /** The end of what a pair holds: of its value, or of its key when it has none. */
315
+ function pairEnd(pair) {
316
+ return ((isNode(pair.value) && !(isScalar(pair.value) && pair.value.value === null)
317
+ ? pair.value.range?.[1]
318
+ : undefined) ?? (isNode(pair.key) ? pair.key.range?.[1] : undefined));
319
+ }
320
+ /**
321
+ * A text of YAML without one key: its line, and the lines under it. A section that held nothing else goes with it
322
+ * (auth: with only basic). Nothing else of the file is written anew.
323
+ */
324
+ export function removeKey(text, path, shown) {
325
+ const document = parseDocument(text, { uniqueKeys: true, logLevel: 'error' });
326
+ const found = locate(document, path);
327
+ if (found === null || found.pair === undefined || found.depth !== path.length - 1) {
328
+ return text;
329
+ }
330
+ if (found.map.items.length === 1 && path.length > 1) {
331
+ return removeKey(text, path.slice(0, -1), shown);
332
+ }
333
+ const { pair } = found;
334
+ const end = pairEnd(pair);
335
+ if (!isScalar(pair.key) || pair.key.range == null || end === undefined) {
336
+ return refuse(path, shown);
337
+ }
338
+ const from = lineStart(text, pair.key.range[0]);
339
+ const to = afterLine(text, Math.max(end - 1, pair.key.range[0]));
340
+ return `${to.text.slice(0, from)}${to.text.slice(to.at)}`;
341
+ }
342
+ /**
343
+ * A text of YAML with one key set, by changing its value alone or adding its lines: nothing else of the file is
344
+ * written anew, so comments, order, quotes and indentation stay exactly as they are. The YAML library is only asked
345
+ * where things stand.
346
+ */
347
+ export function setKey(text, path, entry, shown) {
348
+ const document = parseDocument(text, { uniqueKeys: true, logLevel: 'error' });
349
+ const unit = indentUnit(text);
350
+ const found = locate(document, path);
351
+ if (found === null) {
352
+ return refuse(path, shown);
353
+ }
354
+ const { map, depth, pair } = found;
355
+ const rest = path.slice(depth);
356
+ if (pair === undefined) {
357
+ // After the last entry of this mapping, at its indent
358
+ const last = map.items[map.items.length - 1];
359
+ const first = map.items[0];
360
+ const end = last === undefined ? undefined : pairEnd(last);
361
+ if (first === undefined || !isScalar(first.key) || first.key.range == null || end === undefined) {
362
+ return refuse(path, shown);
363
+ }
364
+ const column = first.key.range[0] - lineStart(text, first.key.range[0]);
365
+ const place = afterLine(text, Math.max(end - 1, 0));
366
+ return `${place.text.slice(0, place.at)}${newLines(' '.repeat(column), unit, rest, entry)}${place.text.slice(place.at)}`;
367
+ }
368
+ if (!isScalar(pair.key) || pair.key.range == null) {
369
+ return refuse(path, shown);
370
+ }
371
+ const keyStart = pair.key.range[0];
372
+ const column = keyStart - lineStart(text, keyStart);
373
+ const last = depth === path.length - 1;
374
+ if (isScalar(pair.value) && pair.value.value === null) {
375
+ // A name with nothing under it (every key commented, or left empty)
376
+ if (last && typeof entry === 'string') {
377
+ const colon = text.indexOf(':', pair.key.range[1]);
378
+ return `${text.slice(0, colon + 1)} ${entry}${text.slice(colon + 1)}`;
379
+ }
380
+ const place = afterLine(text, keyStart);
381
+ const under = last && typeof entry !== 'string'
382
+ ? entry.map((line) => `${' '.repeat(column)}${unit}${line}\n`).join('')
383
+ : newLines(' '.repeat(column) + unit, unit, rest.slice(1), entry);
384
+ return `${place.text.slice(0, place.at)}${under}${place.text.slice(place.at)}`;
385
+ }
386
+ if (!last) {
387
+ return refuse(path, shown);
388
+ }
389
+ if (typeof entry === 'string' && isScalar(pair.value) && pair.value.range != null) {
390
+ const [start, end] = pair.value.range;
391
+ return `${text.slice(0, start)}${entry}${text.slice(end)}`;
392
+ }
393
+ // Something of another shape stands there (a list in place of a value, or a list that changes): its lines are
394
+ // replaced, at the place of the key
395
+ const end = pairEnd(pair);
396
+ if (end === undefined) {
397
+ return refuse(path, shown);
398
+ }
399
+ const from = lineStart(text, keyStart);
400
+ const to = afterLine(text, Math.max(end - 1, keyStart));
401
+ return `${to.text.slice(0, from)}${newLines(' '.repeat(column), unit, [path[depth] ?? ''], entry)}${to.text.slice(to.at)}`;
402
+ }
403
+ /** A text of YAML with one true or false set. */
404
+ export function setBoolean(text, path, value, shown) {
405
+ const document = parseDocument(text, { uniqueKeys: true, logLevel: 'error' });
406
+ const found = locate(document, path);
407
+ if (found === null) {
408
+ return refuse(path, shown);
409
+ }
410
+ const there = found.depth === path.length - 1 ? found.pair?.value : undefined;
411
+ // Only a true, a false or nothing is replaced by a true or false
412
+ if (there !== undefined &&
413
+ there !== null &&
414
+ !(isScalar(there) && (typeof there.value === 'boolean' || there.value === null))) {
415
+ return refuse(path, shown);
416
+ }
417
+ return setKey(text, path, value ? 'true' : 'false', shown);
418
+ }
419
+ /** A text of YAML with the name of a key changed. */
420
+ function renameKey(text, path, name, shown) {
421
+ const document = parseDocument(text, { uniqueKeys: true, logLevel: 'error' });
422
+ const found = locate(document, path);
423
+ const key = found?.depth === path.length - 1 ? found.pair?.key : undefined;
424
+ if (!isScalar(key) || key.range == null) {
425
+ return refuse(path, shown);
426
+ }
427
+ return `${text.slice(0, key.range[0])}${yamlText(name)}${text.slice(key.range[1])}`;
428
+ }
429
+ /** The lines of a list of log files: a path alone, or path and name when the name is its own. */
430
+ function logLines(logs) {
431
+ const lines = [];
432
+ logs.forEach((log, index) => {
433
+ if (log.name === logName(log.path, logs.slice(0, index))) {
434
+ lines.push(`- ${yamlText(log.path)}`);
435
+ }
436
+ else {
437
+ lines.push(`- path: ${yamlText(log.path)}`, ` name: ${yamlText(log.name)}`);
438
+ }
439
+ });
440
+ return lines;
180
441
  }
181
442
  /**
182
443
  * The text of a hopwire.yaml with settings changed: only the keys that differ between `before` and `after` are
183
444
  * touched, so comments, order and everything else stay as the user wrote them. `before` is what the file held when it
184
- * was last read or written by this run. The file is read anew for every save: a key it holds already, because it was
185
- * changed there in the meantime, is left alone, and every other change made there stays.
445
+ * was last read or written by this run. The file is read anew for every save, and everything else changed there stays.
186
446
  */
187
447
  export function editConfigText(text, before, after, shown) {
448
+ if (parseDocument(text, { uniqueKeys: true, logLevel: 'error' }).errors.length > 0) {
449
+ throw new HopwireError(`${shown} is no longer valid YAML; correct the file, then save again.`);
450
+ }
188
451
  let edited = text;
189
- for (const id of changedSettings(before, after)) {
190
- const document = parseDocument(edited, { uniqueKeys: true, logLevel: 'error' });
191
- if (document.errors.length > 0) {
192
- throw new HopwireError(`${shown} is no longer valid YAML; correct the file, then save again.`);
452
+ const switches = {
453
+ share: ['p2p', 'share'],
454
+ team: ['p2p', 'team'],
455
+ relay: ['p2p', 'relay'],
456
+ websocket: ['capture', 'websocket'],
457
+ agent: ['agent'],
458
+ };
459
+ const fallback = { share: false, team: false, relay: false, websocket: true, agent: true };
460
+ const changed = changedSettings(before, after);
461
+ // The names last: until then every service is found under the name the file has
462
+ const ordered = [...changed.filter((id) => !id.endsWith(':name')), ...changed.filter((id) => id.endsWith(':name'))];
463
+ for (const id of ordered) {
464
+ const value = settingValue(after, id);
465
+ const of = serviceField(id);
466
+ if (id === 'allow') {
467
+ edited =
468
+ after.allow.length === 0
469
+ ? removeKey(edited, ['p2p', 'allow'], shown)
470
+ : setKey(edited, ['p2p', 'allow'], after.allow.map((key) => `- ${key}`), shown);
471
+ continue;
193
472
  }
194
- const { path, fallback } = fileKey(id);
195
- const inFile = document.getIn(path);
196
- const now = typeof inFile === 'boolean' ? inFile : fallback;
197
- const wanted = settingValue(after, id);
198
- if (now === wanted) {
473
+ if (of === null) {
474
+ const path = switches[id];
475
+ const inFile = parseDocument(edited).getIn(path);
476
+ // A key the file holds already, changed there since the start, is left alone
477
+ if ((typeof inFile === 'boolean' ? inFile : fallback[id]) !== value) {
478
+ edited = setBoolean(edited, path, value === true, shown);
479
+ }
199
480
  continue;
200
481
  }
201
- edited = setBoolean(edited, path, wanted, shown);
482
+ const service = ['services', before.services[of.index]?.name ?? ''];
483
+ const wanted = after.services[of.index];
484
+ if (wanted === undefined) {
485
+ continue;
486
+ }
487
+ switch (of.field) {
488
+ case 'public':
489
+ edited = setBoolean(edited, [...service, 'public'], wanted.public, shown);
490
+ break;
491
+ case 'subdomain':
492
+ edited =
493
+ wanted.subdomain === null
494
+ ? removeKey(edited, [...service, 'subdomain'], shown)
495
+ : setKey(edited, [...service, 'subdomain'], yamlText(wanted.subdomain), shown);
496
+ break;
497
+ case 'auth':
498
+ edited =
499
+ wanted.basicAuth === null
500
+ ? removeKey(edited, [...service, 'auth', 'basic'], shown)
501
+ : setKey(edited, [...service, 'auth', 'basic'], JSON.stringify(wanted.basicAuth), shown);
502
+ break;
503
+ case 'logs':
504
+ edited =
505
+ wanted.logs.length === 0
506
+ ? removeKey(edited, [...service, 'logs'], shown)
507
+ : setKey(edited, [...service, 'logs'], logLines(wanted.logs), shown);
508
+ break;
509
+ case 'name':
510
+ edited = renameKey(edited, service, wanted.name, shown);
511
+ break;
512
+ }
202
513
  }
203
514
  // What is written must be a file hopwire up accepts
204
515
  parseConfig(edited, shown);
@@ -220,30 +531,44 @@ export async function saveToConfigFile(file, shown, before, after) {
220
531
  * this run. Never replaces a file.
221
532
  */
222
533
  export async function createConfigFile(target, settings) {
223
- const isPublic = settings.services[0]?.public ?? false;
224
- if (isPublic && target.urls === null) {
534
+ const [service] = settings.services;
535
+ if (service === undefined) {
536
+ throw new HopwireError('There is no service to write; nothing was saved.');
537
+ }
538
+ if (service.public && target.urls === null) {
225
539
  throw new HopwireError('A file with a public service names the edge of your account; run hopwire login first. Nothing was saved.');
226
540
  }
227
541
  const template = renderConfig({
228
542
  services: [
229
543
  {
230
- name: target.serviceName,
231
- local: target.local,
232
- public: isPublic,
233
- subdomain: isPublic ? target.subdomain : null,
544
+ name: service.name,
545
+ local: new URL(service.target),
546
+ public: service.public,
547
+ subdomain: service.public ? service.subdomain : null,
234
548
  logs: [],
235
549
  },
236
550
  ],
237
- edgeUrl: isPublic ? (target.urls?.edgeUrl ?? null) : null,
238
- controlPlaneUrl: isPublic ? (target.urls?.controlPlaneUrl ?? null) : null,
551
+ edgeUrl: service.public ? (target.urls?.edgeUrl ?? null) : null,
552
+ controlPlaneUrl: service.public ? (target.urls?.controlPlaneUrl ?? null) : null,
239
553
  share: settings.share,
240
554
  team: settings.team,
241
555
  allowAgents: false,
242
556
  shareLogs: false,
243
557
  });
244
- // What the template has no answer for: set on top of it, from the defaults
245
- const written = { ...settings, relay: false, websocket: true, agent: true };
246
- const text = editConfigText(template, written, settings, target.shown);
558
+ // What the template has no answer for is set on top of it, from the defaults
559
+ const written = {
560
+ ...settings,
561
+ relay: false,
562
+ allow: [],
563
+ websocket: true,
564
+ agent: true,
565
+ services: [{ ...service, basicAuth: null, logs: [] }],
566
+ };
567
+ const wanted = {
568
+ ...settings,
569
+ services: [{ ...service, basicAuth: service.public ? service.basicAuth : null }],
570
+ };
571
+ const text = editConfigText(template, written, wanted, target.shown);
247
572
  try {
248
573
  // wx: a file that is there is not replaced
249
574
  await writeFile(target.file, text, { flag: 'wx' });