agl 41.1.0 → 42.0.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 (106) hide show
  1. package/changelog.md +48 -0
  2. package/dist_serve/bundle.js +2190 -2193
  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 +22 -0
  11. package/dist_ts/classes.authstore.js +152 -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 +12 -12
  17. package/dist_ts/classes.controller.js +46 -117
  18. package/dist_ts/classes.controllermanagement.d.ts +42 -9
  19. package/dist_ts/classes.controllermanagement.js +72 -23
  20. package/dist_ts/classes.controllerservice.d.ts +3 -31
  21. package/dist_ts/classes.controllerservice.js +3 -47
  22. package/dist_ts/classes.inferencegateway.js +4 -3
  23. package/dist_ts/classes.inferenceusage.d.ts +19 -7
  24. package/dist_ts/classes.inferenceusage.js +49 -13
  25. package/dist_ts/classes.inferenceusagetap.d.ts +15 -3
  26. package/dist_ts/classes.inferenceusagetap.js +16 -9
  27. package/dist_ts/classes.mcpcontrollerhost.js +9 -3
  28. package/dist_ts/classes.processinspection.d.ts +8 -1
  29. package/dist_ts/classes.processinspection.js +92 -2
  30. package/dist_ts/classes.proxycontrol.js +6 -1
  31. package/dist_ts/classes.proxydaemon.d.ts +2 -2
  32. package/dist_ts/classes.proxydaemon.js +1 -1
  33. package/dist_ts/classes.proxystore.d.ts +2 -11
  34. package/dist_ts/classes.proxystore.js +3 -25
  35. package/dist_ts/classes.tpmsecretcodec.d.ts +13 -0
  36. package/dist_ts/classes.tpmsecretcodec.js +28 -0
  37. package/dist_ts/classes.trustedproxysecrets.d.ts +91 -0
  38. package/dist_ts/classes.trustedproxysecrets.js +338 -0
  39. package/dist_ts/classes.upgradecoordinator.d.ts +14 -1
  40. package/dist_ts/classes.upgradecoordinator.js +21 -3
  41. package/dist_ts/classes.upgradetransaction.d.ts +32 -0
  42. package/dist_ts/classes.upgradetransaction.js +101 -4
  43. package/dist_ts/classes.usagefeed.js +3 -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.remotecli.d.ts +27 -0
  47. package/dist_ts/functions.remotecli.js +236 -0
  48. package/dist_ts/functions.retiredenvironment.d.ts +11 -2
  49. package/dist_ts/functions.retiredenvironment.js +22 -5
  50. package/dist_ts/index.d.ts +1 -0
  51. package/dist_ts/index.js +2 -1
  52. package/dist_ts/interfaces.auth.d.ts +29 -4
  53. package/dist_ts/interfaces.auth.js +5 -1
  54. package/dist_ts/interfaces.config.d.ts +14 -0
  55. package/dist_ts/interfaces.config.js +9 -2
  56. package/dist_ts/interfaces.lifecycle.d.ts +3 -0
  57. package/dist_ts_authswitch/classes.authoritydaemon.js +6 -1
  58. package/dist_ts_interfaces/interfaces.d.ts +2 -2
  59. package/dist_ts_interfaces/interfaces.js +1 -1
  60. package/dist_ts_interfaces/management.d.ts +2 -2
  61. package/dist_ts_interfaces/management.js +2 -2
  62. package/dist_ts_interfaces/metrics.d.ts +29 -7
  63. package/dist_ts_interfaces/metrics.js +14 -1
  64. package/dist_ts_interfaces/requests.d.ts +1 -2
  65. package/dist_ts_interfaces/requests.js +1 -1
  66. package/dist_ts_interfaces/requests.upgrade.d.ts +0 -12
  67. package/package.json +12 -11
  68. package/readme.md +99 -28
  69. package/ts/00_commitinfo_data.ts +1 -1
  70. package/ts/aglapi/aglapisurface.document.ts +3 -3
  71. package/ts/classes.authmodels.ts +68 -25
  72. package/ts/classes.authstore.ts +151 -24
  73. package/ts/classes.cli.ts +38 -61
  74. package/ts/classes.config.ts +70 -21
  75. package/ts/classes.controller.ts +50 -163
  76. package/ts/classes.controllermanagement.ts +123 -49
  77. package/ts/classes.controllerservice.ts +3 -56
  78. package/ts/classes.inferencegateway.ts +3 -2
  79. package/ts/classes.inferenceusage.ts +58 -19
  80. package/ts/classes.inferenceusagetap.ts +27 -8
  81. package/ts/classes.mcpcontrollerhost.ts +10 -5
  82. package/ts/classes.processinspection.ts +84 -3
  83. package/ts/classes.proxycontrol.ts +2 -0
  84. package/ts/classes.proxydaemon.ts +3 -2
  85. package/ts/classes.proxystore.ts +4 -25
  86. package/ts/classes.tpmsecretcodec.ts +26 -0
  87. package/ts/classes.trustedproxysecrets.ts +317 -0
  88. package/ts/classes.upgradecoordinator.ts +33 -3
  89. package/ts/classes.upgradetransaction.ts +130 -1
  90. package/ts/classes.usagefeed.ts +2 -1
  91. package/ts/functions.controlleradmission.ts +168 -0
  92. package/ts/functions.remotecli.ts +264 -0
  93. package/ts/functions.retiredenvironment.ts +25 -3
  94. package/ts/index.ts +1 -0
  95. package/ts/interfaces.auth.ts +36 -3
  96. package/ts/interfaces.config.ts +15 -0
  97. package/ts/interfaces.lifecycle.ts +3 -0
  98. package/ts_authswitch/classes.authoritydaemon.ts +2 -0
  99. package/ts_interfaces/interfaces.ts +2 -2
  100. package/ts_interfaces/management.ts +2 -2
  101. package/ts_interfaces/metrics.ts +34 -7
  102. package/ts_interfaces/requests.ts +0 -10
  103. package/ts_interfaces/requests.upgrade.ts +0 -16
  104. package/ts_web/00_commitinfo_data.ts +1 -1
  105. package/ts_web/classes.controllersocketclient.ts +5 -2
  106. package/ts_web/elements.metricsboard.ts +68 -18
