agl 41.2.0 → 42.1.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 (120) hide show
  1. package/changelog.md +41 -0
  2. package/dist_serve/bundle.js +2625 -2278
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +3 -68
  5. package/dist_serve/bundle.js.third-party-notices.txt +4 -137
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +4 -4
  8. package/dist_ts/classes.authmodels.d.ts +2 -8
  9. package/dist_ts/classes.authmodels.js +60 -23
  10. package/dist_ts/classes.authstore.d.ts +24 -0
  11. package/dist_ts/classes.authstore.js +185 -23
  12. package/dist_ts/classes.cli.d.ts +3 -6
  13. package/dist_ts/classes.cli.js +38 -51
  14. package/dist_ts/classes.config.d.ts +17 -3
  15. package/dist_ts/classes.config.js +55 -18
  16. package/dist_ts/classes.controller.d.ts +83 -14
  17. package/dist_ts/classes.controller.js +545 -229
  18. package/dist_ts/classes.controllerdevices.d.ts +128 -0
  19. package/dist_ts/classes.controllerdevices.js +472 -0
  20. package/dist_ts/classes.controllermanagement.d.ts +42 -9
  21. package/dist_ts/classes.controllermanagement.js +72 -23
  22. package/dist_ts/classes.controllerservice.d.ts +3 -31
  23. package/dist_ts/classes.controllerservice.js +3 -47
  24. package/dist_ts/classes.mcpcontrollerhost.js +9 -3
  25. package/dist_ts/classes.processinspection.d.ts +8 -1
  26. package/dist_ts/classes.processinspection.js +92 -2
  27. package/dist_ts/classes.proxycontrol.js +6 -1
  28. package/dist_ts/classes.proxydaemon.d.ts +2 -2
  29. package/dist_ts/classes.proxydaemon.js +1 -1
  30. package/dist_ts/classes.proxystore.d.ts +2 -11
  31. package/dist_ts/classes.proxystore.js +3 -25
  32. package/dist_ts/classes.sessionfeed.d.ts +10 -1
  33. package/dist_ts/classes.sessionfeed.js +12 -2
  34. package/dist_ts/classes.tpmsecretcodec.d.ts +13 -0
  35. package/dist_ts/classes.tpmsecretcodec.js +28 -0
  36. package/dist_ts/classes.trustedproxysecrets.d.ts +91 -0
  37. package/dist_ts/classes.trustedproxysecrets.js +338 -0
  38. package/dist_ts/classes.upgradecoordinator.d.ts +14 -1
  39. package/dist_ts/classes.upgradecoordinator.js +21 -3
  40. package/dist_ts/classes.upgradetransaction.d.ts +32 -0
  41. package/dist_ts/classes.upgradetransaction.js +101 -4
  42. package/dist_ts/classes.validation.d.ts +2 -0
  43. package/dist_ts/classes.validation.js +2 -2
  44. package/dist_ts/functions.controlleradmission.d.ts +67 -0
  45. package/dist_ts/functions.controlleradmission.js +127 -0
  46. package/dist_ts/functions.deviceapi.d.ts +28 -0
  47. package/dist_ts/functions.deviceapi.js +246 -0
  48. package/dist_ts/functions.deviceproof.d.ts +33 -0
  49. package/dist_ts/functions.deviceproof.js +93 -0
  50. package/dist_ts/functions.remotecli.d.ts +27 -0
  51. package/dist_ts/functions.remotecli.js +241 -0
  52. package/dist_ts/functions.retiredenvironment.d.ts +11 -2
  53. package/dist_ts/functions.retiredenvironment.js +22 -5
  54. package/dist_ts/index.d.ts +1 -0
  55. package/dist_ts/index.js +2 -1
  56. package/dist_ts/interfaces.auth.d.ts +29 -4
  57. package/dist_ts/interfaces.auth.js +10 -1
  58. package/dist_ts/interfaces.config.d.ts +14 -0
  59. package/dist_ts/interfaces.config.js +9 -2
  60. package/dist_ts/interfaces.lifecycle.d.ts +3 -0
  61. package/dist_ts_authswitch/classes.authoritydaemon.js +6 -1
  62. package/dist_ts_interfaces/devices.d.ts +331 -0
  63. package/dist_ts_interfaces/devices.js +34 -0
  64. package/dist_ts_interfaces/index.d.ts +2 -0
  65. package/dist_ts_interfaces/index.js +3 -1
  66. package/dist_ts_interfaces/interfaces.d.ts +5 -3
  67. package/dist_ts_interfaces/interfaces.js +3 -2
  68. package/dist_ts_interfaces/management.d.ts +2 -2
  69. package/dist_ts_interfaces/management.js +2 -2
  70. package/dist_ts_interfaces/mcprequests.d.ts +1 -1
  71. package/dist_ts_interfaces/requests.d.ts +2 -2
  72. package/dist_ts_interfaces/requests.devices.d.ts +89 -0
  73. package/dist_ts_interfaces/requests.devices.js +2 -0
  74. package/dist_ts_interfaces/requests.upgrade.d.ts +0 -12
  75. package/package.json +12 -11
  76. package/readme.md +116 -24
  77. package/ts/00_commitinfo_data.ts +1 -1
  78. package/ts/aglapi/aglapisurface.document.ts +3 -3
  79. package/ts/classes.authmodels.ts +68 -25
  80. package/ts/classes.authstore.ts +183 -24
  81. package/ts/classes.cli.ts +38 -61
  82. package/ts/classes.config.ts +70 -21
  83. package/ts/classes.controller.ts +746 -329
  84. package/ts/classes.controllerdevices.ts +469 -0
  85. package/ts/classes.controllermanagement.ts +123 -49
  86. package/ts/classes.controllerservice.ts +3 -56
  87. package/ts/classes.mcpcontrollerhost.ts +10 -5
  88. package/ts/classes.processinspection.ts +84 -3
  89. package/ts/classes.proxycontrol.ts +2 -0
  90. package/ts/classes.proxydaemon.ts +3 -2
  91. package/ts/classes.proxystore.ts +4 -25
  92. package/ts/classes.sessionfeed.ts +13 -1
  93. package/ts/classes.tpmsecretcodec.ts +26 -0
  94. package/ts/classes.trustedproxysecrets.ts +317 -0
  95. package/ts/classes.upgradecoordinator.ts +33 -3
  96. package/ts/classes.upgradetransaction.ts +130 -1
  97. package/ts/classes.validation.ts +1 -1
  98. package/ts/functions.controlleradmission.ts +168 -0
  99. package/ts/functions.deviceapi.ts +295 -0
  100. package/ts/functions.deviceproof.ts +118 -0
  101. package/ts/functions.remotecli.ts +270 -0
  102. package/ts/functions.retiredenvironment.ts +25 -3
  103. package/ts/index.ts +1 -0
  104. package/ts/interfaces.auth.ts +41 -3
  105. package/ts/interfaces.config.ts +15 -0
  106. package/ts/interfaces.lifecycle.ts +3 -0
  107. package/ts_authswitch/classes.authoritydaemon.ts +2 -0
  108. package/ts_interfaces/devices.schema.json +890 -0
  109. package/ts_interfaces/devices.ts +392 -0
  110. package/ts_interfaces/index.ts +2 -0
  111. package/ts_interfaces/interfaces.ts +5 -2
  112. package/ts_interfaces/management.ts +2 -2
  113. package/ts_interfaces/mcprequests.ts +1 -1
  114. package/ts_interfaces/requests.devices.ts +95 -0
  115. package/ts_interfaces/requests.ts +10 -10
  116. package/ts_interfaces/requests.upgrade.ts +0 -16
  117. package/ts_web/00_commitinfo_data.ts +1 -1
  118. package/ts_web/classes.controllersocketclient.ts +27 -0
  119. package/ts_web/elements.devices.ts +752 -0
  120. package/ts_web/elements.harnesscontrollerapp.ts +18 -1
