@camstack/server 1.2.828 → 1.2.829

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.
Files changed (126) hide show
  1. package/CHANGELOG.md +14 -3
  2. package/dist/agent/agent-boot-mode.js +14 -1
  3. package/dist/agent/agent-http.js +12 -0
  4. package/dist/agent/agent-hub-rediscovery.js +205 -0
  5. package/dist/agent/agent-membership-watch.js +29 -1
  6. package/dist/agent/agent-pairing-store.js +47 -3
  7. package/dist/agent/hubs-found.js +1 -0
  8. package/dist/agent/main.js +64 -6
  9. package/dist/api/core/agent-pairing.router.js +9 -0
  10. package/dist/api/core/cluster-update.provider.js +98 -0
  11. package/dist/api/mesh-membership-routes.js +3 -2
  12. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  13. package/dist/api/trpc/generated-cap-routers.js +2339 -2286
  14. package/dist/api/trpc/server-provided-caps.js +1 -0
  15. package/dist/api/trpc/trpc.router.js +5 -0
  16. package/dist/auth/auth-provider-gate.js +6 -2
  17. package/dist/core/addon/device-meta-mirror.js +1 -0
  18. package/dist/core/cluster-update/cluster-update-job-store.js +106 -0
  19. package/dist/core/cluster-update/cluster-update-plan.js +147 -0
  20. package/dist/core/cluster-update/cluster-update-seams.js +13 -0
  21. package/dist/core/cluster-update/cluster-update-steps.js +293 -0
  22. package/dist/core/cluster-update/cluster-update.service.js +319 -0
  23. package/dist/main.js +3 -0
  24. package/dist/manual-boot.js +19 -0
  25. package/package.json +17 -10
  26. package/system/dist/addon-runner.js +12 -0
  27. package/system/dist/addon-runner.mjs +12 -0
  28. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  29. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  30. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  31. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  32. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  33. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  34. package/system/dist/builtins/autotrack/index.js +1 -1
  35. package/system/dist/builtins/autotrack/index.mjs +1 -1
  36. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  37. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  38. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  39. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  40. package/system/dist/builtins/camera-grid/index.js +1 -1
  41. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  42. package/system/dist/builtins/composer/composer.addon.js +4 -4
  43. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  44. package/system/dist/builtins/console-logging/index.js +1 -1
  45. package/system/dist/builtins/console-logging/index.mjs +1 -1
  46. package/system/dist/builtins/core-blocks/core-blocks.addon.js +3 -3
  47. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +3 -3
  48. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  49. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  50. package/system/dist/builtins/device-manager/device-aggregation.d.ts +25 -1
  51. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +6 -0
  52. package/system/dist/builtins/device-manager/device-manager.addon.js +354 -7
  53. package/system/dist/builtins/device-manager/device-manager.addon.mjs +354 -7
  54. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +6 -0
  55. package/system/dist/builtins/device-manager/device-meta-types.d.ts +4 -0
  56. package/system/dist/builtins/device-manager/device-row-store.d.ts +2 -1
  57. package/system/dist/builtins/device-manager/device-search.d.ts +42 -0
  58. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  59. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  60. package/system/dist/builtins/keychain/index.js +4 -4
  61. package/system/dist/builtins/keychain/index.mjs +4 -4
  62. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  63. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  64. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  65. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  66. package/system/dist/builtins/local-network/hub-mdns.d.ts +5 -1
  67. package/system/dist/builtins/local-network/local-network.addon.js +24 -13
  68. package/system/dist/builtins/local-network/local-network.addon.mjs +24 -13
  69. package/system/dist/builtins/loki-logging/index.js +1 -1
  70. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  71. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  72. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  73. package/system/dist/builtins/platform-probe/index.js +1 -1
  74. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  75. package/system/dist/builtins/record-entries/index.js +1 -1
  76. package/system/dist/builtins/record-entries/index.mjs +1 -1
  77. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  78. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  79. package/system/dist/builtins/snapshot/index.js +1 -1
  80. package/system/dist/builtins/snapshot/index.mjs +1 -1
  81. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  82. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  83. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  84. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  85. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  86. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  87. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  88. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  89. package/system/dist/builtins/system-config/system-config.addon.js +59 -20
  90. package/system/dist/builtins/system-config/system-config.addon.mjs +48 -10
  91. package/system/dist/builtins/winston-logging/index.js +1 -1
  92. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  93. package/system/dist/{capture-engine-B0yQx6hA.mjs → capture-engine-CsFrmbpC.mjs} +1 -1
  94. package/system/dist/{capture-engine-1A7HAX3x.js → capture-engine-Cvetsl63.js} +1 -1
  95. package/system/dist/{composition-sources-CyJ0d6Sc.mjs → composition-sources-Yw0KDrdI.mjs} +1 -1
  96. package/system/dist/{composition-sources-BzM19ASO.js → composition-sources-wNOckeFb.js} +1 -1
  97. package/system/dist/{constants-B_FLEjP_.mjs → constants-B7-Ccoim.mjs} +1 -1
  98. package/system/dist/{constants-DSO4ZEO3.js → constants-BqrgVNCL.js} +1 -1
  99. package/system/dist/{device-ca-CveuNCHp.mjs → device-ca-BDKMOSKW.mjs} +1 -1
  100. package/system/dist/{device-ca-DLTDsonl.js → device-ca-C9VMoted.js} +1 -1
  101. package/system/dist/{dist-CIyyHwVx.mjs → dist-Bv_ADY4Y.mjs} +385 -20
  102. package/system/dist/{dist-DhbzVygm.js → dist-KJhkakFo.js} +385 -20
  103. package/system/dist/file-host-worker.js +1 -1
  104. package/system/dist/file-host-worker.mjs +1 -1
  105. package/system/dist/{agent-https-BlLVD9hG.js → hub-identity-BS1rzEes.js} +120 -1
  106. package/system/dist/{agent-https-BSxTUzKT.mjs → hub-identity-DSLLzLph.mjs} +97 -2
  107. package/system/dist/{hub-mdns-ciao-C_ITDs0-.js → hub-mdns-ciao-BQh04Eo9.js} +18 -18
  108. package/system/dist/{hub-mdns-ciao-CQdCUsrI.mjs → hub-mdns-ciao-FVifxI5j.mjs} +2 -2
  109. package/system/dist/index.js +61 -44
  110. package/system/dist/index.mjs +22 -10
  111. package/system/dist/kernel/hub-identity.d.ts +17 -0
  112. package/system/dist/kernel/index.d.ts +2 -0
  113. package/system/dist/kernel/moleculer/mesh-mtls/mesh-membership.d.ts +7 -0
  114. package/system/dist/kernel/moleculer/mesh-mtls/pairing/agent-pairing.d.ts +11 -1
  115. package/system/dist/kernel/moleculer/mesh-mtls/pairing/hub-pairing.d.ts +5 -0
  116. package/system/dist/kernel/moleculer/mesh-mtls/pairing/index.d.ts +1 -1
  117. package/system/dist/kernel/moleculer/mesh-mtls/pairing/pairing-protocol.d.ts +2 -0
  118. package/system/dist/{legacy-integration-rows-door-D_tfRhsx.js → legacy-integration-rows-door-B3K3A9JU.js} +1 -1
  119. package/system/dist/{legacy-integration-rows-door-tX6Qktxd.mjs → legacy-integration-rows-door-Cu9uee1R.mjs} +1 -1
  120. package/system/dist/{rename-composition-block-DNhbAonr.js → rename-composition-block-31JmUak2.js} +1 -1
  121. package/system/dist/{rename-composition-block-COaMxshT.mjs → rename-composition-block-BglTrMYB.mjs} +1 -1
  122. package/system/dist/{restore-archive-BMqp_hMT.mjs → restore-archive-5UHNYi4u.mjs} +1 -1
  123. package/system/dist/{restore-archive-Dbzuv5hK.js → restore-archive-BHOc02Fh.js} +1 -1
  124. package/system/dist/{wal-maintenance-CWODOTsa.js → wal-maintenance-At5TeYwr.js} +0 -0
  125. package/system/dist/{wal-maintenance-ITsLGvFA.mjs → wal-maintenance-COJdLp-y.mjs} +0 -0
  126. package/system/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.829] - 2026-11-10
