agl 42.0.0 → 42.2.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 (168) hide show
  1. package/changelog.md +44 -0
  2. package/dist_serve/bundle.js +2520 -2158
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/aglapisurface.document.js +124 -10
  6. package/dist_ts/classes.accountsactions.d.ts +3 -1
  7. package/dist_ts/classes.accountsactions.js +16 -1
  8. package/dist_ts/classes.authstore.d.ts +2 -0
  9. package/dist_ts/classes.authstore.js +58 -17
  10. package/dist_ts/classes.cli.js +19 -49
  11. package/dist_ts/classes.configurationauthority.js +2 -2
  12. package/dist_ts/classes.controller.d.ts +71 -2
  13. package/dist_ts/classes.controller.js +500 -113
  14. package/dist_ts/classes.controllerdevices.d.ts +128 -0
  15. package/dist_ts/classes.controllerdevices.js +472 -0
  16. package/dist_ts/classes.controllerservice.d.ts +20 -2
  17. package/dist_ts/classes.controllerservice.js +42 -6
  18. package/dist_ts/classes.flexservice.js +8 -3
  19. package/dist_ts/classes.inferencegateway.d.ts +30 -2
  20. package/dist_ts/classes.inferencegateway.js +115 -20
  21. package/dist_ts/classes.inferencerouter.d.ts +16 -0
  22. package/dist_ts/classes.inferencerouter.js +5 -3
  23. package/dist_ts/classes.inferenceservice.js +7 -3
  24. package/dist_ts/classes.sessionfeed.d.ts +10 -1
  25. package/dist_ts/classes.sessionfeed.js +12 -2
  26. package/dist_ts/classes.ticketmodels.js +4 -3
  27. package/dist_ts/classes.ticketnotifier.js +9 -2
  28. package/dist_ts/classes.ticketstore.js +9 -5
  29. package/dist_ts/classes.upgradecoordinator.d.ts +6 -1
  30. package/dist_ts/classes.upgradecoordinator.js +9 -2
  31. package/dist_ts/classes.upgradetransaction.d.ts +27 -1
  32. package/dist_ts/classes.upgradetransaction.js +92 -2
  33. package/dist_ts/classes.validation.d.ts +2 -0
  34. package/dist_ts/classes.validation.js +2 -2
  35. package/dist_ts/configuration/functions.master.d.ts +7 -2
  36. package/dist_ts/configuration/functions.master.js +7 -4
  37. package/dist_ts/driver/classes.drivereventrelay.d.ts +1 -1
  38. package/dist_ts/driver/classes.drivereventrelay.js +3 -3
  39. package/dist_ts/fleet/classes.boardpump.d.ts +1 -1
  40. package/dist_ts/fleet/classes.boardpump.js +7 -4
  41. package/dist_ts/fleet/classes.claudeworkers.d.ts +6 -0
  42. package/dist_ts/fleet/classes.claudeworkers.js +17 -7
  43. package/dist_ts/fleet/classes.deploymodels.d.ts +19 -0
  44. package/dist_ts/fleet/classes.deploymodels.js +140 -0
  45. package/dist_ts/fleet/functions.validation.d.ts +8 -1
  46. package/dist_ts/fleet/functions.validation.js +65 -3
  47. package/dist_ts/fleet/interfaces.workers.d.ts +6 -0
  48. package/dist_ts/fleet/interfaces.workers.js +65 -2
  49. package/dist_ts/functions.deviceapi.d.ts +28 -0
  50. package/dist_ts/functions.deviceapi.js +246 -0
  51. package/dist_ts/functions.deviceproof.d.ts +33 -0
  52. package/dist_ts/functions.deviceproof.js +93 -0
  53. package/dist_ts/functions.fleetworkercli.d.ts +16 -3
  54. package/dist_ts/functions.fleetworkercli.js +21 -7
  55. package/dist_ts/functions.inferencecli.js +4 -2
  56. package/dist_ts/functions.mcptickettools.d.ts +1 -0
  57. package/dist_ts/functions.remotecli.d.ts +1 -1
  58. package/dist_ts/functions.remotecli.js +12 -7
  59. package/dist_ts/functions.ticketvalidation.d.ts +36 -3
  60. package/dist_ts/functions.ticketvalidation.js +45 -14
  61. package/dist_ts/interfaces.auth.d.ts +1 -1
  62. package/dist_ts/interfaces.auth.js +7 -1
  63. package/dist_ts_authswitch/authority-contract.d.ts +23 -0
  64. package/dist_ts_authswitch/authority-contract.js +1 -1
  65. package/dist_ts_authswitch/classes.authoritybroker.d.ts +6 -0
  66. package/dist_ts_authswitch/classes.authoritybroker.js +31 -4
  67. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  68. package/dist_ts_authswitch/classes.authoritycli.js +26 -1
  69. package/dist_ts_authswitch/classes.authorityclient.d.ts +3 -1
  70. package/dist_ts_authswitch/classes.authorityclient.js +10 -4
  71. package/dist_ts_authswitch/classes.authoritydaemon.js +7 -1
  72. package/dist_ts_authswitch/classes.authorityimport.js +2 -2
  73. package/dist_ts_authswitch/classes.authoritymodels.d.ts +3 -0
  74. package/dist_ts_authswitch/classes.authoritymodels.js +10 -3
  75. package/dist_ts_authswitch/testsupport.js +4 -4
  76. package/dist_ts_authswitch/ts_migration/0012_account_claude_code.d.ts +11 -0
  77. package/dist_ts_authswitch/ts_migration/0012_account_claude_code.js +18 -0
  78. package/dist_ts_authswitch/ts_migration/index.js +3 -1
  79. package/dist_ts_interfaces/deployments.d.ts +104 -0
  80. package/dist_ts_interfaces/deployments.js +8 -0
  81. package/dist_ts_interfaces/devices.d.ts +331 -0
  82. package/dist_ts_interfaces/devices.js +34 -0
  83. package/dist_ts_interfaces/fleet.d.ts +2 -0
  84. package/dist_ts_interfaces/index.d.ts +3 -0
  85. package/dist_ts_interfaces/index.js +4 -1
  86. package/dist_ts_interfaces/interfaces.d.ts +4 -2
  87. package/dist_ts_interfaces/interfaces.js +3 -2
  88. package/dist_ts_interfaces/mcprequests.d.ts +1 -1
  89. package/dist_ts_interfaces/requests.accounts.d.ts +18 -0
  90. package/dist_ts_interfaces/requests.accounts.js +1 -1
  91. package/dist_ts_interfaces/requests.d.ts +3 -2
  92. package/dist_ts_interfaces/requests.devices.d.ts +89 -0
  93. package/dist_ts_interfaces/requests.devices.js +2 -0
  94. package/dist_ts_interfaces/requests.js +1 -1
  95. package/dist_ts_interfaces/tickets.d.ts +53 -4
  96. package/dist_ts_interfaces/tickets.js +6 -2
  97. package/dist_ts_migration/index.d.ts +1 -0
  98. package/dist_ts_migration/index.js +2 -1
  99. package/dist_ts_migration/v41_ticketmigrationmarkers.d.ts +19 -0
  100. package/dist_ts_migration/v41_ticketmigrationmarkers.js +85 -0
  101. package/docs/authswitch.md +6 -0
  102. package/package.json +5 -5
  103. package/readme.md +84 -16
  104. package/ts/00_commitinfo_data.ts +1 -1
  105. package/ts/aglapi/aglapisurface.document.ts +123 -9
  106. package/ts/classes.accountsactions.ts +24 -0
  107. package/ts/classes.authstore.ts +54 -14
  108. package/ts/classes.cli.ts +17 -54
  109. package/ts/classes.configurationauthority.ts +1 -1
  110. package/ts/classes.controller.ts +697 -167
  111. package/ts/classes.controllerdevices.ts +469 -0
  112. package/ts/classes.controllerservice.ts +49 -6
  113. package/ts/classes.flexservice.ts +7 -2
  114. package/ts/classes.inferencegateway.ts +133 -19
  115. package/ts/classes.inferencerouter.ts +20 -2
  116. package/ts/classes.inferenceservice.ts +6 -3
  117. package/ts/classes.sessionfeed.ts +13 -1
  118. package/ts/classes.ticketmodels.ts +3 -2
  119. package/ts/classes.ticketnotifier.ts +8 -1
  120. package/ts/classes.ticketstore.ts +8 -4
  121. package/ts/classes.upgradecoordinator.ts +14 -4
  122. package/ts/classes.upgradetransaction.ts +118 -0
  123. package/ts/classes.validation.ts +1 -1
  124. package/ts/configuration/functions.master.ts +6 -3
  125. package/ts/driver/classes.drivereventrelay.ts +2 -2
  126. package/ts/fleet/classes.boardpump.ts +7 -4
  127. package/ts/fleet/classes.claudeworkers.ts +16 -6
  128. package/ts/fleet/classes.deploymodels.ts +44 -0
  129. package/ts/fleet/functions.validation.ts +50 -2
  130. package/ts/fleet/interfaces.workers.ts +56 -1
  131. package/ts/functions.deviceapi.ts +295 -0
  132. package/ts/functions.deviceproof.ts +118 -0
  133. package/ts/functions.fleetworkercli.ts +26 -8
  134. package/ts/functions.inferencecli.ts +3 -1
  135. package/ts/functions.remotecli.ts +11 -5
  136. package/ts/functions.ticketvalidation.ts +48 -13
  137. package/ts/interfaces.auth.ts +6 -0
  138. package/ts_authswitch/authority-contract.ts +18 -0
  139. package/ts_authswitch/classes.authoritybroker.ts +29 -3
  140. package/ts_authswitch/classes.authoritycli.ts +29 -0
  141. package/ts_authswitch/classes.authorityclient.ts +12 -4
  142. package/ts_authswitch/classes.authoritydaemon.ts +8 -1
  143. package/ts_authswitch/classes.authorityimport.ts +1 -1
  144. package/ts_authswitch/classes.authoritymodels.ts +5 -1
  145. package/ts_authswitch/native-contracts.md +10 -0
  146. package/ts_authswitch/testsupport.ts +3 -3
  147. package/ts_authswitch/ts_migration/0012_account_claude_code.ts +17 -0
  148. package/ts_authswitch/ts_migration/index.ts +2 -0
  149. package/ts_interfaces/deployments.ts +98 -0
  150. package/ts_interfaces/devices.schema.json +890 -0
  151. package/ts_interfaces/devices.ts +392 -0
  152. package/ts_interfaces/fleet.ts +2 -0
  153. package/ts_interfaces/index.ts +3 -0
  154. package/ts_interfaces/interfaces.ts +4 -1
  155. package/ts_interfaces/mcprequests.ts +1 -1
  156. package/ts_interfaces/requests.accounts.ts +16 -0
  157. package/ts_interfaces/requests.devices.ts +95 -0
  158. package/ts_interfaces/requests.ts +12 -0
  159. package/ts_interfaces/tickets.ts +34 -4
  160. package/ts_migration/index.ts +1 -0
  161. package/ts_migration/v41_ticketmigrationmarkers.ts +28 -0
  162. package/ts_web/00_commitinfo_data.ts +1 -1
  163. package/ts_web/classes.accountsreadmodel.ts +12 -1
  164. package/ts_web/classes.controllersocketclient.ts +27 -0
  165. package/ts_web/elements.accounts.ts +44 -0
  166. package/ts_web/elements.devices.ts +752 -0
  167. package/ts_web/elements.harnesscontrollerapp.ts +18 -1
  168. package/ts_web/elements.ticketboard.ts +15 -4