@@ -7,6 +7,8 @@ import { WorkerCallerBindingModel } from './classes.workercallerbindings.js';
7
7
  import { FleetTicketEffectModel } from './fleet/classes.ticketeffects.js';
8
8
  import { ControllerCodexOriginMigrationModel } from '../ts_migration/v29_codexorigins.js';
9
9
  import { ControllerCodexConnectionStore } from './classes.codexconnectionstore.js';
10
+ import { ControllerTrustedProxySecretModel } from './classes.trustedproxysecrets.js';
11
+ import { ControllerDeviceModel, deleteControllerDevices } from './classes.controllerdevices.js';
10
12
  import { ControllerClaudeSessionStore } from './classes.claudesessionstore.js';
11
13
  import { ControllerClaudeSessionModel } from './classes.claudesessionmodels.js';
12
14
  import { ControllerPendingPromptStore } from './classes.pendingpromptstore.js';
@@ -44,7 +46,6 @@ import {
44
46
  import {
45
47
  ControllerAuditEventModel,
46
48
  ControllerAuthModel,
47
- ControllerRuntimeConfigFromLaterReleaseError,
48
49
  ControllerPendingPromptModel,
49
50
  ControllerProjectModel,
50
51
  ControllerResourceModel,
@@ -203,24 +204,6 @@ const auditPruneMaxBatchesPerSweep = 50;
203
204
  const auditCountPruneMaxBatchesPerSweep = 250;
204
205
  const auditPruneIntervalMs = 30 * 60 * 1000;
205
206
 
206
- /**
207
- * The stored authentication document of `controllerIdArg`. A runtime configuration only a later release writes is
208
- * refused with its own reason (`ControllerRuntimeConfigFromLaterReleaseError`), not the client's generic assertion
209
- * failure, so the operator reads the remedy.
210
- */
211
- const findStoredAuthDocument = async (
212
- controllerIdArg: string,
213
- ): Promise<plugins.nosqldb.TStoredDocument<IControllerAuthDocument> | null> => {
214
- try {
215
- return await ControllerAuthModel.exact.findStoredOne({ id: controllerIdArg });
216
- } catch (errorArg) {
217
- if (errorArg instanceof Error && errorArg.cause instanceof ControllerRuntimeConfigFromLaterReleaseError) {
218
- throw errorArg.cause;
219
- }
220
- throw errorArg;
221
- }
222
- };
223
-
224
207
  /** A concurrent prune that removed an event first leaves nothing to do for it. */
225
208
  const deleteStoredAuditEvents = async (
226
209
  eventsArg: Array<plugins.nosqldb.TStoredDocument<IControllerAuditEvent>>,
@@ -455,6 +438,7 @@ const cloneRuntimeConfig = (
455
438
  projectsRoot: runtimeConfigArg.projectsRoot,
456
439
  opencodePort: runtimeConfigArg.opencodePort,
457
440
  tlsMode: runtimeConfigArg.tlsMode,
441
+ ...(runtimeConfigArg.gatewaySources === undefined ? {} : { gatewaySources: [...runtimeConfigArg.gatewaySources] }),
458
442
  });
459
443
 
460
444
  const runtimeConfigsEqual = (
@@ -465,7 +449,8 @@ const runtimeConfigsEqual = (
465
449
  && leftArg.rpId === rightArg.rpId
466
450
  && leftArg.projectsRoot === rightArg.projectsRoot
467
451
  && leftArg.opencodePort === rightArg.opencodePort
468
- && leftArg.tlsMode === rightArg.tlsMode;
452
+ && leftArg.tlsMode === rightArg.tlsMode
453
+ && (leftArg.gatewaySources ?? []).join(',') === (rightArg.gatewaySources ?? []).join(',');
469
454
 
470
455
  const hashSetupCode = (setupCodeArg: string): string =>
471
456
  plugins.crypto.createHash('sha256').update(setupCodeArg, 'utf8').digest('base64url');
@@ -816,6 +801,8 @@ const setAuthStoreModelManager = (
816
801
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerCodexTurnModel);
817
802
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexTranscriptGrantModel);
818
803
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerTrackedConversationModel);
804
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerTrustedProxySecretModel);
805
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerDeviceModel);
819
806
  plugins.nosqldb.setDefaultManagerForDoc(
820
807
  managerArg,
821
808
  ControllerLegacyManagedSessionMigrationModel,
@@ -1100,6 +1087,11 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1100
1087
  await ControllerCodexTurnModel.init();
1101
1088
  await FlexTranscriptGrantModel.init();
1102
1089
  await ControllerTrackedConversationModel.init();
1090
+ await ControllerTrustedProxySecretModel.init();
1091
+ await ControllerDeviceModel.init();
1092
+ // `moveRuntimeConfig` changes the configuration and deletes the paired devices in one transaction.
1093
+ await ControllerAuthModel.exact.prepare();
1094
+ await ControllerDeviceModel.exact.prepare();
1103
1095
  await new PostDatabaseDocumentMigrationRunner(this.database).run();
1104
1096
  this.initialized = true;
1105
1097
  if (!this.closeStarted) this.projectMutationAdmissionOpen = true;
@@ -1313,6 +1305,80 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1313
1305
  }
