hopwire 0.5.0 → 0.6.0

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/bin.js CHANGED
@@ -40,6 +40,8 @@ const quiet = () => spinner?.stop();
40
40
  const fullScreen = keys && color && process.stdout.isTTY === true;
41
41
  const facts = fullScreen ? new Facts() : null;
42
42
  let app = null;
43
+ /** The Settings tab is starting the tunnel again */
44
+ let restarting = false;
43
45
  let held = fullScreen ? [] : null;
44
46
  /** What was written to standard error while the view ran, with its time: shown again after it is gone */
45
47
  const problems = [];
@@ -90,12 +92,16 @@ const hop = () => {
90
92
  * Opens the full-screen view for a tunnel that runs: the terminal goes into raw mode and the alternate screen, and
91
93
  * both are given back when the process exits, however it does.
92
94
  */
93
- function openView(info, known, running) {
95
+ function openView(info, known, running, restart) {
94
96
  let rowWidth = 100;
95
97
  const rows = new TerminalScreen({ look, width: () => rowWidth, version: readVersion(), shortcuts: false });
96
- if ((running.kind === 'http' || running.kind === 'up') && running.webhookSecrets !== undefined) {
97
- rows.checkSignatures(running.webhookSecrets);
98
- }
98
+ const settingsOf = (tunnel) => tunnel.kind === 'http' || tunnel.kind === 'up' ? (tunnel.settings ?? null) : null;
99
+ const signatures = (tunnel) => {
100
+ if ((tunnel.kind === 'http' || tunnel.kind === 'up') && tunnel.webhookSecrets !== undefined) {
101
+ rows.checkSignatures(tunnel.webhookSecrets);
102
+ }
103
+ };
104
+ signatures(running);
99
105
  const dataDir = argv.findIndex((arg) => arg === '--data-dir' || arg.startsWith('--data-dir='));
100
106
  const dataDirValue = dataDir < 0
101
107
  ? null
@@ -129,7 +135,21 @@ function openView(info, known, running) {
129
135
  return response.json();
130
136
  },
131
137
  interrupt: () => process.kill(process.pid, 'SIGINT'),
138
+ applySettings: async (settings) => {
139
+ restarting = true;
140
+ known.reset();
141
+ try {
142
+ const { running: now, problem } = await restart(settings);
143
+ signatures(now);
144
+ return { info: tunnelInfo(now) ?? info, access: settingsOf(now), problem };
145
+ }
146
+ finally {
147
+ known.start();
148
+ restarting = false;
149
+ }
150
+ },
132
151
  },
152
+ settings: settingsOf(running),
133
153
  });
134
154
  known.start();
135
155
  held = null;