11
+
12
+ ### Changed
13
+
14
+ - An agent that rediscovers its hub on the LAN now also refuses a revoked answer or one naming another hub id, and names a rejected candidate at most once per 15 minutes
15
+ - A paired agent keeps the hub address it paired with; one that has none finds its hub on the LAN by the hub's id, or reports it is unconfigured instead of crash-looping, and a paired agent's hub address can no longer be cleared
16
+ - A paired agent saves a rediscovered hub address only after that hub answers with the CA from pairing, and an older pairing records the hub id from that answer
17
+ - Pickers can now search devices by capability, location, integration and type with live readings, through the new deviceManager.search query
18
+ - Cluster update in one job on the hub: backup, the hub, each agent (verified, an agent back without capabilities fails), then addons — clusterUpdate.startClusterUpdate / getClusterUpdateJob, resumed across the hub's own restart
19
+ - Disabling a login method from the Authentication table now gates sign-in like the other auth capabilities
20
+ - The device meta mirror carries a container's declared primary-child preference
21
+
10
22
  ## [1.2.828] - 2026-11-10
11
23
 
12
24
  ### Changed
@@ -21,6 +33,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
21
33
  - Capability method signatures now mark optional cover, fan, climate, lock and media-player methods; bindings report implemented methods
22
34
  - Device features are re-derived only from a provider whose node is online; an offline agent's cameras keep theirs
23
35
 
36
+ ### Fixed
37
+
24
38
  ## [1.2.826] - 2026-11-10
25
39
 
26
40
  ### Changed
@@ -79,7 +93,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
79
93
  - Rebuilt against updated dependencies.
80
94
  ### Changed
81
95
 
82
-
83
96
  ## [1.2.818] - 2026-11-09
84
97
 
85
98
  ### Changed
@@ -87,10 +100,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
87
100
  - Rebuilt against updated dependencies.
88
101
  ### Changed
89
102
 
90
-
91
103
  ### Removed