1314
1306
  }
1315
1307
 
1308
+ /**
1309
+ * Reads the stored runtime configuration of `controllerPortArg` without running this release on the store: only
1310
+ * the configuration's own collection is prepared (it holds the same declaration in every release that reads it),
1311
+ * no migration runs and no other collection or index is created, so a release older than this one still starts on
1312
+ * the store afterwards. The store is closed before this returns and cannot be initialized afterwards. For checks
1313
+ * made before an older release is put back, such as an upgrade recovery that is about to restore one.
1314
+ */
1315
+ public async readRuntimeConfigOnly(
1316
+ controllerPortArg: number,
1317
+ ): Promise<IControllerRuntimeConfig | undefined> {
1318
+ if (
1319
+ !Number.isSafeInteger(controllerPortArg)
1320
+ || controllerPortArg < 1
1321
+ || controllerPortArg > 65535
1322
+ ) {
1323
+ throw new Error('controllerPort must be an integer between 1 and 65535.');
1324
+ }
1325
+ if (this.closeStarted || this.initPromise || this.initialized || this.database || this.embeddedDatabase) {
1326
+ throw new Error('SmartDataAuthStore reads a runtime configuration only on a store it has not opened.');
1327
+ }
1328
+ this.closeStarted = true;
1329
+ let databaseInitialized = false;
1330
+ let result: IControllerRuntimeConfig | undefined;
1331
+ let readError: unknown;
1332
+ try {
1333
+ this.releaseModelOwnership = claimAuthStoreModelOwnership(this.modelOwner, this.smartDataManager);
1334
+ let mongoDbUrl = this.options.mongoDbUrl?.trim();
1335
+ if (!mongoDbUrl) {
1336
+ const embedded = new EmbeddedControllerDatabase({ dataDirectory: this.options.embeddedDataDirectory! });
1337
+ this.embeddedDatabase = embedded;
1338
+ mongoDbUrl = await embedded.start();
1339
+ }
1340
+ this.database = new plugins.nosqldb.SmartdataDb({ mongoDbUrl, mongoDbName: this.options.mongoDbName });
1341
+ await this.db.init();
1342
+ databaseInitialized = true;
1343
+ await ControllerAuthModel.init();
1344
+ const stored = await ControllerAuthModel.exact.findStoredOne({ id: `controller:${controllerPortArg}` });
1345
+ result = stored ? cloneRuntimeConfig(ControllerAuthModel.exact.toPersisted(stored).config) : undefined;
1346
+ } catch (errorArg) {
1347
+ readError = errorArg;
1348
+ }
1349
+ const cleanupErrors: unknown[] = [];
1350
+ if (this.database) {
1351
+ if (databaseInitialized) {
1352
+ try {
1353
+ await this.database.close();
1354
+ this.database = undefined;
1355
+ } catch (closeErrorArg) {
1356
+ cleanupErrors.push(closeErrorArg);
1357
+ }
1358
+ } else {
1359
+ this.database = undefined;
1360
+ }
1361
+ }
1362
+ if (!this.database) {
1363
+ try {
1364
+ await this.stopEmbeddedDatabase();
1365
+ } catch (stopErrorArg) {
1366
+ cleanupErrors.push(stopErrorArg);
1367
+ }
1368
+ }
1369
+ try {
1370
+ this.releaseModelOwnershipIfResourcesClosed();
1371
+ } catch (releaseErrorArg) {
1372
+ cleanupErrors.push(releaseErrorArg);
1373
+ }
1374
+ if (readError !== undefined || cleanupErrors.length > 0) {
1375
+ const errors = readError === undefined ? cleanupErrors : [readError, ...cleanupErrors];
1376
+ if (errors.length === 1) throw errors[0];
1377
+ throw new AggregateError(errors, 'Reading the stored runtime configuration failed and cleanup was incomplete.');
1378
+ }
1379
+ return result;
1380
+ }
1381
+
1316
1382
  public async getRuntimeConfig(
1317
1383
  controllerPortArg: number,
1318
1384
  ): Promise<IControllerRuntimeConfig | undefined> {
@@ -1325,7 +1391,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1325
1391
  throw new Error('controllerPort must be an integer between 1 and 65535.');
1326
1392
  }
1327
1393
  this.controllerId = `controller:${controllerPortArg}`;
1328
- const stored = await findStoredAuthDocument(this.controllerId);
1394
+ const stored = await ControllerAuthModel.exact.findStoredOne({ id: this.controllerId });
1329
1395
  if (!stored) return undefined;
1330
1396
  return cloneRuntimeConfig(ControllerAuthModel.exact.toPersisted(stored).config);
1331
1397
  }
@@ -1355,7 +1421,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1355
1421
  }
1356
1422
  const controllerId = `controller:${runtimeConfigArg.controllerPort}`;
1357
1423
  this.controllerId = controllerId;