@@ -175,7 +195,13 @@ await main({
175
195
  env: process.env,
176
196
  print: (line) => {
177
197
  if (app !== null) {
178
- app.line(line);
198
+ // The lines of a tunnel that is starting again are its facts, as at the first start
199
+ if (restarting && facts !== null) {
200
+ facts.line(line);
201
+ }
202
+ else {
203
+ app.line(line);
204
+ }
179
205
  return;
180
206
  }
181
207
  if (held !== null && facts !== null && screen !== null) {
@@ -192,6 +218,11 @@ await main({
192
218
  error: (line) => {
193
219
  quiet();
194
220
  if (app !== null) {
221
+ if (restarting && facts !== null) {
222
+ // A notice of the start, as at the first one; a start that failed reports itself to the view
223
+ facts.note(line);
224
+ return;
225
+ }
195
226
  problems.push({ at: Date.now(), line });
196
227
  app.problem(line);
197
228
  return;
@@ -254,11 +285,11 @@ await main({
254
285
  }
255
286
  }
256
287
  : undefined,
257
- started: (running) => {
288
+ started: (running, restart) => {
258
289
  quiet();
259
290
  const info = fullScreen && facts !== null ? tunnelInfo(running) : null;
260
291
  if (info !== null && facts !== null) {
261
- app = openView(info, facts, running);
292
+ app = openView(info, facts, running, restart);
262
293
  return;
263
294
  }
264
295
  release();
package/dist/cli.js CHANGED
@@ -21,6 +21,7 @@ import { parseTarget } from './traffic.js';
21
21
  import { ConfigError, isServiceName, loadConfig } from './config.js';
22
22
  import { HopwireError, TemporaryError, UsageError, errorCode } from './errors.js';
23
23
  import { commandHelp, overview } from './help.js';
24
+ import { configWithSettings, createConfigFile, saveToConfigFile, settingsOfConfig, } from './settings.js';
24
25
  import { loadOrCreateIdentity } from './identity.js';
25
26
  import { defaultLogName, isFollowablePath } from './log-follow.js';
26
27
  import { DOCS_URL, printable } from './output.js';
@@ -529,7 +530,9 @@ export async function run(argv, io) {
529
530
  }
530
531
  const cwd = io.cwd ?? process.cwd();
531
532
  const { file, shown } = configFile(cwd, values.config);
532
- const config = await loadConfig(file, values.config !== undefined, shown);
533
+ const loaded = await loadConfig(file, values.config !== undefined, shown);
534
+ // The Settings tab restarted the tunnel: its settings stand in for those of the file
535
+ const config = io.view?.settings === undefined ? loaded : configWithSettings(loaded, io.view.settings);
533
536
  // Read before anything starts: a variable that is not set stops the start, like any other mistake in the file
534
537
  const webhookSecrets = new Map(config.services.map((service) => [
535
538
  service.name,
@@ -552,14 +555,44 @@ export async function run(argv, io) {
552
555
  // The edge is only contacted for p2p.relay, and then only through the relay
553
556
  relay: config.relay ? await relayAccess('p2p.relay', store) : undefined,
554
557
  bootstrap: config.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
555
- agent: agent ?? config.agent ?? undefined,
558
+ agent: io.view?.settings?.agent ?? agent ?? config.agent ?? undefined,
556
559
  signal: io.signal,
557
560
  });
558
561
  // After the lines of the start, so the mode stays the first line of every tunnel
559
562
  update.print(io.print);
560
- return Object.assign(running, { webhookSecrets });
563
+ // What the file holds, for a save: only keys that differ from it are written
564
+ let inFile = settingsOfConfig(loaded, undefined);
565
+ const settings = {
566
+ current: io.view?.settings ?? settingsOfConfig(loaded, agent),
567
+ file: { shown, exists: true },
568
+ save: async (next) => {
569
+ await saveToConfigFile(file, shown, inFile, next);
570
+ inFile = next;
571
+ return `Saved to ${shown}.`;
572
+ },
573
+ };
574
+ return Object.assign(running, { webhookSecrets, settings });
561
575
  }
562
576
  noMoreArguments(rest, 1, 'hopwire http <port>');
577
+ // The Settings tab restarted the tunnel: its settings stand in for those of the command line
578
+ const wanted = io.view?.settings;
579
+ if (wanted !== undefined) {
580
+ const isPublic = wanted.services[0]?.public ?? false;
581
+ Object.assign(values, {
582
+ share: wanted.share,
583
+ team: wanted.team,
584
+ relay: wanted.relay,
585
+ public: isPublic,
586
+ 'no-ws-capture': !wanted.websocket,
587
+ agent: wanted.agent ? values.agent : undefined,
588
+ 'no-agent': !wanted.agent,
589
+ subdomain: isPublic ? values.subdomain : undefined,
590
+ });
591
+ if (!wanted.share) {
592
+ // What only works with sharing goes with it; a later change that shares again reads the command line anew
593
+ Object.assign(values, { allow: undefined, 'allow-agents': undefined, 'share-logs': undefined });
594
+ }
595
+ }
563
596
  if (values.inspect !== undefined && values['no-inspect']) {
564
597
  throw new UsageError('--inspect and --no-inspect cannot be combined');
565
598
  }
@@ -633,7 +666,44 @@ export async function run(argv, io) {
633
666
  });
634
667
  // After the lines of the start, so the mode stays the first line of every tunnel
635
668
  update.print(io.print);
636
- return Object.assign(running, { webhookSecrets });
669
+ const serviceName = values.name ?? 'default';
670
+ const target = configFile(io.cwd ?? process.cwd(), undefined);
671
+ const view = io.view ?? {};
672
+ const settings = {
673
+ current: {
674
+ share: values.share ?? false,
675
+ team: values.team ?? false,
676
+ relay: values.relay ?? false,
677
+ websocket: !(values['no-ws-capture'] ?? false),
678
+ agent: agentChoice(values) !== false,
679
+ services: [{ name: serviceName, public: values.public ?? false }],
680
+ },
681
+ file: { shown: target.shown, exists: view.created !== undefined },
682
+ save: async (next) => {
683
+ if (view.created !== undefined) {
684
+ await saveToConfigFile(target.file, target.shown, view.created.before, next);
685
+ view.created.before = next;
686
+ return `Saved to ${target.shown}.`;
687
+ }
688
+ // The edge of the account goes into a file with a public service, as hopwire init writes it
689
+ const isPublic = next.services[0]?.public ?? false;
690
+ const account = isPublic ? await readAccount(store) : null;
691
+ const edgeUrl = account === null ? null : await boundEdge(store);
692
+ await createConfigFile({
693
+ file: target.file,
694
+ shown: target.shown,
695
+ serviceName,
696
+ local: new URL(`http://127.0.0.1:${port}`),
697
+ subdomain: values.subdomain ?? null,
698
+ urls: account === null || edgeUrl === null
699
+ ? null
700
+ : { edgeUrl, controlPlaneUrl: account.controlPlaneUrl },
701
+ }, next);
702
+ view.created = { before: next };
703
+ return `Created ${target.shown}; hopwire up starts this tunnel from now on.`;
704
+ },
705
+ };
706
+ return Object.assign(running, { webhookSecrets, settings });
637
707
  }
638
708
  /** 30s, 30m, 2h, 1d as milliseconds. */
639
709
  function parseDuration(value) {
@@ -1,13 +1,11 @@
1
1
  import { ChecksFailed, HopwireError } from '../errors.js';
2
2
  import { printable } from '../output.js';
3
- import { isSignedProvider, signedBy } from '../signature.js';
3
+ import { carriesTime, isSignedProvider, signedBy } from '../signature.js';
4
4
  import { readSnapshot, send } from '../traffic.js';
5
5
  import { recogniseWebhook } from '../webhook.js';
6
6
  import { requestLabel, secretFor } from './verify.js';
7
7
  /** How far in the past a stale signature is made: twice the five minutes providers allow by default. */
8
8
  const STALE_SECONDS = 10 * 60;
9
- /** Providers whose signatures carry a time, so a stale one can be made. */
10
- const TIMESTAMPED = new Set(['stripe', 'slack', 'svix', 'paddle']);
11
9
  /** An id as providers write them: a lowercase prefix, an underscore, letters and digits with a digit or capital. */
12
10
  const ID = /^[a-z]{1,16}_(?=[A-Za-z0-9]*[0-9A-Z])[A-Za-z0-9]+$/;
13
11
  /** Headers that carry the id of a delivery, which handlers and libraries use to drop duplicates. */
@@ -18,29 +16,28 @@ const DELIVERY_HEADERS = new Set([
18
16
  'svix-id',
19
17
  'webhook-id',
20
18
  ]);
19
+ /** A JSON string literal, and the colon after it when it is the name of a member. */
20
+ const STRING_LITERAL = /"(?:[^"\\]|\\.)*"(\s*:)?/g;
21
21
  /**
22
- * A copy of a webhook whose ids are new: every string in the JSON body that looks like a provider id gets `tag`
22
+ * A copy of a webhook whose ids are new: every string value in the JSON body that looks like a provider id gets `tag`
23
23
  * appended, the same way in every webhook, so related events still name each other; delivery id headers too. The
24
+ * rest of the body stays byte for byte as recorded (numbers above 2^53 included, which a parse would round). The
24
25
  * signature is made again when it is sent.
25
26
  */
26
27
  export function freshCopy(exchange, tag) {
27
28
  const { request } = exchange;
28
29
  let bodyBase64 = request.bodyBase64;
30
+ const text = Buffer.from(request.bodyBase64, 'base64').toString('utf8');
29
31
  try {
30
- const parsed = JSON.parse(Buffer.from(request.bodyBase64, 'base64').toString('utf8'));
31
- const rewrite = (value) => {
32
- if (typeof value === 'string') {
33
- return ID.test(value) ? `${value}${tag}` : value;
32
+ JSON.parse(text);
33
+ const rewritten = text.replace(STRING_LITERAL, (literal, name) => {
34
+ if (name !== undefined) {
35
+ return literal;
34
36
  }
35
- if (Array.isArray(value)) {
36
- return value.map(rewrite);
37
- }
38
- if (typeof value === 'object' && value !== null) {
39
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, rewrite(child)]));
40
- }
41
- return value;
42
- };
43
- bodyBase64 = Buffer.from(JSON.stringify(rewrite(parsed))).toString('base64');
37
+ const value = JSON.parse(literal);
38
+ return ID.test(value) ? JSON.stringify(`${value}${tag}`) : literal;
39
+ });
40
+ bodyBase64 = Buffer.from(rewritten).toString('base64');
44
41
  }
45
42
  catch {
46
43
  // Not JSON: sent as it is
@@ -161,7 +158,10 @@ export async function chaos(options) {
161
158
  }
162
159
  }
163
160
  report('wrong signature', wrong, 'every webhook with a signature made with another key was refused with 4xx', 'a webhook with a wrong signature was not refused with 4xx; anyone who knows the URL can send events');
164
- const timed = signed.filter((exchange) => TIMESTAMPED.has(recogniseWebhook(exchange)?.provider ?? ''));
161
+ const timed = signed.filter((exchange) => {
162
+ const secret = secretFor(exchange, options.secrets);
163
+ return secret !== undefined && carriesTime(exchange.request.headers, secret);
164
+ });
165
165
  if (timed.length === 0) {
166
166
  options.print('skip stale signature: the signatures of these providers carry no time');
167
167
  }
package/dist/main.js CHANGED
@@ -19,7 +19,9 @@ export async function main(proc) {
19
19
  // the rest
20
20
  const { run } = await (proc.load ?? (() => import('./cli.js')))();
21
21
  signal.throwIfAborted();
22
- const running = await run(proc.argv, {
22
+ // The same for every start of this process: the Settings tab changes it before a restart
23
+ const view = {};
24
+ const start = () => run(proc.argv, {
23
25
  print: proc.print,
24
26
  notice: proc.error,
25
27
  env: proc.env,
@@ -29,11 +31,66 @@ export async function main(proc) {
29
31
  openBrowser: proc.openBrowser,
30
32
  input: proc.input,
31
33
  exchange: proc.exchange,
34
+ view,
32
35
  });
33
- if (running !== null && !signal.aborted) {
34
- proc.started?.(running);
36
+ const first = await start();
37
+ if (first === null || signal.aborted) {
38
+ return first;
35
39
  }
36
- return running;
40
+ // What runs now; a restart puts another tunnel in its place, and the process follows that one
41
+ let current = first;
42
+ let restarting = Promise.resolve();
43
+ let ended = () => { };
44
+ const follow = (running) => {
45
+ if ('ended' in running) {
46
+ void running.ended.then((error) => {
47
+ if (current === running) {
48
+ ended(error);
49
+ }
50
+ });
51
+ }
52
+ };
53
+ follow(first);
54
+ const restart = (settings) => {
55
+ const work = restarting.then(async () => {
56
+ const before = view.settings;
57
+ const closed = current;
58
+ // Not followed any more: a tunnel that is closed on purpose has not ended by itself
59
+ current = { ...closed };
60
+ await closed.close();
61
+ let problem = null;
62
+ try {
63
+ view.settings = settings;
64
+ current = (await start()) ?? closed;
65
+ }
66
+ catch (error) {
67
+ problem = error instanceof HopwireError ? error.message : unexpectedFailure(error);
68
+ view.settings = before;
69
+ try {
70
+ current = (await start()) ?? closed;
71
+ }
72
+ catch (again) {
73
+ // Not even as it was: the process stops with that sentence
74
+ const failure = again instanceof HopwireError ? again : new HopwireError(unexpectedFailure(again));
75
+ ended(failure);
76
+ throw failure;
77
+ }
78
+ }
79
+ follow(current);
80
+ return { running: current, problem };
81
+ });
82
+ restarting = work.catch(() => { });
83
+ return work;
84
+ };
85
+ proc.started?.(first, restart);
86
+ return {
87
+ // A stop during a restart waits for it, then closes what runs
88
+ close: () => restarting.then(() => current.close()),
89
+ ended: new Promise((resolve) => {
90
+ ended = resolve;
91
+ }),
92
+ ...('finished' in first ? { finished: first.finished } : {}),
93
+ };
37
94
  }, { on: proc.on, exit: proc.exit, error: proc.error });
38
95
  }
39
96
  catch (error) {
@@ -0,0 +1,256 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { isMap, isNode, isScalar, parseDocument } from 'yaml';
3
+ import { parseConfig } from './config.js';
4
+ import { renderConfig } from './config-template.js';
5
+ import { HopwireError, errorCode } from './errors.js';
6
+ /** The value of one setting. */
7
+ export function settingValue(settings, id) {
8
+ if (id.startsWith('public:')) {
9
+ return settings.services.find((service) => `public:${service.name}` === id)?.public ?? false;
10
+ }
11
+ return settings[id];
12
+ }
13
+ /**
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.
16
+ */
17
+ 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) {
22
+ service.public = value;
23
+ }
24
+ return next;
25
+ }
26
+ next[id] = value;
27
+ if (id === 'relay' && value) {
28
+ next.team = true;
29
+ }
30
+ if (!next.share) {
31
+ next.team = false;
32
+ next.relay = false;
33
+ }
34
+ if (!next.team) {
35
+ next.relay = false;
36
+ }
37
+ return next;
38
+ }
39
+ /** Why a setting cannot be turned on as things are; null when it can. */
40
+ export function unavailable(settings, id) {
41
+ if ((id === 'team' || id === 'relay') && !settings.share) {
42
+ return 'needs sharing';
43
+ }
44
+ return null;
45
+ }
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}`),
50
+ 'share',
51
+ 'team',
52
+ 'relay',
53
+ 'websocket',
54
+ 'agent',
55
+ ];
56
+ return ids.filter((id) => settingValue(before, id) !== settingValue(after, id));
57
+ }
58
+ /** The settings a hopwire.yaml has. */
59
+ export function settingsOfConfig(config, agent) {
60
+ return {
61
+ share: config.share,
62
+ team: config.team,
63
+ relay: config.relay,
64
+ websocket: config.captureWebSocket,
65
+ agent: agent ?? config.agent ?? true,
66
+ services: config.services.map((service) => ({ name: service.name, public: service.public })),
67
+ };
68
+ }
69
+ /** A config with the settings of the page in place of its own. */
70
+ export function configWithSettings(config, settings) {
71
+ return {
72
+ ...config,
73
+ share: settings.share,
74
+ team: settings.team,
75
+ relay: settings.relay,
76
+ captureWebSocket: settings.websocket,
77
+ agent: settings.agent,
78
+ // Without sharing there is nothing these could apply to
79
+ 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
+ })),
85
+ };
86
+ }
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
+ }
105
+ /** Where a line starts that holds this position of a text. */
106
+ function lineStart(text, at) {
107
+ return text.lastIndexOf('\n', at - 1) + 1;
108
+ }
109
+ /** The position after the end of the line that holds this position; the text gets a last newline when it has none. */
110
+ function afterLine(text, at) {
111
+ const end = text.indexOf('\n', at);
112
+ return end === -1 ? { text: `${text}\n`, at: text.length + 1 } : { text, at: end + 1 };
113
+ }
114
+ /** The indent of the file: the spaces of its first indented line that is not a comment; four when it has none. */
115
+ function indentUnit(text) {
116
+ return /^( +)[^\s#]/m.exec(text)?.[1] ?? ' ';
117
+ }
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);
130
+ let map = document.contents;
131
+ for (let depth = 0; depth < path.length; depth += 1) {
132
+ if (!isMap(map)) {
133
+ return refuse();
134
+ }
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)}`;
157
+ }
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)}`;
176
+ }
177
+ map = pair.value;
178
+ }
179
+ return refuse();
180
+ }
181
+ /**
182
+ * The text of a hopwire.yaml with settings changed: only the keys that differ between `before` and `after` are
183
+ * 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.
186
+ */
187
+ export function editConfigText(text, before, after, shown) {
188
+ 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.`);
193
+ }
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) {
199
+ continue;
200
+ }
201
+ edited = setBoolean(edited, path, wanted, shown);
202
+ }
203
+ // What is written must be a file hopwire up accepts
204
+ parseConfig(edited, shown);
205
+ return edited;
206
+ }
207
+ /** Writes changed settings into an existing hopwire.yaml. */
208
+ export async function saveToConfigFile(file, shown, before, after) {
209
+ let text;
210
+ try {
211
+ text = await readFile(file, 'utf8');
212
+ }
213
+ catch (error) {
214
+ throw new HopwireError(`${shown} cannot be read (${errorCode(error) ?? 'UNKNOWN'}); nothing was saved.`);
215
+ }
216
+ await writeFile(file, editConfigText(text, before, after, shown));
217
+ }
218
+ /**
219
+ * Creates a hopwire.yaml for a tunnel started with hopwire http, with the text hopwire init writes and the settings of
220
+ * this run. Never replaces a file.
221
+ */
222
+ export async function createConfigFile(target, settings) {
223
+ const isPublic = settings.services[0]?.public ?? false;
224
+ if (isPublic && target.urls === null) {
225
+ throw new HopwireError('A file with a public service names the edge of your account; run hopwire login first. Nothing was saved.');
226
+ }
227
+ const template = renderConfig({
228
+ services: [
229
+ {
230
+ name: target.serviceName,
231
+ local: target.local,
232
+ public: isPublic,
233
+ subdomain: isPublic ? target.subdomain : null,
234
+ logs: [],
235
+ },
236
+ ],
237
+ edgeUrl: isPublic ? (target.urls?.edgeUrl ?? null) : null,
238
+ controlPlaneUrl: isPublic ? (target.urls?.controlPlaneUrl ?? null) : null,
239
+ share: settings.share,
240
+ team: settings.team,
241
+ allowAgents: false,
242
+ shareLogs: false,
243
+ });
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);
247
+ try {
248
+ // wx: a file that is there is not replaced
249
+ await writeFile(target.file, text, { flag: 'wx' });
250
+ }
251
+ catch (error) {
252
+ throw new HopwireError(errorCode(error) === 'EEXIST'
253
+ ? `${target.shown} exists already and hopwire http does not read it; change it there and start it with hopwire up. Nothing was saved.`
254
+ : `${target.shown} cannot be written (${errorCode(error) ?? 'UNKNOWN'}); nothing was saved.`);
255
+ }
256
+ }
package/dist/signature.js CHANGED
@@ -73,12 +73,22 @@ const VERIFIERS = {
73
73
  return same(value.slice(7), hmac(secret, body, 'hex')) ? { timestamp: null } : MISMATCH;
74
74
  },