@@ -0,0 +1,469 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { TControllerTlsMode } from './interfaces.config.js';
3
+ import {
4
+ deviceChallengeLifetimeMs,
5
+ deviceLabelMaximumCharacters,
6
+ devicePairingLifetimeMs,
7
+ deviceSecretBytes,
8
+ maximumDevices,
9
+ maximumPendingDevicePairings,
10
+ type IReq_DevicePair,
11
+ type TDeviceRefusalCode,
12
+ } from '../ts_interfaces/devices.js';
13
+ import type {
14
+ IControllerDevice,
15
+ IControllerDevicePairingOutcome,
16
+ IReq_ControllerDevicesPairingBegin,
17
+ TControllerDevicePairingAvailability,
18
+ } from '../ts_interfaces/requests.devices.js';
19
+ import {
20
+ decodeDeviceBase64Url,
21
+ deviceAuthenticationMessage,
22
+ deviceKeyFingerprint,
23
+ devicePairingMessage,
24
+ devicePairingPayload,
25
+ importDevicePublicKey,
26
+ verifyDeviceSignature,
27
+ } from './functions.deviceproof.js';
28
+
29
+ /** One paired device of a controller. Revoking it deletes the record; its history is the audit log's. */
30
+ export interface IControllerDeviceDocument {
31
+ /** 18 random bytes, base64url. */
32
+ id: string;
33
+ /** `controller:<port>`. */
34
+ controllerId: string;
35
+ name: string;
36
+ model: string;
37
+ /** The device key: a P-256 SubjectPublicKeyInfo in DER, base64url. */
38
+ publicKey: string;
39
+ /** The public origin the device paired with and signs; a device of another origin never authenticates. */
40
+ origin: string;
41
+ /** Unix milliseconds. */
42
+ pairedAt: number;
43
+ /** Unix milliseconds of the last authenticated connection, written at most every `lastSeenWriteIntervalMs`. */
44
+ lastSeenAt?: number;
45
+ }
46
+
47
+ const deviceIdPattern = /^[A-Za-z0-9_-]{24}$/u;
48
+ const publicKeyPattern = /^[A-Za-z0-9_-]{122}$/u;
49
+
50
+ /** A device's name or model: 1 to 64 characters of one line, without surrounding blanks. */
51
+ const isDeviceLabel = (valueArg: unknown): valueArg is string => typeof valueArg === 'string'
52
+ && valueArg === valueArg.trim()
53
+ && valueArg.length > 0
54
+ && [...valueArg].length <= deviceLabelMaximumCharacters
55
+ && !/\p{Cc}/u.test(valueArg);
56
+
57
+ const isTimestamp = (valueArg: unknown): valueArg is number => Number.isSafeInteger(valueArg) && (valueArg as number) > 0;
58
+
59
+ const assertDocument: (valueArg: unknown) => asserts valueArg is IControllerDeviceDocument = (valueArg) => {
60
+ const value = valueArg as Partial<IControllerDeviceDocument> | null;
61
+ const keys = value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value) : [];
62
+ const expected = ['id', 'controllerId', 'name', 'model', 'publicKey', 'origin', 'pairedAt'];
63
+ if (
64
+ !value
65
+ || keys.length !== expected.length + (Object.hasOwn(value, 'lastSeenAt') ? 1 : 0)
66
+ || !expected.every((keyArg) => Object.hasOwn(value, keyArg))
67
+ || typeof value.id !== 'string' || !deviceIdPattern.test(value.id)
68
+ || typeof value.controllerId !== 'string' || !/^controller:[1-9][0-9]{0,4}$/u.test(value.controllerId)
69
+ || !isDeviceLabel(value.name)
70
+ || !isDeviceLabel(value.model)
71
+ || typeof value.publicKey !== 'string' || !publicKeyPattern.test(value.publicKey)
72
+ || typeof value.origin !== 'string' || !/^https:\/\/[^/\s]{1,512}$/u.test(value.origin)
73
+ || !isTimestamp(value.pairedAt)
74
+ || (Object.hasOwn(value, 'lastSeenAt') && !isTimestamp(value.lastSeenAt))
75
+ ) {
76
+ throw new Error('Invalid device record.');
77
+ }
78
+ };
79
+
80
+ @plugins.nosqldb.managed({ collectionName: 'agl_controller_devices' })
81
+ @plugins.nosqldb.exactPersistence({ assertDocument })
82
+ export class ControllerDeviceModel extends plugins.nosqldb.SmartDataDbDoc<ControllerDeviceModel, IControllerDeviceDocument> {
83
+ declare static exact: plugins.nosqldb.TExact<ControllerDeviceModel>;
84
+ @plugins.nosqldb.unI() public id!: string;
85
+ @plugins.nosqldb.svDb() public controllerId!: string;
86
+ // `name` shadows a base-class property; the initializer makes that explicit.
87
+ @plugins.nosqldb.svDb() public name: string = '';
88
+ @plugins.nosqldb.svDb() public model!: string;
89
+ @plugins.nosqldb.svDb() public publicKey!: string;
90
+ @plugins.nosqldb.svDb() public origin!: string;
91
+ @plugins.nosqldb.svDb() public pairedAt!: number;
92
+ @plugins.nosqldb.svDb() public lastSeenAt?: number;
93
+ }
94
+
95
+ /**
96
+ * Deletes every device of a controller whose public origin moves: each signed the old origin and could never
97
+ * authenticate at the new one. Answers how many it deleted. `optionsArg.session` runs it inside the caller's
98
+ * transaction (`moveRuntimeConfig` deletes the devices with the configuration change, or not at all).
99
+ */
100
+ export const deleteControllerDevices = async (
101
+ controllerIdArg: string,
102
+ optionsArg: plugins.nosqldb.IExactSessionOptions = {},
103
+ ): Promise<number> => {
104
+ let deleted = 0;
105
+ for (const current of await ControllerDeviceModel.exact.findStored({ filter: { controllerId: controllerIdArg }, ...optionsArg })) {
106
+ const result = await ControllerDeviceModel.exact.delete({ current }, optionsArg);
107
+ const { id } = ControllerDeviceModel.exact.toPersisted(current);
108
+ if (result.status !== 'deleted' && await ControllerDeviceModel.exact.findStoredOne({ id }, optionsArg)) {
109
+ throw new Error('A paired device could not be removed.');
110
+ }
111
+ deleted += 1;
112
+ }
113
+ return deleted;
114
+ };
115
+
116
+ /** A refusal a device or the owner sees, with its code in `error.data.code`. */
117
+ export const deviceRefusal = (codeArg: TDeviceRefusalCode, messageArg: string): plugins.typedrequest.TypedResponseError => (
118
+ new plugins.typedrequest.TypedResponseError(messageArg, { code: codeArg })
119
+ );
120
+
121
+ /** The connection a device authenticates: the controller socket's peer, whose state only the server writes. */
122
+ export interface IControllerDevicePeer {
123
+ id: string;
124
+ context: { state: Record<string, unknown> };
125
+ close?(codeArg?: number, reasonArg?: string): void;
126
+ }
127
+
128
+ /** The peer state of an authenticated device connection: the device's id. */
129
+ export const devicePeerStateKey = '__aglDeviceId';
130
+ /** The peer state of a nonce handed out on a connection. */
131
+ const deviceChallengeStateKey = '__aglDeviceChallenge';
132
+
133
+ interface IDeviceChallenge {
134
+ deviceId: string;
135
+ nonce: Buffer;
136
+ expiresAt: number;
137
+ }
138
+
139
+ interface IPendingPairing {
140
+ pairingId: string;
141
+ expiresAt: number;
142
+ }
143
+
144
+ /** The last-seen time is written at most this often per device. */
145
+ const lastSeenWriteIntervalMs = 5 * 60 * 1000;
146
+
147
+ export interface IControllerDevicesOptions {
148
+ /** `controller:<port>`. */
149
+ controllerId: string;
150
+ /** The runtime configuration the controller started with. */
151
+ publicOrigin: string;
152
+ tlsMode: TControllerTlsMode;
153
+ /** A device paired, was revoked, or its first connection came or its last one went. */
154
+ changed(pairingArg?: IControllerDevicePairingOutcome): void;
155
+ now?: () => number;
156
+ }
157
+
158
+ /**
159
+ * The paired devices of one running controller: their records (the controller's database is the authority, and this
160
+ * controller its only writer), the pairing codes in memory only (a restart voids them), the nonces of connections and
161
+ * the authenticated connections of each device. Pairing needs a public HTTPS origin; local mode refuses it.
162
+ */
163
+ export class ControllerDevices {
164
+ /** Pairing codes by the SHA-256 of their bytes, hex. */
165
+ private readonly pending = new Map<string, IPendingPairing>();
166
+ private readonly records = new Map<string, IControllerDeviceDocument>();
167
+ private readonly live = new Map<string, Set<IControllerDevicePeer>>();
168
+ private readonly lastSeenWrites = new Map<string, Promise<void>>();
169
+ private mutationTail: Promise<unknown> = Promise.resolve();
170
+ private closed = false;
171
+
172
+ private constructor(private readonly options: IControllerDevicesOptions) {}
173
+
174
+ /** Reads the devices of the controller. */
175
+ public static async open(optionsArg: IControllerDevicesOptions): Promise<ControllerDevices> {
176
+ const devices = new ControllerDevices(optionsArg);
177
+ for (const stored of await ControllerDeviceModel.exact.findStored({ filter: { controllerId: optionsArg.controllerId } })) {
178
+ const record = ControllerDeviceModel.exact.toPersisted(stored);
179
+ devices.records.set(record.id, record);
180
+ }
181
+ return devices;
182
+ }
183
+
184
+ private now(): number {
185
+ return this.options.now?.() ?? Date.now();
186
+ }
187
+
188
+ /** Whether a device can pair now; local mode never, and not at the device limit. */
189
+ public availability(): TControllerDevicePairingAvailability {
190
+ if (this.options.tlsMode !== 'proxy' || !this.options.publicOrigin.startsWith('https://')) {
191
+ return { available: false, reason: 'publicOriginRequired' };
192
+ }
193
+ return this.records.size >= maximumDevices ? { available: false, reason: 'deviceLimit' } : { available: true };
194
+ }
195
+
196
+ /** The devices, newest paired first. */
197
+ public list(): IControllerDevice[] {
198
+ return [...this.records.values()]
199
+ .sort((leftArg, rightArg) => rightArg.pairedAt - leftArg.pairedAt || leftArg.id.localeCompare(rightArg.id))
200
+ .map((recordArg) => this.view(recordArg));
201
+ }
202
+
203
+ private view(recordArg: IControllerDeviceDocument): IControllerDevice {
204
+ return {
205
+ id: recordArg.id,
206
+ name: recordArg.name,
207
+ model: recordArg.model,
208
+ fingerprint: deviceKeyFingerprint(Buffer.from(recordArg.publicKey, 'base64url')),
209
+ pairedAt: recordArg.pairedAt,
210
+ ...(recordArg.lastSeenAt === undefined ? {} : { lastSeenAt: recordArg.lastSeenAt }),
211
+ connected: (this.live.get(recordArg.id)?.size ?? 0) > 0,
212
+ };
213
+ }
214
+
215
+ private assertOpen(): void {
216
+ if (this.closed) throw deviceRefusal('device_pairing_unavailable', 'The controller is stopping.');
217
+ }
218
+
219
+ private assertPairingAvailable(): void {
220
+ const availability = this.availability();
221
+ if (availability.available) return;
222
+ if (availability.reason === 'deviceLimit') {
223
+ throw deviceRefusal('device_limit', `This controller holds its maximum of ${maximumDevices} devices; revoke one first.`);
224
+ }
225
+ throw deviceRefusal('device_pairing_unavailable',
226
+ 'Devices pair only with a controller that has a public HTTPS origin; this one is reachable on this machine only.');
227
+ }
228
+
229
+ private prunePairings(): void {
230
+ const now = this.now();
231
+ for (const [hash, pairing] of this.pending) if (pairing.expiresAt <= now) this.pending.delete(hash);
232
+ }
233
+
234
+ /** A new single-use pairing code and the payload of its QR code. */
235
+ public beginPairing(): IReq_ControllerDevicesPairingBegin['response'] {
236
+ this.assertOpen();
237
+ this.assertPairingAvailable();
238
+ this.prunePairings();
239
+ if (this.pending.size >= maximumPendingDevicePairings) {
240
+ throw new plugins.typedrequest.TypedResponseError(
241
+ `At most ${maximumPendingDevicePairings} pairing codes wait at once; close another pairing or wait until one expires.`,
242
+ { code: 'device_pairing_limit' },
243
+ );
244
+ }
245
+ const code = plugins.crypto.randomBytes(deviceSecretBytes);
246
+ const pairing: IPendingPairing = {
247
+ pairingId: plugins.crypto.randomBytes(16).toString('base64url'),
248
+ expiresAt: this.now() + devicePairingLifetimeMs,
249
+ };
250
+ this.pending.set(plugins.crypto.createHash('sha256').update(code).digest('hex'), pairing);
251
+ try {
252
+ return {
253
+ pairingId: pairing.pairingId,
254
+ payload: devicePairingPayload(this.options.publicOrigin, this.options.controllerId, code),
255
+ expiresAt: pairing.expiresAt,
256
+ };
257
+ } finally {
258
+ code.fill(0);
259
+ }
260
+ }
261
+
262
+ /** Withdraws a code nobody used yet; answers whether it was still waiting. */
263
+ public cancelPairing(pairingIdArg: string): boolean {
264
+ for (const [hash, pairing] of this.pending) {
265
+ if (pairing.pairingId !== pairingIdArg) continue;
266
+ this.pending.delete(hash);
267
+ return true;
268
+ }
269
+ return false;
270
+ }
271
+
272
+ /** Runs one write after the ones before it; once closed nothing new is taken, and what was taken still runs. */
273
+ private mutate<T>(operationArg: () => Promise<T>): Promise<T> {
274
+ try {
275
+ this.assertOpen();
276
+ } catch (errorArg) {
277
+ return Promise.reject(errorArg);
278
+ }
279
+ const task = this.mutationTail.then(operationArg);
280
+ this.mutationTail = task.then(() => undefined, () => undefined);
281
+ return task;
282
+ }
283
+
284
+ /**
285
+ * Pairs a device with a waiting code: the code is used up whatever follows, the proof must verify against the key it
286
+ * names, and the key must be new to this controller.
287
+ */
288
+ public pair(requestArg: IReq_DevicePair['request']): Promise<IControllerDevicePairingOutcome> {
289
+ return this.mutate(async () => {
290
+ this.assertPairingAvailable();
291
+ const code = decodeDeviceBase64Url(requestArg.code, { bytes: deviceSecretBytes });
292
+ const spki = decodeDeviceBase64Url(requestArg.publicKey, { maximumBytes: 91 });
293
+ const proof = decodeDeviceBase64Url(requestArg.proof, { maximumBytes: 72 });
294
+ if (!code) throw deviceRefusal('device_pairing_invalid', 'The pairing code is invalid, used or expired.');
295
+ this.prunePairings();
296
+ const hash = plugins.crypto.createHash('sha256').update(code).digest('hex');
297
+ const pairing = this.pending.get(hash);
298
+ if (!pairing) throw deviceRefusal('device_pairing_invalid', 'The pairing code is invalid, used or expired.');
299
+ this.pending.delete(hash);
300
+ const key = spki ? importDevicePublicKey(spki) : undefined;
301
+ if (!spki || !key) throw deviceRefusal('device_proof_invalid', 'The device key is not a P-256 public key.');
302
+ const message = devicePairingMessage({
303
+ controllerId: this.options.controllerId, origin: this.options.publicOrigin, publicKey: spki,
304
+ }, code);
305
+ if (!proof || !verifyDeviceSignature(key, message, proof)) {
306
+ throw deviceRefusal('device_proof_invalid', 'The pairing proof does not verify against the device key.');
307
+ }
308
+ const publicKey = spki.toString('base64url');
309
+ if ([...this.records.values()].some((recordArg) => recordArg.publicKey === publicKey)) {
310
+ throw deviceRefusal('device_already_paired', 'This device key is paired with this controller already.');
311
+ }
312
+ if (this.records.size >= maximumDevices) {
313
+ throw deviceRefusal('device_limit', `This controller holds its maximum of ${maximumDevices} devices; revoke one first.`);
314
+ }
315
+ const record: IControllerDeviceDocument = {
316
+ id: plugins.crypto.randomBytes(18).toString('base64url'),
317
+ controllerId: this.options.controllerId,
318
+ name: requestArg.name,
319
+ model: requestArg.model,
320
+ publicKey,
321
+ origin: this.options.publicOrigin,
322
+ pairedAt: this.now(),
323
+ };
324
+ const inserted = await ControllerDeviceModel.exact.insert(record);
325
+ if (inserted.status !== 'inserted') throw new Error('The paired device could not be stored.');
326
+ this.records.set(record.id, record);
327
+ const outcome = { pairingId: pairing.pairingId, device: this.view(record) };
328
+ this.options.changed(outcome);
329
+ return outcome;
330
+ });
331
+ }
332
+
333
+ /** The record of a device this controller's origin can authenticate. */
334
+ private authenticatable(deviceIdArg: string): IControllerDeviceDocument {
335
+ const record = this.records.get(deviceIdArg);
336
+ if (!record || record.origin !== this.options.publicOrigin) {
337
+ throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
338
+ }
339
+ return record;
340
+ }
341
+
342
+ /** A fresh nonce for this connection to sign; it replaces an earlier one of the connection. */
343
+ public challenge(peerArg: IControllerDevicePeer, deviceIdArg: string): { nonce: string } {
344
+ this.assertOpen();
345
+ this.authenticatable(deviceIdArg);
346
+ const challenge: IDeviceChallenge = {
347
+ deviceId: deviceIdArg,
348
+ nonce: plugins.crypto.randomBytes(deviceSecretBytes),
349
+ expiresAt: this.now() + deviceChallengeLifetimeMs,
350
+ };
351
+ peerArg.context.state[deviceChallengeStateKey] = challenge;
352
+ return { nonce: challenge.nonce.toString('base64url') };
353
+ }
354
+
355
+ /**
356
+ * Authenticates the connection as the device when the signature over this connection's nonce verifies; the nonce is
357
+ * used up either way. A connection authenticated as another device before is that device's no more.
358
+ */
359
+ public prove(peerArg: IControllerDevicePeer, deviceIdArg: string, signatureArg: string): IControllerDevice {
360
+ this.assertOpen();
361
+ const challenge = peerArg.context.state[deviceChallengeStateKey] as IDeviceChallenge | undefined;
362
+ delete peerArg.context.state[deviceChallengeStateKey];
363
+ if (!challenge || challenge.deviceId !== deviceIdArg || challenge.expiresAt <= this.now()) {
364
+ throw deviceRefusal('device_challenge_invalid', 'Ask for a nonce on this connection first; it is valid for one minute.');
365
+ }
366
+ const record = this.authenticatable(deviceIdArg);
367
+ const spki = Buffer.from(record.publicKey, 'base64url');
368
+ const key = importDevicePublicKey(spki);
369
+ const signature = decodeDeviceBase64Url(signatureArg, { maximumBytes: 72 });
370
+ const message = deviceAuthenticationMessage({
371
+ controllerId: this.options.controllerId, origin: this.options.publicOrigin, publicKey: spki,
372
+ }, challenge.nonce);
373
+ if (!key || !signature || !verifyDeviceSignature(key, message, signature)) {
374
+ throw deviceRefusal('device_proof_invalid', 'The signature does not verify against the device key.');
375
+ }
376
+ this.leave(peerArg);
377
+ peerArg.context.state[devicePeerStateKey] = record.id;
378
+ let peers = this.live.get(record.id);
379
+ if (!peers) {
380
+ peers = new Set();
381
+ this.live.set(record.id, peers);
382
+ }
383
+ peers.add(peerArg);
384
+ this.recordSeen(record.id);
385
+ if (peers.size === 1) this.options.changed();
386
+ return this.view(this.records.get(record.id) ?? record);
387
+ }
388
+
389
+ /** Writes the device's last-seen time, at most every five minutes; a failed write is reported and tried next time. */
390
+ private recordSeen(deviceIdArg: string): void {
391
+ const record = this.records.get(deviceIdArg);
392
+ const now = this.now();
393
+ if (!record || this.lastSeenWrites.has(deviceIdArg)
394
+ || (record.lastSeenAt !== undefined && now - record.lastSeenAt < lastSeenWriteIntervalMs)) return;
395
+ const write = this.mutate(async () => {
396
+ const current = await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg });
397
+ if (!current) return;
398
+ const result = await ControllerDeviceModel.exact.transition({ current, change: (modelArg) => {
399
+ modelArg.lastSeenAt = now;
400
+ } });
401
+ if (result.status !== 'transitioned') throw new Error('The device record changed concurrently.');
402
+ const stored = this.records.get(deviceIdArg);
403
+ if (stored) this.records.set(deviceIdArg, { ...stored, lastSeenAt: now });
404
+ }).catch((errorArg: unknown) => {
405
+ console.error(`Recording when device ${deviceIdArg} was last seen failed.`, errorArg);
406
+ }).finally(() => {
407
+ this.lastSeenWrites.delete(deviceIdArg);
408
+ });
409
+ this.lastSeenWrites.set(deviceIdArg, write);
410
+ }
411
+
412
+ /** The device a connection is authenticated as, while that device is paired. */
413
+ public deviceIdOf(peerArg: IControllerDevicePeer): string | undefined {
414
+ const deviceId = peerArg.context.state[devicePeerStateKey];
415
+ return typeof deviceId === 'string' && this.live.get(deviceId)?.has(peerArg) === true ? deviceId : undefined;
416
+ }
417
+
418
+ /** Whether any device connection is authenticated now. */
419
+ public hasLivePeers(): boolean {
420
+ return this.live.size > 0;
421
+ }
422
+
423
+ private leave(peerArg: IControllerDevicePeer): void {
424
+ const deviceId = peerArg.context.state[devicePeerStateKey];
425
+ delete peerArg.context.state[devicePeerStateKey];
426
+ if (typeof deviceId !== 'string') return;
427
+ const peers = this.live.get(deviceId);
428
+ if (!peers?.delete(peerArg)) return;
429
+ if (peers.size > 0) return;
430
+ this.live.delete(deviceId);
431
+ if (this.records.has(deviceId)) this.options.changed();
432
+ }
433
+
434
+ /** A connection closed: it is no device's any more, and its nonce is void. */
435
+ public disconnect(peerArg: IControllerDevicePeer): void {
436
+ delete peerArg.context.state[deviceChallengeStateKey];
437
+ this.leave(peerArg);
438
+ }
439
+
440
+ /**
441
+ * Revokes a device: its record is deleted, and every connection authenticated as it loses that at once. Answers the
442
+ * connections, which the caller closes, or `revoked: false` for a device that is gone already.
443
+ */
444
+ public revoke(deviceIdArg: string): Promise<{ revoked: boolean; peers: IControllerDevicePeer[] }> {
445
+ return this.mutate(async () => {
446
+ if (!this.records.has(deviceIdArg)) return { revoked: false, peers: [] };
447
+ const current = await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg });
448
+ if (current) {
449
+ const result = await ControllerDeviceModel.exact.delete({ current });
450
+ if (result.status !== 'deleted' && await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg })) {
451
+ throw new Error('The device record changed concurrently and was not revoked.');
452
+ }
453
+ }
454
+ this.records.delete(deviceIdArg);
455
+ const peers = [...this.live.get(deviceIdArg) ?? []];
456
+ this.live.delete(deviceIdArg);
457
+ for (const peer of peers) delete peer.context.state[devicePeerStateKey];
458
+ this.options.changed();
459
+ return { revoked: true, peers };
460
+ });
461
+ }
462
+
463
+ /** Voids every pairing code and refuses everything from now on; waits for the writes already taken. */
464
+ public async close(): Promise<void> {
465
+ this.closed = true;
466
+ this.pending.clear();
467
+ await Promise.allSettled([this.mutationTail, ...this.lastSeenWrites.values()]);
468
+ }
469
+ }
@@ -159,6 +159,29 @@ export const controllerServiceEnvironment = (environmentArg: NodeJS.ProcessEnv):
159
159
  return environment;
