@quolu/lattice 0.12.11 → 0.12.12

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.12.11",
3
+ "version": "0.12.12",
4
4
  "description": "Lattice — phase-aware TODO graph compiler and conflict-aware orchestration runtime",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -54,7 +54,7 @@
54
54
  "test": "node scripts/run-product-tests.mjs",
55
55
  "test:sensor": "npm --prefix sensor test",
56
56
  "precheck": "node --check src/bridge-launch-agent.mjs",
57
- "check": "node --check bin/lattice.mjs && node --check bin/lattice-mcp.mjs && node --check bin/lattice-dashboard.mjs && node --check bin/lattice-bridge.mjs && node --check src/cli-stdio.mjs && node --check src/todo-gantt-layout.mjs && node --check src/todo-gantt-scope.mjs && node --check src/bridge-config.mjs && node --check src/bridge-server.mjs && node --check src/bridge-daemon.mjs && node --check src/bridge-cli.mjs && node --check src/project-cli.mjs && node --check src/sensor-cli.mjs && node --check src/sensor-runtime.mjs && node --check src/sensor-adapter.mjs && node --check src/factory-diagnostics.mjs && node --check src/runtime-errors.mjs && node --check src/runtime-contracts.mjs && node --check src/runtime-event-store.mjs && node --check src/hash-chain.mjs && node --check src/dag-chain.mjs && node --check src/todo-contracts.mjs && node --check src/todo-chain.mjs && node --check src/todo-store.mjs && node --check src/todo-migration.mjs && node --check src/todo-revision.mjs && node --check src/todo-status.mjs && node --check src/todo-cli.mjs && node --check src/todo-dashboard-registry.mjs && node --check src/todo-gantt-presentation.mjs && node --check src/todo-gantt-live.mjs && node --check src/bounded-seam.mjs && node --check src/todo-narrative-anchor.mjs && node --check src/todo-markdown-renderer.mjs && node --check src/todo-gantt-svg.mjs && node --check src/todo-gantt-html.mjs && node --check src/runtime-projection.mjs && node --check src/runtime-decision-verifier.mjs && node --check src/runtime-front-end.mjs && node --check src/runtime-cli.mjs && node --check src/rc3-dogfood-scaffold.mjs && node --check src/runtime-engine.mjs && node --check src/runtime-scripted-executor.mjs && node --check src/runtime-diff-observer.mjs && node --check src/runtime-worktree-executor.mjs && node --check src/runtime-hold-recompile.mjs && node --check src/rc3-scripted-campaign.mjs && node --check src/rc3-actual-dogfood.mjs && node --check src/rc4-stage1-dogfood.mjs && node --check research/fixtures/dispatch-record/src/dispatch-record.mjs && node --check test/research-dispatch-record.test.mjs",
57
+ "check": "node --check bin/lattice.mjs && node --check bin/lattice-mcp.mjs && node --check bin/lattice-dashboard.mjs && node --check bin/lattice-bridge.mjs && node --check src/cli-stdio.mjs && node --check src/bridge-address.mjs && node --check src/bridge-registrar.mjs && node --check src/todo-gantt-layout.mjs && node --check src/todo-gantt-scope.mjs && node --check src/bridge-config.mjs && node --check src/bridge-server.mjs && node --check src/bridge-daemon.mjs && node --check src/bridge-cli.mjs && node --check src/project-cli.mjs && node --check src/sensor-cli.mjs && node --check src/sensor-runtime.mjs && node --check src/sensor-adapter.mjs && node --check src/factory-diagnostics.mjs && node --check src/runtime-errors.mjs && node --check src/runtime-contracts.mjs && node --check src/runtime-event-store.mjs && node --check src/hash-chain.mjs && node --check src/dag-chain.mjs && node --check src/todo-contracts.mjs && node --check src/todo-chain.mjs && node --check src/todo-store.mjs && node --check src/todo-migration.mjs && node --check src/todo-revision.mjs && node --check src/todo-status.mjs && node --check src/todo-cli.mjs && node --check src/todo-dashboard-registry.mjs && node --check src/todo-gantt-presentation.mjs && node --check src/todo-gantt-live.mjs && node --check src/bounded-seam.mjs && node --check src/todo-narrative-anchor.mjs && node --check src/todo-markdown-renderer.mjs && node --check src/todo-gantt-svg.mjs && node --check src/todo-gantt-html.mjs && node --check src/runtime-projection.mjs && node --check src/runtime-decision-verifier.mjs && node --check src/runtime-front-end.mjs && node --check src/runtime-cli.mjs && node --check src/rc3-dogfood-scaffold.mjs && node --check src/runtime-engine.mjs && node --check src/runtime-scripted-executor.mjs && node --check src/runtime-diff-observer.mjs && node --check src/runtime-worktree-executor.mjs && node --check src/runtime-hold-recompile.mjs && node --check src/rc3-scripted-campaign.mjs && node --check src/rc3-actual-dogfood.mjs && node --check src/rc4-stage1-dogfood.mjs && node --check research/fixtures/dispatch-record/src/dispatch-record.mjs && node --check test/research-dispatch-record.test.mjs",
58
58
  "check:project-identity": "node --check src/project-identity.mjs",