75
75
  },
76
- // X-Gitlab-Token: the secret token itself
76
+ // Two kinds of secret, both optional on a GitLab webhook: a signing token (whsec_<base64 key>, GitLab 19.0 and later)
77
+ // signs with the Standard Webhooks headers webhook-id, webhook-timestamp and webhook-signature, as Svix does; a
78
+ // secret token is sent as it is in X-Gitlab-Token. The secret named decides which one is checked.
77
79
  gitlab: {
78
- signs: (h) => h.has('x-gitlab-token'),
79
- check: (h, _body, secret) => same(h.get('x-gitlab-token') ?? '', secret)
80
- ? { timestamp: null }
81
- : 'the X-Gitlab-Token header is not the secret token of this webhook',
80
+ signs: (h) => h.has('x-gitlab-token') || (h.has('x-gitlab-event') && h.has('webhook-signature')),
81
+ check: (h, body, secret) => {
82
+ if (isSigningToken(secret) && h.has('webhook-signature')) {
83
+ return standardWebhook(h, body, secret, 'webhook');
84
+ }
85
+ if (h.has('x-gitlab-token')) {
86
+ return same(h.get('x-gitlab-token') ?? '', secret)
87
+ ? { timestamp: null }
88
+ : 'the X-Gitlab-Token header is not the secret token of this webhook';
89
+ }
90
+ return 'this webhook is signed with a signing token (whsec_...), and the secret named is not one';
91
+ },
82
92
  },