92
104
 
93
-
94
105
  ## [1.2.817] - 2026-11-08
95
106
 
96
107
  ### Changed
@@ -1,6 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.decideAgentBootMode = decideAgentBootMode;
4
+ exports.awaitingHubBoot = awaitingHubBoot;
4
5
  function decideAgentBootMode(input) {
5
- return input.paired ? 'full' : 'pairing-only';
6
+ if (!input.paired)
7
+ return 'pairing-only';
8
+ const hasAddress = typeof input.hubAddress === 'string' && input.hubAddress.trim().length > 0;
9
+ return hasAddress ? 'full' : 'awaiting-hub';
10
+ }
11
+ /** What the agent does about a missing hub, from the same facts as the boot mode. */
12
+ function awaitingHubBoot(input) {
13
+ const waiting = decideAgentBootMode(input) === 'awaiting-hub';
14
+ return {
15
+ rediscoverBeforeBroker: waiting,
16
+ watchUntilFound: waiting,
17
+ onReconnect: waiting ? 'relaunch' : 'reconnect',
18
+ };
6
19
  }
@@ -569,6 +569,18 @@ async function createAgentHttpServer(getBroker, config) {
569
569
  error: `Not editable here: ${refused.join(', ')}. Editable: ${EDITABLE_CONFIG_KEYS.join(', ')}`,
570
570
  });
571
571
  }
572
+ // A paired agent dials the hub it paired with: clearing its address would leave it dialling
573
+ // nobody after the next restart (#494). Leaving the hub is `forget`, not an empty field.
574
+ const clearsHubAddress = Object.prototype.hasOwnProperty.call(body, 'hubAddress') &&
575
+ (body.hubAddress === null ||
576
+ body.hubAddress === undefined ||
577
+ body.hubAddress.trim().length === 0);
578
+ if (clearsHubAddress && (0, agent_pairing_store_js_1.isAgentPaired)(config.configPath)) {
579
+ return reply.status(400).send({
580
+ success: false,
581
+ error: 'This agent is paired: it keeps the address of the hub it paired with. Set a new address, or leave the hub.',
582
+ });
583
+ }
572
584
  const patch = Object.fromEntries(Object.entries(body));
573
585
  const existing = readConfigFile(config.configPath);