160
160
  };
161
161
 
162
+ /**
163
+ * The `PATH` a rewritten unit carries (AGL-1108): the installing shell's `PATH` as it is, then each entry of the
164
+ * installed unit's `PATH` it lacks, in the installed order. The installing shell decides precedence, so a new
165
+ * toolchain it puts first wins; a directory the controller ran with is kept behind it, so a shell without some
166
+ * tool directory never removes it. Only an absolute directory that still exists is kept: an empty or relative entry
167
+ * would resolve against the unit's working directory, and a removed one, such as a deleted Node.js version, would
168
+ * otherwise stay forever. A first install has no installed `PATH` and carries the shell's unchanged.
169
+ */
170
+ export const controllerServicePath = async (
171
+ installerPathArg: string,
172
+ installedPathArg: string | undefined,
173
+ ): Promise<{ path: string; kept: string[] }> => {
174
+ const present = new Set(installerPathArg.split(plugins.path.delimiter));
175
+ const kept: string[] = [];
176
+ for (const entry of installedPathArg?.split(plugins.path.delimiter) ?? []) {
177
+ if (present.has(entry) || !plugins.path.isAbsolute(entry)) continue;
178
+ present.add(entry);
179
+ const stats = await plugins.fs.promises.stat(entry).catch(() => null);
180
+ if (stats?.isDirectory()) kept.push(entry);
181
+ }
182
+ return { path: [installerPathArg, ...kept].join(plugins.path.delimiter), kept };
183
+ };
184
+
162
185
  /** The controller service as `agl service install` left it, read back from the file and the manager. */