83
93
  // X-Shopify-Hmac-Sha256: base64 HMAC-SHA256 over the body
84
94
  shopify: {
@@ -99,24 +109,10 @@ const VERIFIERS = {
99
109
  },
100
110
  },
101
111
  // svix-id, svix-timestamp, svix-signature: "v1,<base64> ..."; the secret is whsec_<base64 key>
112
+ // (Standard Webhooks uses the same scheme with webhook-* headers; a GitLab webhook signed that way is GitLab's)
102
113
  svix: {
103
- signs: (h) => h.has('svix-signature') || h.has('webhook-signature'),
104
- check: (h, body, secret) => {
105
- const id = h.get('svix-id') ?? h.get('webhook-id') ?? '';
106
- const ts = h.get('svix-timestamp') ?? h.get('webhook-timestamp') ?? '';
107
- const value = h.get('svix-signature') ?? h.get('webhook-signature') ?? '';
108
- if (id === '' || !/^\d+$/.test(ts)) {
109
- return 'the id or timestamp header of the signature is missing';
110
- }
111
- const key = Buffer.from(secret.startsWith('whsec_') ? secret.slice(6) : secret, 'base64');
112
- const expected = createHmac('sha256', key)
113
- .update(Buffer.concat([Buffer.from(`${id}.${ts}.`), body]))
114
- .digest('base64');
115
- const signatures = value.split(' ').map((entry) => entry.split(',', 2));
116
- return signatures.some(([version, signature]) => version === 'v1' && same(signature ?? '', expected))
117
- ? { timestamp: Number(ts) * 1000 }
118
- : MISMATCH;
119
- },
114
+ signs: (h) => h.has('svix-signature') || (h.has('webhook-signature') && !h.has('x-gitlab-event')),
115
+ check: (h, body, secret) => standardWebhook(h, body, secret, h.has('svix-signature') ? 'svix' : 'webhook'),
120
116
  },
121
117
  // Paddle-Signature: ts=<seconds>;h1=<hex>; HMAC-SHA256 over "<ts>:<body>"
122
118
  paddle: {
@@ -138,6 +134,33 @@ const VERIFIERS = {
138
134
  check: (h, body, secret) => same(h.get('linear-signature') ?? '', hmac(secret, body, 'hex')) ? { timestamp: null } : MISMATCH,
139
135
  },
140
136
  };
137
+ /** A signing secret of the Standard Webhooks scheme: whsec_ and the base64 of the key. */
138
+ function isSigningToken(secret) {
139
+ return secret.startsWith('whsec_');
140
+ }
141
+ /** The key of a Standard Webhooks secret: the bytes the base64 after whsec_ stands for. */
142
+ function standardKey(secret) {
143
+ return Buffer.from(isSigningToken(secret) ? secret.slice(6) : secret, 'base64');
144
+ }
145
+ /** <prefix>-id, <prefix>-timestamp, <prefix>-signature: "v1,<base64> ..."; HMAC-SHA256 over "<id>.<timestamp>.<body>" */
146
+ function standardWebhook(h, body, secret, prefix) {
147
+ const id = h.get(`${prefix}-id`) ?? '';
148
+ const ts = h.get(`${prefix}-timestamp`) ?? '';
149
+ const value = h.get(`${prefix}-signature`) ?? '';
150
+ if (id === '' || !/^\d+$/.test(ts)) {
151
+ return 'the id or timestamp header of the signature is missing';
152
+ }
153
+ const expected = standardSignature(standardKey(secret), id, ts, body);
154
+ const signatures = value.split(' ').map((entry) => entry.split(',', 2));
155
+ return signatures.some(([version, signature]) => version === 'v1' && same(signature ?? '', expected))
156
+ ? { timestamp: Number(ts) * 1000 }
157
+ : MISMATCH;
158
+ }
159
+ function standardSignature(key, id, timestamp, body) {
160
+ return createHmac('sha256', key)
161
+ .update(Buffer.concat([Buffer.from(`${id}.${timestamp}.`), body]))
162
+ .digest('base64');
163
+ }
141
164
  function hmac(secret, data, encoding) {
142
165
  return createHmac('sha256', secret).update(data).digest(encoding);
143
166
  }