@@ -4,9 +4,12 @@ import { assertControllerFlexCleanupCohort } from './classes.managedsessionmodel
4
4
  import { isControllerTerminalAgentSessionId } from './functions.terminalagents.js';
5
5
  import { resourceKindAcceptsTerminalSubject } from './functions.resourceattachments.js';
6
6
  import { isAgentMessageSubject } from './functions.agentmessage.js';
7
+ import { canonicalGatewaySources } from './functions.controlleradmission.js';
7
8
  import {
8
9
  controllerAuditEventTypes,
9
10
  type IControllerAuditEvent,
11
+ type IControllerAuditRemoteEndpoint,
12
+ type IControllerAuditRemoteMove,
10
13
  type IControllerAuthDocument,
11
14
  type IControllerTempPasswordDocument,
12
15
  type ISetupAuthorityState,
@@ -97,8 +100,9 @@ const isBoundedPlainJson = (valueArg: unknown, depthArg: number): boolean => {
97
100
  };
98
101
 
99
102
  /**
100
- * An audit event's `details`: this release never writes or reads them; a later release records what its own types
101
- * add there. Bounded plain JSON: an object at most eight levels deep and 4 KiB serialized.
103
+ * An audit event's `details`: what a type records beyond the envelope (this release's `remoteMove` on `remote.set`
104
+ * and `remote.unset`, a later release's own keys on its types). Bounded plain JSON: an object at most eight levels
105
+ * deep and 4 KiB serialized.
102
106
  */
103
107
  const isAuditDetails = (valueArg: unknown): valueArg is Record<string, unknown> =>
104
108
  isPlainObject(valueArg)
@@ -155,6 +159,17 @@ const isValidDate = (valueArg: unknown): valueArg is Date =>
155
159
  const isValidPort = (valueArg: unknown): valueArg is number =>
156
160
  Number.isSafeInteger(valueArg) && (valueArg as number) >= 1 && (valueArg as number) <= 65535;
157
161
 
162
+ /** Stored only in TLS-proxy mode and only while it names an address, canonical and sorted. */
163
+ const isStoredGatewaySources = (valueArg: unknown, tlsModeArg: unknown): boolean => {
164
+ if (tlsModeArg !== 'proxy' || !Array.isArray(valueArg) || valueArg.length === 0
165
+ || !valueArg.every((entryArg) => typeof entryArg === 'string')) return false;
166
+ try {
167
+ return canonicalGatewaySources(valueArg).join(',') === valueArg.join(',');
168
+ } catch {
169
+ return false;
170
+ }
171
+ };
172
+
158
173
  const isRuntimeConfig = (valueArg: unknown): valueArg is IControllerRuntimeConfig => {
159
174
  if (!isPlainObject(valueArg)) return false;
160
175
  if (
@@ -165,7 +180,8 @@ const isRuntimeConfig = (valueArg: unknown): valueArg is IControllerRuntimeConfi
165
180
  'projectsRoot',
166
181
  'opencodePort',
167
182
  'tlsMode',
168
- ])
183
+ ], ['gatewaySources'])
184
+ || (Object.hasOwn(valueArg, 'gatewaySources') && !isStoredGatewaySources(valueArg.gatewaySources, valueArg.tlsMode))
169
185
  || !isNonEmptyString(valueArg.projectsRoot)