59
59
  "ci": "npm run test && npm run test:sensor && npm run check && npm run check:project-identity"
60
60
  }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Bridge listen-address resolution.
3
+ *
4
+ * The bridge is configured with a literal IP so the operator controls exactly
5
+ * which interface it is exposed on. A DHCP lease change silently invalidates
6
+ * that choice: the address disappears from the host, the old socket lingers on
7
+ * a dead address, and nothing on the LAN can reach the bridge any more —
8
+ * while `bridge status` keeps reporting `enabled: true`.
9
+ *
10
+ * This module answers two questions without any I/O:
11
+ * 1. is the configured address still present on this host?
12
+ * 2. if not, is there an address that is obviously the same intent?
13
+ *
14
+ * "Same intent" is deliberately narrow. A DHCP lease change moves the host
15
+ * inside its own subnet, so only a non-internal address of the same family in
16
+ * the same subnet (IPv4 /24, IPv6 /64) is adopted. An address on a different
17
+ * network — a VPN, a second NIC, a public interface — is never adopted
18
+ * automatically, because that would expose the bridge somewhere the operator
19
+ * did not choose. Loopback is never adopted either: it would silently take the
20
+ * bridge off the LAN while still looking healthy.
21
+ */
22
+
23
+ import { isIP } from 'node:net';
24
+
25
+ /** Wildcards already bind every interface, so they are never "absent". */
26
+ const WILDCARDS = new Set(['0.0.0.0', '::']);
27
+
28
+ export const BRIDGE_LISTEN_STATES = Object.freeze([
29
+ 'present', 'rebindable', 'absent', 'unconfigured',
30
+ ]);
31
+
32
+ function normalize(value) {
33
+ return typeof value === 'string' ? value.trim().toLowerCase() : '';
34
+ }
35
+
36
+ /**
37
+ * Flatten `os.networkInterfaces()` into the addresses a bridge may bind.
38
+ * Internal (loopback) addresses are kept but marked, so callers can exclude
39
+ * them from adoption while still recognising an explicitly configured one.
40
+ */
41
+ export function bridgeHostAddresses(interfaces = {}) {
42
+ const result = [];
43
+ for (const entries of Object.values(interfaces ?? {})) {
44
+ for (const entry of entries ?? []) {
45
+ const address = normalize(entry?.address);
46
+ if (address === '' || isIP(address) === 0) continue;
47
+ result.push({ address, family: isIP(address), internal: entry?.internal === true });
48
+ }
49
+ }
50
+ return result.sort((left, right) => (left.address < right.address ? -1
51
+ : left.address > right.address ? 1 : 0));
52
+ }
53
+
54
+ /** IPv4 /24 or IPv6 /64 prefix, used as the "same network" test. */
55
+ function subnetKey(address) {
56
+ const family = isIP(address);
57
+ if (family === 4) return address.split('.').slice(0, 3).join('.');
58
+ if (family !== 6) return null;
59
+ // Expand the IPv6 form enough to compare the first four hextets.
60
+ const [head] = address.split('%');
61
+ const parts = head.split('::');
62
+ const left = parts[0] === '' ? [] : parts[0].split(':');
63
+ const right = parts.length > 1 ? (parts[1] === '' ? [] : parts[1].split(':')) : [];
64
+ const fill = Array.from({ length: Math.max(0, 8 - left.length - right.length) }, () => '0');
65
+ const hextets = (parts.length > 1 ? [...left, ...fill, ...right] : left)
66
+ .map((entry) => entry.replace(/^0+(?=[0-9a-f])/u, ''));
67
+ return hextets.slice(0, 4).join(':');
68
+ }
69
+
70
+ /**
71
+ * Decide which address the bridge should actually listen on.
72
+ *
73
+ * @param {object} options
74
+ * @param {string|null} options.configured configured literal address.
75
+ * @param {object} [options.interfaces] `os.networkInterfaces()` shaped object.
76
+ * @returns {{state: string, effective: string|null, configured: string|null,
77
+ * candidates: string[], reason: string|null}}
78
+ */
79
+ export function resolveBridgeListenAddress({ configured, interfaces = {} } = {}) {
80
+ const wanted = normalize(configured);
81
+ if (wanted === '' || isIP(wanted) === 0) {
82
+ return { state: 'unconfigured', effective: null, configured: null, candidates: [], reason: 'listen_address_unconfigured' };
83
+ }
84
+ if (WILDCARDS.has(wanted)) {
85
+ return { state: 'present', effective: wanted, configured: wanted, candidates: [], reason: null };
86
+ }
87
+
88
+ const addresses = bridgeHostAddresses(interfaces);
89
+ if (addresses.some((entry) => entry.address === wanted)) {
90
+ return { state: 'present', effective: wanted, configured: wanted, candidates: [], reason: null };
91
+ }
92
+
93
+ const family = isIP(wanted);
94
+ const wantedSubnet = subnetKey(wanted);
95
+ const candidates = addresses
96
+ .filter((entry) => !entry.internal && entry.family === family
97
+ && wantedSubnet !== null && subnetKey(entry.address) === wantedSubnet)
98
+ .map((entry) => entry.address);
99
+
100
+ if (candidates.length === 0) {
101
+ return { state: 'absent', effective: null, configured: wanted, candidates: [],
102
+ reason: 'configured_address_absent_from_host' };
103
+ }
104
+ // Deterministic pick; `candidates` is reported so an ambiguous host is visible.
105
+ return { state: 'rebindable', effective: candidates[0], configured: wanted, candidates,
106
+ reason: 'configured_address_absent_rebound_within_subnet' };
107
+ }
@@ -1,6 +1,9 @@
1
- import { isIP } from 'node:net';
1
+ import { createConnection, isIP } from 'node:net';
2
+ import { networkInterfaces } from 'node:os';
2
3
  import * as clack from '@clack/prompts';
