agl 41.2.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 (91) hide show
  1. package/changelog.md +35 -0
  2. package/dist_serve/bundle.js +1996 -1999
  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.mcpcontrollerhost.js +9 -3
  23. package/dist_ts/classes.processinspection.d.ts +8 -1
  24. package/dist_ts/classes.processinspection.js +92 -2
  25. package/dist_ts/classes.proxycontrol.js +6 -1
  26. package/dist_ts/classes.proxydaemon.d.ts +2 -2
  27. package/dist_ts/classes.proxydaemon.js +1 -1
  28. package/dist_ts/classes.proxystore.d.ts +2 -11
  29. package/dist_ts/classes.proxystore.js +3 -25
  30. package/dist_ts/classes.tpmsecretcodec.d.ts +13 -0
  31. package/dist_ts/classes.tpmsecretcodec.js +28 -0
  32. package/dist_ts/classes.trustedproxysecrets.d.ts +91 -0
  33. package/dist_ts/classes.trustedproxysecrets.js +338 -0
  34. package/dist_ts/classes.upgradecoordinator.d.ts +14 -1
  35. package/dist_ts/classes.upgradecoordinator.js +21 -3
  36. package/dist_ts/classes.upgradetransaction.d.ts +32 -0
  37. package/dist_ts/classes.upgradetransaction.js +101 -4
  38. package/dist_ts/functions.controlleradmission.d.ts +67 -0
  39. package/dist_ts/functions.controlleradmission.js +127 -0
  40. package/dist_ts/functions.remotecli.d.ts +27 -0
  41. package/dist_ts/functions.remotecli.js +236 -0
  42. package/dist_ts/functions.retiredenvironment.d.ts +11 -2
  43. package/dist_ts/functions.retiredenvironment.js +22 -5
  44. package/dist_ts/index.d.ts +1 -0
  45. package/dist_ts/index.js +2 -1
  46. package/dist_ts/interfaces.auth.d.ts +29 -4
  47. package/dist_ts/interfaces.auth.js +5 -1
  48. package/dist_ts/interfaces.config.d.ts +14 -0
  49. package/dist_ts/interfaces.config.js +9 -2
  50. package/dist_ts/interfaces.lifecycle.d.ts +3 -0
  51. package/dist_ts_authswitch/classes.authoritydaemon.js +6 -1
  52. package/dist_ts_interfaces/interfaces.d.ts +2 -2
  53. package/dist_ts_interfaces/interfaces.js +1 -1
  54. package/dist_ts_interfaces/management.d.ts +2 -2
  55. package/dist_ts_interfaces/management.js +2 -2
  56. package/dist_ts_interfaces/requests.d.ts +1 -2
  57. package/dist_ts_interfaces/requests.js +1 -1
  58. package/dist_ts_interfaces/requests.upgrade.d.ts +0 -12
  59. package/package.json +12 -11
  60. package/readme.md +84 -24
  61. package/ts/00_commitinfo_data.ts +1 -1
  62. package/ts/aglapi/aglapisurface.document.ts +3 -3
  63. package/ts/classes.authmodels.ts +68 -25
  64. package/ts/classes.authstore.ts +151 -24
  65. package/ts/classes.cli.ts +38 -61
  66. package/ts/classes.config.ts +70 -21
  67. package/ts/classes.controller.ts +50 -163
  68. package/ts/classes.controllermanagement.ts +123 -49
  69. package/ts/classes.controllerservice.ts +3 -56
  70. package/ts/classes.mcpcontrollerhost.ts +10 -5
  71. package/ts/classes.processinspection.ts +84 -3
  72. package/ts/classes.proxycontrol.ts +2 -0
  73. package/ts/classes.proxydaemon.ts +3 -2
  74. package/ts/classes.proxystore.ts +4 -25
  75. package/ts/classes.tpmsecretcodec.ts +26 -0
  76. package/ts/classes.trustedproxysecrets.ts +317 -0
  77. package/ts/classes.upgradecoordinator.ts +33 -3
  78. package/ts/classes.upgradetransaction.ts +130 -1
  79. package/ts/functions.controlleradmission.ts +168 -0
  80. package/ts/functions.remotecli.ts +264 -0
  81. package/ts/functions.retiredenvironment.ts +25 -3
  82. package/ts/index.ts +1 -0
  83. package/ts/interfaces.auth.ts +36 -3
  84. package/ts/interfaces.config.ts +15 -0
  85. package/ts/interfaces.lifecycle.ts +3 -0
  86. package/ts_authswitch/classes.authoritydaemon.ts +2 -0
  87. package/ts_interfaces/interfaces.ts +2 -2
  88. package/ts_interfaces/management.ts +2 -2
  89. package/ts_interfaces/requests.ts +0 -10
  90. package/ts_interfaces/requests.upgrade.ts +0 -16
  91. package/ts_web/00_commitinfo_data.ts +1 -1