@@ -154,8 +177,8 @@ export function isVariableName(name) {
154
177
  /**
155
178
  * The headers of a request signed again for `provider` at `timestampSeconds` (hopwire verify and chaos): the recorded
156
179
  * signature headers are replaced, the rest kept. With `wrongKey` the signature is made with another key, for a handler
157
- * that must refuse it. Without a timestamp in the provider's scheme (GitHub, GitLab, Shopify, Linear) only the
158
- * signature changes.
180
+ * that must refuse it. Without a timestamp in the provider's scheme (GitHub, Shopify, Linear, a GitLab secret token)
181
+ * only the signature changes.
159
182
  */
160
183
  export function signHeaders(headers, body, secret, timestampSeconds, wrongKey = false) {
161
184
  const key = wrongKey ? `${secret.secret}-not-the-signing-secret` : secret.secret;
@@ -168,9 +191,17 @@ export function signHeaders(headers, body, secret, timestampSeconds, wrongKey =
168
191
  case 'github':
169
192
  set.set('x-hub-signature-256', `sha256=${hmac(key, body, 'hex')}`);
170
193
  break;
171
- case 'gitlab':
172
- set.set('x-gitlab-token', key);
194
+ case 'gitlab': {
195
+ // a signing token signs again with a fresh time; a secret token is the header itself
196
+ const lower = new Map(headers.map(([name, value]) => [name.toLowerCase(), value]));
197
+ if (isSigningToken(secret.secret) && lower.has('webhook-signature')) {
198
+ standardHeaders(set, 'webhook', lower.get('webhook-id') ?? 'msg_hopwire', t, body, secret.secret, wrongKey);
199
+ }
200
+ else {
201
+ set.set('x-gitlab-token', key);
202
+ }
173
203
  break;
204
+ }
174
205
  case 'shopify':
175
206
  set.set('x-shopify-hmac-sha256', hmac(key, body, 'base64'));
176
207
  break;
@@ -181,14 +212,7 @@ export function signHeaders(headers, body, secret, timestampSeconds, wrongKey =
181
212
  case 'svix': {
182
213
  const lower = new Map(headers.map(([name, value]) => [name.toLowerCase(), value]));
183
214
  const prefix = lower.has('webhook-id') && !lower.has('svix-id') ? 'webhook' : 'svix';
184
- const id = lower.get(`${prefix}-id`) ?? 'msg_hopwire';
185
- const raw = Buffer.from(key.startsWith('whsec_') ? key.slice(6) : key, 'base64');
186
- const signature = createHmac('sha256', wrongKey ? Buffer.concat([raw, Buffer.from('x')]) : raw)
187
- .update(Buffer.concat([Buffer.from(`${id}.${t}.`), body]))
188
- .digest('base64');
189
- set.set(`${prefix}-id`, id);
190
- set.set(`${prefix}-timestamp`, t);
191
- set.set(`${prefix}-signature`, `v1,${signature}`);
215
+ standardHeaders(set, prefix, lower.get(`${prefix}-id`) ?? 'msg_hopwire', t, body, secret.secret, wrongKey);
192
216
  break;
193
217
  }
194
218
  case 'paddle':
@@ -201,6 +225,31 @@ export function signHeaders(headers, body, secret, timestampSeconds, wrongKey =
201
225
  const kept = headers.filter(([name]) => !set.has(name.toLowerCase()));
202
226
  return [...kept, ...set.entries()];
203
227
  }
228
+ /** The Standard Webhooks headers of `body`, with another key when `wrongKey`. */
229
+ function standardHeaders(set, prefix, id, timestamp, body, secret, wrongKey) {
230
+ const raw = standardKey(secret);
231
+ const key = wrongKey ? Buffer.concat([raw, Buffer.from('x')]) : raw;
232
+ set.set(`${prefix}-id`, id);
233
+ set.set(`${prefix}-timestamp`, timestamp);
234
+ set.set(`${prefix}-signature`, `v1,${standardSignature(key, id, timestamp, body)}`);
235
+ }
236
+ /**
237
+ * Whether the signature of a request carries the time it was made, so a stale one can be made: always for Stripe,
238
+ * Slack, Svix and Paddle, for GitLab only when it is signed with a signing token and the secret named is one.
239
+ */
240
+ export function carriesTime(headers, secret) {
241
+ switch (secret.provider) {
242
+ case 'stripe':
243
+ case 'slack':
244
+ case 'svix':
245
+ case 'paddle':
246
+ return true;
247
+ case 'gitlab':
248
+ return isSigningToken(secret.secret) && headers.some(([name]) => name.toLowerCase() === 'webhook-signature');
249
+ default:
250
+ return false;
251
+ }
252
+ }
204
253
  /** Whether a request carries a signature of `provider`: only those are signed again. */
205
254
  export function signedBy(headers, provider) {
206
255
  return VERIFIERS[provider].signs(new Map(headers.map(([name, value]) => [name.toLowerCase(), value])));
package/dist/tui/app.js CHANGED
@@ -5,7 +5,9 @@ import { FLASH_MS, headerLine, keysLine, rule, statusLine, tabBar } from './chro
5
5
  import { parseInput } from './input.js';
6
6
  import { Traffic } from './model.js';
7
7
  import { menuItems, requestsLines } from './requests.js';
8
- import { TABS, TAB_KEYS, listWindow, sectionsOf, target } from './state.js';
8
+ import { TAB_KEYS, listWindow, sectionsOf, tabsOf, target, } from './state.js';
9
+ import { settingValue, unavailable, withSetting } from '../settings.js';
10
+ import { changeChoices, settingName, settingRows, settingsLines } from './settings.js';
9
11
  import { helpContent, scrolled, shareItems, shareLines, statusContent, tools, toolsLines } from './tabs.js';
10
12
  /** Rows of the window that are not the tab: two of the header, two rules, two of the footer. */
11
13
  const CHROME_ROWS = 6;
@@ -36,6 +38,17 @@ export class App {
36
38
  detail: null,
37
39
  menu: null,
38
40
  cursor: { share: 0, tools: 0 },
41
+ settings: options.settings == null || options.actions.applySettings === undefined
42
+ ? null
43
+ : {
44
+ access: options.settings,
45
+ atStart: options.settings.current,
46
+ history: [],
47
+ cursor: 0,
48
+ problem: null,
49
+ box: null,
50
+ },
51
+ restarting: false,
39
52
  scroll: { status: 0, help: 0 },
40
53
  flash: null,
41
54
  stopping: false,
@@ -73,6 +86,9 @@ export class App {
73
86
  body = shown.lines;
74
87
  break;
75
88
  }
89
+ case 'settings':
90
+ body = settingsLines(state, ui, width, height);
91
+ break;
76
92
  case 'help': {
77
93
  const shown = scrolled(helpContent(ui), state.scroll.help, height);
78
94
  state.scroll.help = shown.scroll;
@@ -255,6 +271,18 @@ export class App {
255
271
  state.cursor.tools = Number(value);
256
272
  this.copyTool();
257
273
  break;
274
+ case 'setting':
275
+ if (state.settings !== null && state.settings.box === null) {
276
+ state.settings.cursor = Number(value);
277
+ this.settingsKey('enter');
278
+ }
279
+ break;
280
+ case 'choice':
281
+ if (state.settings?.box != null) {
282
+ state.settings.box.choice = Number(value);
283
+ this.settingsKey('enter');
284
+ }
285
+ break;
258
286
  default:
259
287
  break;
260
288
  }
@@ -304,15 +332,20 @@ export class App {
304
332
  this.quit();
305
333
  return;
306
334
  }
307
- const tab = TABS.find((name) => TAB_KEYS[name] === key);
335
+ if (state.tab === 'settings' && state.settings?.box != null) {
336
+ this.settingsKey(key);
337
+ return;
338
+ }
339
+ const tabs = tabsOf(state);
340
+ const tab = tabs.find((name) => TAB_KEYS[name] === key);
308
341
  if (tab !== undefined) {
309
342
  this.show(tab);
310
343
  return;
311
344
  }
312
345
  const inDetail = state.tab === 'requests' && state.detail !== null;
313
346
  if (!inDetail && (key === 'left' || key === 'right')) {
314
- const at = TABS.indexOf(state.tab) + (key === 'right' ? 1 : -1);
315
- this.show(TABS[(at + TABS.length) % TABS.length] ?? 'requests');
347
+ const at = tabs.indexOf(state.tab) + (key === 'right' ? 1 : -1);
348
+ this.show(tabs[(at + tabs.length) % tabs.length] ?? 'requests');
316
349
  return;
317
350
  }
318
351
  switch (state.tab) {
@@ -330,6 +363,9 @@ export class App {
330
363
  case 'tools':
331
364
  this.cursorKey(key, 'tools', tools(state).length, () => this.copyTool());
332
365
  break;
366
+ case 'settings':
367
+ this.settingsKey(key);
368
+ break;
333
369
  case 'status':
334
370
  state.scroll.status += scrollStep(key, this.bodyHeight);
335
371
  break;
@@ -338,6 +374,115 @@ export class App {
338
374
  break;
339
375
  }
340
376
  }
377
+ /** Keys of the Settings tab and of its change box. */
378
+ settingsKey(key) {
379
+ const view = this.state.settings;
380
+ if (view === null) {
381
+ return;
382
+ }
383
+ const settings = view.access.current;
384
+ const rows = settingRows(settings);
385
+ if (view.box !== null) {
386
+ const { box } = view;
387
+ const on = !settingValue(settings, box.id);
388
+ const choices = changeChoices(view.access, on);
389
+ if (key === 'up') {
390
+ box.choice = Math.max(box.choice - 1, 0);
391
+ }
392
+ else if (key === 'down') {
393
+ box.choice = Math.min(box.choice + 1, choices.length - 1);
394
+ }
395
+ else if (key === 'esc' || key === 'q') {
396
+ view.box = null;
397
+ }
398
+ else if (key === 'enter') {
399
+ view.box = null;
400
+ if (box.choice < 2) {
401
+ this.change(withSetting(settings, box.id, on), box.choice === 1, `${settingName(settings, box.id)}: ${on ? 'on' : 'off'}`);
402
+ }
403
+ }
404
+ return;
405
+ }
406
+ const row = rows[view.cursor];
407
+ if (key === 'up') {
408
+ view.cursor = Math.max(view.cursor - 1, 0);
409
+ }
410
+ else if (key === 'down') {
411
+ view.cursor = Math.min(view.cursor + 1, rows.length - 1);
412
+ }
413
+ else if ((key === 'enter' || key === 'space') && row !== undefined) {
414
+ const reason = settingValue(settings, row.id) ? null : unavailable(settings, row.id);
415
+ if (this.state.restarting) {
416
+ this.flash('The tunnel is restarting; one change at a time.', true, false);
417
+ }
418
+ else if (reason !== null) {
419
+ this.flash(`${row.label.trim()} ${reason}.`, true, false);
420
+ }
421
+ else {
422
+ view.box = { id: row.id, choice: 0 };
423
+ }
424
+ }
425
+ else if (key === 's') {
426
+ this.save();
427
+ }
428
+ else if (key === 'u') {
429
+ const before = view.history.pop();
430
+ if (before === undefined) {
431
+ this.flash('Nothing was changed in this run.', true, false);
432
+ }
433
+ else {
434
+ this.change(before, false, 'The last change is undone', false, false);
435
+ }
436
+ }
437
+ }
438
+ /** Restarts the tunnel with changed settings, and saves them when asked. */
439
+ change(next, save, done, remember = true, forRun = true) {
440
+ const { state } = this;
441
+ const view = state.settings;
442
+ const apply = this.actions.applySettings;
443
+ if (view === null || apply === undefined || state.restarting) {
444
+ return;
445
+ }
446
+ const before = view.access.current;
447
+ view.problem = null;
448
+ state.restarting = true;
449
+ this.invalidate();
450
+ void apply(next).then(({ info, access, problem }) => {
451
+ state.restarting = false;
452
+ state.info = info;
453
+ if (access !== null) {
454
+ // What the file is, and whether it exists, is known here; a restart does not change it
455
+ view.access = { ...access, file: view.access.file, save: access.save };
456
+ }
457
+ if (problem !== null) {
458
+ view.problem = problem;
459
+ this.flash(`Not changed: ${problem}`, true);
460
+ }
461
+ else {
462
+ if (remember) {
463
+ view.history.push(before);
464
+ }
465
+ this.flash(`${done}${save || !forRun ? '' : ' for this run'}.`);
466
+ if (save) {
467
+ this.save();
468
+ }
469
+ }
470
+ }, (error) => {
471
+ state.restarting = false;
472
+ this.flash(error instanceof Error ? error.message : 'The tunnel could not be started again.', true);
473
+ });
474
+ }
475
+ /** Writes the settings that run to hopwire.yaml. */
476
+ save() {
477
+ const view = this.state.settings;
478
+ if (view === null) {
479
+ return;
480
+ }
481
+ void view.access.save(view.access.current).then((sentence) => {
482
+ view.access = { ...view.access, file: { ...view.access.file, exists: true } };
483
+ this.flash(sentence);
484
+ }, (error) => this.flash(error instanceof Error ? error.message : 'The file could not be written.', true));
485
+ }
341
486
  quit() {
342
487
  this.state.typing = false;
343
488
  this.state.menu = null;
@@ -1,6 +1,6 @@
1
1
  import { paint } from '../terminal.js';
2
2
  import { shortKey } from '../output.js';
3
- import { TABS, TAB_KEYS, TAB_TITLES, listWindow, target } from './state.js';
3
+ import { TAB_KEYS, TAB_TITLES, listWindow, tabsOf, target } from './state.js';
4
4
  import { clip, sides, width as widthOf } from './text.js';
5
5
  /**
6
6
  * What stands around every tab: the two lines of the header (what runs, and the navigation), and the two lines of
@@ -90,7 +90,7 @@ export function headerLine(state, ui, width) {
90
90
  export function tabBar(state, ui) {
91
91
  const { look } = ui;
92
92
  const line = new LineBuilder().add(' ');
93
- for (const tab of TABS) {
93
+ for (const tab of tabsOf(state)) {
94
94
  const current = tab === state.tab;
95
95
  const problem = tab === 'status' && state.facts.unseenProblems > 0;
96
96
  const label = `${TAB_KEYS[tab]} ${TAB_TITLES[tab]}`;
@@ -155,7 +155,11 @@ export function statusLine(state, ui, width, bodyHeight) {
155
155
  const flash = state.flash !== null && ui.now() - state.flash.at < FLASH_MS
156
156
  ? `${paint(look, '›', state.flash.problem ? palette.err : palette.green, true)} ${state.flash.problem ? paint(look, state.flash.text, palette.err) : state.flash.text}`
157
157
  : null;
158
- const right = state.stopping ? muted(look, 'Stopping…') : (flash ?? hint(state, ui) ?? '');
158
+ const right = state.stopping
159
+ ? muted(look, 'Stopping…')
160
+ : state.restarting
161
+ ? paint(look, 'Restarting the tunnel…', palette.info)
162
+ : (flash ?? hint(state, ui) ?? '');
159
163
  // What just happened matters more than the counts: it gets the room it needs
160
164
  const rightWidth = Math.min(widthOf(right), Math.max(width - 12, 0));
161
165
  return { text: sides(left, `${clip(right, rightWidth)} `, width) };
@@ -202,6 +206,23 @@ export function keysOf(state) {
202
206
  case 'share':
203
207
  case 'tools':
204
208
  return [['↑↓', 'select', 'down'], ['enter', 'copy', 'enter'], quit];
209
+ case 'settings':
210
+ if (state.settings?.box != null) {
211
+ return [
212
+ ['↑↓', 'select', 'down'],
213
+ ['enter', 'choose', 'enter'],
214
+ ['esc', 'cancel', 'esc'],
215
+ ];
216
+ }
217
+ return [
218
+ ['↑↓', 'select', 'down'],
219
+ ['enter', 'change', 'enter'],
220
+ ['s', `save to ${state.settings?.access.file.shown ?? 'hopwire.yaml'}`, 's'],
221
+ ...(state.settings !== null && state.settings.history.length > 0
222
+ ? [['u', 'undo', 'u']]
223
+ : []),
224
+ quit,
225
+ ];
205
226
  default:
206
227
  return [['↑↓', 'scroll', 'down'], quit];
207
228
  }
package/dist/tui/model.js CHANGED
@@ -69,6 +69,13 @@ export class Facts {
69
69
  constructor(now = Date.now) {
70
70
  this.now = now;
71
71
  }
72
+ /** The tunnel is started again with other settings: its lines are the facts from now on. */
73
+ reset() {
74
+ this.facts.length = 0;
75
+ this.started = false;
76
+ this.edge = null;
77
+ this.teammates.clear();
78
+ }
72
79
  /** The tunnel runs: from now on a line is something that happened, not a fact of the start. */
73
80
  start() {
74
81
  this.started = true;
@@ -0,0 +1,179 @@
1
+ import { changedSettings, settingValue, unavailable, } from '../settings.js';
2
+ import { paint, wrap } from '../terminal.js';
3
+ import { bold, muted } from './chrome.js';
4
+ import { hitLine } from './state.js';
5
+ import { after, clip, fit, onBackground, sides } from './text.js';
6
+ /** The rows of the tab, in the order they are shown. */
7
+ export function settingRows(settings) {
8
+ const one = settings.services.length === 1;
9
+ return [
10
+ ...settings.services.map((service) => ({
11
+ id: `public:${service.name}`,
12
+ group: 'Reach',
13
+ label: one ? 'Public URL' : `Public URL of ${service.name}`,
14
+ what: 'a public HTTPS address through the edge',
15
+ })),
16
+ {
17
+ id: 'share',
18
+ group: 'Reach',
19
+ label: 'Share with teammates',
20
+ what: 'direct P2P: connect and watch with your keys',
21
+ },
22
+ { id: 'team', group: 'Reach', label: ' Team only', what: 'only machines of your organisation (Team plan)' },
23
+ {
24
+ id: 'relay',
25
+ group: 'Reach',
26
+ label: ' Relay',
27
+ what: 'through the edge when no direct connection comes about',
28
+ },
29
+ {
30
+ id: 'websocket',
31
+ group: 'Recording',
32
+ label: 'WebSocket messages',
33
+ what: 'both directions, up to 64 KiB per message',
34
+ },
35
+ {
36
+ id: 'agent',
37
+ group: 'Recording',
38
+ label: 'Coding agents',
39
+ what: 'an agent on this machine can read and replay',
40
+ },
41
+ ];
42
+ }
43
+ /** What a change does, in the words the user confirms. Turning something on that opens the service says to whom. */
44
+ export function changeSentence(id, on) {
45
+ if (id.startsWith('public:')) {
46
+ return on
47
+ ? 'Anyone who knows the address can call your service through the Hopwire edge. It needs an account (hopwire login), and the requests pass through the edge.'
48
+ : 'The public address stops working. Requests to it are no longer answered by your service.';
49
+ }
50
+ switch (id) {
51
+ case 'share':
52
+ return on
53
+ ? 'Teammates with your keys can call your service and read the traffic log: headers and bodies as captured, credentials included, earlier runs too. Direct P2P, end-to-end encrypted, no servers of ours.'
54
+ : 'Teammates lose the connection: nobody can call your service or follow the log any more. Team only and Relay go off with it.';
55
+ case 'team':
56
+ return on
57
+ ? 'Only machines of the members of your organisation get in (Team plan). The control plane of your account names their keys and gets the key of this machine; your traffic still passes none.'
58
+ : 'Anyone with your keys gets in again, not only your organisation. Relay goes off with it.';
59
+ case 'relay':
60
+ return on
61
+ ? 'Teammates whose network allows no direct connection come in through the edge of your account. End-to-end encrypted: the edge passes on bytes it cannot read, and sees addresses, your organisation, keys and byte counts. Turns on Team only.'
62
+ : 'Teammates connect directly only. One whose network allows no direct connection no longer gets in.';
63
+ case 'websocket':
64
+ return on
65
+ ? 'The messages of WebSockets are recorded in both directions, up to 64 KiB per message.'
66
+ : 'Only the handshake of a WebSocket is recorded, not its messages.';
67
+ default:
68
+ return on
69
+ ? 'A coding agent on this machine can read the traffic and replay it through hopwire mcp. What it reads goes to its model provider.'
70
+ : 'hopwire mcp can no longer read or replay the traffic of this tunnel.';
71
+ }
72
+ }
73
+ /** The choices of the change box. */
74
+ export function changeChoices(access, on) {
75
+ const turn = on ? 'Turn on' : 'Turn off';
76
+ return [
77
+ `${turn} for this run`,
78
+ access.file.exists ? `${turn} and save to ${access.file.shown}` : `${turn} and create ${access.file.shown}`,
79
+ 'Cancel',
80
+ ];
81
+ }
82
+ function highlight(look) {
83
+ const light = look.palette.mark === null;
84
+ return look.truecolor ? (light ? '48;2;226;232;240' : '48;2;30;41;59') : light ? '48;5;254' : '48;5;237';
85
+ }
86
+ /** The label of a setting without its indent, for sentences. */
87
+ export function settingName(settings, id) {
88
+ return (settingRows(settings)
89
+ .find((row) => row.id === id)
90
+ ?.label.trim() ?? id);
91
+ }
92
+ export function settingsLines(state, ui, width, height) {
93
+ const { look } = ui;
94
+ const { palette } = look;
95
+ const view = state.settings;
96
+ if (view === null) {
97
+ return [];
98
+ }
99
+ const settings = view.access.current;
100
+ const rows = settingRows(settings);
101
+ const labels = Math.max(...rows.map((row) => row.label.length)) + 2;
102
+ const lines = [];
103
+ let group = '';
104
+ rows.forEach((row, index) => {
105
+ if (row.group !== group) {
106
+ group = row.group;
107
+ lines.push({ text: '' }, { text: ` ${bold(look, group)}` });
108
+ }
109
+ const reason = unavailable(settings, row.id);
110
+ const on = settingValue(settings, row.id);
111
+ const value = reason !== null && !on ? muted(look, '-') : on ? paint(look, 'on', palette.ok, true) : muted(look, 'off');
112
+ const current = index === view.cursor;
113
+ const text = `${current ? paint(look, '▌', palette.green) : ' '} ${fit(row.label, labels)}${fit(value, 6)}${muted(look, reason !== null && !on ? reason : row.what)}`;
114
+ lines.push({
115
+ text: current ? onBackground(fit(text, width), highlight(look)) : text,
116
+ hits: hitLine(`setting:${index}`, width),
117
+ });
118
+ });
119
+ const changed = changedSettings(view.atStart, settings).map((id) => `${settingName(settings, id)} ${settingValue(settings, id) ? 'on' : 'off'}`);
120
+ const left = ` ${muted(look, 'Changed in this run:')} ${changed.length === 0 ? muted(look, 'nothing') : changed.join(', ')}`;
121
+ const file = view.access.file.exists
122
+ ? `${muted(look, 'file:')} ${view.access.file.shown} `
123
+ : muted(look, `no ${view.access.file.shown} here yet; saving creates it `);
124
+ lines.push({ text: '' }, { text: sides(left, file, width) });
125
+ if (view.problem !== null && !state.restarting) {
126
+ lines.push({ text: '' });
127
+ for (const part of wrap(`Not changed: ${view.problem}`, Math.max(width - 2, 20))) {
128
+ lines.push({ text: ` ${paint(look, part, palette.err)}` });
129
+ }
130
+ }
131
+ if (state.restarting) {
132
+ lines.push({ text: '' }, { text: ` ${paint(look, 'The tunnel is restarting with the new settings…', palette.info)}` });
133
+ }
134
+ const filled = Array.from({ length: height }, (_, row) => lines[row] ?? { text: '' });
135
+ return view.box === null ? filled : withBox(ui, filled, view, width);
136
+ }
137
+ /** The change box over the rows: what the change does, and the choices. */
138
+ function withBox(ui, lines, view, width) {
139
+ const { look } = ui;
140
+ const { box } = view;
141
+ if (box === null) {
142
+ return lines;
143
+ }
144
+ const settings = view.access.current;
145
+ const on = !settingValue(settings, box.id);
146
+ const inner = Math.min(Math.max(width - 8, 30), 64);
147
+ const title = settingName(settings, box.id);
148
+ const text = [
149
+ ...wrap(changeSentence(box.id, on), inner - 2),
150
+ ...wrap('The tunnel restarts for it; a request that arrives in that moment fails.', inner - 2),
151
+ ];
152
+ const bar = muted(look, '│');
153
+ const content = [
154
+ { text: muted(look, `┌ ${title} ${'─'.repeat(Math.max(inner - title.length - 2, 0))}┐`) },
155
+ ...text.map((part) => ({ text: `${bar} ${fit(part, inner - 2)} ${bar}` })),
156
+ { text: `${bar}${' '.repeat(inner)}${bar}` },
157
+ ...changeChoices(view.access, on).map((choice, index) => {
158
+ const current = index === box.choice;
159
+ const label = ` ${current ? paint(look, '▸', look.palette.green, true) : ' '} ${fit(choice, inner - 4)} `;
160
+ return {
161
+ text: `${bar}${current ? onBackground(label, highlight(look)) : label}${bar}`,
162
+ hits: [{ from: 0, to: inner + 2, id: `choice:${index}` }],
163
+ };
164
+ }),
165
+ { text: muted(look, `└${'─'.repeat(inner)}┘`) },
166
+ ];
167
+ const x = Math.max(Math.min(4, width - inner - 2), 0);
168
+ const y = Math.max(Math.min(2, lines.length - content.length), 0);
169
+ return lines.map((line, row) => {
170
+ const part = content[row - y];
171
+ if (part === undefined) {
172
+ return line;
173
+ }
174
+ return {
175
+ text: `${fit(clip(line.text, x, false), x)}${part.text}${after(line.text, x + inner + 2)}`,
176
+ hits: (part.hits ?? []).map((hit) => ({ ...hit, from: hit.from + x, to: hit.to + x })),
177
+ };
178
+ });
179
+ }
package/dist/tui/state.js CHANGED
@@ -1,15 +1,27 @@
1
1
  import { recogniseWebhook } from '../webhook.js';
2
2
  /** The tabs of the navigation, in the order of the bar. */
3
- export const TABS = ['requests', 'share', 'tools', 'status', 'help'];
3
+ export const TABS = ['requests', 'share', 'tools', 'status', 'settings', 'help'];
4
4
  export const TAB_TITLES = {
5
5
  requests: 'Requests',
6
6
  share: 'Share',
7
7
  tools: 'Tools',
8
8
  status: 'Status',
9
+ settings: 'Settings',
9
10
  help: 'Help',
10
11
  };
11
12
  /** The key of a tab: its number, and ? for the help. */
12
- export const TAB_KEYS = { requests: '1', share: '2', tools: '3', status: '4', help: '?' };
13
+ export const TAB_KEYS = {
14
+ requests: '1',
15
+ share: '2',
16
+ tools: '3',
17
+ status: '4',
18
+ settings: '5',
19
+ help: '?',
20
+ };
21
+ /** The tabs this tunnel has: Settings only where there is something to change (http and up). */
22
+ export function tabsOf(state) {
23
+ return TABS.filter((tab) => tab !== 'settings' || state.settings !== null);
24
+ }
13
25
  /** A hit over a whole line. */
14
26
  export function hitLine(id, width) {
15
27
  return [{ from: 0, to: width, id }];
package/dist/tui/tabs.js CHANGED
@@ -203,7 +203,7 @@ export function helpContent(ui) {
203
203
  return [
204
204
  '',
205
205
  ` ${bold(look, 'Everywhere')}`,
206
- key('1 2 3 4 ?', 'Requests, Share, Tools, Status, Help'),
206
+ key('1 2 3 4 5 ?', 'Requests, Share, Tools, Status, Settings, Help'),
207
207
  key('← →', 'the tab before and after'),
208
208
  key('q', 'stop the tunnel and quit'),
209
209
  '',
@@ -222,6 +222,10 @@ export function helpContent(ui) {
222
222
  key('↑ ↓', 'scroll; page up and page down for more'),
223
223
  key('esc', 'back to the list'),
224
224
  '',
225
+ ` ${bold(look, 'Settings')}`,
226
+ key('enter', 'change the picked setting: for this run, or saved to hopwire.yaml'),
227
+ key('s u', 'save the settings that run to hopwire.yaml, undo the last change'),
228
+ '',
225
229
  ` ${bold(look, 'Mouse')}`,
226
230
  ` ${'Click a tab, a request, a key in the last line or an address. The wheel scrolls.'}`,
227
231
  ` ${muted(look, 'To select text hold Option (iTerm, Apple Terminal) or Shift (most others) while you drag.')}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopwire",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "mcpName": "to.hopwire/hopwire",
5
5
  "description": "Record, share and replay the HTTP traffic of your local services: private P2P sharing with teammates, and public HTTPS URLs.",
6
6
  "license": "Apache-2.0",