agl 41.2.0 → 42.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/changelog.md +41 -0
  2. package/dist_serve/bundle.js +2625 -2278
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +3 -68
  5. package/dist_serve/bundle.js.third-party-notices.txt +4 -137
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +4 -4
  8. package/dist_ts/classes.authmodels.d.ts +2 -8
  9. package/dist_ts/classes.authmodels.js +60 -23
  10. package/dist_ts/classes.authstore.d.ts +24 -0
  11. package/dist_ts/classes.authstore.js +185 -23
  12. package/dist_ts/classes.cli.d.ts +3 -6
  13. package/dist_ts/classes.cli.js +38 -51
  14. package/dist_ts/classes.config.d.ts +17 -3
  15. package/dist_ts/classes.config.js +55 -18
  16. package/dist_ts/classes.controller.d.ts +83 -14
  17. package/dist_ts/classes.controller.js +545 -229
  18. package/dist_ts/classes.controllerdevices.d.ts +128 -0
  19. package/dist_ts/classes.controllerdevices.js +472 -0
  20. package/dist_ts/classes.controllermanagement.d.ts +42 -9
  21. package/dist_ts/classes.controllermanagement.js +72 -23
  22. package/dist_ts/classes.controllerservice.d.ts +3 -31
  23. package/dist_ts/classes.controllerservice.js +3 -47
  24. package/dist_ts/classes.mcpcontrollerhost.js +9 -3
  25. package/dist_ts/classes.processinspection.d.ts +8 -1
  26. package/dist_ts/classes.processinspection.js +92 -2
  27. package/dist_ts/classes.proxycontrol.js +6 -1
  28. package/dist_ts/classes.proxydaemon.d.ts +2 -2
  29. package/dist_ts/classes.proxydaemon.js +1 -1
  30. package/dist_ts/classes.proxystore.d.ts +2 -11
  31. package/dist_ts/classes.proxystore.js +3 -25
  32. package/dist_ts/classes.sessionfeed.d.ts +10 -1
  33. package/dist_ts/classes.sessionfeed.js +12 -2
  34. package/dist_ts/classes.tpmsecretcodec.d.ts +13 -0
  35. package/dist_ts/classes.tpmsecretcodec.js +28 -0
  36. package/dist_ts/classes.trustedproxysecrets.d.ts +91 -0
  37. package/dist_ts/classes.trustedproxysecrets.js +338 -0
  38. package/dist_ts/classes.upgradecoordinator.d.ts +14 -1
  39. package/dist_ts/classes.upgradecoordinator.js +21 -3
  40. package/dist_ts/classes.upgradetransaction.d.ts +32 -0
  41. package/dist_ts/classes.upgradetransaction.js +101 -4
  42. package/dist_ts/classes.validation.d.ts +2 -0
  43. package/dist_ts/classes.validation.js +2 -2
  44. package/dist_ts/functions.controlleradmission.d.ts +67 -0
  45. package/dist_ts/functions.controlleradmission.js +127 -0
  46. package/dist_ts/functions.deviceapi.d.ts +28 -0
  47. package/dist_ts/functions.deviceapi.js +246 -0
  48. package/dist_ts/functions.deviceproof.d.ts +33 -0
  49. package/dist_ts/functions.deviceproof.js +93 -0
  50. package/dist_ts/functions.remotecli.d.ts +27 -0
  51. package/dist_ts/functions.remotecli.js +241 -0
  52. package/dist_ts/functions.retiredenvironment.d.ts +11 -2
  53. package/dist_ts/functions.retiredenvironment.js +22 -5
  54. package/dist_ts/index.d.ts +1 -0
  55. package/dist_ts/index.js +2 -1
  56. package/dist_ts/interfaces.auth.d.ts +29 -4
  57. package/dist_ts/interfaces.auth.js +10 -1
  58. package/dist_ts/interfaces.config.d.ts +14 -0
  59. package/dist_ts/interfaces.config.js +9 -2
  60. package/dist_ts/interfaces.lifecycle.d.ts +3 -0
  61. package/dist_ts_authswitch/classes.authoritydaemon.js +6 -1
  62. package/dist_ts_interfaces/devices.d.ts +331 -0
  63. package/dist_ts_interfaces/devices.js +34 -0
  64. package/dist_ts_interfaces/index.d.ts +2 -0
  65. package/dist_ts_interfaces/index.js +3 -1
  66. package/dist_ts_interfaces/interfaces.d.ts +5 -3
  67. package/dist_ts_interfaces/interfaces.js +3 -2
  68. package/dist_ts_interfaces/management.d.ts +2 -2
  69. package/dist_ts_interfaces/management.js +2 -2
  70. package/dist_ts_interfaces/mcprequests.d.ts +1 -1
  71. package/dist_ts_interfaces/requests.d.ts +2 -2
  72. package/dist_ts_interfaces/requests.devices.d.ts +89 -0
  73. package/dist_ts_interfaces/requests.devices.js +2 -0
  74. package/dist_ts_interfaces/requests.upgrade.d.ts +0 -12
  75. package/package.json +12 -11
  76. package/readme.md +116 -24
  77. package/ts/00_commitinfo_data.ts +1 -1
  78. package/ts/aglapi/aglapisurface.document.ts +3 -3
  79. package/ts/classes.authmodels.ts +68 -25
  80. package/ts/classes.authstore.ts +183 -24
  81. package/ts/classes.cli.ts +38 -61
  82. package/ts/classes.config.ts +70 -21
  83. package/ts/classes.controller.ts +746 -329
  84. package/ts/classes.controllerdevices.ts +469 -0
  85. package/ts/classes.controllermanagement.ts +123 -49
  86. package/ts/classes.controllerservice.ts +3 -56
  87. package/ts/classes.mcpcontrollerhost.ts +10 -5
  88. package/ts/classes.processinspection.ts +84 -3
  89. package/ts/classes.proxycontrol.ts +2 -0
  90. package/ts/classes.proxydaemon.ts +3 -2
  91. package/ts/classes.proxystore.ts +4 -25
  92. package/ts/classes.sessionfeed.ts +13 -1
  93. package/ts/classes.tpmsecretcodec.ts +26 -0
  94. package/ts/classes.trustedproxysecrets.ts +317 -0
  95. package/ts/classes.upgradecoordinator.ts +33 -3
  96. package/ts/classes.upgradetransaction.ts +130 -1
  97. package/ts/classes.validation.ts +1 -1
  98. package/ts/functions.controlleradmission.ts +168 -0
  99. package/ts/functions.deviceapi.ts +295 -0
  100. package/ts/functions.deviceproof.ts +118 -0
  101. package/ts/functions.remotecli.ts +270 -0
  102. package/ts/functions.retiredenvironment.ts +25 -3
  103. package/ts/index.ts +1 -0
  104. package/ts/interfaces.auth.ts +41 -3
  105. package/ts/interfaces.config.ts +15 -0
  106. package/ts/interfaces.lifecycle.ts +3 -0
  107. package/ts_authswitch/classes.authoritydaemon.ts +2 -0
  108. package/ts_interfaces/devices.schema.json +890 -0
  109. package/ts_interfaces/devices.ts +392 -0
  110. package/ts_interfaces/index.ts +2 -0
  111. package/ts_interfaces/interfaces.ts +5 -2
  112. package/ts_interfaces/management.ts +2 -2
  113. package/ts_interfaces/mcprequests.ts +1 -1
  114. package/ts_interfaces/requests.devices.ts +95 -0
  115. package/ts_interfaces/requests.ts +10 -10
  116. package/ts_interfaces/requests.upgrade.ts +0 -16
  117. package/ts_web/00_commitinfo_data.ts +1 -1
  118. package/ts_web/classes.controllersocketclient.ts +27 -0
  119. package/ts_web/elements.devices.ts +752 -0
  120. package/ts_web/elements.harnesscontrollerapp.ts +18 -1
@@ -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
+ }