3
4
 
5
+ import { resolveBridgeListenAddress } from './bridge-address.mjs';
6
+ import { registerBridgeUpstream } from './bridge-registrar.mjs';
4
7
  import {
5
8
  BridgeConfigError, configureBridge, disableBridge, readBridgeConfig, restoreBridgeConfig,
6
9
  normalizeBridgeAllowedHost, withBridgeOperationLock,
@@ -15,7 +18,52 @@ import {
15
18
  snapshotBridgeLaunchAgent,
16
19
  } from './bridge-launch-agent.mjs';
17
20
 
18
- const RESULT_SCHEMA = 'lattice.bridge_cli_result.v1';
21
+ // v2 adds the liveness fields. `enabled` only says the configuration is on;
22
+ // it never said the bridge could actually be reached, which let a DHCP lease
23
+ // change take the published surface down while status kept reporting health.
24
+ const RESULT_SCHEMA = 'lattice.bridge_cli_result.v2';
25
+ const REACHABILITY_PROBE_TIMEOUT_MS = 750;
26
+
27
+ /** TCP connect probe. Answers "is anything accepting there right now". */
28
+ export function probeBridgeListener({ address, port, timeoutMs = REACHABILITY_PROBE_TIMEOUT_MS }) {
29
+ return new Promise((resolve) => {
30
+ let settled = false;
31
+ const finish = (value) => {
32
+ if (settled) return;
33
+ settled = true;
34
+ socket.destroy();
35
+ resolve(value);
36
+ };
37
+ const socket = createConnection({ host: address, port });
38
+ socket.setTimeout(timeoutMs);
39
+ socket.once('connect', () => finish(true));
40
+ socket.once('timeout', () => finish(false));
41
+ socket.once('error', () => finish(false));
42
+ });
43
+ }
44
+
45
+ /**
46
+ * Liveness of the configured listen address: does it still exist on this host,
47
+ * did it move inside its subnet, and is anything accepting connections there.
48
+ */
49
+ async function bridgeLiveness(config, { interfaces = networkInterfaces(), probe = probeBridgeListener } = {}) {
50
+ if (config === null || config.enabled !== true) {
51
+ return { listen_state: 'unconfigured', effective_listen: null, listen_candidates: [],
52
+ reachable: null, liveness_reason: null };
53
+ }
54
+ const resolved = resolveBridgeListenAddress({ configured: config.listen.address, interfaces });
55
+ const effective = resolved.effective === null ? null
56
+ : { address: resolved.effective, port: config.listen.port };
57
+ const reachable = effective === null ? false
58
+ : await probe({ address: effective.address, port: effective.port });
59
+ return {
60
+ listen_state: resolved.state,
61
+ effective_listen: effective,
62
+ listen_candidates: resolved.candidates,
63
+ reachable,
64
+ liveness_reason: resolved.reason ?? (reachable ? null : 'listener_not_accepting'),
65
+ };
66
+ }
19
67
 
20
68
  function fail(stderr, code, message) {
21
69
  stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code, message })}\n`);
@@ -48,10 +96,15 @@ function parseOptions(words) {
48
96
  return options;
49
97
  }
50
98
 
51
- function result(action, config, recovery = null) {
99
+ function result(action, config, recovery = null, liveness = null) {
52
100
  return { schema: RESULT_SCHEMA, action, configured: config !== null, enabled: config?.enabled ?? false,
53
101
  listen: config?.listen ?? null, allowed_hosts: config?.allowed_hosts ?? null,
54
- upstream: config?.upstream ?? null, updated_at: config?.updated_at ?? null, recovery };
102
+ upstream: config?.upstream ?? null, updated_at: config?.updated_at ?? null, recovery,
103
+ listen_state: liveness?.listen_state ?? null,
104
+ effective_listen: liveness?.effective_listen ?? null,
105
+ listen_candidates: liveness?.listen_candidates ?? null,
106
+ reachable: liveness?.reachable ?? null,
107
+ liveness_reason: liveness?.liveness_reason ?? null };
55
108
  }
56
109
 
57
110
  export async function collectBridgeSetupWizard({ input, output, prompts = clack } = {}) {
@@ -104,13 +157,13 @@ export async function runBridgeCli({ argv, stdout, stderr, env = process.env,
104
157
  stop: stopBridgeDaemon, clearStop: clearBridgeStopControl },
105
158
  launchAgent = { snapshot: snapshotBridgeLaunchAgent, install: installBridgeLaunchAgent,
106
159
  disable: disableBridgeLaunchAgent, restore: restoreBridgeLaunchAgent },
107
- prompts = clack } = {}) {
160
+ prompts = clack, probe = probeBridgeListener, interfaces = networkInterfaces() } = {}) {
108
161
  if (!Array.isArray(argv)) {
109
- return fail(stderr, 'USAGE', 'usage: lattice bridge <setup|reconfigure|status|disable> [options] --json');
162
+ return fail(stderr, 'USAGE', 'usage: lattice bridge <setup|reconfigure|status|disable|register> [options] --json');
110
163
  }
111
164
  const wizard = argv.length === 1 && argv[0] === 'setup';
112
165
  if (!wizard && argv.at(-1) !== '--json') {
113
- return fail(stderr, 'USAGE', 'usage: lattice bridge <setup|reconfigure|status|disable> [options] --json');
166
+ return fail(stderr, 'USAGE', 'usage: lattice bridge <setup|reconfigure|status|disable|register> [options] --json');
114
167
  }
115
168
  if (wizard && (!stdin?.isTTY || !stdout?.isTTY)) {
116
169
  return fail(stderr, 'BRIDGE_SETUP_REQUIRES_TTY',
@@ -118,6 +171,20 @@ export async function runBridgeCli({ argv, stdout, stderr, env = process.env,
118
171
  }
119
172
  const [command, ...words] = wizard ? argv : argv.slice(0, -1);
120
173
  try {
174
+ if (command === 'register' && words.length === 0) {
175
+ const current = await readBridgeConfig({ env });
176
+ if (current === null || current.enabled !== true) {
177
+ return fail(stderr, 'BRIDGE_DISABLED', 'bridge is not enabled; nothing to register');
178
+ }
179
+ const resolved = resolveBridgeListenAddress({ configured: current.listen.address, interfaces });
180
+ if (resolved.effective === null) {
181
+ return fail(stderr, 'BRIDGE_LISTEN_ADDRESS_ABSENT',
182
+ 'configured bridge listen address is not present on this host');
183
+ }
184
+ const registration = await registerBridgeUpstream({ port: current.listen.port, env });
185
+ stdout.write(`${JSON.stringify(registration)}\n`);
186
+ return registration.state === 'failed' ? 1 : 0;
187
+ }
121
188
  let config;
122
189
  let recovery = null;
123
190
  if (command === 'status' && words.length === 0) config = await readBridgeConfig({ env });
@@ -216,8 +283,11 @@ export async function runBridgeCli({ argv, stdout, stderr, env = process.env,
216
283
  return configured;
217
284
  });
218
285
  } else return fail(stderr, 'USAGE', 'unknown bridge command or options');
286
+ // Liveness is only meaningful for a read: the mutating commands have just
287
+ // reconfigured the daemon and the socket may not have settled yet.
288
+ const liveness = command === 'status' ? await bridgeLiveness(config, { probe, interfaces }) : null;
219
289
  if (wizard) stdout.write(`Lattice bridgeを${config.listen.address}:${config.listen.port}で有効にしました。\n`);
220
- else stdout.write(`${JSON.stringify(result(command, config, recovery))}\n`);
290
+ else stdout.write(`${JSON.stringify(result(command, config, recovery, liveness))}\n`);
221
291
  return 0;
222
292
  } catch (error) {
223
293
  stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2',
@@ -9,6 +9,7 @@ import { promisify } from 'node:util';
9
9
 
10
10
  import { BridgeConfigError, readBridgeConfig } from './bridge-config.mjs';
11
11
  import { readBridgeDaemonDescriptor } from './bridge-daemon.mjs';
12
+ import { bridgeRegistrarSettings } from './bridge-registrar.mjs';
12
13
 
13
14
  export const BRIDGE_LAUNCH_AGENT_LABEL = 'dev.kitepon.lattice.bridge';
14
15
  const START_TIMEOUT_MS = 5_000;
@@ -126,6 +127,17 @@ function plistDocument({ nodePath, bridgePath, instanceToken, env }) {
126
127
  }
127
128
  environment.push(['LATTICE_CONFIG_DIR', env.LATTICE_CONFIG_DIR]);
128
129
  }
130
+ // The daemon registers its upstream on every new binding, but only if it can
131
+ // see the registrar settings. launchd does not inherit the shell environment,
132
+ // so without baking them in here the self-registration silently never fires —
133
+ // which is exactly the kind of quiet non-recovery this whole path exists to
134
+ // remove. `bridgeRegistrarSettings` rejects a half-configured pair rather than
135
+ // installing an agent that would skip registration forever.
136
+ const registrar = bridgeRegistrarSettings(env);
137
+ if (registrar !== null) {
138
+ environment.push(['LATTICE_BRIDGE_REGISTRAR_SSH_HOST', registrar.host]);
139
+ environment.push(['LATTICE_BRIDGE_REGISTRAR_SCRIPT', registrar.script]);
140
+ }
129
141
  const environmentXml = environment.map(([key, value]) =>
130
142
  ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join('\n');
131
143
  return `<?xml version="1.0" encoding="UTF-8"?>
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Bridge upstream self-registration.
3
+ *
4
+ * The public site is reverse-proxied to a literal LAN address held by another
5
+ * host. When this host's address moves — a DHCP lease change is enough — that
6
+ * literal goes stale and the site starts failing, with nothing on either side
7
+ * noticing. Registration closes that loop: after the bridge binds, it tells the
8
+ * reverse proxy where it actually is.
9
+ *
10
+ * This is an explicit connector, not a hook into someone else's tooling. It
11
+ * runs one fixed shape — `ssh <host> <script> <port>` — over the operator's
12
+ * existing ssh trust, and both operands are validated. Lattice never sends a
13
+ * command string, so the reverse proxy host decides what registration means and
14
+ * can refuse anything it does not like. The remote script is expected to derive
15
+ * the address from the ssh source rather than trusting anything sent to it.
16
+ *
17
+ * Opt-in via environment, so an unconfigured host simply never registers:
18
+ * LATTICE_BRIDGE_REGISTRAR_SSH_HOST ssh destination (an ssh_config alias)
19
+ * LATTICE_BRIDGE_REGISTRAR_SCRIPT absolute path of the remote script
20
+ */
21
+
22
+ import { execFile } from 'node:child_process';
23
+
24
+ export const REGISTRAR_RESULT_SCHEMA = 'lattice.bridge_registrar_result.v1';
25
+
26
+ const SSH_HOST = /^[A-Za-z0-9][A-Za-z0-9._-]{0,253}$/u;
27
+ const REMOTE_SCRIPT = /^\/[A-Za-z0-9._\-/]{1,255}$/u;
28
+ const DEFAULT_TIMEOUT_MS = 15_000;
29
+
30
+ export class BridgeRegistrarError extends Error {
31
+ constructor(code, message, detail = null) {
32
+ super(message);
33
+ this.name = 'BridgeRegistrarError';
34
+ this.code = code;
35
+ this.detail = detail;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Registrar settings, or null when the operator has not opted in.
41
+ * A half-configured registrar is an error rather than a silent no-op: it means
42
+ * someone intended to register and the site will quietly rot if we skip it.
43
+ */
44
+ export function bridgeRegistrarSettings(env = process.env) {
45
+ const host = env.LATTICE_BRIDGE_REGISTRAR_SSH_HOST ?? '';
46
+ const script = env.LATTICE_BRIDGE_REGISTRAR_SCRIPT ?? '';
47
+ if (host === '' && script === '') return null;
48
+ if (!SSH_HOST.test(host)) {
49
+ throw new BridgeRegistrarError('BRIDGE_REGISTRAR_INVALID',
50
+ 'LATTICE_BRIDGE_REGISTRAR_SSH_HOST must be a bare ssh destination', { host });
51
+ }
52
+ if (!REMOTE_SCRIPT.test(script)) {
53
+ throw new BridgeRegistrarError('BRIDGE_REGISTRAR_INVALID',
54
+ 'LATTICE_BRIDGE_REGISTRAR_SCRIPT must be an absolute path without spaces', { script });
55
+ }
56
+ return Object.freeze({ host, script });
57
+ }
58
+
59
+ function runSsh({ host, script, port, timeoutMs, runner }) {
60
+ const args = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', host, script, String(port)];
61
+ return new Promise((resolve) => {
62
+ runner('ssh', args, { timeout: timeoutMs, encoding: 'utf8' }, (error, stdout, stderr) => {
63
+ resolve({ error, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') });
64
+ });
65
+ });
66
+ }
67
+
68
+ /**
69
+ * Register `port` on the reverse proxy host. The address is deliberately NOT
70
+ * sent: the remote end reads it from the ssh connection, so this host can only
71
+ * ever register itself.
72
+ *
73
+ * Never throws for a remote failure — the bridge is still serving locally and
74
+ * taking it down would turn a proxy-config problem into an outage. The failure
75
+ * is returned typed so callers surface it instead of swallowing it.
76
+ */
77
+ export async function registerBridgeUpstream({
78
+ port, env = process.env, timeoutMs = DEFAULT_TIMEOUT_MS, runner = execFile,
79
+ } = {}) {
80
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {
81
+ throw new BridgeRegistrarError('BRIDGE_REGISTRAR_INVALID', 'registration port is invalid', { port });
82
+ }
83
+ const settings = bridgeRegistrarSettings(env);
84
+ if (settings === null) {
85
+ return { schema: REGISTRAR_RESULT_SCHEMA, state: 'not_configured', port,
86
+ host: null, remote: null, detail: null };
87
+ }
88
+ const { error, stdout, stderr } = await runSsh({ ...settings, port, timeoutMs, runner });
89
+ if (error) {
90
+ return { schema: REGISTRAR_RESULT_SCHEMA, state: 'failed', port, host: settings.host,
91
+ remote: null, detail: (stderr.trim() || error.message || 'ssh registration failed').slice(0, 500) };
92
+ }
93
+ let remote = null;
94
+ try { remote = JSON.parse(stdout.trim()); } catch { remote = null; }
95
+ if (remote === null) {
96
+ return { schema: REGISTRAR_RESULT_SCHEMA, state: 'failed', port, host: settings.host,
97
+ remote: null, detail: `registrar returned no parsable result: ${stdout.trim().slice(0, 200)}` };
98
+ }
99
+ return { schema: REGISTRAR_RESULT_SCHEMA,
100
+ state: remote.changed === true ? 'updated' : 'unchanged',
101
+ port, host: settings.host, remote, detail: null };
102
+ }
@@ -5,6 +5,10 @@ import { lstat, open } from 'node:fs/promises';
5
5
  import path from 'node:path';
6
6
  import { parseTree } from 'jsonc-parser';
7
7
 
8
+ import { networkInterfaces } from 'node:os';
9
+
10
+ import { resolveBridgeListenAddress } from './bridge-address.mjs';
11
+ import { registerBridgeUpstream } from './bridge-registrar.mjs';
8
12
  import {
9
13
  BridgeConfigError, bridgeConfigPaths, normalizeBridgeAllowedHost, readBridgeConfig,
10
14
  } from './bridge-config.mjs';
@@ -184,12 +188,28 @@ export async function startBridgeServer({
184
188
  config, env = process.env,
185
189
  instanceToken = null,
186
190
  resolveUpstream = (upstream) => resolveBridgeUpstream(upstream, { env }),
191
+ interfaces = networkInterfaces(),
187
192
  } = {}) {
188
193
  if (config?.enabled !== true) throw new BridgeConfigError('BRIDGE_DISABLED', 'bridge is disabled');
189
194
  if (!Array.isArray(config.allowed_hosts) || config.allowed_hosts.length === 0) {
190
195
  throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge allowed hosts are required');
191
196
  }
197
+ // A DHCP lease change moves the host inside its own subnet and strands the
198
+ // configured literal. Follow it rather than binding a dead address, but only
199
+ // within the same subnet (see bridge-address.mjs for why that bound matters).
200
+ const resolvedListen = resolveBridgeListenAddress({ configured: config.listen.address, interfaces });
201
+ if (resolvedListen.effective === null) {
202
+ throw new BridgeConfigError('BRIDGE_LISTEN_ADDRESS_ABSENT',
203
+ 'configured bridge listen address is not present on this host',
204
+ { ...config.listen, listen_state: resolvedListen.state });
205
+ }
206
+ const listenAddress = resolvedListen.effective;
192
207
  let allowedHosts = new Set(config.allowed_hosts);
208
+ // The rebound address has to answer for itself, otherwise every request to it
209
+ // is rejected by the Host allow-list the operator never knew had gone stale.
210
+ if (listenAddress !== config.listen.address) {
211
+ allowedHosts.add(normalizeBridgeAllowedHost(listenAddress));
212
+ }
193
213
  let currentConfig = config;
194
214
  const handleRequest = async (incoming, response) => {
195
215
  let requestHost;
@@ -249,17 +269,19 @@ export async function startBridgeServer({
249
269
  });
250
270
  await new Promise((resolve, reject) => {
251
271
  server.once('error', reject);
252
- server.listen({ host: config.listen.address, port: config.listen.port, exclusive: true }, resolve);
272
+ server.listen({ host: listenAddress, port: config.listen.port, exclusive: true }, resolve);
253
273
  }).catch((error) => {
254
274
  throw new BridgeConfigError(error?.code === 'EADDRINUSE' ? 'BRIDGE_PORT_UNAVAILABLE' : 'BRIDGE_BIND_FAILED',
255
- 'bridge listen failed', { ...config.listen }, error);
275
+ 'bridge listen failed', { ...config.listen, effective_address: listenAddress }, error);
256
276
  });
257
277
  const boundAddress = server.address();
258
278
  const actualPort = typeof boundAddress === 'object' && boundAddress !== null
259
279
  ? boundAddress.port : config.listen.port;
260
280
  let closed = false;
261
281
  return Object.freeze({
262
- address: config.listen.address,
282
+ address: listenAddress,
283
+ configured_address: config.listen.address,
284
+ rebound: listenAddress !== config.listen.address,
263
285
  port: actualPort,
264
286
  updateConfig(next) {
265
287
  if (next?.enabled !== true || next.listen.address !== config.listen.address
@@ -268,6 +290,9 @@ export async function startBridgeServer({
268
290
  }
269
291
  currentConfig = next;
270
292
  allowedHosts = new Set(next.allowed_hosts);
293
+ if (listenAddress !== config.listen.address) {
294
+ allowedHosts.add(normalizeBridgeAllowedHost(listenAddress));
295
+ }
271
296
  },
272
297
  close: async () => {
273
298
  if (closed) return;
@@ -279,9 +304,27 @@ export async function startBridgeServer({
279
304
  });
280
305
  }
281
306
 
282
- export function bridgeRuntimeController({ env = process.env, instanceToken = null } = {}) {
307
+ export function bridgeRuntimeController({
308
+ env = process.env, instanceToken = null,
309
+ register = registerBridgeUpstream,
310
+ report = (line) => process.stderr.write(`${line}\n`),
311
+ } = {}) {
283
312
  let active = null;
284
313
  let fingerprint = null;
314
+ // A fresh binding is exactly when the reverse proxy's literal may have gone
315
+ // stale, so that is when the bridge tells it where it now is. A registration
316
+ // failure is reported, never swallowed, and never takes the local bridge down:
317
+ // the bridge is still serving, only the published route is behind.
318
+ const announce = async (binding) => {
319
+ try {
320
+ const outcome = await register({ port: binding.port, env });
321
+ if (outcome.state !== 'not_configured') report(JSON.stringify(outcome));
322
+ } catch (error) {
323
+ report(JSON.stringify({ schema: 'lattice.bridge_registrar_result.v1', state: 'failed',
324
+ port: binding.port, host: null, remote: null,
325
+ detail: error?.message ?? 'registration failed' }));
326
+ }
327
+ };
285
328
  return Object.freeze({
286
329
  async reconcile() {
287
330
  const config = await readBridgeConfig({ env });
@@ -293,7 +336,11 @@ export function bridgeRuntimeController({ env = process.env, instanceToken = nul
293
336
  fingerprint = null;
294
337
  return null;
295
338
  }
296
- if (active !== null && active.address === config.listen.address && active.port === config.listen.port) {
339
+ // Compare against the CONFIGURED address: a rebound binding still serves
340
+ // the same configuration, and comparing the effective address would tear
341
+ // the server down and rebuild it on every reconcile.
342
+ if (active !== null && active.configured_address === config.listen.address
343
+ && active.port === config.listen.port) {
297
344
  active.updateConfig(config);
298
345
  fingerprint = next;
299
346
  return active;
@@ -303,6 +350,7 @@ export function bridgeRuntimeController({ env = process.env, instanceToken = nul
303
350
  active = replacement;
304
351
  fingerprint = next;
305
352
  await previous?.close();
353
+ await announce(active);
306
354
  return active;
307
355
  },
308
356
  async close() {
package/src/cli-help.mjs CHANGED
@@ -88,6 +88,10 @@ Commands:
88
88
  reconfigure [--listen <IP>] [--port <49152..65535|auto>] [--dashboard|--upstream <URL>] [--allow-host <host>...]
89
89
  status
90
90
  disable
91
+ register # 現在のlisten portをreverse proxy hostへ自己登録する
92
+
93
+ registerはLATTICE_BRIDGE_REGISTRAR_SSH_HOSTとLATTICE_BRIDGE_REGISTRAR_SCRIPTが
94
+ 両方設定されている時だけ動く。アドレスは送らず、remote側がssh送信元から決める。
91
95
  `,
92
96
  });
93
97
 
@@ -135,6 +139,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
135
139
  'bridge reconfigure': 'bridge reconfigure [--listen <IP>] [--port <49152..65535|auto>] [--dashboard|--upstream <URL>] [--allow-host <host>...] --json',
136
140
  'bridge status': 'bridge status --json',
137
141
  'bridge disable': 'bridge disable --json',
142
+ 'bridge register': 'bridge register --json',
138
143
  });
139
144
 
140
145
  function requestedNamespace(argv) {