170
186
  || !plugins.path.isAbsolute(valueArg.projectsRoot)
171
187
  || plugins.path.normalize(valueArg.projectsRoot) !== valueArg.projectsRoot
@@ -241,29 +257,10 @@ const isStoredCredential = (valueArg: unknown): valueArg is IStoredPasskeyCreden
241
257
  && isBase64Url(valueArg.counterUpdateId, 32);
242
258
  };
243
259
 
244
- /**
245
- * The stored runtime configuration names `gatewaySources`, which only a later release writes (`agl remote set` with
246
- * gateway sources). This release cannot enforce them, so it refuses the document; the message names the one remedy.
247
- */
248
- export class ControllerRuntimeConfigFromLaterReleaseError extends Error {
249
- constructor(controllerPortArg: unknown) {
250
- const port = isValidPort(controllerPortArg) ? String(controllerPortArg) : '<port>';
251
- super(
252
- `The stored runtime configuration of controller:${port} names gatewaySources, which a later AGL release set `
253
- + 'and this release cannot enforce, so it does not start. Run '
254
- + `\`agl remote unset --port ${port}\` on the later release before rolling back.`,
255
- );
256
- this.name = 'ControllerRuntimeConfigFromLaterReleaseError';
257
- }
258
- }
259
-
260
260
  export const assertControllerAuthDocument = (
261
261
  valueArg: unknown,
262
262
  ): asserts valueArg is IControllerAuthDocument => {
263
263
  if (!isPlainObject(valueArg)) throw new Error('Invalid controller authentication document.');
264
- if (isPlainObject(valueArg.config) && Object.hasOwn(valueArg.config, 'gatewaySources')) {
265
- throw new ControllerRuntimeConfigFromLaterReleaseError(valueArg.config.controllerPort);
266
- }
267
264
  if (
268
265
  !hasExactKeys(valueArg, [
269
266
  'id',
@@ -369,12 +366,51 @@ export const assertWebAuthnCeremonyDocument = (
369
366
  }
370
367
  };
371
368
 
369
+ /** A canonical origin with the RP ID it is valid for, as `isRuntimeConfig` holds them; never anything else. */
370
+ const isAuditRemoteEndpoint = (valueArg: unknown): valueArg is IControllerAuditRemoteEndpoint => {
371
+ if (
372
+ !isPlainObject(valueArg)
373
+ || !hasExactKeys(valueArg, ['publicOrigin', 'rpId'])
374
+ || !isNonEmptyString(valueArg.publicOrigin)
375
+ || valueArg.publicOrigin.length > 512
376
+ || !isNonEmptyString(valueArg.rpId)
377
+ || valueArg.rpId.length > 253
378
+ || valueArg.rpId !== valueArg.rpId.toLowerCase()
379
+ || /[/:\s]/.test(valueArg.rpId)
380
+ ) {
381
+ return false;
382
+ }
383
+ try {
384
+ const origin = new URL(valueArg.publicOrigin);
385
+ const hostname = origin.hostname.toLowerCase().replace(/\.$/, '');
386
+ return origin.origin === valueArg.publicOrigin
387
+ && (origin.protocol === 'http:' || origin.protocol === 'https:')
388
+ && (hostname === valueArg.rpId || hostname.endsWith(`.${valueArg.rpId}`));
389
+ } catch {
390
+ return false;
391
+ }
392
+ };
393
+
394
+ const isAuditRemoteMove = (valueArg: unknown): valueArg is IControllerAuditRemoteMove => isPlainObject(valueArg)
395
+ && hasExactKeys(valueArg, ['previous', 'target'])
396
+ && isAuditRemoteEndpoint(valueArg.previous)
397
+ && isAuditRemoteEndpoint(valueArg.target);
398
+
399
+ /**
400
+ * `details` on a type this release knows: only `remote.set` and `remote.unset` record a `remoteMove`, and only a move
401
+ * from one canonical origin and RP ID to another.
402
+ */
403
+ const hasKnownAuditDetails = (typeArg: string, detailsArg: Record<string, unknown>): boolean =>
404
+ !Object.hasOwn(detailsArg, 'remoteMove')
405
+ || ((typeArg === 'remote.set' || typeArg === 'remote.unset') && isAuditRemoteMove(detailsArg.remoteMove));
406
+
372
407
  /**
373
408
  * A stored audit event. The log is shared with later releases, so a type this release does not know (a later
374
409
  * release's, read back after a rollback) is accepted when it is spelled as an audit type: its envelope is checked as
375
410
  * strictly as a known type's, and only the rules that tie a field to particular types (`senderLabel` to
376
411
  * `session.message`, `localCli` to `configuration.*`) are left to the release that knows the type. A known type keeps
377
- * every check. `details` is bounded plain JSON on any type.
412
+ * every check. `details` is bounded plain JSON on any type; on a known type its `remoteMove` is checked strictly
413
+ * (`hasKnownAuditDetails`).
378
414
  */
379
415
  export const assertControllerAuditEventDocument = (
380
416
  valueArg: unknown,
@@ -405,12 +441,19 @@ export const assertControllerAuditEventDocument = (
405
441
  Object.hasOwn(valueArg, 'senderLabel')
406
442
  && ((known && type !== 'session.message') || !isControllerAgentMessageSender(valueArg.senderLabel))
407
443
  )
408
- || (Object.hasOwn(valueArg, 'details') && !isAuditDetails(valueArg.details))
444
+ || (
445
+ Object.hasOwn(valueArg, 'details')
446
+ && (!isAuditDetails(valueArg.details) || (known && !hasKnownAuditDetails(type, valueArg.details)))
447
+ )
409
448
  ) {
410
449
  throw new Error('Invalid controller audit event.');
411
450
  }
412
451
  if (Object.hasOwn(valueArg, 'localCli')) {
413
- if (known && !type.startsWith('configuration.')) throw new Error('Invalid local configuration audit event.');
452
+ // Local configuration and the offline `agl remote` commands are the actions a local OS user takes; a type this
453
+ // release does not know leaves that rule to the release that knows it.
454
+ if (known && !type.startsWith('configuration.') && !type.startsWith('remote.')) {
455
+ throw new Error('Invalid local configuration audit event.');
456
+ }
414
457
  assertConfigurationLocalCliActor(valueArg.localCli);
415
458
  }
416
459
  for (const optionalKey of [
@@ -7,6 +7,7 @@ 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';
10
11
  import { ControllerClaudeSessionStore } from './classes.claudesessionstore.js';
11
12
  import { ControllerClaudeSessionModel } from './classes.claudesessionmodels.js';
12
13
  import { ControllerPendingPromptStore } from './classes.pendingpromptstore.js';
@@ -44,7 +45,6 @@ import {
44
45
  import {
45
46
  ControllerAuditEventModel,
46
47
  ControllerAuthModel,
47
- ControllerRuntimeConfigFromLaterReleaseError,
48
48
  ControllerPendingPromptModel,
49
49
  ControllerProjectModel,
50
50
  ControllerResourceModel,
@@ -203,24 +203,6 @@ const auditPruneMaxBatchesPerSweep = 50;
203
203
  const auditCountPruneMaxBatchesPerSweep = 250;
204
204
  const auditPruneIntervalMs = 30 * 60 * 1000;
205
205
 
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
206
  /** A concurrent prune that removed an event first leaves nothing to do for it. */
225
207
  const deleteStoredAuditEvents = async (
226
208
  eventsArg: Array<plugins.nosqldb.TStoredDocument<IControllerAuditEvent>>,
@@ -455,6 +437,7 @@ const cloneRuntimeConfig = (
455
437
  projectsRoot: runtimeConfigArg.projectsRoot,
456
438
  opencodePort: runtimeConfigArg.opencodePort,
457
439
  tlsMode: runtimeConfigArg.tlsMode,
440
+ ...(runtimeConfigArg.gatewaySources === undefined ? {} : { gatewaySources: [...runtimeConfigArg.gatewaySources] }),
458
441
  });
459
442
 
460
443
  const runtimeConfigsEqual = (
@@ -465,7 +448,8 @@ const runtimeConfigsEqual = (
465
448
  && leftArg.rpId === rightArg.rpId
466
449
  && leftArg.projectsRoot === rightArg.projectsRoot
467
450
  && leftArg.opencodePort === rightArg.opencodePort
468
- && leftArg.tlsMode === rightArg.tlsMode;
451
+ && leftArg.tlsMode === rightArg.tlsMode
452
+ && (leftArg.gatewaySources ?? []).join(',') === (rightArg.gatewaySources ?? []).join(',');
469
453
 
470
454
  const hashSetupCode = (setupCodeArg: string): string =>
471
455
  plugins.crypto.createHash('sha256').update(setupCodeArg, 'utf8').digest('base64url');
@@ -816,6 +800,7 @@ const setAuthStoreModelManager = (
816
800
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerCodexTurnModel);
817
801
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexTranscriptGrantModel);
818
802
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerTrackedConversationModel);
803
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerTrustedProxySecretModel);
819
804
  plugins.nosqldb.setDefaultManagerForDoc(
820
805
  managerArg,
821
806
  ControllerLegacyManagedSessionMigrationModel,
@@ -1100,6 +1085,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1100
1085
  await ControllerCodexTurnModel.init();
1101
1086
  await FlexTranscriptGrantModel.init();
1102
1087
  await ControllerTrackedConversationModel.init();
1088
+ await ControllerTrustedProxySecretModel.init();
1103
1089
  await new PostDatabaseDocumentMigrationRunner(this.database).run();
1104
1090
  this.initialized = true;
1105
1091
  if (!this.closeStarted) this.projectMutationAdmissionOpen = true;
@@ -1313,6 +1299,80 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1313
1299
  }
1314
1300
  }
1315
1301
 
1302
+ /**
1303
+ * Reads the stored runtime configuration of `controllerPortArg` without running this release on the store: only
1304
+ * the configuration's own collection is prepared (it holds the same declaration in every release that reads it),
1305
+ * no migration runs and no other collection or index is created, so a release older than this one still starts on
1306
+ * the store afterwards. The store is closed before this returns and cannot be initialized afterwards. For checks
1307
+ * made before an older release is put back, such as an upgrade recovery that is about to restore one.
1308
+ */
1309
+ public async readRuntimeConfigOnly(
1310
+ controllerPortArg: number,
1311
+ ): Promise<IControllerRuntimeConfig | undefined> {
1312
+ if (
1313
+ !Number.isSafeInteger(controllerPortArg)
1314
+ || controllerPortArg < 1
1315
+ || controllerPortArg > 65535
1316
+ ) {
1317
+ throw new Error('controllerPort must be an integer between 1 and 65535.');
1318
+ }
1319
+ if (this.closeStarted || this.initPromise || this.initialized || this.database || this.embeddedDatabase) {
1320
+ throw new Error('SmartDataAuthStore reads a runtime configuration only on a store it has not opened.');
1321
+ }
1322
+ this.closeStarted = true;
1323
+ let databaseInitialized = false;
1324
+ let result: IControllerRuntimeConfig | undefined;
1325
+ let readError: unknown;
1326
+ try {
1327
+ this.releaseModelOwnership = claimAuthStoreModelOwnership(this.modelOwner, this.smartDataManager);
1328
+ let mongoDbUrl = this.options.mongoDbUrl?.trim();
1329
+ if (!mongoDbUrl) {
1330
+ const embedded = new EmbeddedControllerDatabase({ dataDirectory: this.options.embeddedDataDirectory! });
1331
+ this.embeddedDatabase = embedded;
1332
+ mongoDbUrl = await embedded.start();
1333
+ }
1334
+ this.database = new plugins.nosqldb.SmartdataDb({ mongoDbUrl, mongoDbName: this.options.mongoDbName });
1335
+ await this.db.init();
1336
+ databaseInitialized = true;
1337
+ await ControllerAuthModel.init();
1338
+ const stored = await ControllerAuthModel.exact.findStoredOne({ id: `controller:${controllerPortArg}` });
1339
+ result = stored ? cloneRuntimeConfig(ControllerAuthModel.exact.toPersisted(stored).config) : undefined;
1340
+ } catch (errorArg) {
1341
+ readError = errorArg;
1342
+ }
1343
+ const cleanupErrors: unknown[] = [];
1344
+ if (this.database) {
1345
+ if (databaseInitialized) {
1346
+ try {
1347
+ await this.database.close();
1348
+ this.database = undefined;
1349
+ } catch (closeErrorArg) {
1350
+ cleanupErrors.push(closeErrorArg);
1351
+ }
1352
+ } else {
1353
+ this.database = undefined;
1354
+ }
1355
+ }
1356
+ if (!this.database) {
1357
+ try {
1358
+ await this.stopEmbeddedDatabase();
1359
+ } catch (stopErrorArg) {
1360
+ cleanupErrors.push(stopErrorArg);
1361
+ }
1362
+ }
1363
+ try {
1364
+ this.releaseModelOwnershipIfResourcesClosed();
1365
+ } catch (releaseErrorArg) {
1366
+ cleanupErrors.push(releaseErrorArg);
1367
+ }
1368
+ if (readError !== undefined || cleanupErrors.length > 0) {
1369
+ const errors = readError === undefined ? cleanupErrors : [readError, ...cleanupErrors];
1370
+ if (errors.length === 1) throw errors[0];
1371
+ throw new AggregateError(errors, 'Reading the stored runtime configuration failed and cleanup was incomplete.');
1372
+ }
1373
+ return result;
1374
+ }
1375
+
1316
1376
  public async getRuntimeConfig(
1317
1377
  controllerPortArg: number,
1318
1378
  ): Promise<IControllerRuntimeConfig | undefined> {
@@ -1325,7 +1385,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1325
1385
  throw new Error('controllerPort must be an integer between 1 and 65535.');
1326
1386
  }
1327
1387
  this.controllerId = `controller:${controllerPortArg}`;
1328
- const stored = await findStoredAuthDocument(this.controllerId);
1388
+ const stored = await ControllerAuthModel.exact.findStoredOne({ id: this.controllerId });
1329
1389
  if (!stored) return undefined;
1330
1390
  return cloneRuntimeConfig(ControllerAuthModel.exact.toPersisted(stored).config);
1331
1391
  }
@@ -1355,7 +1415,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1355
1415
  }
1356
1416
  const controllerId = `controller:${runtimeConfigArg.controllerPort}`;
1357
1417
  this.controllerId = controllerId;
1358
- const existing = await findStoredAuthDocument(controllerId);
1418
+ const existing = await ControllerAuthModel.exact.findStoredOne({ id: controllerId });
1359
1419
  if (existing) {
1360
1420
  const document = ControllerAuthModel.exact.toPersisted(existing);
1361
1421
  return this.finalizeRuntimeConfigDocument(document, runtimeConfigArg);
@@ -1375,7 +1435,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1375
1435
  return this.finalizeRuntimeConfigDocument(document, runtimeConfigArg);
1376
1436
  } catch (errorArg) {
1377
1437
  if (!isAmbiguousWrite(errorArg)) throw errorArg;
1378
- const reconciled = await findStoredAuthDocument(controllerId);
1438
+ const reconciled = await ControllerAuthModel.exact.findStoredOne({ id: controllerId });
1379
1439
  if (!reconciled) {
1380
1440
  throw new AuthError(
1381
1441
  'ambiguous_write',
@@ -1447,6 +1507,59 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1447
1507
  }
1448
1508
  }
1449
1509
 
1510
+ /**
1511
+ * Moves the runtime configuration of the port `getRuntimeConfig` resolved to `targetArg` (`agl remote set` and
1512
+ * `unset`, against a stopped controller only; a starting controller never changes it). The controller keeps its
1513
+ * id and every record. When the origin or RP ID changes, the passkey enrollment is removed, since a passkey is bound
1514
+ * to its RP ID, and every temporary password of the controller is revoked first, so nothing that signed in to the
1515
+ * old origin signs in to the new one: the controller then starts in setup and its start prints a fresh setup code.
1516
+ */
1517
+ public async moveRuntimeConfig(targetArg: IControllerRuntimeConfig): Promise<{
1518
+ previous: IControllerRuntimeConfig;
1519
+ changed: boolean;
1520
+ enrollmentReset: boolean;
1521
+ }> {
1522
+ const stored = await this.findStoredState();
1523
+ const current = ControllerAuthModel.exact.toPersisted(stored);
1524
+ if (targetArg.controllerPort !== current.config.controllerPort) {
1525
+ throw new AuthError('config_mismatch', 'A runtime configuration moves only within its own port.');
1526
+ }
1527
+ const previous = cloneRuntimeConfig(current.config);
1528
+ if (runtimeConfigsEqual(current.config, targetArg)) return { previous, changed: false, enrollmentReset: false };
1529
+ const enrollmentReset = current.config.publicOrigin !== targetArg.publicOrigin || current.config.rpId !== targetArg.rpId;
1530
+ if (enrollmentReset) await this.revokeTempPasswords();
1531
+ const result = await ControllerAuthModel.exact.transition({
1532
+ current: stored,
1533
+ change: (model) => {
1534
+ model.config = cloneRuntimeConfig(targetArg);
1535
+ if (!enrollmentReset) return;
1536
+ model.credentials = [];
1537
+ model.authState = 'setupRequired';
1538
+ model.setup = null;
1539
+ },
1540
+ });
1541
+ if (result.status !== 'transitioned') {
1542
+ throw new AuthError('concurrent_change', 'The controller configuration changed concurrently and was not moved.');
1543
+ }
1544
+ return { previous, changed: true, enrollmentReset };
1545
+ }
1546
+
1547
+ /** Deletes every temporary password of this controller, expired or not. */
1548
+ private async revokeTempPasswords(): Promise<void> {
1549
+ const controllerId = this.requireControllerId();
1550
+ for (;;) {
1551
+ const batch = await ControllerTempPasswordModel.exact.findStored({ filter: { controllerId }, limit: tempPasswordPruneBatchSize });
1552
+ if (batch.length === 0) return;
1553
+ for (const current of batch) {
1554
+ const deleted = await ControllerTempPasswordModel.exact.delete({ current });
1555
+ const { id } = ControllerTempPasswordModel.exact.toPersisted(current);
1556
+ if (deleted.status !== 'deleted' && await ControllerTempPasswordModel.exact.findStoredOne({ id })) {
1557
+ throw new AuthError('concurrent_change', 'A temporary password could not be revoked.');
1558
+ }
1559
+ }
1560
+ }
1561
+ }
1562
+
1450
1563
  public async getState(): Promise<IControllerAuthDocument> {
1451
1564
  const stored = await this.findStoredState();
1452
1565
  return ControllerAuthModel.exact.toPersisted(stored);
@@ -1765,6 +1878,20 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1765
1878
  ...(eventArg.requestId === undefined ? {} : { requestId: { ...eventArg.requestId } }),
1766
1879
  ...(eventArg.senderLabel === undefined ? {} : { senderLabel: eventArg.senderLabel }),
1767
1880
  ...(eventArg.localCli === undefined ? {} : { localCli: { ...eventArg.localCli } }),
1881
+ ...(eventArg.details === undefined ? {} : {
1882
+ details: {
1883
+ remoteMove: {
1884
+ previous: {
1885
+ publicOrigin: eventArg.details.remoteMove.previous.publicOrigin,
1886
+ rpId: eventArg.details.remoteMove.previous.rpId,
1887
+ },
1888
+ target: {
1889
+ publicOrigin: eventArg.details.remoteMove.target.publicOrigin,
1890
+ rpId: eventArg.details.remoteMove.target.rpId,
1891
+ },
1892
+ },
1893
+ },
1894
+ }),
1768
1895
  };
1769
1896
  try {
1770
1897
  const result = await ControllerAuditEventModel.exact.insert(event);
@@ -2345,7 +2472,7 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
2345
2472
  if (!this.controllerId) {
2346
2473
  throw new AuthError('not_initialized', 'The controller runtime configuration is unresolved.');
2347
2474
  }
2348
- const stored = await findStoredAuthDocument(this.controllerId);
2475
+ const stored = await ControllerAuthModel.exact.findStoredOne({ id: this.controllerId });
2349
2476
  if (!stored) {
2350
2477
  throw new AuthError('not_initialized', 'The controller authentication document is missing.');
2351
2478
  }
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;