agl 43.1.0 → 43.3.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.
Files changed (259) hide show
  1. package/changelog.md +32 -0
  2. package/dist_serve/bundle.js +5950 -5530
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +31 -31
  5. package/dist_serve/bundle.js.third-party-notices.txt +31 -31
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +521 -17
  8. package/dist_ts/aglapi/interfaces.d.ts +3 -0
  9. package/dist_ts/aglapi/interfaces.js +2 -1
  10. package/dist_ts/classes.accountsactions.d.ts +3 -1
  11. package/dist_ts/classes.accountsactions.js +21 -3
  12. package/dist_ts/classes.authmodels.js +17 -4
  13. package/dist_ts/classes.authstore.js +16 -2
  14. package/dist_ts/classes.claudeharness.d.ts +16 -0
  15. package/dist_ts/classes.claudeharness.js +24 -2
  16. package/dist_ts/classes.cli.d.ts +4 -2
  17. package/dist_ts/classes.cli.js +6 -3
  18. package/dist_ts/classes.codexclientadapter.d.ts +11 -0
  19. package/dist_ts/classes.codexclientadapter.js +14 -2
  20. package/dist_ts/classes.controller.d.ts +175 -11
  21. package/dist_ts/classes.controller.js +1213 -173
  22. package/dist_ts/classes.controllerdevices.d.ts +2 -0
  23. package/dist_ts/classes.controllerdevices.js +6 -1
  24. package/dist_ts/classes.controllermanagement.d.ts +14 -4
  25. package/dist_ts/classes.controllermanagement.js +20 -2
  26. package/dist_ts/classes.gatewayclient.d.ts +115 -0
  27. package/dist_ts/classes.gatewayclient.js +336 -0
  28. package/dist_ts/classes.gatewayclientstore.d.ts +97 -0
  29. package/dist_ts/classes.gatewayclientstore.js +261 -0
  30. package/dist_ts/classes.inbox.d.ts +72 -0
  31. package/dist_ts/classes.inbox.js +231 -0
  32. package/dist_ts/classes.inferencerouter.d.ts +19 -0
  33. package/dist_ts/classes.inferencerouter.js +15 -3
  34. package/dist_ts/classes.inferenceservice.d.ts +9 -0
  35. package/dist_ts/classes.inferenceservice.js +28 -2
  36. package/dist_ts/classes.mcpclient.d.ts +4 -1
  37. package/dist_ts/classes.mcpclient.js +42 -6
  38. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -1
  39. package/dist_ts/classes.mcpcontrollerhost.js +11 -1
  40. package/dist_ts/classes.mcptools.d.ts +3 -3
  41. package/dist_ts/classes.mcptools.js +38 -8
  42. package/dist_ts/classes.mcpvalidation.d.ts +5 -0
  43. package/dist_ts/classes.mcpvalidation.js +38 -2
  44. package/dist_ts/classes.nativesessions.d.ts +17 -4
  45. package/dist_ts/classes.nativesessions.js +41 -9
  46. package/dist_ts/classes.opencodeclient.d.ts +23 -2
  47. package/dist_ts/classes.opencodeclient.js +47 -3
  48. package/dist_ts/classes.proxycontrol.d.ts +11 -0
  49. package/dist_ts/classes.proxycontrol.js +7 -1
  50. package/dist_ts/classes.proxycontrolclient.d.ts +17 -0
  51. package/dist_ts/classes.proxycontrolclient.js +35 -1
  52. package/dist_ts/classes.proxydaemon.js +8 -1
  53. package/dist_ts/classes.proxymonitor.d.ts +7 -0
  54. package/dist_ts/classes.proxymonitor.js +13 -1
  55. package/dist_ts/classes.publishedset.d.ts +38 -0
  56. package/dist_ts/classes.publishedset.js +50 -0
  57. package/dist_ts/classes.sessionfeed.d.ts +3 -3
  58. package/dist_ts/classes.sessionfeed.js +18 -26
  59. package/dist_ts/classes.systemmetricssampler.d.ts +6 -0
  60. package/dist_ts/classes.systemmetricssampler.js +15 -3
  61. package/dist_ts/classes.ticketstore.d.ts +50 -3
  62. package/dist_ts/classes.ticketstore.js +45 -8
  63. package/dist_ts/classes.trustedproxysecrets.d.ts +2 -0
  64. package/dist_ts/classes.trustedproxysecrets.js +5 -1
  65. package/dist_ts/driver/classes.directreports.d.ts +14 -4
  66. package/dist_ts/driver/classes.directreports.js +25 -6
  67. package/dist_ts/driver/classes.driverservice.d.ts +44 -3
  68. package/dist_ts/driver/classes.driverservice.js +50 -16
  69. package/dist_ts/fleet/classes.claudeworkers.d.ts +21 -5
  70. package/dist_ts/fleet/classes.claudeworkers.js +142 -46
  71. package/dist_ts/fleet/classes.codexworkers.d.ts +16 -4
  72. package/dist_ts/fleet/classes.codexworkers.js +22 -5
  73. package/dist_ts/fleet/classes.workercommand.d.ts +6 -1
  74. package/dist_ts/fleet/classes.workercommand.js +15 -4
  75. package/dist_ts/fleet/classes.workers.d.ts +5 -1
  76. package/dist_ts/fleet/classes.workers.js +8 -2
  77. package/dist_ts/fleet/functions.unbounddrivers.js +2 -2
  78. package/dist_ts/fleet/functions.workervalidation.js +2 -2
  79. package/dist_ts/fleet/interfaces.workers.d.ts +21 -3
  80. package/dist_ts/fleet/interfaces.workers.js +1 -1
  81. package/dist_ts/functions.agentmessage.d.ts +3 -0
  82. package/dist_ts/functions.agentmessage.js +4 -1
  83. package/dist_ts/functions.controllermanagementsurface.d.ts +4 -0
  84. package/dist_ts/functions.controllermanagementsurface.js +15 -1
  85. package/dist_ts/functions.deviceapi.d.ts +151 -4
  86. package/dist_ts/functions.deviceapi.js +893 -38
  87. package/dist_ts/functions.fleetworkercli.d.ts +1 -1
  88. package/dist_ts/functions.fleetworkercli.js +11 -8
  89. package/dist_ts/functions.gatewaycli.d.ts +24 -0
  90. package/dist_ts/functions.gatewaycli.js +395 -0
  91. package/dist_ts/functions.gatewayroute.d.ts +135 -0
  92. package/dist_ts/functions.gatewayroute.js +366 -0
  93. package/dist_ts/functions.inferencecli.js +32 -1
  94. package/dist_ts/functions.inferencecliarguments.d.ts +8 -2
  95. package/dist_ts/functions.inferencecliarguments.js +31 -3
  96. package/dist_ts/functions.mcpfleetworkertools.js +2 -2
  97. package/dist_ts/functions.proxycapacity.d.ts +50 -0
  98. package/dist_ts/functions.proxycapacity.js +142 -0
  99. package/dist_ts/functions.proxycapacitycli.d.ts +30 -0
  100. package/dist_ts/functions.proxycapacitycli.js +65 -0
  101. package/dist_ts/functions.remotecli.d.ts +30 -3
  102. package/dist_ts/functions.remotecli.js +44 -18
  103. package/dist_ts/functions.ticketvalidation.js +11 -2
  104. package/dist_ts/interfaces.auth.d.ts +25 -4
  105. package/dist_ts/interfaces.auth.js +15 -1
  106. package/dist_ts/plugins.d.ts +5 -1
  107. package/dist_ts/plugins.js +10 -2
  108. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  109. package/dist_ts_authswitch/authority-contract.js +1 -1
  110. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  111. package/dist_ts_authswitch/authority-overview.js +17 -6
  112. package/dist_ts_authswitch/authority-placement.d.ts +20 -16
  113. package/dist_ts_authswitch/authority-placement.js +19 -26
  114. package/dist_ts_authswitch/authority-renewal.d.ts +34 -0
  115. package/dist_ts_authswitch/authority-renewal.js +56 -0
  116. package/dist_ts_authswitch/authority-usagelimit.d.ts +29 -0
  117. package/dist_ts_authswitch/authority-usagelimit.js +66 -2
  118. package/dist_ts_authswitch/authority-usagewindows.d.ts +6 -0
  119. package/dist_ts_authswitch/authority-usagewindows.js +15 -1
  120. package/dist_ts_authswitch/classes.authoritybroker.d.ts +8 -0
  121. package/dist_ts_authswitch/classes.authoritybroker.js +35 -2
  122. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  123. package/dist_ts_authswitch/classes.authoritycli.js +44 -3
  124. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  125. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  126. package/dist_ts_authswitch/classes.authoritydaemon.js +8 -1
  127. package/dist_ts_authswitch/classes.authoritydatabase.js +6 -2
  128. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  129. package/dist_ts_authswitch/classes.authoritymodels.js +21 -5
  130. package/dist_ts_interfaces/devices.d.ts +1012 -5
  131. package/dist_ts_interfaces/devices.js +68 -2
  132. package/dist_ts_interfaces/fleetworkers.d.ts +5 -3
  133. package/dist_ts_interfaces/gateway.d.ts +151 -0
  134. package/dist_ts_interfaces/gateway.js +66 -0
  135. package/dist_ts_interfaces/inbox.d.ts +234 -0
  136. package/dist_ts_interfaces/inbox.js +101 -0
  137. package/dist_ts_interfaces/index.d.ts +3 -0
  138. package/dist_ts_interfaces/index.js +4 -1
  139. package/dist_ts_interfaces/interfaces.d.ts +10 -3
  140. package/dist_ts_interfaces/interfaces.js +4 -2
  141. package/dist_ts_interfaces/management.d.ts +4 -4
  142. package/dist_ts_interfaces/management.js +3 -2
  143. package/dist_ts_interfaces/mcprequests.d.ts +48 -6
  144. package/dist_ts_interfaces/mcprequests.js +12 -1
  145. package/dist_ts_interfaces/mcpworkspacerequests.d.ts +4 -1
  146. package/dist_ts_interfaces/mcpworkspacerequests.js +1 -1
  147. package/dist_ts_interfaces/nativesessions.d.ts +16 -3
  148. package/dist_ts_interfaces/plugins.d.ts +2 -1
  149. package/dist_ts_interfaces/plugins.js +4 -2
  150. package/dist_ts_interfaces/proxycapacity.d.ts +99 -0
  151. package/dist_ts_interfaces/proxycapacity.js +74 -0
  152. package/dist_ts_interfaces/requests.accounts.d.ts +21 -0
  153. package/dist_ts_interfaces/requests.accounts.js +3 -1
  154. package/dist_ts_interfaces/requests.d.ts +3 -2
  155. package/dist_ts_interfaces/requests.js +1 -1
  156. package/docs/authswitch.md +20 -1
  157. package/package.json +6 -5
  158. package/readme.md +191 -31
  159. package/ts/00_commitinfo_data.ts +1 -1
  160. package/ts/aglapi/aglapisurface.document.ts +520 -16
  161. package/ts/aglapi/interfaces.ts +1 -0
  162. package/ts/classes.accountsactions.ts +30 -3
  163. package/ts/classes.authmodels.ts +22 -3
  164. package/ts/classes.authstore.ts +15 -1
  165. package/ts/classes.claudeharness.ts +27 -1
  166. package/ts/classes.cli.ts +7 -3
  167. package/ts/classes.codexclientadapter.ts +14 -1
  168. package/ts/classes.controller.ts +1428 -249
  169. package/ts/classes.controllerdevices.ts +6 -0
  170. package/ts/classes.controllermanagement.ts +40 -7
  171. package/ts/classes.gatewayclient.ts +401 -0
  172. package/ts/classes.gatewayclientstore.ts +272 -0
  173. package/ts/classes.inbox.ts +239 -0
  174. package/ts/classes.inferencerouter.ts +27 -2
  175. package/ts/classes.inferenceservice.ts +28 -1
  176. package/ts/classes.mcpclient.ts +42 -3
  177. package/ts/classes.mcpcontrollerhost.ts +15 -0
  178. package/ts/classes.mcptools.ts +42 -9
  179. package/ts/classes.mcpvalidation.ts +32 -1
  180. package/ts/classes.nativesessions.ts +50 -12
  181. package/ts/classes.opencodeclient.ts +55 -4
  182. package/ts/classes.proxycontrol.ts +16 -0
  183. package/ts/classes.proxycontrolclient.ts +30 -0
  184. package/ts/classes.proxydaemon.ts +8 -0
  185. package/ts/classes.proxymonitor.ts +12 -0
  186. package/ts/classes.publishedset.ts +56 -0
  187. package/ts/classes.sessionfeed.ts +17 -20
  188. package/ts/classes.systemmetricssampler.ts +13 -2
  189. package/ts/classes.ticketstore.ts +73 -12
  190. package/ts/classes.trustedproxysecrets.ts +5 -0
  191. package/ts/driver/classes.directreports.ts +25 -6
  192. package/ts/driver/classes.driverservice.ts +75 -14
  193. package/ts/fleet/classes.claudeworkers.ts +112 -39
  194. package/ts/fleet/classes.codexworkers.ts +21 -6
  195. package/ts/fleet/classes.workercommand.ts +14 -4
  196. package/ts/fleet/classes.workers.ts +9 -2
  197. package/ts/fleet/functions.unbounddrivers.ts +1 -1
  198. package/ts/fleet/functions.workervalidation.ts +1 -1
  199. package/ts/fleet/interfaces.workers.ts +20 -5
  200. package/ts/functions.agentmessage.ts +3 -0
  201. package/ts/functions.controllermanagementsurface.ts +15 -0
  202. package/ts/functions.deviceapi.ts +1071 -34
  203. package/ts/functions.fleetworkercli.ts +10 -7
  204. package/ts/functions.gatewaycli.ts +436 -0
  205. package/ts/functions.gatewayroute.ts +429 -0
  206. package/ts/functions.inferencecli.ts +26 -0
  207. package/ts/functions.inferencecliarguments.ts +30 -4
  208. package/ts/functions.mcpfleetworkertools.ts +1 -1
  209. package/ts/functions.proxycapacity.ts +191 -0
  210. package/ts/functions.proxycapacitycli.ts +104 -0
  211. package/ts/functions.remotecli.ts +56 -20
  212. package/ts/functions.ticketvalidation.ts +11 -1
  213. package/ts/interfaces.auth.ts +36 -4
  214. package/ts/plugins.ts +12 -0
  215. package/ts_authswitch/authority-contract.ts +20 -0
  216. package/ts_authswitch/authority-overview.ts +28 -6
  217. package/ts_authswitch/authority-placement.ts +27 -32
  218. package/ts_authswitch/authority-renewal.ts +64 -0
  219. package/ts_authswitch/authority-usagelimit.ts +84 -1
  220. package/ts_authswitch/authority-usagewindows.ts +13 -0
  221. package/ts_authswitch/classes.authoritybroker.ts +34 -1
  222. package/ts_authswitch/classes.authoritycli.ts +49 -2
  223. package/ts_authswitch/classes.authorityclient.ts +14 -4
  224. package/ts_authswitch/classes.authoritydaemon.ts +9 -1
  225. package/ts_authswitch/classes.authoritydatabase.ts +5 -1
  226. package/ts_authswitch/classes.authoritymodels.ts +23 -3
  227. package/ts_authswitch/native-contracts.md +21 -0
  228. package/ts_authswitch/readme.md +1 -1
  229. package/ts_interfaces/devices.schema.json +3573 -603
  230. package/ts_interfaces/devices.ts +1093 -4
  231. package/ts_interfaces/fleetworkers.ts +5 -3
  232. package/ts_interfaces/gateway.ts +242 -0
  233. package/ts_interfaces/inbox.ts +287 -0
  234. package/ts_interfaces/index.ts +3 -0
  235. package/ts_interfaces/interfaces.ts +9 -2
  236. package/ts_interfaces/management.ts +6 -4
  237. package/ts_interfaces/mcprequests.ts +61 -4
  238. package/ts_interfaces/mcpworkspacerequests.ts +4 -2
  239. package/ts_interfaces/nativesessions.ts +17 -3
  240. package/ts_interfaces/plugins.ts +3 -1
  241. package/ts_interfaces/proxycapacity.ts +162 -0
  242. package/ts_interfaces/requests.accounts.ts +20 -0
  243. package/ts_interfaces/requests.ts +4 -0
  244. package/ts_web/00_commitinfo_data.ts +1 -1
  245. package/ts_web/accounts.plugins.ts +4 -2
  246. package/ts_web/classes.accountsreadmodel.ts +33 -0
  247. package/ts_web/classes.browserpresentation.ts +19 -6
  248. package/ts_web/classes.inboxfeed.ts +329 -0
  249. package/ts_web/classes.nativesessionstate.ts +9 -23
  250. package/ts_web/elements.accounts.ts +121 -113
  251. package/ts_web/elements.configurationpane.ts +24 -37
  252. package/ts_web/elements.deployments.ts +66 -2
  253. package/ts_web/elements.devices.ts +4 -17
  254. package/ts_web/elements.flexlimitstrip.ts +21 -70
  255. package/ts_web/elements.harnesscontrollerapp.ts +198 -222
  256. package/ts_web/elements.inbox.ts +808 -0
  257. package/ts_web/functions.inbox.ts +95 -0
  258. package/ts_web/functions.sessioncards.ts +40 -0
  259. package/ts_web/plugins.ts +2 -0