1358
- const existing = await findStoredAuthDocument(controllerId);
1424
+ const existing = await ControllerAuthModel.exact.findStoredOne({ id: controllerId });
1359
1425
  if (existing) {
1360
1426
  const document = ControllerAuthModel.exact.toPersisted(existing);
1361
1427
  return this.finalizeRuntimeConfigDocument(document, runtimeConfigArg);
@@ -1375,7 +1441,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1375
1441
  return this.finalizeRuntimeConfigDocument(document, runtimeConfigArg);
1376
1442
  } catch (errorArg) {
1377
1443
  if (!isAmbiguousWrite(errorArg)) throw errorArg;
1378
- const reconciled = await findStoredAuthDocument(controllerId);
1444
+ const reconciled = await ControllerAuthModel.exact.findStoredOne({ id: controllerId });
1379
1445
  if (!reconciled) {
1380
1446
  throw new AuthError(
1381
1447
  'ambiguous_write',
@@ -1447,6 +1513,85 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1447
1513
  }
1448
1514
  }
1449
1515
 
1516
+ /**
1517
+ * Moves the runtime configuration of the port `getRuntimeConfig` resolved to `targetArg` (`agl remote set` and
1518
+ * `unset`, against a stopped controller only; a starting controller never changes it). The controller keeps its
1519
+ * id and every record. When the origin or RP ID changes, the passkey enrollment is removed, since a passkey is bound
1520
+ * to its RP ID, and every temporary password of the controller is revoked first, so nothing that signed in to the
1521
+ * old origin signs in to the new one: the controller then starts in setup and its start prints a fresh setup code.
1522
+ */
1523
+ public async moveRuntimeConfig(targetArg: IControllerRuntimeConfig): Promise<{
1524
+ previous: IControllerRuntimeConfig;
1525
+ changed: boolean;
1526
+ enrollmentReset: boolean;
1527
+ /** How many paired devices the move removed: a device signs the public origin, so a new origin removes them all. */
1528
+ devicesRemoved: number;
1529
+ }> {
1530
+ const stored = await this.findStoredState();
1531
+ const current = ControllerAuthModel.exact.toPersisted(stored);
1532
+ if (targetArg.controllerPort !== current.config.controllerPort) {
1533
+ throw new AuthError('config_mismatch', 'A runtime configuration moves only within its own port.');
1534
+ }
1535
+ const previous = cloneRuntimeConfig(current.config);
1536
+ if (runtimeConfigsEqual(current.config, targetArg)) {
1537
+ return { previous, changed: false, enrollmentReset: false, devicesRemoved: 0 };
1538
+ }
1539
+ const enrollmentReset = current.config.publicOrigin !== targetArg.publicOrigin || current.config.rpId !== targetArg.rpId;
1540
+ if (enrollmentReset) await this.revokeTempPasswords();
1541
+ // Every paired device signs the public origin; none could authenticate at another one. The devices go in the
1542
+ // configuration's own transaction, so a move that fails keeps them along with the old origin.
1543
+ const removesDevices = current.config.publicOrigin !== targetArg.publicOrigin;
1544
+ const controllerId = this.requireControllerId();
1545
+ let devicesRemoved = 0;
1546
+ const session = this.db.createSession();
1547
+ try {
1548
+ await session.withTransaction(async (transactionArg) => {
1549
+ devicesRemoved = 0;
1550
+ const result = await ControllerAuthModel.exact.transition({
1551
+ current: stored,
1552
+ change: (model) => {
1553
+ model.config = cloneRuntimeConfig(targetArg);
1554
+ if (!enrollmentReset) return;
1555
+ model.credentials = [];
1556
+ model.authState = 'setupRequired';
1557
+ model.setup = null;
1558
+ },
1559
+ }, { session: transactionArg });
1560
+ if (result.status !== 'transitioned') {
1561
+ throw new AuthError('concurrent_change', 'The controller configuration changed concurrently and was not moved.');
1562
+ }
1563
+ if (removesDevices) devicesRemoved = await deleteControllerDevices(controllerId, { session: transactionArg });
1564
+ });
1565
+ } catch (errorArg) {
1566
+ if (plugins.nosqldb.SmartdataSession.getCommitOutcome(errorArg) === 'not_committed') throw errorArg;
1567
+ // The commit may have landed: the move stands only if the store shows all of it.
1568
+ const reconciled = ControllerAuthModel.exact.toPersisted(await this.findStoredState());
1569
+ const remaining = removesDevices ? await ControllerDeviceModel.exact.count({ controllerId }) : 0;
1570
+ if (!runtimeConfigsEqual(reconciled.config, targetArg) || remaining !== 0) {
1571
+ throw new AuthError('ambiguous_write', 'The runtime configuration move has an ambiguous outcome.', { cause: errorArg });
1572
+ }
1573
+ } finally {
1574
+ await session.close();
1575
+ }
1576
+ return { previous, changed: true, enrollmentReset, devicesRemoved };
1577
+ }
1578
+
1579
+ /** Deletes every temporary password of this controller, expired or not. */
1580
+ private async revokeTempPasswords(): Promise<void> {
1581
+ const controllerId = this.requireControllerId();
1582
+ for (;;) {
1583
+ const batch = await ControllerTempPasswordModel.exact.findStored({ filter: { controllerId }, limit: tempPasswordPruneBatchSize });
1584
+ if (batch.length === 0) return;
1585
+ for (const current of batch) {
1586
+ const deleted = await ControllerTempPasswordModel.exact.delete({ current });
1587
+ const { id } = ControllerTempPasswordModel.exact.toPersisted(current);
1588
+ if (deleted.status !== 'deleted' && await ControllerTempPasswordModel.exact.findStoredOne({ id })) {
1589
+ throw new AuthError('concurrent_change', 'A temporary password could not be revoked.');
1590
+ }
1591
+ }
1592
+ }
1593
+ }
1594
+
1450
1595
  public async getState(): Promise<IControllerAuthDocument> {
1451
1596
  const stored = await this.findStoredState();
1452
1597
  return ControllerAuthModel.exact.toPersisted(stored);
@@ -1765,6 +1910,20 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1765
1910
  ...(eventArg.requestId === undefined ? {} : { requestId: { ...eventArg.requestId } }),
1766
1911
  ...(eventArg.senderLabel === undefined ? {} : { senderLabel: eventArg.senderLabel }),
1767
1912
  ...(eventArg.localCli === undefined ? {} : { localCli: { ...eventArg.localCli } }),
1913
+ ...(eventArg.details === undefined ? {} : {
1914
+ details: {
1915
+ remoteMove: {
1916
+ previous: {
1917
+ publicOrigin: eventArg.details.remoteMove.previous.publicOrigin,
1918
+ rpId: eventArg.details.remoteMove.previous.rpId,
1919
+ },
1920
+ target: {
1921
+ publicOrigin: eventArg.details.remoteMove.target.publicOrigin,
1922
+ rpId: eventArg.details.remoteMove.target.rpId,
1923
+ },
1924
+ },
1925
+ },
1926
+ }),
1768
1927
  };
1769
1928
  try {
1770
1929
  const result = await ControllerAuditEventModel.exact.insert(event);
@@ -2345,7 +2504,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
2345
2504
  if (!this.controllerId) {
2346
2505
  throw new AuthError('not_initialized', 'The controller runtime configuration is unresolved.');
2347
2506
  }
2348
- const stored = await findStoredAuthDocument(this.controllerId);
2507
+ const stored = await ControllerAuthModel.exact.findStoredOne({ id: this.controllerId });
2349
2508
  if (!stored) {
2350
2509
  throw new AuthError('not_initialized', 'The controller authentication document is missing.');
2351
2510
  }
package/ts/classes.cli.ts CHANGED
@@ -11,18 +11,14 @@ import {
11
11
  describeBrowserPaintAvailability,
12
12
  type IControllerStatus,
13
13
  } from '../ts_interfaces/index.js';
14
- import {
15
- defaultControllerPort,
16
- readTrustedProxySecret,
17
- trustedProxySecretEnvironmentVariable,
18
- } from './classes.config.js';
14
+ import { defaultControllerPort } from './classes.config.js';
19
15
  import { resolveAGLHomePaths } from './classes.aglhome.js';
20
16
  import { resolveOptionalAuthoritySocketPaths } from './classes.authorityclient.js';
21
17
  import {
22
18
  ensureControllerDataRoot,
23
19
  preflightAGLHomeMigration,
24
20
  } from './functions.controllerdataroot.js';
25
- import type { IControllerRuntimeOverrides, TControllerTlsMode } from './interfaces.config.js';
21
+ import type { IControllerRuntimeOverrides } from './interfaces.config.js';
26
22
  import type { IControllerIssuerIdentity } from './interfaces.identity.js';
27
23
  import type {
28
24
  IControllerReadyIpcMessage,
@@ -40,6 +36,7 @@ import {
40
36
  stopRunningController,
41
37
  tryQueryControllerStatus as tryQueryManagedControllerStatus,
42
38
  waitUntilControllerExited,
39
+ isUnmanagedControllerError,
43
40
  type IControllerStatusQuery,
44
41
  } from './classes.controllermanagement.js';
45
42
  import {
@@ -94,12 +91,7 @@ import {
94
91
  import { ControllerMcpClient, ControllerMcpClientError } from './classes.mcpclient.js';
95
92
  import {
96
93
  AglControllerService,
97
- assertControllerServiceTlsMode,
98
- controllerServiceDetachedRemedy,
99
- controllerServiceInstallRemedy,
100
- ControllerServiceTlsProxyRefusal,
101
94
  controllerServiceStandDownExitStatus,
102
- isControllerServiceTlsProxyRefusal,
103
95
  resolveControllerStartRoute,
104
96
  type IControllerServiceOverrides,
105
97
  type IInstalledControllerService,
@@ -152,6 +144,7 @@ Usage:
152
144
  ${currentCliName} proxy service|serve|status|credential|run [options]
153
145
  ${currentCliName} foreground [options]
154
146
  ${currentCliName} temp-password [--port 4097] [--ttl-hours 24]
147
+ ${currentCliName} remote set|unset|secret import [--port 4097] [options]
155
148
  ${currentCliName} feed list [--state failed] [--json] | acknowledge <row-id> --updated-at <ms> [--json]
156
149
 
157
150
  Commands:
@@ -171,6 +164,8 @@ Commands:
171
164
  proxy Serve an account-routing API or launch a harness through it (proxy --help)
172
165
  foreground Run ${currentRuntimeName} attached to this terminal
173
166
  temp-password Mint a temporary browser login password (max 24 hours)
167
+ remote Move a stopped controller between localhost and a public origin behind a TLS
168
+ reverse proxy, or import the proxy's secret (remote --help)
174
169
  help Show this help
175
170
 
176
171
  Startup options:
@@ -230,6 +225,8 @@ password authenticates the browser UI without a passkey until it expires.
230
225
 
231
226
  The first successful start prints a one-time setup code. Runtime configuration
232
227
  is immutable after initialization; use the same --port for later management.
228
+ Only remote set and remote unset move a stopped controller's port to another
229
+ public origin, RP ID or gateway source; the next start prints a new setup code.
233
230
  --directory is transient and may be supplied on any stopped start.
234
231
  Detached starts append ${currentRuntimeName} errors to
235
232
  $AGL_HOME/logs/controller-<port>.log. Upgrade workers write a separate private
@@ -242,9 +239,9 @@ upgrade drive that unit, which restarts ${currentRuntimeName} after a failure an
242
239
  login. Move a running detached controller into it with restart; change its
243
240
  settings with stop, service install, then start. The unit carries PATH,
244
241
  AGL_HOME and the database, harness, certificate and proxy variables, never a
245
- secret: install refuses while AGL_TRUSTED_PROXY_SECRET, AGL_FORWARD_ENV or a
246
- credentialed AGL_MONGO_URL, HTTP_PROXY or HTTPS_PROXY is set, and for a
247
- controller behind a TLS proxy, which needs that secret and runs detached.
242
+ secret: install refuses while AGL_FORWARD_ENV or a credentialed AGL_MONGO_URL,
243
+ HTTP_PROXY or HTTPS_PROXY is set. A controller behind a TLS reverse proxy runs
244
+ in the unit too: its trusted-proxy secret is sealed in its database.
248
245
  It appends errors to the same controller-<port>.log.
249
246
 
250
247
  service protect, run once per install as the user who owns the units (not
@@ -421,6 +418,7 @@ const currentStatusExpectation: IControllerStatusQuery = {
421
418
  protocolVersion: controllerProtocolVersion,
422
419
  upgradeManagementVersion: controllerUpgradeManagementVersion,
423
420
  managementProtocolVersion: controllerManagementProtocolVersion,
421
+ identity: 'caller',
424
422
  };
425
423
 
426
424
  const assertStatus = (statusArg: unknown): IControllerStatus => assertControllerStatus(
@@ -509,7 +507,7 @@ const resolveCliPath = async (): Promise<string> => {
509
507
  };
510
508
 
511
509
  export const acquireStartAdmission = async (
512
- commandArg: 'start' | 'restart' | 'service' | 'foreground' | 'temp-password' | 'config',
510
+ commandArg: 'start' | 'restart' | 'service' | 'foreground' | 'temp-password' | 'config' | 'remote',
513
511
  installationArg?: IPnpmGlobalInstallation,
514
512
  ): Promise<UpgradeStartLease | undefined> => {
515
513
  if (process.platform === 'win32') return undefined;
@@ -1070,7 +1068,11 @@ export const admitControllerServiceSelfStart = async (
1070
1068
  throw new ControllerServiceStandDown(`${controllerServiceUnitName} runs only the active pnpm-global installation of `
1071
1069
  + `${currentRuntimeName}, not a development checkout.`);
1072
1070
  }
1073
- if (await tryQueryControllerStatus(portArg)) {
1071
+ const running = await tryQueryControllerStatus(portArg).catch((errorArg: unknown) => {
1072
+ if (isUnmanagedControllerError(errorArg)) throw new ControllerServiceStandDown(errorArg.message);
1073
+ throw errorArg;
1074
+ });
1075
+ if (running) {
1074
1076
  throw new ControllerServiceStandDown(`An ${currentRuntimeName} controller already answers on port ${portArg}.`);
1075
1077
  }
1076
1078
  await preflightAGLHomeMigration();
@@ -1288,9 +1290,8 @@ const runStartedControllerProcess = async (
1288
1290
  const failure = errors.length > 1
1289
1291
  ? new AggregateError(errors, `Detached controller startup failed: ${formatCliError(normalized)}`)
1290
1292
  : normalized;
1291
- // The CLI that asked for this start reports the failure, and a controller the unit cannot run fails the same way
1292
- // every time: the service manager must not retry either.
1293
- if (kindArg === 'service' && (transportArg.kind === 'socket' || isControllerServiceTlsProxyRefusal(normalized))) {
1293
+ // The CLI that asked for this start reports the failure: the service manager must not retry it.
1294
+ if (kindArg === 'service' && transportArg.kind === 'socket') {
1294
1295
  process.stderr.write(`${currentCliName}: ${formatCliError(failure)}\n`);
1295
1296
  process.exitCode = controllerServiceStandDownExitStatus;
1296
1297
  return;
@@ -1301,7 +1302,8 @@ const runStartedControllerProcess = async (
1301
1302
 
1302
1303
  const showStatus = async (argvArg: TParsedArguments): Promise<void> => {
1303
1304
  const port = readPortOption(argvArg, 'port', 'port', defaultControllerPort)!;
1304
- const status = await queryControllerStatus(port).catch(() => {
1305
+ const status = await queryControllerStatus(port).catch((errorArg: unknown) => {
1306
+ if (isUnmanagedControllerError(errorArg)) throw errorArg;
1305
1307
  throw new Error(`No compatible ${currentRuntimeName} instance is responding on 127.0.0.1:${port}.`);
1306
1308
  });
1307
1309
  // The installed units' OOM scores are read here, on the host they run on; only Linux runs them. A shell whose
@@ -1445,22 +1447,6 @@ const stopController = async (argvArg: TParsedArguments): Promise<void> => {
1445
1447
  process.stdout.write(`${currentRuntimeName} stopped.\n`);
1446
1448
  };
1447
1449
 
1448
- /**
1449
- * A restart never stops a controller it could not start again. One behind a TLS proxy cannot run as the unit, and
1450
- * runs detached only with `AGL_TRUSTED_PROXY_SECRET` in this shell, checked as its start checks it and never shown.
1451
- */
1452
- export const assertControllerStartsAgain = (statusArg: IControllerStatus, routeArg: 'detached' | 'unit'): void => {
1453
- if (statusArg.tlsMode !== 'proxy') return;
1454
- if (routeArg === 'unit') throw new ControllerServiceTlsProxyRefusal(`${controllerServiceDetachedRemedy} Nothing was stopped.`);
1455
- try {
1456
- readTrustedProxySecret('proxy');
1457
- } catch (errorArg) {
1458
- throw new Error(`${currentRuntimeName} runs behind a TLS proxy and starts again only with `
1459
- + `${trustedProxySecretEnvironmentVariable} set in this shell: ${formatCliError(errorArg)} Set it and run `
1460
- + `\`${currentCliName} restart\` again; nothing was stopped.`, { cause: errorArg });
1461
- }
1462
- };
1463
-
1464
1450
  /**
1465
1451
  * Stops the controller and starts it again, through its unit when one is installed for this AGL home and port.
1466
1452
  * The start is checked before anything stops, so a start that would be refused never follows a stop. Sessions are
@@ -1477,9 +1463,8 @@ const restartController = async (argvArg: TParsedArguments): Promise<void> => {
1477
1463
  try {
1478
1464
  const serviceInstallation = process.platform === 'linux' ? installation : undefined;
1479
1465
  const overrides = parseRuntimeOverrides(argvArg);
1480
- const route = await resolveCliStartRoute(serviceInstallation, overrides);
1481
- const running = await tryQueryControllerStatus(overrides.controllerPort);
1482
- if (running) assertControllerStartsAgain(running, route.kind);
1466
+ // A start the unit would refuse is refused before anything stops.
1467
+ await resolveCliStartRoute(serviceInstallation, overrides);
1483
1468
  await stopController(argvArg);
1484
1469
  await startControllerWithoutAdmission(argvArg, serviceInstallation);
1485
1470
  } finally {
@@ -1510,33 +1495,11 @@ const resolveServiceInstallInstallation = async (): Promise<IPnpmGlobalInstallat
1510
1495
  return installation;
1511
1496
  };
1512
1497
 
1513
- /** The TLS mode stored for the controller on `portArg`, read under start admission; undefined before its first start. */
1514
- const readStoredControllerTlsMode = async (
1515
- portArg: number,
1516
- installationArg: IPnpmGlobalInstallation,
1517
- ): Promise<TControllerTlsMode | undefined> => {
1518
- await preflightAGLHomeMigration();
1519
- const lease = await acquireStartAdmission('service', installationArg);
1520
- try {
1521
- return await withControllerAuthStore('Reading the stored runtime configuration', async (authStoreArg) => (
1522
- (await authStoreArg.getRuntimeConfig(portArg))?.tlsMode
1523
- ));
1524
- } finally {
1525
- await lease?.release();
1526
- }
1527
- };
1528
-
1529
1498
  const installControllerService = async (argvArg: TParsedArguments): Promise<void> => {
1530
1499
  const overrides = parseRuntimeOverrides(argvArg);
1531
1500
  const port = overrides.controllerPort;
1532
- // Startup options asking for a mode the unit cannot run are refused before anything else is asked.
1533
- assertControllerServiceTlsMode({ requested: overrides, remedy: controllerServiceInstallRemedy });
1534
1501
  const installation = await resolveServiceInstallInstallation();
1535
1502
  const executable = await resolveVerifiedPnpmGlobalShim(installation);
1536
- assertControllerServiceTlsMode({
1537
- stored: await readStoredControllerTlsMode(port, installation),
1538
- remedy: controllerServiceInstallRemedy,
1539
- });
1540
1503
  const service = new AglControllerService();
1541
1504
  const installed = await service.install({ executable, port, overrides: requestedServiceOverrides(overrides) });
1542
1505
  const running = await tryQueryControllerStatus(port);
@@ -1651,6 +1614,8 @@ export interface ICreateCurrentPackageUpgradeTransactionOptions {
1651
1614
  token: string;
1652
1615
  port: number;
1653
1616
  sourceVersion: string;
1617
+ /** The installed source package's `controllerGatewaySourcesVersion` (`IPnpmGlobalInstallation.gatewaySourcesVersion`). */
1618
+ sourceGatewaySourcesVersion?: number;
1654
1619
  registryUrl?: string;
1655
1620
  controllerWasRunning: boolean;
1656
1621
  continueSessions: boolean;
@@ -1767,10 +1732,15 @@ const upgradeController = async (argvArg: TParsedArguments): Promise<void> => {
1767
1732
  if (racedOrphan) {
1768
1733
  throw new Error('An orphaned upgrade appeared after normal upgrade preflight.');
1769
1734
  }
1735
+ // The installation is the installed package this upgrade replaces, its source: the transaction records what that
1736
+ // package's package.json declares, never this build's own constants.
1770
1737
  await createCurrentPackageUpgradeTransaction(coordinator, {
1771
1738
  token: payload.token,
1772
1739
  port,
1773
1740
  sourceVersion: installation.packageVersion,
1741
+ ...(installation.gatewaySourcesVersion === undefined
1742
+ ? {}
1743
+ : { sourceGatewaySourcesVersion: installation.gatewaySourcesVersion }),
1774
1744
  ...(registryUrl === undefined ? {} : { registryUrl }),
1775
1745
  controllerWasRunning,
1776
1746
  continueSessions,
@@ -2109,6 +2079,13 @@ const runCliCommand = async (testArgvArg?: string[]): Promise<void> => {
2109
2079
  await runFeedCli(runtimeArguments.slice(1));
2110
2080
  return;
2111
2081
  }
2082
+ if (runtimeArguments[0] === 'remote') {
2083
+ // It opens the controller's database, and is how a retired trusted-proxy secret moves into it.
2084
+ assertNoRetiredControllerEnvironment(process.env, { allowRemedied: true });
2085
+ const { runRemoteCli } = await import('./functions.remotecli.js');
2086
+ await runRemoteCli(runtimeArguments.slice(1));
2087
+ return;
2088
+ }
2112
2089
  // The console owns the terminal only while it parses and prints help or the version. The selected
2113
2090
  // command, a long-lived controller for foreground and __serve, runs after the console is released.
2114
2091
  let selectedCommand: (() => Promise<void>) | undefined;
@@ -9,10 +9,12 @@ import type {
9
9
  IControllerRuntimeOverrides,
10
10
  TControllerTlsMode,
11
11
  } from './interfaces.config.js';
12
+ import { canonicalGatewaySources } from './functions.controlleradmission.js';
12
13
 
13
14
  export const defaultControllerPort = 4097;
14
15
  export const defaultOpenCodePort = 4098;
15
- export const trustedProxySecretEnvironmentVariable = 'AGL_TRUSTED_PROXY_SECRET';
16
+ /** Where an initialized port's origin, RP ID, TLS mode and gateway sources change. */
17
+ const remoteMoveRemedy = 'Change it with `agl remote set` or `agl remote unset` while the controller is stopped.';
16
18
 
17
19
  export interface IControllerDataDirectoryOptions extends IAGLHomeOptions {}
18
20
 
@@ -133,21 +135,6 @@ export const readDatabaseConfig = (
133
135
  };
134
136
  };
135
137
 
136
- export const readTrustedProxySecret = (tlsModeArg: TControllerTlsMode): string | undefined => {
137
- if (tlsModeArg === 'local') return undefined;
138
- const secret = process.env[trustedProxySecretEnvironmentVariable]?.trim();
139
- if (
140
- !secret
141
- || !/^[A-Za-z0-9_-]{43}$/u.test(secret)
142
- || Buffer.from(secret, 'base64url').byteLength !== 32
143
- ) {
144
- throw new Error(
145
- `${trustedProxySecretEnvironmentVariable} must be a 32-byte base64url secret in proxy mode.`,
146
- );
147
- }
148
- return secret;
149
- };
150
-
151
138
  export const resolveInitialRuntimeConfig = async (
152
139
  overridesArg: IControllerRuntimeOverrides,
153
140
  ): Promise<IControllerRuntimeConfig> => {
@@ -216,16 +203,24 @@ export const resolveStoredRuntimeConfig = async (
216
203
  if (storedArg.tlsMode !== 'proxy' && effectivePort(storedOrigin) !== storedArg.controllerPort) {
217
204
  throw new Error('Stored local public-origin port does not match the controller port.');
218
205
  }
206
+ if (storedArg.gatewaySources !== undefined && (
207
+ storedArg.tlsMode !== 'proxy'
208
+ || !Array.isArray(storedArg.gatewaySources)
209
+ || storedArg.gatewaySources.length === 0
210
+ || canonicalGatewaySources(storedArg.gatewaySources).join(',') !== storedArg.gatewaySources.join(',')
211
+ )) {
212
+ throw new Error('Stored gateway sources are invalid.');
213
+ }
219
214
  if (overridesArg.publicOrigin !== undefined) {
220
215
  const requestedOrigin = normalizeOrigin(overridesArg.publicOrigin).origin;
221
216
  if (requestedOrigin !== storedArg.publicOrigin) {
222
- throw new Error('publicOrigin is immutable after controller initialization.');
217
+ throw new Error(`publicOrigin is immutable after controller initialization. ${remoteMoveRemedy}`);
223
218
  }
224
219
  }
225
220
  if (overridesArg.rpId !== undefined) {
226
221
  const requestedRpId = normalizeRpId(overridesArg.rpId, storedOrigin.hostname);
227
222
  if (requestedRpId !== storedArg.rpId) {
228
- throw new Error('rpId is immutable after controller initialization.');
223
+ throw new Error(`rpId is immutable after controller initialization. ${remoteMoveRemedy}`);
229
224
  }
230
225
  }
231
226
  if (overridesArg.opencodePort !== undefined && overridesArg.opencodePort !== storedArg.opencodePort) {
@@ -233,11 +228,11 @@ export const resolveStoredRuntimeConfig = async (
233
228
  }
234
229
  if (storedArg.tlsMode === 'proxy') {
235
230
  if (overridesArg.behindTlsProxy === false) {
236
- throw new Error('Stored TLS proxy mode is immutable.');
231
+ throw new Error(`Stored TLS proxy mode is immutable. ${remoteMoveRemedy}`);
237
232
  }
238
233
  } else {
239
234
  if (overridesArg.behindTlsProxy) {
240
- throw new Error('Stored localhost mode cannot be changed to TLS mode.');
235
+ throw new Error(`Stored localhost mode cannot be changed to TLS mode. ${remoteMoveRemedy}`);
241
236
  }
242
237
  }
243
238
  if (
@@ -252,5 +247,59 @@ export const resolveStoredRuntimeConfig = async (
252
247
  throw new Error('The projects root is immutable after it has been adopted.');
253
248
  }
254
249
  }
255
- return { ...storedArg };
250
+ return cloneRuntimeConfig(storedArg);
251
+ };
252
+
253
+ const cloneRuntimeConfig = (configArg: IControllerRuntimeConfig): IControllerRuntimeConfig => ({
254
+ controllerPort: configArg.controllerPort,
255
+ publicOrigin: configArg.publicOrigin,
256
+ rpId: configArg.rpId,
257
+ projectsRoot: configArg.projectsRoot,
258
+ opencodePort: configArg.opencodePort,
259
+ tlsMode: configArg.tlsMode,
260
+ ...(configArg.gatewaySources === undefined ? {} : { gatewaySources: [...configArg.gatewaySources] }),
261
+ });
262
+
263
+ /** The public origin `agl remote set` moves a port to, behind a TLS reverse proxy. */
264
+ export interface IControllerRemoteTarget {
265
+ publicOrigin: string;
266
+ /** The origin's hostname when absent. */
267
+ rpId?: string;
268
+ /** May be empty: then only a reverse proxy on this host reaches the controller. */
269
+ gatewaySources: readonly string[];
270
+ }
271
+
272
+ /**
273
+ * The runtime configuration an initialized port moves to: `agl remote set` (a public origin behind a TLS reverse
274
+ * proxy) or `agl remote unset` (`local`: back to `http://localhost:<port>`, RP ID `localhost`). The port, projects root
275
+ * and OpenCode port stay. `storedArg` must already be a validated stored configuration
276
+ * (`resolveStoredRuntimeConfig`). The only path that changes these settings once a port is initialized; a starting
277
+ * controller never does.
278
+ */
279
+ export const resolveMovedRuntimeConfig = (
280
+ storedArg: IControllerRuntimeConfig,
281
+ targetArg: IControllerRemoteTarget | 'local',
282
+ ): IControllerRuntimeConfig => {
283
+ const kept = {
284
+ controllerPort: storedArg.controllerPort,
285
+ projectsRoot: storedArg.projectsRoot,
286
+ opencodePort: storedArg.opencodePort,
287
+ };
288
+ if (targetArg === 'local') {
289
+ return { ...kept, publicOrigin: `http://localhost:${storedArg.controllerPort}`, rpId: 'localhost', tlsMode: 'local' };
290
+ }
291
+ const origin = normalizeOrigin(targetArg.publicOrigin);
292
+ if (origin.protocol !== 'https:') {
293
+ throw new Error('agl remote set takes an HTTPS public origin; `agl remote unset` moves back to localhost.');
294
+ }
295
+ const tlsMode = resolveTlsMode(origin, true);
296
+ const rpId = normalizeRpId(targetArg.rpId ?? origin.hostname, origin.hostname);
297
+ const gatewaySources = canonicalGatewaySources(targetArg.gatewaySources);
298
+ return {
299
+ ...kept,
300
+ publicOrigin: origin.origin,
301
+ rpId,
302
+ tlsMode,
303
+ ...(gatewaySources.length === 0 ? {} : { gatewaySources }),
304
+ };
256
305
  };