@@ -0,0 +1,317 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { ITpmSecretCodec } from './classes.tpmsecretcodec.js';
3
+
4
+ /** One sealed generation of a controller's trusted-proxy secret. */
5
+ export interface IControllerTrustedProxySealedSecret {
6
+ /** Grows with every rotation and import; the secret is sealed under a name that binds it. */
7
+ generation: number;
8
+ /** TPM2-sealed (`TpmSecretCodec`); the plaintext exists only in the running controller and its gateway's route. */
9
+ ciphertext: string;
10
+ }
11
+
12
+ export interface IControllerTrustedProxySecretDocument {
13
+ /** The controller's id, `controller:<port>`. */
14
+ id: string;
15
+ /** The secret the controller accepts and its reverse proxy injects. */
16
+ active: IControllerTrustedProxySealedSecret;
17
+ /**
18
+ * A rotation its gateway's route does not carry yet: accepted beside `active` until `confirm` makes it the active
19
+ * one. Present only while a rotation is in progress.
20
+ */
21
+ next?: IControllerTrustedProxySealedSecret;
22
+ }
23
+
24
+ const isSealedSecret = (valueArg: unknown): valueArg is IControllerTrustedProxySealedSecret => {
25
+ const value = valueArg as Partial<IControllerTrustedProxySealedSecret> | null;
26
+ return !!value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 2
27
+ && Number.isSafeInteger(value.generation) && value.generation! >= 1
28
+ && typeof value.ciphertext === 'string' && /^[A-Za-z0-9_-]{1,131072}$/u.test(value.ciphertext);
29
+ };
30
+
31
+ const assertDocument: (valueArg: unknown) => asserts valueArg is IControllerTrustedProxySecretDocument = (valueArg) => {
32
+ const value = valueArg as Partial<IControllerTrustedProxySecretDocument> | null;
33
+ if (!value || typeof value !== 'object'
34
+ || Object.keys(value).length !== (Object.hasOwn(value, 'next') ? 3 : 2)
35
+ || typeof value.id !== 'string' || !/^controller:[1-9][0-9]{0,4}$/u.test(value.id)
36
+ || !isSealedSecret(value.active)
37
+ || (Object.hasOwn(value, 'next') && (!isSealedSecret(value.next) || value.next.generation !== value.active.generation + 1))) {
38
+ throw new Error('Invalid trusted-proxy secret record.');
39
+ }
40
+ };
41
+
42
+ @plugins.nosqldb.managed({ collectionName: 'agl_controller_trusted_proxy_secrets' })
43
+ @plugins.nosqldb.exactPersistence({ assertDocument })
44
+ export class ControllerTrustedProxySecretModel
45
+ extends plugins.nosqldb.SmartDataDbDoc<ControllerTrustedProxySecretModel, IControllerTrustedProxySecretDocument> {
46
+ declare static exact: plugins.nosqldb.TExact<ControllerTrustedProxySecretModel>;
47
+ @plugins.nosqldb.unI() public id!: string;
48
+ @plugins.nosqldb.svDb() public active!: IControllerTrustedProxySealedSecret;
49
+ @plugins.nosqldb.svDb() public next?: IControllerTrustedProxySealedSecret;
50
+ }
51
+
52
+ /** What a reverse proxy injects as `X-Harness-Controller-Proxy-Secret`: 32 random bytes, base64url (43 characters). */
53
+ const trustedProxySecretPattern = /^[A-Za-z0-9_-]{43}$/u;
54
+
55
+ /** The bytes a well-formed secret encodes; refused, naming the format but never the value, otherwise. */
56
+ export const decodeTrustedProxySecret = (valueArg: string): Buffer => {
57
+ const refusal = 'A trusted-proxy secret is 32 bytes, base64url-encoded (43 characters).';
58
+ if (!trustedProxySecretPattern.test(valueArg)) throw new Error(refusal);
59
+ const bytes = Buffer.from(valueArg, 'base64url');
60
+ if (bytes.byteLength !== 32 || bytes.toString('base64url') !== valueArg) {
61
+ bytes.fill(0);
62
+ throw new Error(refusal);
63
+ }
64
+ return bytes;
65
+ };
66
+
67
+ export interface IControllerTrustedProxySecretsOptions {
68
+ /** `controller:<port>`. */
69
+ controllerId: string;
70
+ /** The controller database's issuer id: the secret is sealed under a name bound to it. */
71
+ issuerId: string;
72
+ codec: ITpmSecretCodec;
73
+ }
74
+
75
+ /** The secret a gateway's route must carry, and the generation `confirm` names once the route carries it. */
76
+ export interface IControllerTrustedProxyRouteSecret {
77
+ secret: string;
78
+ generation: number;
79
+ }
80
+
81
+ interface IOpenSecret {
82
+ generation: number;
83
+ /** The base64url text's bytes, compared in constant time and wiped on close. */
84
+ text: Buffer;
85
+ }
86
+
87
+ const sealName = (optionsArg: Pick<IControllerTrustedProxySecretsOptions, 'controllerId' | 'issuerId'>, generationArg: number): string =>
88
+ `agl-controller.${optionsArg.issuerId.slice(0, 22)}.${optionsArg.controllerId.replace(':', '-')}.trusted-proxy.${generationArg}`;
89
+
90
+ const sealSecret = async (
91
+ optionsArg: IControllerTrustedProxySecretsOptions,
92
+ generationArg: number,
93
+ bytesArg: Buffer,
94
+ ): Promise<IControllerTrustedProxySealedSecret> => ({
95
+ generation: generationArg,
96
+ ciphertext: await optionsArg.codec.seal(sealName(optionsArg, generationArg), bytesArg),
97
+ });
98
+
99
+ const unsealSecret = async (
100
+ optionsArg: IControllerTrustedProxySecretsOptions,
101
+ sealedArg: IControllerTrustedProxySealedSecret,
102
+ ): Promise<IOpenSecret> => {
103
+ let bytes: Uint8Array;
104
+ try {
105
+ bytes = await optionsArg.codec.unseal(sealName(optionsArg, sealedArg.generation), sealedArg.ciphertext);
106
+ } catch (errorArg) {
107
+ throw new Error(`The trusted-proxy secret of ${optionsArg.controllerId} cannot be unsealed on this machine. Stop `
108
+ + 'the controller and import a secret with `agl remote secret import`.', { cause: errorArg });
109
+ }
110
+ try {
111
+ if (bytes.byteLength !== 32) throw new Error(`The sealed trusted-proxy secret of ${optionsArg.controllerId} is invalid.`);
112
+ return { generation: sealedArg.generation, text: Buffer.from(Buffer.from(bytes).toString('base64url'), 'utf8') };
113
+ } finally {
114
+ bytes.fill(0);
115
+ }
116
+ };
117
+
118
+ const readRecord = (controllerIdArg: string) => ControllerTrustedProxySecretModel.exact.findStoredOne({ id: controllerIdArg });
119
+
120
+ type TStoredRecord = NonNullable<Awaited<ReturnType<typeof readRecord>>>;
121
+
122
+ /**
123
+ * The trusted-proxy secret of a controller in TLS-proxy mode: AGL generates it, keeps it TPM2-sealed in the
124
+ * controller's database and hands it only to its own gateway's route (or an operator imports it for another reverse
125
+ * proxy). Admission accepts the active secret and, while a rotation is in progress, the next one: a rotation keeps
126
+ * the previous secret valid until the route carrying the new one is confirmed. One running controller owns the
127
+ * record; the offline `agl remote` commands write it only while that controller is stopped.
128
+ */
129
+ export class ControllerTrustedProxySecrets {
130
+ private mutationTail = Promise.resolve();
131
+ private closed = false;
132
+
133
+ private constructor(
134
+ private readonly options: IControllerTrustedProxySecretsOptions,
135
+ private active: IOpenSecret,
136
+ private next: IOpenSecret | undefined,
137
+ ) {}
138
+
139
+ /** Opens the record of `controllerId`, generating and sealing the first secret when it has none. */
140
+ public static async open(optionsArg: IControllerTrustedProxySecretsOptions): Promise<ControllerTrustedProxySecrets> {
141
+ let stored = await readRecord(optionsArg.controllerId);
142
+ if (!stored) {
143
+ const bytes = plugins.crypto.randomBytes(32);
144
+ let active: IControllerTrustedProxySealedSecret;
145
+ try { active = await sealSecret(optionsArg, 1, bytes); } finally { bytes.fill(0); }
146
+ const inserted = await ControllerTrustedProxySecretModel.exact.insert({ id: optionsArg.controllerId, active });
147
+ if (inserted.status !== 'inserted' && inserted.status !== 'already_committed' && inserted.status !== 'conflict') {
148
+ throw new Error('The trusted-proxy secret could not be stored.');
149
+ }
150
+ stored = await readRecord(optionsArg.controllerId);
151
+ if (!stored) throw new Error('The trusted-proxy secret could not be read back.');
152
+ }
153
+ const record = ControllerTrustedProxySecretModel.exact.toPersisted(stored);
154
+ const active = await unsealSecret(optionsArg, record.active);
155
+ try {
156
+ const next = record.next ? await unsealSecret(optionsArg, record.next) : undefined;
157
+ return new ControllerTrustedProxySecrets(optionsArg, active, next);
158
+ } catch (errorArg) {
159
+ active.text.fill(0);
160
+ throw errorArg;
161
+ }
162
+ }
163
+
164
+ /** Whether a request's header value is the active secret or the rotation's; constant time per secret. */
165
+ public accepts(valueArg: string | null): boolean {
166
+ if (valueArg === null || this.closed) return false;
167
+ const candidate = Buffer.from(valueArg, 'utf8');
168
+ let accepted = false;
169
+ for (const secret of [this.active, this.next]) {
170
+ if (secret && candidate.byteLength === secret.text.byteLength
171
+ && plugins.crypto.timingSafeEqual(candidate, secret.text)) accepted = true;
172
+ }
173
+ return accepted;
174
+ }
175
+
176
+ /** The secret the gateway's route must carry: the rotation's while one is in progress, else the active one. */
177
+ public routeSecret(): IControllerTrustedProxyRouteSecret {
178
+ this.assertOpen();
179
+ const secret = this.next ?? this.active;
180
+ return { secret: secret.text.toString('utf8'), generation: secret.generation };
181
+ }
182
+
183
+ /**
184
+ * Starts a rotation: a new secret, accepted beside the active one from now on, which the route must carry next.
185
+ * A rotation already in progress is returned again, so a sync that failed is retried with the same secret.
186
+ */
187
+ public rotate(): Promise<IControllerTrustedProxyRouteSecret> {
188
+ return this.mutate(async () => {
189
+ if (this.next) return { secret: this.next.text.toString('utf8'), generation: this.next.generation };
190
+ const current = await this.readOwnRecord();
191
+ const generation = this.active.generation + 1;
192
+ const bytes = plugins.crypto.randomBytes(32);
193
+ const text = Buffer.from(bytes.toString('base64url'), 'utf8');
194
+ let installed = false;
195
+ try {
196
+ let next: IControllerTrustedProxySealedSecret;
197
+ try {
198
+ next = await sealSecret(this.options, generation, bytes);
199
+ } finally {
200
+ bytes.fill(0);
201
+ }
202
+ this.assertOpen();
203
+ const result = await ControllerTrustedProxySecretModel.exact.transition({ current, change: (modelArg) => {
204
+ modelArg.next = next;
205
+ } });
206
+ if (result.status !== 'transitioned') throw new Error('The trusted-proxy secret changed concurrently.');
207
+ // Closed while the rotation was being stored: it is not installed here; the next open resumes it.
208
+ this.assertOpen();
209
+ this.next = { generation, text };
210
+ installed = true;
211
+ return { secret: text.toString('utf8'), generation };
212
+ } finally {
213
+ if (!installed) text.fill(0);
214
+ }
215
+ });
216
+ }
217
+
218
+ /**
219
+ * Ends a rotation once the route carries generation `generationArg`: it becomes the active secret and the previous
220
+ * one is refused from then on. Confirming the active generation again changes nothing; any other is refused.
221
+ */
222
+ public confirm(generationArg: number): Promise<void> {
223
+ return this.mutate(async () => {
224
+ if (!this.next && this.active.generation === generationArg) return;
225
+ if (!this.next || this.next.generation !== generationArg) {
226
+ throw new Error(`Generation ${generationArg} is not the trusted-proxy secret rotation in progress.`);
227
+ }
228
+ const current = await this.readOwnRecord();
229
+ const result = await ControllerTrustedProxySecretModel.exact.transition({ current, change: (modelArg) => {
230
+ modelArg.active = modelArg.next!;
231
+ delete modelArg.next;
232
+ } });
233
+ if (result.status !== 'transitioned') throw new Error('The trusted-proxy secret changed concurrently.');
234
+ // Closed while the confirmation was being stored: it stays stored, and the next open loads it as the active one.
235
+ this.assertOpen();
236
+ this.active.text.fill(0);
237
+ this.active = this.next;
238
+ this.next = undefined;
239
+ });
240
+ }
241
+
242
+ /**
243
+ * Forgets the secrets in memory; the record stays. A rotation or confirmation still running fails, and what it
244
+ * stored meanwhile is not installed: the next open resumes the rotation or loads the confirmed secret.
245
+ */
246
+ public close(): void {
247
+ this.closed = true;
248
+ this.active.text.fill(0);
249
+ this.next?.text.fill(0);
250
+ this.next = undefined;
251
+ }
252
+
253
+ private assertOpen(): void {
254
+ if (this.closed) throw new Error('The trusted-proxy secrets are closed.');
255
+ }
256
+
257
+ private mutate<T>(operationArg: () => Promise<T>): Promise<T> {
258
+ if (this.closed) return Promise.reject(new Error('The trusted-proxy secrets are closed.'));
259
+ const task = this.mutationTail.then(() => {
260
+ this.assertOpen();
261
+ return operationArg();
262
+ });
263
+ this.mutationTail = task.then(() => undefined, () => undefined);
264
+ return task;
265
+ }
266
+
267
+ /** The stored record, which must still hold exactly what this controller opened or wrote. */
268
+ private async readOwnRecord(): Promise<TStoredRecord> {
269
+ const stored = await readRecord(this.options.controllerId);
270
+ const record = stored ? ControllerTrustedProxySecretModel.exact.toPersisted(stored) : undefined;
271
+ if (!stored || record?.active.generation !== this.active.generation
272
+ || record.next?.generation !== this.next?.generation) {
273
+ throw new Error('The trusted-proxy secret changed outside this controller.');
274
+ }
275
+ return stored;
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Replaces a stopped controller's trusted-proxy secret with one an operator chose for another reverse proxy; a
281
+ * rotation in progress ends with it. Returns the new generation. The secret is never logged or echoed.
282
+ */
283
+ export const importControllerTrustedProxySecret = async (
284
+ optionsArg: IControllerTrustedProxySecretsOptions & { secret: string },
285
+ ): Promise<{ generation: number }> => {
286
+ const bytes = decodeTrustedProxySecret(optionsArg.secret);
287
+ try {
288
+ const stored = await readRecord(optionsArg.controllerId);
289
+ const record = stored ? ControllerTrustedProxySecretModel.exact.toPersisted(stored) : undefined;
290
+ const generation = Math.max(record?.active.generation ?? 0, record?.next?.generation ?? 0) + 1;
291
+ const active = await sealSecret(optionsArg, generation, bytes);
292
+ if (!stored) {
293
+ const inserted = await ControllerTrustedProxySecretModel.exact.insert({ id: optionsArg.controllerId, active });
294
+ if (inserted.status !== 'inserted') throw new Error('The trusted-proxy secret changed concurrently.');
295
+ return { generation };
296
+ }
297
+ const result = await ControllerTrustedProxySecretModel.exact.transition({ current: stored, change: (modelArg) => {
298
+ modelArg.active = active;
299
+ delete modelArg.next;
300
+ } });
301
+ if (result.status !== 'transitioned') throw new Error('The trusted-proxy secret changed concurrently.');
302
+ return { generation };
303
+ } finally {
304
+ bytes.fill(0);
305
+ }
306
+ };
307
+
308
+ /** Removes a stopped controller's trusted-proxy secret; whether there was one. */
309
+ export const removeControllerTrustedProxySecret = async (controllerIdArg: string): Promise<boolean> => {
310
+ const stored = await readRecord(controllerIdArg);
311
+ if (!stored) return false;
312
+ const deleted = await ControllerTrustedProxySecretModel.exact.delete({ current: stored });
313
+ if (deleted.status !== 'deleted' && await readRecord(controllerIdArg)) {
314
+ throw new Error('The trusted-proxy secret could not be removed.');
315
+ }
316
+ return true;
317
+ };
@@ -86,13 +86,13 @@ interface IUpgradeSemver {
86
86
  }
87
87
 
88
88
  const upgradeOwnerCommands = [
89
- '__serve', '__upgrade-worker', 'upgrade', 'start', 'restart', 'service', 'foreground', 'temp-password', 'config',
89
+ '__serve', '__upgrade-worker', 'upgrade', 'start', 'restart', 'service', 'foreground', 'temp-password', 'config', 'remote',
90
90
  ] as const;
91
91
  /** The CLI commands this release runs under an upgrade lock or a start lease. */
92
92
  type TUpgradeOwnerCommand = (typeof upgradeOwnerCommands)[number];
93
93
  const upgradeOwnerCommandSet: ReadonlySet<string> = new Set(upgradeOwnerCommands);
94
94
  /**
95
- * A command a later release's CLI holds a start lease under (`agl remote` from 42 on), read back after a rollback:
95
+ * A command a later release's CLI holds a start lease under, read back after a rollback:
96
96
  * its owner is live while that command runs and stale once it ended, like any other.
97
97
  */
98
98
  const laterReleaseStartCommandPattern = /^[a-z][a-z0-9-]{0,31}$/;
@@ -253,6 +253,12 @@ export interface IUpgradeAuthorityHandoff {
253
253
  export interface IUpgradeTransactionV2 extends IUpgradeTransactionBase {
254
254
  version: typeof coordinationVersion;
255
255
  sourceVersion: string;
256
+ /**
257
+ * What the source package declares about gateway sources (`controllerGatewaySourcesVersion` in its installed
258
+ * `package.json`), recorded by the CLI that creates the transaction and never changed afterwards. Absent when the
259
+ * source declares none, as every release before 42, whose CLI never writes it: absence means unsupported.
260
+ */
261
+ sourceGatewaySourcesVersion?: number;
256
262
  targetVersion?: string;
257
263
  registryUrl?: string;
258
264
  targetStartupInvoked?: true;
@@ -845,6 +851,14 @@ const parseUpgradeAuthorityHandoff = (valueArg: unknown): IUpgradeAuthorityHando
845
851
  };
846
852
  };
847
853
 
854
+ /**
855
+ * A declared gateway-sources contract (`controllerGatewaySourcesVersion` in a package, `sourceGatewaySourcesVersion`
856
+ * in an upgrade transaction): a safe integer of 1 or more.
857
+ */
858
+ export const isControllerGatewaySourcesVersion = (valueArg: unknown): valueArg is number => (
859
+ typeof valueArg === 'number' && Number.isSafeInteger(valueArg) && valueArg >= 1
860
+ );
861
+
848
862
  const parseUpgradeTransactionV2 = (valueArg: unknown): IUpgradeTransactionV2 => {
849
863
  if (!valueArg || typeof valueArg !== 'object' || Array.isArray(valueArg)) {
850
864
  throw new Error('Upgrade transaction metadata is malformed.');
@@ -855,6 +869,7 @@ const parseUpgradeTransactionV2 = (valueArg: unknown): IUpgradeTransactionV2 =>
855
869
  'continueSessions', 'gracePeriodMs', 'phase', 'message', 'createdAt', 'updatedAt',
856
870
  'phaseStartedAt', 'sessions',
857
871
  ...(value.blockers === undefined ? [] : ['blockers']),
872
+ ...(value.sourceGatewaySourcesVersion === undefined ? [] : ['sourceGatewaySourcesVersion']),
858
873
  ...(value.targetVersion === undefined ? [] : ['targetVersion']),
859
874
  ...(value.registryUrl === undefined ? [] : ['registryUrl']),
860
875
  ...(value.targetStartupInvoked === undefined ? [] : ['targetStartupInvoked']),
@@ -874,6 +889,8 @@ const parseUpgradeTransactionV2 = (valueArg: unknown): IUpgradeTransactionV2 =>
874
889
  || !Number.isSafeInteger(value.revision)
875
890
  || (value.revision as number) < 0
876
891
  || typeof value.controllerWasRunning !== 'boolean'
892
+ || (value.sourceGatewaySourcesVersion !== undefined
893
+ && !isControllerGatewaySourcesVersion(value.sourceGatewaySourcesVersion))
877
894
  || (value.targetStartupInvoked !== undefined && value.targetStartupInvoked !== true)
878
895
  || typeof value.continueSessions !== 'boolean'
879
896
  || !Number.isSafeInteger(value.gracePeriodMs)
@@ -1001,6 +1018,9 @@ const parseUpgradeTransactionV2 = (valueArg: unknown): IUpgradeTransactionV2 =>
1001
1018
  revision: value.revision as number,
1002
1019
  port: assertPort(value.port),
1003
1020
  sourceVersion: assertBoundedText(value.sourceVersion, 'The upgrade source version', 128),
1021
+ ...(value.sourceGatewaySourcesVersion === undefined
1022
+ ? {}
1023
+ : { sourceGatewaySourcesVersion: value.sourceGatewaySourcesVersion as number }),
1004
1024
  ...(value.targetVersion === undefined
1005
1025
  ? {}
1006
1026
  : { targetVersion: assertBoundedText(value.targetVersion, 'The upgrade target version', 128) }),
@@ -3017,7 +3037,7 @@ export class UpgradeCoordinator {
3017
3037
  token: string;
3018
3038
  cliPath: string;
3019
3039
  /** `__serve` is the service unit's controller starting without a CLI: after a failure, at login or at boot. */
3020
- command: 'start' | 'restart' | 'service' | 'foreground' | 'temp-password' | 'config' | '__serve';
3040
+ command: 'start' | 'restart' | 'service' | 'foreground' | 'temp-password' | 'config' | 'remote' | '__serve';
3021
3041
  upgradeToken?: string;
3022
3042
  }): Promise<UpgradeStartLease> {
3023
3043
  await this.init();
@@ -3488,6 +3508,8 @@ export class UpgradeCoordinator {
3488
3508
  token: string;
3489
3509
  port: number;
3490
3510
  sourceVersion: string;
3511
+ /** The source package's `controllerGatewaySourcesVersion`, read from its installed `package.json`. */
3512
+ sourceGatewaySourcesVersion?: number;
3491
3513
  registryUrl?: string;
3492
3514
  controllerWasRunning: boolean;
3493
3515
  continueSessions: boolean;
@@ -3501,6 +3523,9 @@ export class UpgradeCoordinator {
3501
3523
  revision: 0,
3502
3524
  port: assertPort(optionsArg.port),
3503
3525
  sourceVersion: assertBoundedText(optionsArg.sourceVersion, 'The upgrade source version', 128),
3526
+ ...(optionsArg.sourceGatewaySourcesVersion === undefined
3527
+ ? {}
3528
+ : { sourceGatewaySourcesVersion: optionsArg.sourceGatewaySourcesVersion }),
3504
3529
  ...(optionsArg.registryUrl === undefined
3505
3530
  ? {}
3506
3531
  : { registryUrl: normalizeUpgradeRegistryUrl(optionsArg.registryUrl) }),
@@ -3665,6 +3690,11 @@ export class UpgradeCoordinator {
3665
3690
  && next.version === coordinationVersion
3666
3691
  && currentArg.registryUrl !== next.registryUrl
3667
3692
  ) throw new Error('The upgrade registry cannot change after the transaction is created.');
3693
+ if (
3694
+ currentArg.version === coordinationVersion
3695
+ && next.version === coordinationVersion
3696
+ && currentArg.sourceGatewaySourcesVersion !== next.sourceGatewaySourcesVersion
3697
+ ) throw new Error('The upgrade source\'s gateway-sources declaration cannot change after the transaction is created.');
3668
3698
  if (
3669
3699
  (currentArg.preparationAcceptedAt !== undefined
3670
3700
  && next.preparationAcceptedAt !== currentArg.preparationAcceptedAt)