163
186
  export interface IInstalledControllerService {
164
187
  record: plugins.smartdaemon.ISystemdUnitFileRecord;
@@ -232,11 +255,15 @@ export class AglControllerService {
232
255
  return resolveControllerLogFilePath(resolveAGLHomePaths({ environment: this.environment }).logs, portArg);
233
256
  }
234
257
 
235
- /** The unit AGL writes for `executableArg` (the verified pnpm-global shim) on `portArg`. */
258
+ /**
259
+ * The unit AGL writes for `executableArg` (the verified pnpm-global shim) on `portArg`, with the installing
260
+ * shell's `PATH` unless `path` (`controllerServicePath`) replaces it.
261
+ */
236
262
  public definition(optionsArg: {
237
263
  executable: string;
238
264
  port: number;
239
265
  overrides: IControllerServiceOverrides;
266
+ path?: string;
240
267
  }): plugins.smartdaemon.SystemdServiceDefinition {
241
268
  if (!Number.isInteger(optionsArg.port) || optionsArg.port < 1 || optionsArg.port > 65_535) {
242
269
  throw new Error('The controller port must be 1 to 65535.');
@@ -263,7 +290,10 @@ export class AglControllerService {
263
290
  conflicts: [],
264
291
  },
265
292
  install: { wantedBy: ['default.target'], requiredBy: [] },
266
- environment: controllerServiceEnvironment(this.environment),
293
+ environment: {
294
+ ...controllerServiceEnvironment(this.environment),
295
+ ...(optionsArg.path === undefined ? {} : { PATH: optionsArg.path }),
296
+ },
267
297
  // Standard output stays discarded, as for a detached controller: the transport logs every connection there.
268
298
  standardOutput: 'null',
269
299
  standardError: { append: this.logFilePath(optionsArg.port) },
@@ -273,17 +303,30 @@ export class AglControllerService {
273
303
  /**
274
304
  * Writes the unit and enables it, so the user manager starts the controller at login or boot. Never starts or
275
305
  * stops it: unchanged bytes are left alone, so this also runs while the unit does, and a changed definition is
276
- * refused while the unit runs (`agl stop` first, then `agl start` once it is written).
306
+ * refused while the unit runs (`agl stop` first, then `agl start` once it is written). A rewrite keeps the
307
+ * installed unit's `PATH` directories the installing shell lacks (`controllerServicePath`), named in `keptPath`.
277
308
  */
278
309
  public async install(optionsArg: {
279
310
  executable: string;
280
311
  port: number;
281
312
  overrides: IControllerServiceOverrides;
282
- }): Promise<{ changed: boolean; record: plugins.smartdaemon.ISystemdUnitFileRecord; state: plugins.smartdaemon.ISystemdUnitState }> {
283
- const definition = this.definition(optionsArg);
313
+ }): Promise<{
314
+ changed: boolean;
315
+ record: plugins.smartdaemon.ISystemdUnitFileRecord;
316
+ state: plugins.smartdaemon.ISystemdUnitState;
317
+ keptPath: string[];
318
+ }> {
319
+ let definition = this.definition(optionsArg);
284
320
  await this.unit.requireManagerVersion(controllerServiceManagerMajor);
285
321
  await prepareControllerLogFile(this.logFilePath(optionsArg.port));
286
322
  const previous = await this.unitFile.inspect();
323
+ let keptPath: string[] = [];
324
+ if (previous) {
325
+ const installedPath = (await this.unit.inspectServiceSettings()).environment.PATH;
326
+ const merged = await controllerServicePath(controllerServiceEnvironment(this.environment).PATH, installedPath);
327
+ keptPath = merged.kept;
328
+ if (keptPath.length > 0) definition = this.definition({ ...optionsArg, path: merged.path });
329
+ }
287
330
  let record = previous;
288
331
  let changed = false;
289
332
  if (previous?.sha256 !== definition.sha256) {
@@ -301,7 +344,7 @@ export class AglControllerService {
301
344
  }
302
345
  let state = await this.unit.inspect();
303
346
  if (state.unitFileState !== 'enabled') state = await this.unit.enable();
304
- return { changed, record: record!, state };
347
+ return { changed, record: record!, state, keptPath };
305
348
  }
306
349
 
307
350
  /** The installed unit, or null when no unit file exists; the manager is contacted only when one does. */
@@ -14,6 +14,7 @@ import {
14
14
  filesystemIdentitiesEqual,
15
15
  } from './functions.canonicaldirectory.js';
16
16
  import { controllerProjectLimit } from './interfaces.projects.js';
17
+ import { controllerMcpMaximumNodeMajorExclusive, controllerMcpMinimumNodeMajor } from './classes.mcpplatform.js';
17
18
  import {
18
19
  FlexHostRequestFailureError,
19
20
  FlexServiceError,
@@ -209,7 +210,6 @@ interface IFlexUploadGrant {
209
210
  runId?: string;
210
211
  }
211
212
 
212
- const supportedNodeMajors = new Set([24, 25]);
213
213
  const toolOutputBytes = 256 * 1024;
214
214
  const providerOperationTimeoutMs = 30_000;
215
215
  const flexModelHintPrefix = 'hcon-flex-choice:';
@@ -532,9 +532,14 @@ export const projectFlexChildError = (
532
532
  publicFlexChildFailure(errorArg) ?? opaqueArg
533
533
  );
534
534
 
535
+ /**
536
+ * Flex runs on the Node.js majors AGL itself runs on (`engines`, the range `agl mcp` checks), on Linux x64 (AGL-1156).
537
+ * It used to stop at 25 while `engines` admitted 26, so a controller on Node.js 26 had no Flex.
538
+ */
535
539
  const runtimeSupported = (): boolean => {
536
540
  const major = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10);
537
- return supportedNodeMajors.has(major) && process.platform === 'linux' && process.arch === 'x64';
541
+ return major >= controllerMcpMinimumNodeMajor && major < controllerMcpMaximumNodeMajorExclusive
542
+ && process.platform === 'linux' && process.arch === 'x64';
538
543
  };
539
544
 
540
545
  const maximumPromptCorrelations = flexIpcMaximumPromptQueueEntries * 2;