@@ -200,6 +200,12 @@ export class ControllerDevices {
200
200
  .map((recordArg) => this.view(recordArg));
201
201
  }
202
202
 
203
+ /** One paired device, while it is paired. */
204
+ public get(deviceIdArg: string): IControllerDevice | undefined {
205
+ const record = this.records.get(deviceIdArg);
206
+ return record === undefined ? undefined : this.view(record);
207
+ }
208
+
203
209
  private view(recordArg: IControllerDeviceDocument): IControllerDevice {
204
210
  return {
205
211
  id: recordArg.id,
@@ -6,8 +6,13 @@ import {
6
6
  controllerPackageName,
7
7
  controllerProtocolVersion,
8
8
  controllerServiceUnitName,
9
+ readControllerGatewayStatus,
10
+ type IConfigurationLocalCliActor,
11
+ type IControllerGatewayStatus,
12
+ type IControllerManagementStatus,
9
13
  type IControllerStatus,
10
- type IReq_ControllerStatus,
14
+ type IReq_ControllerGatewaySync,
15
+ type IReq_ControllerManagementStatus,
11
16
  type IReq_ControllerUpgradeLaunch,
12
17
  type IReq_ControllerUpgradePrepareBegin,
13
18
  type IReq_ControllerUpgradeFinalize,
@@ -238,7 +243,7 @@ export const assertControllerStatus = (
238
243
  statusArg: unknown,
239
244
  expectationArg: IControllerStatusExpectation,
240
245
  knownProtocolVersionArg: number = controllerProtocolVersion,
241
- ): IControllerStatus => {
246
+ ): IControllerManagementStatus => {
242
247
  if (typeof statusArg !== 'object' || statusArg === null) {
243
248
  throw new Error(`The service on the management port is not an ${currentRuntimeName} endpoint.`);
244
249
  }
@@ -276,10 +281,13 @@ export const assertControllerStatus = (
276
281
  throw new Error('The service on the management port has an incompatible controller identity.');
277
282
  }
278
283
  // A section a newer controller reports in a form this release cannot read is left out.
279
- const readableStatus: Partial<IControllerStatus> = { ...status, harnesses };
284
+ const readableStatus: Partial<IControllerManagementStatus> = { ...status, harnesses };
280
285
  if (!isControllerUpgradeStatus(status.upgrade, exactShape)) delete readableStatus.upgrade;
281
286
  if (!isControllerProxyStatus(status.proxy, exactShape)) delete readableStatus.proxy;
282
- return readableStatus as IControllerStatus;
287
+ // The gateway section only the management endpoint reports (AGL-828); a controller before it reports none.
288
+ const gateway = (statusArg as Partial<IControllerManagementStatus>).gateway;
289
+ if (gateway === undefined || !readControllerGatewayStatus(gateway)) delete readableStatus.gateway;
290
+ return readableStatus as IControllerManagementStatus;
283
291
  };
284
292
 
285
293
  /** A management request the controller answered with an error, or whose answer this build cannot read. */
@@ -532,9 +540,9 @@ export const queryControllerStatus = async (
532
540
  portArg: number,
533
541
  queryArg: IControllerStatusQuery,
534
542
  timeoutMsArg = 2_500,
535
- ): Promise<IControllerStatus> => {
543
+ ): Promise<IControllerManagementStatus> => {
536
544
  const status = assertControllerStatus(
537
- await requestManagedController<IReq_ControllerStatus>(
545
+ await requestManagedController<IReq_ControllerManagementStatus>(
538
546
  portArg,
539
547
  queryArg,
540
548
  'controller.status',
@@ -561,7 +569,7 @@ export const isUnmanagedControllerError = (errorArg: unknown): errorArg is Contr
561
569
  export const tryQueryControllerStatus = async (
562
570
  portArg: number,
563
571
  queryArg: IControllerStatusQuery,
564
- ): Promise<IControllerStatus | undefined> => {
572
+ ): Promise<IControllerManagementStatus | undefined> => {
565
573
  try {
566
574
  return await queryControllerStatus(portArg, queryArg);
567
575
  } catch (errorArg) {
@@ -570,6 +578,31 @@ export const tryQueryControllerStatus = async (
570
578
  }
571
579
  };
572
580
 
581
+ /**
582
+ * Syncs the gateway route of the controller `controllerArg` names now, rotating its trusted-proxy secret first when
583
+ * `rotateArg` is set (`agl remote gateway sync`). `localCliArg` is this process: the controller proves that it holds
584
+ * the request's loopback connection and runs as the controller's user before it acts, and audits it as the actor.
585
+ * The sync talks to the gateway, so it may take as long as the gateway's DNS reconciliation.
586
+ */
587
+ export const requestControllerGatewaySync = async (
588
+ portArg: number,
589
+ controllerArg: IControllerManagementTarget,
590
+ optionsArg: { rotate: boolean; localCli: IConfigurationLocalCliActor },
591
+ timeoutMsArg = 180_000,
592
+ ): Promise<IControllerGatewayStatus> => {
593
+ const response = await requestManagedController<IReq_ControllerGatewaySync>(
594
+ portArg,
595
+ controllerArg,
596
+ 'controller.gateway.sync',
597
+ { rotate: optionsArg.rotate, localCli: optionsArg.localCli },
598
+ { timeoutMs: timeoutMsArg },
599
+ );
600
+ const gateway = isPlainRecord(response) && Object.keys(response).length === 1
601
+ ? readControllerGatewayStatus(response.gateway) : undefined;
602
+ if (!gateway) throw new Error('The controller returned an invalid gateway sync response.');
603
+ return gateway;
604
+ };
605
+
573
606
  export const isLoopbackPortListening = async (
574
607
  portArg: number,
575
608
  timeoutMsArg = 500,
@@ -0,0 +1,401 @@
1
+ import * as plugins from './plugins.js';
2
+ import {
3
+ ControllerGatewayClientStore,
4
+ controllerGatewayEnrolment,
5
+ type IControllerGatewayClientDocument,
6
+ type IControllerGatewaySyncRecord,
7
+ } from './classes.gatewayclientstore.js';
8
+ import type { ControllerTrustedProxySecrets } from './classes.trustedproxysecrets.js';
9
+ import {
10
+ deleteGatewayRoutes,
11
+ gatewayContextProblem,
12
+ gatewayProblemOf,
13
+ gatewayRouteHeaderRefusal,
14
+ gatewayRouteReadBack,
15
+ gatewayRouteSyncOutcome,
16
+ gatewayRouteSyncRequest,
17
+ GatewayClientTransport,
18
+ GatewaySyncProblemError,
19
+ type IGatewayRouteSpec,
20
+ } from './functions.gatewayroute.js';
21
+ import type { IControllerRuntimeConfig } from './interfaces.config.js';
22
+ import {
23
+ controllerGatewayProblemKind,
24
+ type IControllerGatewayDns,
25
+ type IControllerGatewayProblem,
26
+ type IControllerGatewayStatus,
27
+ type TControllerGatewayState,
28
+ } from '../ts_interfaces/index.js';
29
+
30
+ type IReq_GetGatewayClientContext = plugins.servezoneInterfaces.requests.gateway.IReq_GetGatewayClientContext;
31
+ type IReq_GetGatewayClientRoutes = plugins.servezoneInterfaces.requests.gateway.IReq_GetGatewayClientRoutes;
32
+ type IReq_SyncGatewayClientRoute = plugins.servezoneInterfaces.requests.gateway.IReq_SyncGatewayClientRoute;
33
+
34
+ /** The timers a scheduler runs on: Node's own, or a test's clock. */
35
+ export interface IGatewaySyncClock {
36
+ now(): number;
37
+ setTimeout(callbackArg: () => void, delayMsArg: number): unknown;
38
+ clearTimeout(handleArg: unknown): void;
39
+ }
40
+
41
+ const nodeClock: IGatewaySyncClock = {
42
+ now: () => Date.now(),
43
+ setTimeout: (callbackArg, delayMsArg) => setTimeout(callbackArg, delayMsArg),
44
+ clearTimeout: (handleArg) => clearTimeout(handleArg as NodeJS.Timeout),
45
+ };
46
+
47
+ /**
48
+ * When the gateway route is synced again (Linus, AGL-828): a failure a later sync can fix is retried with jittered
49
+ * exponential backoff from 30 s up to 15 min, reset by a sync that writes the route; a written route is synced again
50
+ * after six hours to repair drift; a gateway without request headers is asked again with the same backoff once, up to
51
+ * 15 min, and then at every six-hour sync; a terminal failure waits for the operator.
52
+ */
53
+ export const gatewaySyncTimings = Object.freeze({
54
+ retryInitialMs: 30_000,
55
+ retryMaximumMs: 15 * 60_000,
56
+ /** ±20 % around the nominal delay, within the maximum. */
57
+ retryJitter: 0.2,
58
+ resyncMs: 6 * 60 * 60_000,
59
+ });
60
+
61
+ /** The delay before retry `attemptArg` (1 for the first) after a transient failure. */
62
+ export const gatewayRetryDelayMs = (attemptArg: number, randomArg: () => number): number => {
63
+ const { retryInitialMs, retryMaximumMs, retryJitter } = gatewaySyncTimings;
64
+ const nominal = Math.min(retryInitialMs * 2 ** Math.min(Math.max(attemptArg, 1) - 1, 30), retryMaximumMs);
65
+ const factor = 1 - retryJitter + 2 * retryJitter * Math.min(Math.max(randomArg(), 0), 1);
66
+ return Math.min(Math.round(nominal * factor), retryMaximumMs);
67
+ };
68
+
69
+ /** How a sync ended, for the scheduler: what it decides the next sync by. */
70
+ export type TGatewaySyncPassResult = 'synced' | 'transient' | 'waiting' | 'terminal' | 'idle';
71
+
72
+ /** The waits of a backoff from 30 s until one reaches 15 min: after them, a waiting state is asked every six hours. */
73
+ export const gatewayWaitingRetries = Math.ceil(Math.log2(gatewaySyncTimings.retryMaximumMs / gatewaySyncTimings.retryInitialMs)) + 1;
74
+
75
+ export interface IGatewaySyncSchedulerOptions {
76
+ pass: () => Promise<TGatewaySyncPassResult>;
77
+ clock?: IGatewaySyncClock;
78
+ random?: () => number;
79
+ }
80
+
81
+ /**
82
+ * Runs one sync at a time: first at `start`, then as the last one's result decides (`gatewaySyncTimings`), and on
83
+ * demand (`syncNow`), which replaces the sync that was scheduled. `close` clears the timer and waits for a running
84
+ * sync; nothing runs after it.
85
+ */
86
+ export class GatewaySyncScheduler {
87
+ private readonly clock: IGatewaySyncClock;
88
+ private readonly random: () => number;
89
+ private chain: Promise<void> = Promise.resolve();
90
+ private timer: unknown;
91
+ private timerDueAt: number | undefined;
92
+ private attempts = 0;
93
+ private waitingAttempts = 0;
94
+ private closed = false;
95
+
96
+ constructor(private readonly options: IGatewaySyncSchedulerOptions) {
97
+ this.clock = options.clock ?? nodeClock;
98
+ this.random = options.random ?? Math.random;
99
+ }
100
+
101
+ /** Schedules the first sync at once; it runs after the caller's turn, never inside it. */
102
+ public start(): void {
103
+ this.schedule(0);
104
+ }
105
+
106
+ /** Runs a sync now, after one that is running, and resolves once it ended. */
107
+ public syncNow(): Promise<void> {
108
+ if (this.closed) return Promise.reject(new Error('The gateway client is stopped.'));
109
+ this.cancelTimer();
110
+ return this.enqueue();
111
+ }
112
+
113
+ /** When the next sync runs on its own; `undefined` while none is scheduled. */
114
+ public nextSyncAt(): number | undefined {
115
+ return this.timerDueAt;
116
+ }
117
+
118
+ /** Whether a timer is armed; false after `close`. */
119
+ public hasTimer(): boolean {
120
+ return this.timer !== undefined;
121
+ }
122
+
123
+ public async close(): Promise<void> {
124
+ this.closed = true;
125
+ this.cancelTimer();
126
+ await this.chain;
127
+ }
128
+
129
+ private schedule(delayMsArg: number): void {
130
+ this.cancelTimer();
131
+ if (this.closed) return;
132
+ this.timerDueAt = this.clock.now() + delayMsArg;
133
+ this.timer = this.clock.setTimeout(() => {
134
+ this.timer = undefined;
135
+ this.timerDueAt = undefined;
136
+ void this.enqueue();
137
+ }, delayMsArg);
138
+ }
139
+
140
+ private cancelTimer(): void {
141
+ if (this.timer !== undefined) this.clock.clearTimeout(this.timer);
142
+ this.timer = undefined;
143
+ this.timerDueAt = undefined;
144
+ }
145
+
146
+ private enqueue(): Promise<void> {
147
+ const run = this.chain.then(() => this.runOnce());
148
+ this.chain = run.catch(() => undefined);
149
+ return run;
150
+ }
151
+
152
+ private async runOnce(): Promise<void> {
153
+ if (this.closed) return;
154
+ // A sync now replaces the one that was scheduled.
155
+ this.cancelTimer();
156
+ let result: TGatewaySyncPassResult;
157
+ try {
158
+ result = await this.options.pass();
159
+ } catch {
160
+ result = 'transient';
161
+ }
162
+ if (this.closed) return;
163
+ if (result !== 'transient') this.attempts = 0;
164
+ if (result !== 'waiting') this.waitingAttempts = 0;
165
+ if (result === 'synced') {
166
+ this.schedule(gatewaySyncTimings.resyncMs);
167
+ } else if (result === 'transient') {
168
+ this.attempts += 1;
169
+ this.schedule(gatewayRetryDelayMs(this.attempts, this.random));
170
+ } else if (result === 'waiting') {
171
+ this.waitingAttempts += 1;
172
+ this.schedule(this.waitingAttempts <= gatewayWaitingRetries
173
+ ? gatewayRetryDelayMs(this.waitingAttempts, this.random) : gatewaySyncTimings.resyncMs);
174
+ }
175
+ }
176
+ }
177
+
178
+ export interface IControllerGatewayClientOptions {
179
+ store: ControllerGatewayClientStore;
180
+ /** The controller's runtime configuration: its origin, port and TLS mode. */
181
+ runtimeConfig: () => IControllerRuntimeConfig;
182
+ /** The trusted-proxy secret the route carries; absent in local mode. */
183
+ secrets: () => ControllerTrustedProxySecrets | undefined;
184
+ clock?: IGatewaySyncClock;
185
+ random?: () => number;
186
+ /** Per gateway request. */
187
+ requestTimeoutMs?: number;
188
+ /** Where a change of the client's state is reported; the controller's log by default. */
189
+ log?: (textArg: string) => void;
190
+ }
191
+
192
+ /**
193
+ * The controller's gateway client (AGL-828): with the credential `agl remote gateway enrol` stored, it keeps the
194
+ * controller's route on its gateway, in the background, after the listener is up; the controller's start never waits
195
+ * for the gateway. A sync checks the credential, deletes the client's routes the controller no longer serves (an
196
+ * earlier hostname), and writes the route with the trusted-proxy secret, then confirms a rotation the route carries.
197
+ */
198
+ export class ControllerGatewayClient {
199
+ private readonly scheduler: GatewaySyncScheduler;
200
+ private readonly abortController = new AbortController();
201
+ private readonly log: (textArg: string) => void;
202
+ private state: TControllerGatewayState = 'not_enrolled';
203
+ private record: IControllerGatewayClientDocument | undefined;
204
+ private lastSync: IControllerGatewaySyncRecord = {};
205
+ private loggedProblem: string | undefined;
206
+
207
+ constructor(private readonly options: IControllerGatewayClientOptions) {
208
+ this.log = options.log ?? ((textArg) => { console.log(textArg); });
209
+ this.scheduler = new GatewaySyncScheduler({
210
+ pass: () => this.pass(),
211
+ ...(options.clock ? { clock: options.clock } : {}),
212
+ ...(options.random ? { random: options.random } : {}),
213
+ });
214
+ }
215
+
216
+ /** Reads the enrolment, for the status to report before the first sync. */
217
+ public async load(): Promise<void> {
218
+ this.adopt(await this.options.store.read());
219
+ }
220
+
221
+ /** Schedules the first sync; it runs in the background. */
222
+ public start(): void {
223
+ if (this.record?.active && !this.record.candidate) this.state = 'syncing';
224
+ this.scheduler.start();
225
+ }
226
+
227
+ public status(): IControllerGatewayStatus {
228
+ const record = this.record;
229
+ const credential = record?.active ?? record?.candidate;
230
+ const nextSyncAt = this.scheduler.nextSyncAt();
231
+ const secrets = this.options.secrets();
232
+ return {
233
+ state: this.state,
234
+ ...(credential ? { enrolment: controllerGatewayEnrolment(credential, this.options.runtimeConfig().controllerPort) } : {}),
235
+ ...(this.lastSync.syncedAt === undefined ? {} : { lastSyncedAt: this.lastSync.syncedAt }),
236
+ ...(this.lastSync.dns ? { dns: { ...this.lastSync.dns } } : {}),
237
+ ...(this.lastSync.sourceProfileVerified === undefined ? {} : { sourceProfileVerified: this.lastSync.sourceProfileVerified }),
238
+ ...(this.lastSync.problem ? { problem: { ...this.lastSync.problem } } : {}),
239
+ ...(nextSyncAt === undefined ? {} : { nextSyncAt }),
240
+ ...(secrets?.rotating() ? { rotationPending: true } : {}),
241
+ };
242
+ }
243
+
244
+ /**
245
+ * Syncs now (`agl remote gateway sync`), after rotating the trusted-proxy secret when `rotate` is set: the route
246
+ * then carries the new secret, and the previous one is refused once a sync wrote it. Resolves with the status after
247
+ * that sync.
248
+ */
249
+ public async sync(optionsArg: { rotate: boolean }): Promise<IControllerGatewayStatus> {
250
+ if (optionsArg.rotate) {
251
+ const record = await this.options.store.read();
252
+ if (!record?.active) throw new Error('This controller is not enrolled with a gateway, so no route carries a rotated secret.');
253
+ const secrets = this.options.secrets();
254
+ if (!secrets) throw new Error('This controller runs no trusted reverse proxy, so it has no secret to rotate.');
255
+ await secrets.rotate();
256
+ }
257
+ await this.scheduler.syncNow();
258
+ return this.status();
259
+ }
260
+
261
+ /** Whether any timer is armed; false once closed. */
262
+ public hasTimer(): boolean {
263
+ return this.scheduler.hasTimer();
264
+ }
265
+
266
+ /** Stops every timer, aborts a running sync's requests and waits for it. */
267
+ public async close(): Promise<void> {
268
+ this.abortController.abort(new Error('The controller is stopping.'));
269
+ await this.scheduler.close();
270
+ }
271
+
272
+ private adopt(recordArg: IControllerGatewayClientDocument | undefined): void {
273
+ this.record = recordArg;
274
+ this.lastSync = structuredClone(recordArg?.lastSync ?? {});
275
+ if (!recordArg) this.state = 'not_enrolled';
276
+ else if (recordArg.candidate) this.state = 'finalize_pending';
277
+ }
278
+
279
+ private async pass(): Promise<TGatewaySyncPassResult> {
280
+ let record: IControllerGatewayClientDocument | undefined;
281
+ try {
282
+ record = await this.options.store.read();
283
+ } catch (errorArg) {
284
+ this.log(`The gateway client could not read its enrolment: ${errorArg instanceof Error ? errorArg.message : String(errorArg)}`);
285
+ return 'transient';
286
+ }
287
+ this.adopt(record);
288
+ const active = record?.active;
289
+ if (!record || !active) {
290
+ if (record?.candidate) {
291
+ return this.finish(undefined, { code: 'finalize_pending', message: 'The gateway has not confirmed the enrolment\'s '
292
+ + 'credential. Stop the controller and run `agl remote gateway enrol` again to finish it.' });
293
+ }
294
+ return 'idle';
295
+ }
296
+ if (record.candidate) {
297
+ return this.finish(active.tokenId, { code: 'finalize_pending', message: 'A new enrolment is not finished. Stop the '
298
+ + 'controller and run `agl remote gateway enrol` again to finish it.' });
299
+ }
300
+ const config = this.options.runtimeConfig();
301
+ if (config.tlsMode !== 'proxy') {
302
+ return this.finish(active.tokenId, { code: 'not_proxied', message: 'The controller is not behind a TLS reverse '
303
+ + 'proxy (`agl remote set`), so it has no route.' });
304
+ }
305
+ this.state = 'syncing';
306
+ try {
307
+ // Refuses a stored URL that is plain http off loopback (`gateway_url_insecure`) before the token is unsealed.
308
+ const transport = new GatewayClientTransport(active.gatewayUrl, {
309
+ ...(this.options.requestTimeoutMs === undefined ? {} : { timeoutMs: this.options.requestTimeoutMs }),
310
+ signal: this.abortController.signal,
311
+ });
312
+ const token = await this.options.store.unseal(active);
313
+ const context = await transport.fire<IReq_GetGatewayClientContext>('getGatewayClientContext', { apiToken: token });
314
+ const contextProblem = gatewayContextProblem(context, active.gatewayClientId);
315
+ if (contextProblem) throw new GatewaySyncProblemError(contextProblem);
316
+ // The client's routes for anything the controller no longer serves go first: an earlier hostname's. `agl remote
317
+ // set` refuses another hostname while enrolled, so this and `origin_changed` are the safety net for a leftover
318
+ // (an interrupted change, or a move an earlier release made after a rollback).
319
+ const hostname = new URL(config.publicOrigin).hostname;
320
+ const removed = await deleteGatewayRoutes(transport, token, (routeArg) => routeArg.ownership.appId === active.appId
321
+ && routeArg.ownership.hostname === hostname && routeArg.ownership.routeRef === undefined);
322
+ if (removed.length > 0) this.log(`The gateway client deleted routes the controller no longer serves: ${removed.join(', ')}.`);
323
+ if (hostname !== active.hostname) {
324
+ throw new GatewaySyncProblemError({ code: 'origin_changed', message: `The controller's public origin is `
325
+ + `${config.publicOrigin}, but it was enrolled for ${active.hostname}. Run \`agl remote gateway enrol\` again `
326
+ + `for ${hostname}.` });
327
+ }
328
+ // No route is written without the trusted-proxy secret, which only a gateway that takes request headers sets.
329
+ const headerRefusal = gatewayRouteHeaderRefusal(context.capabilities);
330
+ if (headerRefusal) throw new GatewaySyncProblemError(headerRefusal);
331
+ const secrets = this.options.secrets();
332
+ if (!secrets) {
333
+ throw new GatewaySyncProblemError({ code: 'not_proxied', message: 'The controller has no trusted-proxy secret for its route.' });
334
+ }
335
+ const spec: IGatewayRouteSpec = {
336
+ gatewayClientId: active.gatewayClientId,
337
+ appId: active.appId,
338
+ hostname,
339
+ targetHost: active.targetHost,
340
+ targetPort: config.controllerPort,
341
+ };
342
+ // The secret the route carries: a rotation's while one is in progress, so the sync that writes it confirms it.
343
+ const carried = secrets.routeSecret();
344
+ const outcome = gatewayRouteSyncOutcome(await transport.fire<IReq_SyncGatewayClientRoute>(
345
+ 'syncGatewayClientRoute',
346
+ gatewayRouteSyncRequest(token, spec, carried.secret),
347
+ ));
348
+ if (!outcome.synced) throw new GatewaySyncProblemError(outcome.problem);
349
+ const readBack = gatewayRouteReadBack(
350
+ (await transport.fire<IReq_GetGatewayClientRoutes>('getGatewayClientRoutes', { apiToken: token })).routes,
351
+ spec,
352
+ );
353
+ if (readBack.problem) throw new GatewaySyncProblemError(readBack.problem);
354
+ // The route carries the secret: a rotation it carries ends, and the previous secret is refused from now on. One
355
+ // that began while this sync ran is carried by the next sync, which runs right after it.
356
+ if (secrets.routeSecret().generation === carried.generation) await secrets.confirm(carried.generation);
357
+ return await this.finish(active.tokenId, undefined, outcome.dns, readBack.sourceProfileVerified);
358
+ } catch (errorArg) {
359
+ if (this.abortController.signal.aborted) return 'idle';
360
+ return this.finish(active.tokenId, gatewayProblemOf(errorArg));
361
+ }
362
+ }
363
+
364
+ /** Records a sync's end, in memory and in the database, and tells the scheduler what follows. */
365
+ private async finish(
366
+ tokenIdArg: string | undefined,
367
+ problemArg: IControllerGatewayProblem | undefined,
368
+ dnsArg?: IControllerGatewayDns,
369
+ sourceProfileVerifiedArg?: boolean,
370
+ ): Promise<TGatewaySyncPassResult> {
371
+ const kind = problemArg === undefined ? undefined : controllerGatewayProblemKind[problemArg.code];
372
+ const transient = kind === 'transient';
373
+ const previous = this.lastSync;
374
+ const lastSync: IControllerGatewaySyncRecord = problemArg
375
+ ? { ...(previous.syncedAt === undefined ? {} : { syncedAt: previous.syncedAt }),
376
+ ...(previous.dns ? { dns: previous.dns } : {}),
377
+ ...(previous.sourceProfileVerified === undefined ? {} : { sourceProfileVerified: previous.sourceProfileVerified }),
378
+ problem: problemArg }
379
+ : { syncedAt: this.options.clock?.now() ?? Date.now(), ...(dnsArg ? { dns: dnsArg } : {}),
380
+ ...(sourceProfileVerifiedArg === undefined ? {} : { sourceProfileVerified: sourceProfileVerifiedArg }) };
381
+ const logged = problemArg ? `${problemArg.code}: ${problemArg.message}` : undefined;
382
+ if (logged !== this.loggedProblem) {
383
+ this.log(problemArg ? `The gateway route was not synced (${problemArg.code}${kind === 'terminal' ? '' : ', asked again'}): `
384
+ + `${problemArg.message}` : 'The gateway route is synced.');
385
+ this.loggedProblem = logged;
386
+ }
387
+ if (tokenIdArg !== undefined) {
388
+ try {
389
+ await this.options.store.recordSync(tokenIdArg, lastSync);
390
+ } catch (errorArg) {
391
+ this.log(`The gateway client could not record its sync: ${errorArg instanceof Error ? errorArg.message : String(errorArg)}`);
392
+ }
393
+ }
394
+ // The status shows the sync's end once it is recorded; the scheduler arms the next one right after.
395
+ this.lastSync = lastSync;
396
+ this.state = !problemArg ? 'synced'
397
+ : problemArg.code === 'finalize_pending' ? 'finalize_pending'
398
+ : transient ? 'retrying' : kind === 'waiting' ? 'waiting' : 'failed';
399
+ return !problemArg ? 'synced' : kind === 'terminal' ? 'terminal' : kind === 'waiting' ? 'waiting' : 'transient';
400
+ }
401
+ }