574
586
  writeConfigFile(config.configPath, { ...existing, ...patch });
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.REJECTED_CANDIDATE_WARN_INTERVAL_MS = exports.HUB_REDISCOVERY_INTERVAL_MS = exports.HUB_REDISCOVERY_BROWSE_MS = exports.HUB_ADDRESS_REPAIR_HINT = void 0;
37
+ exports.createHubRediscoveryNotice = createHubRediscoveryNotice;
38
+ exports.pinnedCaAccepts = pinnedCaAccepts;
39
+ exports.rediscoverPairedHub = rediscoverPairedHub;
40
+ exports.startHubRediscoveryWatch = startHubRediscoveryWatch;
41
+ const system_1 = require("@camstack/server/system");
42
+ const agent_json_file_js_1 = require("./agent-json-file.js");
43
+ const agent_pairing_store_js_1 = require("./agent-pairing-store.js");
44
+ const hub_membership_client_js_1 = require("./hub-membership-client.js");
45
+ /** Where an operator sets the address. The agent page shows it read-only. */
46
+ exports.HUB_ADDRESS_REPAIR_HINT = "Re-pair this agent from the hub's Nodes page; the hub address on this agent is read-only";
47
+ const NO_HUB_ID_WARNING = 'Paired, but no hub address and no hub id on record: this agent cannot find its hub on its own. ' +
48
+ exports.HUB_ADDRESS_REPAIR_HINT;
49
+ /** How long one boot-time browse listens. */
50
+ exports.HUB_REDISCOVERY_BROWSE_MS = 4_000;
51
+ /** While a paired agent waits for its hub, how often it looks again. */
52
+ exports.HUB_REDISCOVERY_INTERVAL_MS = 60_000;
53
+ function createHubRediscoveryNotice() {
54
+ return { noHubIdWarned: false, rejectedWarnedAt: new Map() };
55
+ }
56
+ /** A candidate that keeps failing the pinned-CA check is named at most this often. */
57
+ exports.REJECTED_CANDIDATE_WARN_INTERVAL_MS = 15 * 60_000;
58
+ async function defaultBrowse(options) {
59
+ // Lazy: the socket library is loaded only when an agent actually lost its hub.
60
+ const { browseHubsMdns } = await Promise.resolve().then(() => __importStar(require('@camstack/develop/hub-discovery')));
61
+ return browseHubsMdns(options);
62
+ }
63
+ function hasHubAddress(config) {
64
+ const value = config['hubAddress'];
65
+ return typeof value === 'string' && value.trim().length > 0;
66
+ }
67
+ /** The dialable host of an announced hub URL, or `null`. */
68
+ function hostOf(url) {
69
+ try {
70
+ return (0, system_1.dialableHubHost)(new URL(url).hostname);
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ /**
77
+ * The pinned CA vouches for `hubUrl`, or the candidate is refused: a CA-signed `member`/`unknown`
78
+ * answer (never `revoked`) that, when it names a hub id, names the announced one. A thrown client
79
+ * is a refusal.
80
+ */
81
+ async function pinnedCaAccepts(configPath, hubUrl, announcedHubId) {
82
+ const identity = (0, agent_pairing_store_js_1.readPairedHubIdentity)(configPath);
83
+ const nodeId = (0, agent_json_file_js_1.readJsonFile)(configPath)['nodeId'];
84
+ if (identity === null || typeof nodeId !== 'string' || nodeId.length === 0)
85
+ return false;
86
+ const result = await (0, hub_membership_client_js_1.askHubMembership)({
87
+ hubUrl,
88
+ nodeId,
89
+ certPem: identity.certPem,
90
+ keyPem: identity.keyPem,
91
+ caCertPem: identity.caCertPem,
92
+ });
93
+ if (result.kind !== 'answer')
94
+ return false;
95
+ const { answer } = result;
96
+ if (answer.status === 'revoked')
97
+ return false;
98
+ return answer.hubId === undefined || answer.hubId === announcedHubId;
99
+ }
100
+ function warnNoHubId(deps) {
101
+ if (deps.notice?.noHubIdWarned === true)
102
+ return;
103
+ deps.log.warn(NO_HUB_ID_WARNING);
104
+ if (deps.notice !== undefined)
105
+ deps.notice.noHubIdWarned = true;
106
+ }
107
+ async function authenticateCandidate(deps, candidate) {
108
+ const authenticate = deps.authenticate ?? ((c) => pinnedCaAccepts(deps.configPath, c.hubUrl, c.hubId));
109
+ try {
110
+ return await authenticate(candidate);
111
+ }
112
+ catch (err) {
113
+ deps.log.warn('hub authentication failed', {
114
+ meta: { hubUrl: candidate.hubUrl, error: err instanceof Error ? err.message : String(err) },
115
+ });
116
+ return false;
117
+ }
118
+ }
119
+ /** Once per candidate address per interval when a shared notice exists; one-shot callers always warn. */
120
+ function warnRejectedCandidate(deps, hubId, hubUrl) {
121
+ const now = (deps.now ?? Date.now)();
122
+ const seen = deps.notice?.rejectedWarnedAt;
123
+ const last = seen?.get(hubUrl);
124
+ if (last !== undefined && now - last < exports.REJECTED_CANDIDATE_WARN_INTERVAL_MS)
125
+ return;
126
+ seen?.set(hubUrl, now);
127
+ deps.log.warn('an announced hub has this hub id but did not authenticate against the CA pinned at pairing', { meta: { hubId, hubUrl } });
128
+ }
129
+ async function rediscoverPairedHub(deps) {
130
+ const config = (0, agent_json_file_js_1.readJsonFile)(deps.configPath);
131
+ if (!(0, agent_pairing_store_js_1.isAgentPaired)(deps.configPath) || hasHubAddress(config))
132
+ return { kind: 'not-needed' };
133
+ const hubId = config['hubId'];
134
+ if (!(0, system_1.isAnnouncedHubId)(hubId)) {
135
+ warnNoHubId(deps);
136
+ return { kind: 'no-hub-id' };
137
+ }
138
+ if (deps.notice !== undefined)
139
+ deps.notice.noHubIdWarned = false;
140
+ const announced = await (deps.browse ?? defaultBrowse)({
141
+ timeoutMs: deps.timeoutMs ?? exports.HUB_REDISCOVERY_BROWSE_MS,
142
+ onProblem: (message) => deps.log.warn(`hub browse problem: ${message}`),
143
+ });
144
+ for (const hub of announced) {
145
+ if (hub.hubId !== hubId)
146
+ continue;
147
+ const hubAddress = hostOf(hub.url);
148
+ if (hubAddress === null)
149
+ continue;
150
+ if (!(await authenticateCandidate(deps, { hubUrl: hub.url, hubId }))) {
151
+ warnRejectedCandidate(deps, hubId, hub.url);
152
+ continue;
153
+ }
154
+ // Re-read right before writing: only the address keys change.
155
+ (0, agent_json_file_js_1.writeJsonFile0600)(deps.configPath, {
156
+ ...(0, agent_json_file_js_1.readJsonFile)(deps.configPath),
157
+ hubAddress,
158
+ hubUrl: hub.url,
159
+ });
160
+ deps.log.info('Found the paired hub on the LAN by its hub id - address saved', {
161
+ meta: { hubId, hubAddress, hubUrl: hub.url },
162
+ });
163
+ return { kind: 'found', hubAddress, hubUrl: hub.url };
164
+ }
165
+ deps.log.warn(`No hub on the LAN announces this agent's hub id ${hubId}`, {
166
+ meta: { hubId, announced: announced.length },
167
+ });
168
+ return { kind: 'not-found', announced: announced.length };
169
+ }
170
+ /**
171
+ * While a paired agent has no hub (boot mode `awaiting-hub`), look for its hub id again on a
172
+ * fixed cadence - one browse at a time - until it is found once. Returns a stop function.
173
+ */
174
+ function startHubRediscoveryWatch(deps) {
175
+ let running = false;
176
+ let done = false;
177
+ const tick = async () => {
178
+ if (running || done)
179
+ return;
180
+ running = true;
181
+ try {
182
+ const outcome = await rediscoverPairedHub(deps);
183
+ // `not-needed`: an address arrived another way (the agent page); relaunch for it as well.
184
+ if (outcome.kind === 'found' || outcome.kind === 'not-needed') {
185
+ done = true;
186
+ clearInterval(timer);
187
+ deps.onFound();
188
+ }
189
+ }
190
+ catch (err) {
191
+ deps.log.warn('hub rediscovery failed', {
192
+ meta: { error: err instanceof Error ? err.message : String(err) },
193
+ });
194
+ }
195
+ finally {
196
+ running = false;
197
+ }
198
+ };
199
+ const timer = setInterval(() => void tick(), deps.intervalMs ?? exports.HUB_REDISCOVERY_INTERVAL_MS);
200
+ timer.unref?.();
201
+ return () => {
202
+ done = true;
203
+ clearInterval(timer);
204
+ };
205
+ }
@@ -19,10 +19,20 @@ class AgentMembershipWatch {
19
19
  async tick(now) {
20
20
  if (this.asking)
21
21
  return;
22
- if (!this.deps.isPaired() || this.deps.isConnected()) {
22
+ if (!this.deps.isPaired()) {
23
23
  this.reset();
24
24
  return;
25
25
  }
26
+ if (this.deps.isConnected()) {
27
+ this.disconnectedSince = null;
28
+ this.revokedReads = 0;
29
+ if (this.deps.needsHubId?.() === true) {
30
+ await this.askBackfill(now);
31
+ return;
32
+ }
33
+ this.lastAskAt = null;
34
+ return;
35
+ }
26
36
  this.disconnectedSince ??= now;
27
37
  if (now - this.disconnectedSince < (this.deps.graceMs ?? exports.DEFAULT_MEMBERSHIP_GRACE_MS))
28
38
  return;
@@ -45,8 +55,26 @@ class AgentMembershipWatch {
45
55
  this.lastAskAt = null;
46
56
  this.revokedReads = 0;
47
57
  }
58
+ /** While connected, one CA-signed answer is enough to learn the hub id. Revocation stays on the disconnected path. */
59
+ async askBackfill(now) {
60
+ const interval = this.deps.askIntervalMs ?? exports.DEFAULT_MEMBERSHIP_ASK_INTERVAL_MS;
61
+ if (this.lastAskAt !== null && now - this.lastAskAt < interval)
62
+ return;
63
+ this.lastAskAt = now;
64
+ this.asking = true;
65
+ try {
66
+ const result = await this.deps.ask();
67
+ if (result.kind === 'answer')
68
+ this.deps.onAuthenticated?.(result.answer);
69
+ }
70
+ finally {
71
+ this.asking = false;
72
+ }
73
+ }
48
74
  async handle(result) {
49
75
  const tags = { nodeId: this.deps.nodeId };
76
+ if (result.kind === 'answer')
77
+ this.deps.onAuthenticated?.(result.answer);
50
78
  if (result.kind === 'unreachable') {
51
79
  this.revokedReads = 0;
52
80
  this.deps.log.info('could not ask the hub whether this agent is still a member - keeping the pairing', {
@@ -36,9 +36,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.isAgentPaired = isAgentPaired;
37
37
  exports.pinnedMeshCaCert = pinnedMeshCaCert;
38
38
  exports.persistPairing = persistPairing;
39
+ exports.recordHubIdIfMissing = recordHubIdIfMissing;
39
40
  exports.readPairedHubIdentity = readPairedHubIdentity;
40
41
  exports.forgetPairing = forgetPairing;
41
42
  exports.pairedLeafFingerprint = pairedLeafFingerprint;
43
+ exports.needsHubId = needsHubId;
44
+ exports.recordHubIdFromAnswer = recordHubIdFromAnswer;
42
45
  /**
43
46
  * What pairing writes to, and removes from, `agent.json` (D857). The file is
44
47
  * 0600 on every OS; this module only ever touches the keys named below. An older
@@ -55,6 +58,7 @@ const PAIRED_KEYS = [
55
58
  'meshSwap',
56
59
  'hubAddress',
57
60
  'hubUrl',
61
+ 'hubId',
58
62
  ];
59
63
  /** `agent.json` holds mesh material: the agent is paired. */
60
64
  function isAgentPaired(configPath) {
@@ -73,17 +77,41 @@ function pinnedMeshCaCert(configPath) {
73
77
  const ca = Reflect.get(meshTls, 'caCertPem');
74
78
  return typeof ca === 'string' && ca.length > 0 ? ca : null;
75
79
  }
76
- /** Persist a completed pairing: the leaf, its key, the pinned CA and the hub's host. */
80
+ /**
81
+ * Persist a completed pairing: the leaf, its key, the pinned CA, the hub's host and its announced
82
+ * id. A pairing with no hub address to dial is refused (thrown: the pairing fails, nothing is
83
+ * written) - a paired agent without one dials nobody after its next restart (#494).
84
+ */
77
85
  function persistPairing(configPath, pairing) {
78
- const { meshTlsPrevious: _previous, meshSwap: _swap, ...existing } = (0, agent_json_file_js_1.readJsonFile)(configPath);
86
+ const hubAddress = pairing.hubAddress.trim();
87
+ if (hubAddress.length === 0) {
88
+ throw new Error('the pairing carries no hub address to dial - nothing was installed');
89
+ }
90
+ const { meshTlsPrevious: _previous, meshSwap: _swap, hubId: _hubId, ...existing } = (0, agent_json_file_js_1.readJsonFile)(configPath);
79
91
  (0, agent_json_file_js_1.writeJsonFile0600)(configPath, {
80
92
  ...existing,
81
- hubAddress: pairing.hubAddress,
93
+ hubAddress,
94
+ // The hub's announced identity: how this agent finds ITS hub again over mDNS (#494).
95
+ ...(pairing.hubId !== null ? { hubId: pairing.hubId } : {}),
82
96
  // The hub's API address the hub itself gave: where a refused agent asks "am I still a member?".
83
97
  hubUrl: pairing.hubUrl,
84
98
  meshTls: pairing.meshTls,
85
99
  });
86
100
  }
101
+ /**
102
+ * Record the hub's announced id when this pairing has none. A CA-signed membership
103
+ * answer is the only caller: an id already on record is left as it is, and an
104
+ * unpaired file is not written.
105
+ */
106
+ function recordHubIdIfMissing(configPath, hubId) {
107
+ if (!(0, system_1.isAnnouncedHubId)(hubId) || !isAgentPaired(configPath))
108
+ return false;
109
+ const existing = (0, agent_json_file_js_1.readJsonFile)(configPath);
110
+ if ((0, system_1.isAnnouncedHubId)(existing['hubId']))
111
+ return false;
112
+ (0, agent_json_file_js_1.writeJsonFile0600)(configPath, { ...existing, hubId });
113
+ return true;
114
+ }
87
115
  function readPairedHubIdentity(configPath) {
88
116
  const config = (0, agent_json_file_js_1.readJsonFile)(configPath);
89
117
  const meshTls = config['meshTls'];
@@ -97,9 +125,11 @@ function readPairedHubIdentity(configPath) {
97
125
  }
98
126
  const hubUrl = config['hubUrl'];
99
127
  const hubAddress = config['hubAddress'];
128
+ const hubId = config['hubId'];
100
129
  return {
101
130
  hubUrl: typeof hubUrl === 'string' && hubUrl.length > 0 ? hubUrl : null,
102
131
  hubAddress: typeof hubAddress === 'string' && hubAddress.length > 0 ? hubAddress : null,
132
+ hubId: (0, system_1.isAnnouncedHubId)(hubId) ? hubId : null,
103
133
  certPem,
104
134
  keyPem,
105
135
  caCertPem,
@@ -133,3 +163,17 @@ function pairedLeafFingerprint(configPath) {
133
163
  return null;
134
164
  }
135
165
  }
166
+ /** Paired, but `agent.json` carries no hub id: the membership watch should ask for one. */
167
+ function needsHubId(configPath) {
168
+ return readPairedHubIdentity(configPath)?.hubId == null;
169
+ }
170
+ /**
171
+ * A CA-verified membership answer: record the hub id it carries when the pairing has none.
172
+ * Returns the id when it was recorded, otherwise `null`.
173
+ */
174
+ function recordHubIdFromAnswer(configPath, answer) {
175
+ const hubId = answer.hubId;
176
+ if (typeof hubId !== 'string')
177
+ return null;
178
+ return recordHubIdIfMissing(configPath, hubId) ? hubId : null;
179
+ }
@@ -46,6 +46,7 @@ function toFoundHub(candidate) {
46
46
  url: candidate.url,
47
47
  host: candidate.host,
48
48
  nodeId: candidate.nodeId,
49
+ ...(candidate.hubId !== undefined ? { hubId: candidate.hubId } : {}),
49
50
  version: candidate.version,
50
51
  sources: candidate.sources,
51
52
  };
@@ -63,6 +63,7 @@ const agent_node_certificates_js_1 = require("./agent-node-certificates.js");
63
63
  const agent_reconnect_js_1 = require("./agent-reconnect.js");
64
64
  const serial_queue_js_1 = require("./serial-queue.js");
65
65
  const agent_boot_mode_js_1 = require("./agent-boot-mode.js");
66
+ const agent_hub_rediscovery_js_1 = require("./agent-hub-rediscovery.js");
66
67
  const agent_status_metrics_js_1 = require("./agent-status-metrics.js");
67
68
  const agent_self_update_js_1 = require("./agent-self-update.js");
68
69
  const update_check_scheduler_js_1 = require("../core/updates/update-check-scheduler.js");
@@ -112,7 +113,28 @@ async function startAgent(configPath) {
112
113
  // record; lines reach the hub through the same LogManager the addons use.
113
114
  const heapWatchLogger = agentLogManager.createLogger().withTags({ addonId: 'heap-watch' });
114
115
  (0, agent_heap_watch_js_1.startAgentHeapWatch)(heapWatchLogger);
115
- const config = (0, agent_config_js_1.loadAgentConfig)(configPath);
116
+ // A paired agent with no hub address finds its hub by the id it recorded at pairing (#494)
117
+ // BEFORE the broker is built, so a found address is dialled by this very boot.
118
+ const bootConfig = (0, agent_config_js_1.loadAgentConfig)(configPath);
119
+ const rediscoveryLogger = agentLogManager
120
+ .createLogger()
121
+ .withTags({ addonId: 'hub-rediscovery', nodeId: bootConfig.nodeId });
122
+ // `consoleLogger` below does not exist yet: it is built with the broker. These
123
+ // lines go through the LogManager (`rediscoveryLogger`) so a paired agent with
124
+ // no hub is on the record before that.
125
+ const rediscoveryNotice = (0, agent_hub_rediscovery_js_1.createHubRediscoveryNotice)();
126
+ const beforeBroker = (0, agent_boot_mode_js_1.awaitingHubBoot)({
127
+ paired: (0, agent_pairing_store_js_1.isAgentPaired)(bootConfig.configPath),
128
+ hubAddress: bootConfig.hubAddress ?? null,
129
+ });
130
+ const rediscovered = beforeBroker.rediscoverBeforeBroker
131
+ ? await (0, agent_hub_rediscovery_js_1.rediscoverPairedHub)({
132
+ configPath: bootConfig.configPath,
133
+ log: rediscoveryLogger,
134
+ notice: rediscoveryNotice,
135
+ })
136
+ : null;
137
+ const config = rediscovered?.kind === 'found' ? (0, agent_config_js_1.loadAgentConfig)(configPath) : bootConfig;
116
138
  // Derive CAMSTACK_HUB_URL from the configured hub address so remote agents
117
139
  // no longer need a second, redundant env var set by hand (the cross-node
118
140
  // source trap). An explicit operator value ALWAYS wins — capture whether it
@@ -129,8 +151,12 @@ async function startAgent(configPath) {
129
151
  if (config.hubAddress) {
130
152
  console.log(`[Agent] Starting node "${config.nodeId}" (name="${config.name}") connecting to ${config.hubAddress}`);
131
153
  }
154
+ else if ((0, agent_pairing_store_js_1.isAgentPaired)(config.configPath)) {
155
+ rediscoveryLogger.error(`Node "${config.nodeId}" is paired but has no hub address and found none on the LAN — UNCONFIGURED. ` +
156
+ `${agent_hub_rediscovery_js_1.HUB_ADDRESS_REPAIR_HINT}; addons boot once an address is recorded`);
157
+ }
132
158
  else {
133
- console.log(`[Agent] Starting node "${config.nodeId}" (name="${config.name}") with no hub address — set one from the agent UI`);
159
+ console.log(`[Agent] Starting node "${config.nodeId}" (name="${config.name}") with no hub address — pair it from the hub`);
134
160
  }
135
161
  console.log(`[Agent] Config: ${config.configPath}`);
136
162
  console.log(`[Agent] Data dir: ${config.dataDir}`);
@@ -304,6 +330,10 @@ async function startAgent(configPath) {
304
330
  const hubAddressConfigured = typeof configNow.hubAddress === 'string' && configNow.hubAddress.length > 0;
305
331
  return hubAddressConfigured ? 'disconnected' : 'unconfigured';
306
332
  }
333
+ /** What decides the boot (agent-boot-mode.ts): paired, and the address this process dials. */
334
+ function bootModeInput() {
335
+ return { paired: (0, agent_pairing_store_js_1.isAgentPaired)(config.configPath), hubAddress: config.hubAddress };
336
+ }
307
337
  function readConfigFile(p) {
308
338
  if (!fs.existsSync(p))
309
339
  return {};
@@ -557,7 +587,7 @@ async function startAgent(configPath) {
557
587
  // An UNPAIRED agent boots no addon, so the registry has no provider: its own page
558
588
  // reads the same native reader the addon would register (see agent-status-metrics.ts).
559
589
  getMetricsProvider: (0, agent_status_metrics_js_1.resolveStatusMetrics)(() => capabilityRegistry.getSingleton('metrics-provider'), () => {
560
- if ((0, agent_boot_mode_js_1.decideAgentBootMode)({ paired: (0, agent_pairing_store_js_1.isAgentPaired)(config.configPath) }) === 'full')
590
+ if ((0, agent_boot_mode_js_1.decideAgentBootMode)(bootModeInput()) === 'full')
561
591
  return null;
562
592
  if (unpairedMetrics === null) {
563
593
  unpairedMetrics = new system_1.NativeMetricsProvider();
@@ -925,7 +955,9 @@ async function startAgent(configPath) {
925
955
  leafFingerprint: (0, agent_pairing_store_js_1.pairedLeafFingerprint)(config.configPath),
926
956
  });
927
957
  };
928
- const addonsBooted = (0, agent_boot_mode_js_1.decideAgentBootMode)({ paired: (0, agent_pairing_store_js_1.isAgentPaired)(config.configPath) }) === 'full';
958
+ const bootMode = (0, agent_boot_mode_js_1.decideAgentBootMode)(bootModeInput());
959
+ const hubBoot = (0, agent_boot_mode_js_1.awaitingHubBoot)(bootModeInput());
960
+ const addonsBooted = bootMode === 'full';
929
961
  // ── Self-update (agent-self-update.ts): keep this closure current with nobody driving it.
930
962
  // Unpaired -> npm latest, at boot; paired -> the hub's version, at the first registration ack.
931
963
  // Then on the update-check cadence (a periodic check, no retry loop). Lifecycle = respawn (D5).
@@ -1027,6 +1059,16 @@ async function startAgent(configPath) {
1027
1059
  });
1028
1060
  },
1029
1061
  onRevoked: (reason) => forgetHubNow(`the hub revoked this agent's certificate (${reason})`),
1062
+ needsHubId: () => (0, agent_pairing_store_js_1.needsHubId)(config.configPath),
1063
+ onAuthenticated: (answer) => {
1064
+ const hubId = (0, agent_pairing_store_js_1.recordHubIdFromAnswer)(config.configPath, answer);
1065
+ if (hubId === null)
1066
+ return;
1067
+ consoleLogger.info("Recorded the hub id from the hub's CA-signed membership answer", {
1068
+ tags: { nodeId: config.nodeId },
1069
+ meta: { hubId },
1070
+ });
1071
+ },
1030
1072
  log: {
1031
1073
  // The console line has no tag column: the node id rides in the text as well.
1032
1074
  warn: (message, extras) => consoleLogger.warn(`${message} [nodeId=${config.nodeId}]`, extras),
@@ -1049,7 +1091,11 @@ async function startAgent(configPath) {
1049
1091
  nodeId: config.nodeId,
1050
1092
  dataDir: config.dataDir,
1051
1093
  configPath: config.configPath,
1052
- onReconnect: reconnect,
1094
+ // A paired agent that booted with no addons relaunches so they start (D5).
1095
+ // An unpaired agent only replaces the transport: pairing relaunches on its own.
1096
+ onReconnect: hubBoot.onReconnect === 'relaunch'
1097
+ ? async () => (0, agent_update_service_js_1.scheduleAgentRestart)(consoleLogger, 'hub address set', config.dataDir)
1098
+ : reconnect,
1053
1099
  pairing,
1054
1100
  onForgetHub: () => forgetHubNow('requested on this agent'),
1055
1101
  getHubConnectionState,
@@ -1109,10 +1155,22 @@ async function startAgent(configPath) {
1109
1155
  process.on('SIGINT', () => void shutdown('SIGINT'));
1110
1156
  // An unpaired agent has no hub to read settings from (D857): serve pairing only and
1111
1157
  // relaunch after the certificate is installed (D5). See agent-boot-mode.ts.
1112
- if (!addonsBooted) {
1158
+ if (bootMode === 'pairing-only') {
1113
1159
  console.log(`[Agent] Node "${config.nodeId}" is unpaired - serving pairing only; addons boot after pairing`);
1114
1160
  return;
1115
1161
  }
1162
+ // Paired, no hub address, none found by hub id (#494): report `unconfigured` and stay up - no
1163
+ // addon dials a hub that is not there, so nothing aborts the process into a respawn loop.
1164
+ if (hubBoot.watchUntilFound) {
1165
+ consoleLogger.error(`Paired but no hub address: UNCONFIGURED - addons are not started. ${agent_hub_rediscovery_js_1.HUB_ADDRESS_REPAIR_HINT}`, { tags: { nodeId: config.nodeId } });
1166
+ (0, agent_hub_rediscovery_js_1.startHubRediscoveryWatch)({
1167
+ configPath: config.configPath,
1168
+ log: rediscoveryLogger,
1169
+ notice: rediscoveryNotice,
1170
+ onFound: () => (0, agent_update_service_js_1.scheduleAgentRestart)(consoleLogger, 'found the paired hub on the LAN', config.dataDir),
1171
+ });
1172
+ return;
1173
+ }
1116
1174
  // ── Phase 1: Load core infrastructure addons (in-process) ──
1117
1175
  // storage + settings + metrics + hub-forwarder (log destination)
1118
1176
  await bootCoreAddons(broker, config, capabilityRegistry, loadedAddons, loggerFactory);
@@ -116,6 +116,15 @@ function createAgentPairingRouter(deps) {
116
116
  hubNodeId: HUB_NODE_ID,
117
117
  hubUrl: async () => (await hubAddresses()).hubUrl,
118
118
  hubMeshAddress: async () => (await hubAddresses()).hubMeshAddress,
119
+ hubId: () => {
120
+ if (deps.hubDataDir === undefined)
121
+ return null;
122
+ const identity = (0, system_1.loadOrCreateHubId)(deps.hubDataDir);
123
+ if (identity.hubId === null) {
124
+ deps.log.warn('the pairing offer carries no hub id', { meta: { problem: identity.problem } });
125
+ }
126
+ return identity.hubId;
127
+ },
119
128
  isNodeConnected,
120
129
  recordIssued: async (nodeId, certPem) => {
121
130
  const registry = meshRegistry();