@matterbridge/core 3.11.3-dev-20261107-92e4713 → 3.11.3-dev-20261113-e1fbc0d

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 (35) hide show
  1. package/dist/backend.d.ts +1 -0
  2. package/dist/backend.js +7 -6
  3. package/dist/backendExpress.d.ts +0 -1
  4. package/dist/backendExpress.js +11 -1
  5. package/dist/backendWsServer.d.ts +2 -1
  6. package/dist/backendWsServer.js +113 -6
  7. package/dist/behaviors/export.d.ts +3 -0
  8. package/dist/behaviors/export.js +3 -0
  9. package/dist/behaviors/snapshot.js +0 -19
  10. package/dist/behaviors/timeSynchronizationServer.d.ts +34 -0
  11. package/dist/behaviors/timeSynchronizationServer.js +202 -0
  12. package/dist/behaviors/tlsCertificateManagementServer.d.ts +58 -0
  13. package/dist/behaviors/tlsCertificateManagementServer.js +352 -0
  14. package/dist/behaviors/tlsClientManagementServer.d.ts +21 -0
  15. package/dist/behaviors/tlsClientManagementServer.js +110 -0
  16. package/dist/behaviors/windowCoveringServer.d.ts +63 -0
  17. package/dist/behaviors/windowCoveringServer.js +3 -0
  18. package/dist/cli.js +1 -1
  19. package/dist/clusters/closure-control.js +1 -1
  20. package/dist/clusters/closure-dimension.js +1 -1
  21. package/dist/clusters/soil-measurement.js +1 -1
  22. package/dist/frontend.d.ts +2 -2
  23. package/dist/frontend.js +36 -36
  24. package/dist/matterNode.d.ts +4 -1
  25. package/dist/matterNode.js +58 -20
  26. package/dist/matterNodeHelpers.d.ts +102 -0
  27. package/dist/matterNodeHelpers.js +44 -0
  28. package/dist/matterbridge.js +15 -19
  29. package/dist/matterbridgeEndpoint.js +5 -63
  30. package/dist/matterbridgeEndpointCommandHandler.d.ts +0 -25
  31. package/dist/matterbridgeEndpointHelpers.d.ts +5 -0
  32. package/dist/matterbridgeEndpointHelpers.js +82 -3
  33. package/dist/matterbridgePlatform.js +52 -0
  34. package/dist/pluginManager.js +24 -1
  35. package/package.json +5 -5
package/dist/backend.d.ts CHANGED
@@ -20,6 +20,7 @@ export declare class Backend extends EventEmitter<BackendEvents> {
20
20
  private listening;
21
21
  private httpServer;
22
22
  private httpsServer;
23
+ serverFetchTimeout: number;
23
24
  readonly secure: boolean;
24
25
  readonly requestCert: boolean;
25
26
  backendExpress: BackendExpress | undefined;
package/dist/backend.js CHANGED
@@ -21,6 +21,7 @@ export class Backend extends EventEmitter {
21
21
  listening = false;
22
22
  httpServer;
23
23
  httpsServer;
24
+ serverFetchTimeout = 5000;
24
25
  secure;
25
26
  requestCert;
26
27
  backendExpress;
@@ -329,28 +330,28 @@ export class Backend extends EventEmitter {
329
330
  }
330
331
  async getApiSettings() {
331
332
  const start = performance.now();
332
- const response = await this.server.fetch({ type: 'matterbridge_apisettings', src: this.server.name, dst: 'matterbridge', params: {} });
333
+ const response = await this.server.fetch({ type: 'matterbridge_apisettings', src: this.server.name, dst: 'matterbridge', params: {} }, this.serverFetchTimeout);
333
334
  if (this.diagnostic)
334
335
  writeDiagnostic('Backend', `getApiSettings() took ${(performance.now() - start).toFixed(2)} ms`);
335
336
  return response.result.data;
336
337
  }
337
338
  async getApiPlugins() {
338
339
  const start = performance.now();
339
- const response = await this.server.fetch({ type: 'plugins_apipluginarray', src: this.server.name, dst: 'plugins', params: undefined });
340
+ const response = await this.server.fetch({ type: 'plugins_apipluginarray', src: this.server.name, dst: 'plugins', params: undefined }, this.serverFetchTimeout);
340
341
  if (this.diagnostic)
341
342
  writeDiagnostic('Backend', `getApiPlugins() took ${(performance.now() - start).toFixed(2)} ms`);
342
343
  return response.result.plugins;
343
344
  }
344
345
  async getDevices(pluginName) {
345
346
  const start = performance.now();
346
- const response = await this.server.fetch({ type: 'devices_array', src: 'frontend', dst: 'devices', params: { pluginName } });
347
+ const response = await this.server.fetch({ type: 'devices_array', src: 'frontend', dst: 'devices', params: { pluginName } }, this.serverFetchTimeout);
347
348
  if (this.diagnostic)
348
349
  writeDiagnostic('Backend', `getDevices() took ${(performance.now() - start).toFixed(2)} ms`);
349
350
  return response.result.devices;
350
351
  }
351
352
  async getApiDevices(pluginName, extended = false) {
352
353
  const start = performance.now();
353
- const response = await this.server.fetch({ type: 'platform_get_apidevices', src: 'frontend', dst: 'platform', params: { pluginName, extended } });
354
+ const response = await this.server.fetch({ type: 'platform_get_apidevices', src: 'frontend', dst: 'platform', params: { pluginName, extended } }, this.serverFetchTimeout);
354
355
  if (this.diagnostic)
355
356
  writeDiagnostic('Backend', `getApiDevices() took ${(performance.now() - start).toFixed(2)} ms`);
356
357
  return response.result.devices;
@@ -363,7 +364,7 @@ export class Backend extends EventEmitter {
363
364
  src: 'frontend',
364
365
  dst: 'platform',
365
366
  params: { pluginName, number, serialNumber, uniqueId },
366
- });
367
+ }, this.serverFetchTimeout);
367
368
  if (this.diagnostic)
368
369
  writeDiagnostic('Backend', `getApiCluster() took ${(performance.now() - start).toFixed(2)} ms`);
369
370
  return response.result.clusters;
@@ -375,7 +376,7 @@ export class Backend extends EventEmitter {
375
376
  }
376
377
  async getApiMatter(id) {
377
378
  const start = performance.now();
378
- const response = await this.server.fetch({ type: 'matter_apimatter', src: 'frontend', dst: 'matter', params: { id } });
379
+ const response = await this.server.fetch({ type: 'matter_apimatter', src: 'frontend', dst: 'matter', params: { id } }, this.serverFetchTimeout);
379
380
  if (this.diagnostic)
380
381
  writeDiagnostic('Backend', `getApiMatter() took ${(performance.now() - start).toFixed(2)} ms`);
381
382
  return response.result.matter;
@@ -11,7 +11,6 @@ export declare class BackendExpress {
11
11
  private readonly server;
12
12
  private fileLimiter;
13
13
  expressApp: express.Application | undefined;
14
- serverFetchTimeout: number;
15
14
  constructor(matterbridge: SharedMatterbridge, backend: Backend);
16
15
  destroy(): void;
17
16
  private broadcastMsgHandler;
@@ -32,7 +32,6 @@ export class BackendExpress {
32
32
  limit: 20,
33
33
  });
34
34
  expressApp;
35
- serverFetchTimeout = 5000;
36
35
  constructor(matterbridge, backend) {
37
36
  this.debug = hasAnyParameter('debug', 'verbose', 'debug-backend', 'verbose-backend');
38
37
  this.verbose = hasAnyParameter('verbose', 'verbose-backend');
@@ -162,6 +161,17 @@ export class BackendExpress {
162
161
  return;
163
162
  res.json(await this.backend.getDevices());
164
163
  });
164
+ this.expressApp.get('/api/platform-devices', async (req, res) => {
165
+ this.log.debug('The frontend sent /api/platform-devices');
166
+ if (!this.validateReq(req, res))
167
+ return;
168
+ const pluginName = req.query.pluginName;
169
+ if (typeof pluginName !== 'string' || pluginName.length < 10) {
170
+ res.status(400).json({ error: 'Wrong parameter pluginName in /api/platform-devices' });
171
+ return;
172
+ }
173
+ res.json(await this.backend.getApiDevices(pluginName, req.query.extended === 'true'));
174
+ });
165
175
  this.expressApp.get('/api/view-mblog', async (req, res) => {
166
176
  this.log.debug('The frontend sent /api/view-mblog');
167
177
  if (!this.validateReq(req, res))
@@ -1,4 +1,4 @@
1
- import type { ApiMatter, BridgeStatus, PluginStatusUpdate, RefreshRequiredChanged, SharedMatterbridge, WsMessageBroadcast } from '@matterbridge/types';
1
+ import { type ApiMatter, type BridgeStatus, type PluginStatusUpdate, type RefreshRequiredChanged, type SharedMatterbridge, type WsMessageBroadcast } from '@matterbridge/types';
2
2
  import { WebSocketServer } from 'ws';
3
3
  import type { Backend } from './backend.js';
4
4
  export declare class BackendWsServer {
@@ -32,4 +32,5 @@ export declare class BackendWsServer {
32
32
  wssSendSnackbarMessage(message: string, timeout?: number, severity?: 'info' | 'warning' | 'error' | 'success'): void;
33
33
  wssSendCloseSnackbarMessage(message: string): void;
34
34
  wssSendAttributeChangedMessage(plugin: string, serialNumber: string, uniqueId: string, number: number, id: string, cluster: string, attribute: string, value: number | string | boolean | null): void;
35
+ private zip;
35
36
  }
@@ -1,13 +1,17 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
1
3
  import { Logger, LogLevel as MatterLogLevel } from '@matter/general';
2
4
  import { BroadcastServer } from '@matterbridge/thread/server';
5
+ import { MATTER_STORAGE_DIR, MATTERBRIDGE_BACKUP_FILE, MATTERBRIDGE_HISTORY_FILE, MATTERBRIDGE_PLUGIN_CONFIG_FILE, MATTERBRIDGE_PLUGIN_STORAGE_FILE, NODE_STORAGE_DIR, } from '@matterbridge/types';
3
6
  import { hasAnyParameter } from '@matterbridge/utils/cli';
4
7
  import { writeDiagnostic } from '@matterbridge/utils/diagnostic';
5
- import { inspectError } from '@matterbridge/utils/error';
8
+ import { getErrorMessage, inspectError } from '@matterbridge/utils/error';
6
9
  import { logModuleLoaded } from '@matterbridge/utils/loader';
7
- import { isValidNumber, isValidString } from '@matterbridge/utils/validate';
10
+ import { isValidArray, isValidNumber, isValidString } from '@matterbridge/utils/validate';
8
11
  import { fireAndForget, withTimeout } from '@matterbridge/utils/wait';
9
12
  import { AnsiLogger, CYAN, debugStringify, nf } from 'node-ansi-logger';
10
13
  import { WebSocket, WebSocketServer } from 'ws';
14
+ import { generateHistoryPage } from './cliHistory.js';
11
15
  logModuleLoaded('BackendWsServer');
12
16
  export class BackendWsServer {
13
17
  debug;
@@ -46,12 +50,41 @@ export class BackendWsServer {
46
50
  this.log.logLevel = msg.params.logLevel;
47
51
  this.server.respond({ ...msg, result: { logLevel: this.log.logLevel } });
48
52
  break;
53
+ case 'frontend_matterbridgestatusupdate':
54
+ this.wssSendMatterbridgeStatusUpdate(msg.params.status);
55
+ this.server.respond({ ...msg, result: { success: true } });
56
+ break;
49
57
  case 'frontend_broadcast_message':
50
58
  this.wssBroadcastMessage(msg.params.msg);
51
59
  this.server.respond({ ...msg, result: { success: true } });
52
60
  break;
53
61
  }
54
62
  }
63
+ if (this.server.isWorkerResponse(msg) && (msg.dst === 'all' || msg.dst === 'frontend')) {
64
+ switch (msg.type) {
65
+ case 'manager_archive_response':
66
+ if (msg.result?.success &&
67
+ isValidString(msg.result.command) &&
68
+ isValidString(msg.result.archivePath) &&
69
+ isValidArray(msg.result.sourcePaths) &&
70
+ isValidString(msg.result.destinationPath)) {
71
+ this.wssBroadcastMessage({
72
+ id: 0,
73
+ src: 'Matterbridge',
74
+ dst: 'Frontend',
75
+ method: 'archive',
76
+ success: true,
77
+ response: {
78
+ command: msg.result.command,
79
+ archivePath: msg.result.archivePath,
80
+ sourcePaths: msg.result.sourcePaths,
81
+ destinationPath: msg.result.destinationPath,
82
+ },
83
+ });
84
+ }
85
+ break;
86
+ }
87
+ }
55
88
  }
56
89
  async start() {
57
90
  this.log.debug(`Creating WebSocketServer...`);
@@ -185,12 +218,12 @@ export class BackendWsServer {
185
218
  }
186
219
  else if (data.method === '/api/restart') {
187
220
  this.wssSendSnackbarMessage('Restarting matterbridge...', 0);
188
- await this.server.fetch({ type: 'matterbridge_restart', src: 'frontend', dst: 'matterbridge', params: undefined });
221
+ await this.server.fetch({ type: 'matterbridge_restart', src: 'frontend', dst: 'matterbridge', params: undefined }, this.backend.serverFetchTimeout);
189
222
  sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
190
223
  }
191
224
  else if (data.method === '/api/shutdown') {
192
225
  this.wssSendSnackbarMessage('Shutting down matterbridge...', 0);
193
- await this.server.fetch({ type: 'matterbridge_shutdown', src: 'frontend', dst: 'matterbridge', params: undefined });
226
+ await this.server.fetch({ type: 'matterbridge_shutdown', src: 'frontend', dst: 'matterbridge', params: undefined }, this.backend.serverFetchTimeout);
194
227
  sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
195
228
  }
196
229
  else if (data.method === '/api/settings') {
@@ -211,7 +244,7 @@ export class BackendWsServer {
211
244
  const start = performance.now();
212
245
  const devices = await this.backend.getDevices(isValidString(data.params.pluginName) ? data.params.pluginName : undefined);
213
246
  if (this.diagnostic)
214
- writeDiagnostic(`Frontend:${data.sender}`, `getDevices() took ${(performance.now() - start).toFixed(2)} ms`);
247
+ writeDiagnostic(`Frontend:${data.sender}`, `getDevices(${data.params.pluginName}) took ${(performance.now() - start).toFixed(2)} ms`);
215
248
  sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true, response: devices });
216
249
  }
217
250
  else if (data.method === '/api/platform-devices') {
@@ -222,7 +255,7 @@ export class BackendWsServer {
222
255
  const start = performance.now();
223
256
  const devices = await this.backend.getApiDevices(data.params.pluginName, data.params.extended);
224
257
  if (this.diagnostic)
225
- writeDiagnostic(`Frontend:${data.sender}`, `getApiDevices() took ${(performance.now() - start).toFixed(2)} ms`);
258
+ writeDiagnostic(`Frontend:${data.sender}`, `getApiDevices(${data.params.pluginName}) took ${(performance.now() - start).toFixed(2)} ms`);
226
259
  sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true, pluginName: data.params.pluginName, response: devices });
227
260
  }
228
261
  else if (data.method === '/api/clusters') {
@@ -306,6 +339,72 @@ export class BackendWsServer {
306
339
  this.server.request({ type: 'platform_rename_device', src: 'frontend', dst: 'platform', params: { pluginName, serialNumber, uniqueId, label } });
307
340
  sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
308
341
  }
342
+ else if (data.method === '/api/select' || data.method === '/api/unselect') {
343
+ if (!isValidString(data.params.pluginName, 10)) {
344
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, error: `Wrong parameter pluginName in ${data.method}` });
345
+ return;
346
+ }
347
+ if (!isValidString(data.params.serialNumber, 1)) {
348
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, error: `Wrong parameter serialNumber in ${data.method}` });
349
+ return;
350
+ }
351
+ if (!isValidString(data.params.deviceName, 1)) {
352
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, error: `Wrong parameter deviceName in ${data.method}` });
353
+ return;
354
+ }
355
+ const { pluginName, serialNumber, deviceName } = data.params;
356
+ const type = data.method === '/api/select' ? 'platform_select_device' : 'platform_unselect_device';
357
+ try {
358
+ await this.server.fetch({ type, src: 'frontend', dst: 'platform', params: { pluginName, serialNumber, deviceName } }, this.backend.serverFetchTimeout);
359
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
360
+ }
361
+ catch (error) {
362
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, error: getErrorMessage(error) });
363
+ }
364
+ }
365
+ else if (data.method === '/api/create-backup') {
366
+ this.wssSendSnackbarMessage('Creating matterbridge backup...', 0);
367
+ this.log.notice(`Creating matterbridge backup...`);
368
+ const backupDirs = [this.matterbridge.matterbridgeDirectory, this.matterbridge.matterbridgePluginDirectory, this.matterbridge.matterbridgeCertDirectory];
369
+ const backupNames = this.matterbridge.profile ? backupDirs.map((dir) => path.basename(path.dirname(path.dirname(dir)))) : undefined;
370
+ this.zip('zip', path.join(os.tmpdir(), MATTERBRIDGE_BACKUP_FILE), backupDirs, '', backupNames);
371
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
372
+ }
373
+ else if (data.method === '/api/create-matterbridge-storage-backup') {
374
+ this.wssSendSnackbarMessage('Creating matterbridge storage backup...', 0);
375
+ this.log.notice(`Creating matterbridge storage backup...`);
376
+ this.zip('zip', path.join(os.tmpdir(), `matterbridge.${NODE_STORAGE_DIR}.zip`), [path.join(this.matterbridge.matterbridgeDirectory, NODE_STORAGE_DIR)], '');
377
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
378
+ }
379
+ else if (data.method === '/api/create-matter-storage-backup') {
380
+ this.wssSendSnackbarMessage('Creating matter storage backup...', 0);
381
+ this.log.notice(`Creating matter storage backup...`);
382
+ this.zip('zip', path.join(os.tmpdir(), `matterbridge.${MATTER_STORAGE_DIR}.zip`), [path.join(this.matterbridge.matterbridgeDirectory, MATTER_STORAGE_DIR)], '');
383
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
384
+ }
385
+ else if (data.method === '/api/create-plugin-backup') {
386
+ this.wssSendSnackbarMessage('Creating plugin backup...', 0);
387
+ this.log.notice(`Creating plugin backup...`);
388
+ this.zip('zip', path.join(os.tmpdir(), MATTERBRIDGE_PLUGIN_STORAGE_FILE), [this.matterbridge.matterbridgePluginDirectory], '');
389
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
390
+ }
391
+ else if (data.method === '/api/create-config-backup') {
392
+ this.wssSendSnackbarMessage('Creating config backup...', 0);
393
+ this.log.notice(`Creating config backup...`);
394
+ const plugins = (await this.server.fetch({ type: 'plugins_storagepluginarray', src: 'frontend', dst: 'plugins', params: undefined }, this.backend.serverFetchTimeout))
395
+ .result.plugins;
396
+ const pluginsPaths = plugins.map((p) => path.join(this.matterbridge.matterbridgeDirectory, p.name + '.config.json'));
397
+ this.zip('zip', path.join(os.tmpdir(), MATTERBRIDGE_PLUGIN_CONFIG_FILE), pluginsPaths, '');
398
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
399
+ }
400
+ else if (data.method === '/api/view-historypage') {
401
+ generateHistoryPage({ outputPath: path.join(this.matterbridge.matterbridgeDirectory, MATTERBRIDGE_HISTORY_FILE), pageTitle: `Matterbridge Cpu & Memory History` });
402
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
403
+ }
404
+ else if (data.method === '/api/download-historypage') {
405
+ generateHistoryPage({ outputPath: path.join(this.matterbridge.matterbridgeDirectory, MATTERBRIDGE_HISTORY_FILE), pageTitle: `Matterbridge Cpu & Memory History` });
406
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
407
+ }
309
408
  }
310
409
  catch (error) {
311
410
  inspectError(this.log, `Error parsing message from websocket client`, error);
@@ -434,4 +533,12 @@ export class BackendWsServer {
434
533
  response: { plugin, serialNumber, uniqueId, number, id, cluster, attribute, value },
435
534
  });
436
535
  }
536
+ zip(command, archivePath, sourcePaths, destinationPath, archiveNames) {
537
+ this.server.request({
538
+ type: 'manager_run',
539
+ src: 'frontend',
540
+ dst: 'manager',
541
+ params: { name: 'ArchiveCommand', workerData: { threadName: 'ArchiveCommand', command, archivePath, sourcePaths, destinationPath, archiveNames } },
542
+ });
543
+ }
437
544
  }
@@ -22,6 +22,9 @@ export * from './smokeCoAlarmServer.js';
22
22
  export * from './switchServer.js';
23
23
  export * from './temperatureAlarmServer.js';
24
24
  export * from './thermostatServer.js';
25
+ export * from './timeSynchronizationServer.js';
26
+ export * from './tlsCertificateManagementServer.js';
27
+ export * from './tlsClientManagementServer.js';
25
28
  export * from './valveConfigurationAndControlServer.js';
26
29
  export * from './waterTankLevelMonitoringServer.js';
27
30
  export * from './windowCoveringServer.js';
@@ -22,6 +22,9 @@ export * from './smokeCoAlarmServer.js';
22
22
  export * from './switchServer.js';
23
23
  export * from './temperatureAlarmServer.js';
24
24
  export * from './thermostatServer.js';
25
+ export * from './timeSynchronizationServer.js';
26
+ export * from './tlsCertificateManagementServer.js';
27
+ export * from './tlsClientManagementServer.js';
25
28
  export * from './valveConfigurationAndControlServer.js';
26
29
  export * from './waterTankLevelMonitoringServer.js';
27
30
  export * from './windowCoveringServer.js';
@@ -1,6 +1,3 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
1
  import { AnsiLogger, MAGENTA } from 'node-ansi-logger';
5
2
  import { hasFfmpeg, redactSource, runFfmpeg } from './ffmpeg.js';
6
3
  const MAX_BYTES = 64000;
@@ -126,19 +123,3 @@ async function grab(src, width, height, q) {
126
123
  });
127
124
  });
128
125
  }
129
- if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
130
- const src = process.argv[2] ?? 'Surface Camera Front';
131
- const outputDir = path.join(process.cwd(), 'temp');
132
- await mkdir(outputDir, { recursive: true });
133
- const resolutions = [
134
- { width: 640, height: 480 },
135
- { width: 1280, height: 720 },
136
- { width: 1920, height: 1080 },
137
- ];
138
- for (const { width, height } of resolutions) {
139
- const result = await captureSnapshot({ src, width, height });
140
- const outputFile = path.join(outputDir, `snapshot-${width}x${height}.jpeg`);
141
- await writeFile(outputFile, result.data);
142
- log.info(`Saved snapshot to ${outputFile} (${result.byteLength}B, ${result.width}x${result.height}, quality=${result.quality}, downgraded=${result.downgraded})`);
143
- }
144
- }
@@ -0,0 +1,34 @@
1
+ import { type Timer } from '@matter/general';
2
+ import { TimeSynchronizationServer } from '@matter/node/behaviors/time-synchronization';
3
+ import { TimeSynchronization } from '@matter/types/clusters/time-synchronization';
4
+ export declare const MATTER_EPOCH_US = 946684800000000n;
5
+ export declare function isCanonicalIpv6(address: string): boolean;
6
+ declare const MatterbridgeTimeSynchronizationServerBase: import("@matter/node").ClusterBehavior.Type<import("@matter/node").ClusterBehavior.Type<typeof TimeSynchronizationServer, TimeSynchronization, typeof TimeSynchronization, new () => {}, "timeSynchronization"> & {
7
+ readonly id: "timeSynchronization";
8
+ }, import("@matter/types").ClusterType.WithSupportedFeatures<TimeSynchronization, {
9
+ ntpClient: true;
10
+ ntpServer: false;
11
+ timeSyncClient: true;
12
+ timeZone: true;
13
+ }>, import("@matter/types").ClusterType.Concrete, new () => {}, "timeSynchronization">;
14
+ export declare class MatterbridgeTimeSynchronizationServer extends MatterbridgeTimeSynchronizationServerBase {
15
+ #private;
16
+ internal: MatterbridgeTimeSynchronizationServer.Internal;
17
+ initialize(): void;
18
+ [Symbol.asyncDispose](): Promise<void>;
19
+ updateClock(): void;
20
+ setUtcTime(request: TimeSynchronization.SetUtcTimeRequest): void;
21
+ setTrustedTimeSource(request: TimeSynchronization.SetTrustedTimeSourceRequest): void;
22
+ setDefaultNtp(request: TimeSynchronization.SetDefaultNtpRequest): void;
23
+ setTimeZone(request: TimeSynchronization.SetTimeZoneRequest): TimeSynchronization.SetTimeZoneResponse;
24
+ setDstOffset(request: TimeSynchronization.SetDstOffsetRequest): void;
25
+ }
26
+ export declare namespace MatterbridgeTimeSynchronizationServer {
27
+ class Internal {
28
+ clockTimer?: Timer;
29
+ dstActive: boolean;
30
+ ready: boolean;
31
+ dstTableEmptyAt?: bigint;
32
+ }
33
+ }
34
+ export {};
@@ -0,0 +1,202 @@
1
+ import { isIPv4, isIPv6 } from 'node:net';
2
+ import { Seconds, Time } from '@matter/general';
3
+ import { CommandModel, FieldModel } from '@matter/main/model';
4
+ import { Node } from '@matter/node';
5
+ import { OperationalCredentialsServer } from '@matter/node/behaviors/operational-credentials';
6
+ import { TimeSynchronizationServer } from '@matter/node/behaviors/time-synchronization';
7
+ import { TimeSynchronization } from '@matter/types/clusters/time-synchronization';
8
+ import { StatusResponseError } from '@matter/types/common';
9
+ import { Status } from '@matter/types/globals';
10
+ import { AnsiLogger, MAGENTA } from 'node-ansi-logger';
11
+ export const MATTER_EPOCH_US = 946684800000000n;
12
+ const CLOCK_INTERVAL = Seconds(1);
13
+ const DST_TABLE_EMPTY_INTERVAL_US = 3600000000n;
14
+ const HOSTNAME_REGEX = /^(?=.{1,253}$)(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))*$/i;
15
+ const log = new AnsiLogger({ logName: 'TimeSync', logLevel: "info", logNameColor: MAGENTA, logTimestampFormat: 4 });
16
+ function nowUs() {
17
+ return BigInt(Time.nowMs) * 1000n;
18
+ }
19
+ export function isCanonicalIpv6(address) {
20
+ if (!isIPv6(address) || address.includes('%'))
21
+ return false;
22
+ if (/^::ffff:\d{1,3}(\.\d{1,3}){3}$/.test(address))
23
+ return true;
24
+ return new URL(`http://[${address}]`).hostname === `[${address}]`;
25
+ }
26
+ const { schema } = TimeSynchronization;
27
+ const setTimeZoneCommand = schema.require(CommandModel, 'SetTimeZone');
28
+ const TimeSynchronizationSchema = schema.extend(undefined, setTimeZoneCommand.extend(undefined, setTimeZoneCommand.require(FieldModel, 'TimeZone').extend({ constraint: 'none' })));
29
+ const MatterbridgeTimeSynchronizationServerBase = TimeSynchronizationServer.for(TimeSynchronization, TimeSynchronizationSchema).with(TimeSynchronization.Feature.TimeSyncClient, TimeSynchronization.Feature.NtpClient, TimeSynchronization.Feature.TimeZone);
30
+ export class MatterbridgeTimeSynchronizationServer extends MatterbridgeTimeSynchronizationServerBase {
31
+ initialize() {
32
+ if (this.state.timeZone.length === 0)
33
+ this.state.timeZone = [{ offset: 0, validAt: MATTER_EPOCH_US }];
34
+ this.state.timeZoneDatabase = TimeSynchronization.TimeZoneDatabase.None;
35
+ this.internal.dstActive = this.#activeDstOffset() !== 0;
36
+ this.updateClock();
37
+ this.internal.ready = true;
38
+ this.internal.clockTimer = Time.getPeriodicTimer('TimeSynchronization clock', CLOCK_INTERVAL, this.callback(this.updateClock, { lock: true })).start();
39
+ const node = Node.forEndpoint(this.endpoint);
40
+ this.reactTo(node.eventsOf(OperationalCredentialsServer).fabrics$Changed, this.#handleFabricsChanged, { offline: true, lock: true });
41
+ }
42
+ async [Symbol.asyncDispose]() {
43
+ this.internal.clockTimer?.stop();
44
+ this.internal.clockTimer = undefined;
45
+ await super[Symbol.asyncDispose]?.();
46
+ }
47
+ updateClock() {
48
+ const now = nowUs();
49
+ this.state.utcTime = now;
50
+ this.state.granularity = TimeSynchronization.Granularity.MillisecondsGranularity;
51
+ this.state.timeSource = TimeSynchronization.TimeSource.Unknown;
52
+ const [currentTimeZone, nextTimeZone] = this.state.timeZone;
53
+ if (nextTimeZone && BigInt(nextTimeZone.validAt) <= now) {
54
+ const { offset, name } = nextTimeZone;
55
+ const changed = offset !== currentTimeZone.offset || name !== currentTimeZone.name;
56
+ this.state.timeZone = [{ offset, validAt: MATTER_EPOCH_US, ...(name === undefined ? {} : { name }) }];
57
+ if (changed) {
58
+ log.info(`MatterbridgeTimeSynchronizationServer: the scheduled TimeZone with offset ${offset}s${name === undefined ? '' : ` (${name})`} became valid, generating TimeZoneStatus (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
59
+ this.events.timeZoneStatus.emit({ offset, name }, this.context);
60
+ }
61
+ }
62
+ const dstOffset = this.state.dstOffset.filter((entry) => entry.validUntil === null || BigInt(entry.validUntil) > now);
63
+ if (dstOffset.length !== this.state.dstOffset.length) {
64
+ this.state.dstOffset = dstOffset;
65
+ if (dstOffset.length === 0) {
66
+ this.#emitDstTableEmpty(now, 'expired');
67
+ }
68
+ }
69
+ else if (dstOffset.length === 0 && (this.internal.dstTableEmptyAt === undefined || now - this.internal.dstTableEmptyAt >= DST_TABLE_EMPTY_INTERVAL_US)) {
70
+ this.#emitDstTableEmpty(now, 'is empty');
71
+ }
72
+ this.#updateDstStatus();
73
+ this.#updateLocalTime(now);
74
+ }
75
+ setUtcTime(request) {
76
+ log.info(`MatterbridgeTimeSynchronizationServer.setUtcTime: time with granularity ${request.granularity} not accepted, the node uses the host clock (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
77
+ throw new TimeSynchronization.TimeNotAcceptedError(`MatterbridgeTimeSynchronizationServer.setUtcTime: time not accepted, the node uses the host clock (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
78
+ }
79
+ setTrustedTimeSource(request) {
80
+ const { trustedTimeSource } = request;
81
+ if (trustedTimeSource === null) {
82
+ this.state.trustedTimeSource = null;
83
+ log.info(`MatterbridgeTimeSynchronizationServer.setTrustedTimeSource: the TrustedTimeSource was cleared, generating MissingTrustedTimeSource (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
84
+ this.events.missingTrustedTimeSource.emit(undefined, this.context);
85
+ return;
86
+ }
87
+ const fabricIndex = this.context.fabric;
88
+ if (fabricIndex === undefined) {
89
+ throw new StatusResponseError(`MatterbridgeTimeSynchronizationServer.setTrustedTimeSource: an accessing fabric is required (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.UnsupportedAccess);
90
+ }
91
+ this.state.trustedTimeSource = { fabricIndex, nodeId: trustedTimeSource.nodeId, endpoint: trustedTimeSource.endpoint };
92
+ log.info(`MatterbridgeTimeSynchronizationServer.setTrustedTimeSource: the TrustedTimeSource was set to node ${trustedTimeSource.nodeId} endpoint ${trustedTimeSource.endpoint} on fabric ${fabricIndex} (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
93
+ }
94
+ setDefaultNtp(request) {
95
+ const { defaultNtp } = request;
96
+ if (defaultNtp !== null && !isCanonicalIpv6(defaultNtp)) {
97
+ if (isIPv4(defaultNtp) || !HOSTNAME_REGEX.test(defaultNtp)) {
98
+ throw new StatusResponseError(`MatterbridgeTimeSynchronizationServer.setDefaultNtp: address ${defaultNtp} is not a domain name or a static IPv6 address (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.InvalidCommand);
99
+ }
100
+ if (!this.state.supportsDnsResolve) {
101
+ throw new StatusResponseError(`MatterbridgeTimeSynchronizationServer.setDefaultNtp: address ${defaultNtp} is a domain name and the node does not support DNS resolution (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.InvalidCommand);
102
+ }
103
+ }
104
+ this.state.defaultNtp = defaultNtp;
105
+ log.info(`MatterbridgeTimeSynchronizationServer.setDefaultNtp: the DefaultNTP was set to ${defaultNtp ?? 'null'} (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
106
+ }
107
+ setTimeZone(request) {
108
+ const { timeZone } = request;
109
+ if (timeZone.length > this.state.timeZoneListMaxSize) {
110
+ throw new StatusResponseError(`MatterbridgeTimeSynchronizationServer.setTimeZone: the list of ${timeZone.length} entries exceeds TimeZoneListMaxSize ${this.state.timeZoneListMaxSize} (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.ResourceExhausted);
111
+ }
112
+ const [first, second] = timeZone;
113
+ if (first === undefined || BigInt(first.validAt) !== MATTER_EPOCH_US || (second !== undefined && BigInt(second.validAt) === MATTER_EPOCH_US)) {
114
+ throw new StatusResponseError(`MatterbridgeTimeSynchronizationServer.setTimeZone: the first entry SHALL have a ValidAt of 0 and a second entry a non-zero ValidAt (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.ConstraintError);
115
+ }
116
+ this.state.timeZone = timeZone;
117
+ const now = nowUs();
118
+ const active = this.#activeTimeZone(now);
119
+ log.info(`MatterbridgeTimeSynchronizationServer.setTimeZone: the TimeZone was set to offset ${active.offset}s${active.name === undefined ? '' : ` (${active.name})`}, generating TimeZoneStatus (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
120
+ this.events.timeZoneStatus.emit({ offset: active.offset, name: active.name }, this.context);
121
+ this.state.dstOffset = [];
122
+ this.#emitDstTableEmpty(now);
123
+ this.#updateDstStatus();
124
+ this.#updateLocalTime(now);
125
+ return { dstOffsetRequired: true };
126
+ }
127
+ setDstOffset(request) {
128
+ const { dstOffset } = request;
129
+ if (dstOffset.length > this.state.dstOffsetListMaxSize) {
130
+ throw new StatusResponseError(`MatterbridgeTimeSynchronizationServer.setDstOffset: the list of ${dstOffset.length} entries exceeds DSTOffsetListMaxSize ${this.state.dstOffsetListMaxSize} (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.ResourceExhausted);
131
+ }
132
+ for (const [index, entry] of dstOffset.entries()) {
133
+ const isLast = index === dstOffset.length - 1;
134
+ const previous = index > 0 ? dstOffset[index - 1] : undefined;
135
+ const validUntilOk = entry.validUntil === null ? isLast : BigInt(entry.validUntil) > BigInt(entry.validStarting);
136
+ const orderOk = previous?.validUntil === null || previous === undefined || BigInt(entry.validStarting) >= BigInt(previous.validUntil);
137
+ if (!validUntilOk || !orderOk) {
138
+ throw new StatusResponseError(`MatterbridgeTimeSynchronizationServer.setDstOffset: entry ${index} does not conform to the DSTOffset list requirements (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.ConstraintError);
139
+ }
140
+ }
141
+ this.state.dstOffset = dstOffset;
142
+ log.info(`MatterbridgeTimeSynchronizationServer.setDstOffset: the DSTOffset was set with ${dstOffset.length} entries (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
143
+ if (dstOffset.length === 0)
144
+ this.#emitDstTableEmpty(nowUs());
145
+ this.#updateDstStatus();
146
+ this.#updateLocalTime(nowUs());
147
+ }
148
+ #handleFabricsChanged(fabrics) {
149
+ if (fabrics.length === 0 && this.state.defaultNtp !== null) {
150
+ this.state.defaultNtp = null;
151
+ log.info(`MatterbridgeTimeSynchronizationServer: the last fabric was removed, the DefaultNTP was cleared (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
152
+ }
153
+ const fabricIndex = this.state.trustedTimeSource?.fabricIndex;
154
+ if (fabricIndex === undefined || fabrics.some((fabric) => fabric.fabricIndex === fabricIndex))
155
+ return;
156
+ this.state.trustedTimeSource = null;
157
+ log.info(`MatterbridgeTimeSynchronizationServer: the TrustedTimeSource fabric ${fabricIndex} was removed, generating MissingTrustedTimeSource (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
158
+ this.events.missingTrustedTimeSource.emit(undefined, this.context);
159
+ }
160
+ #emitDstTableEmpty(now, reason) {
161
+ if (!this.internal.ready)
162
+ return;
163
+ if (reason !== undefined)
164
+ log.info(`MatterbridgeTimeSynchronizationServer: the DSTOffset table ${reason}, generating DSTTableEmpty (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
165
+ this.internal.dstTableEmptyAt = now;
166
+ this.events.dstTableEmpty.emit(undefined, this.context);
167
+ }
168
+ #activeTimeZone(now) {
169
+ const [first, second] = this.state.timeZone;
170
+ return second !== undefined && BigInt(second.validAt) <= now ? second : first;
171
+ }
172
+ #activeDstOffset() {
173
+ const now = nowUs();
174
+ const active = this.state.dstOffset.find((entry) => BigInt(entry.validStarting) <= now && (entry.validUntil === null || now < BigInt(entry.validUntil)));
175
+ return active?.offset ?? 0;
176
+ }
177
+ #updateDstStatus() {
178
+ const dstActive = this.#activeDstOffset() !== 0;
179
+ if (dstActive === this.internal.dstActive)
180
+ return;
181
+ this.internal.dstActive = dstActive;
182
+ log.info(`MatterbridgeTimeSynchronizationServer: the DST offset is ${dstActive ? 'applied' : 'no longer applied'}, generating DSTStatus (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`);
183
+ this.events.dstStatus.emit({ dstOffsetActive: dstActive }, this.context);
184
+ }
185
+ #updateLocalTime(now) {
186
+ if (this.state.dstOffset.length === 0) {
187
+ this.state.localTime = null;
188
+ return;
189
+ }
190
+ const offsetSeconds = this.#activeTimeZone(now).offset + this.#activeDstOffset();
191
+ this.state.localTime = now + BigInt(offsetSeconds) * 1000000n;
192
+ }
193
+ }
194
+ (function (MatterbridgeTimeSynchronizationServer) {
195
+ class Internal {
196
+ clockTimer;
197
+ dstActive = false;
198
+ ready = false;
199
+ dstTableEmptyAt;
200
+ }
201
+ MatterbridgeTimeSynchronizationServer.Internal = Internal;
202
+ })(MatterbridgeTimeSynchronizationServer || (MatterbridgeTimeSynchronizationServer = {}));
@@ -0,0 +1,58 @@
1
+ import { X509Certificate } from 'node:crypto';
2
+ import { TlsCertificateManagementServer } from '@matter/node/behaviors/tls-certificate-management';
3
+ import { Val } from '@matter/protocol';
4
+ import { TlsCertificateManagement } from '@matter/types/clusters/tls-certificate-management';
5
+ export declare const MAX_TLS_CERTIFICATE_ID = 65534;
6
+ export declare const MAX_CERTIFICATE_BYTES = 3000;
7
+ export declare const MAX_FINGERPRINT_BYTES = 64;
8
+ export declare const CLIENT_CSR_NONCE_BYTES = 32;
9
+ export declare const MAX_INTERMEDIATE_CERTIFICATES = 10;
10
+ export declare function createClientCsr(privateKey: Uint8Array): Buffer;
11
+ export declare function signClientCsrNonce(privateKey: Uint8Array, nonce: Uint8Array): Buffer;
12
+ export declare function publicKeyPoint(privateKey: Uint8Array): Buffer;
13
+ export declare function certificateFingerprint(certificate: Uint8Array): Buffer;
14
+ export declare function parseValidCertificate(certificate: Uint8Array): X509Certificate | undefined;
15
+ export declare function allocateId(used: Set<number>, next: number): number;
16
+ declare const MatterbridgeTlsCertificateManagementServerBase: import("@matter/node").ClusterBehavior.Type<typeof TlsCertificateManagementServer, TlsCertificateManagement, typeof TlsCertificateManagement, new () => {}, "tlsCertificateManagement"> & {
17
+ readonly id: "tlsCertificateManagement";
18
+ };
19
+ export declare class MatterbridgeTlsCertificateManagementServer extends MatterbridgeTlsCertificateManagementServerBase {
20
+ #private;
21
+ state: MatterbridgeTlsCertificateManagementServer.State;
22
+ initialize(): void;
23
+ provisionRootCertificate(request: TlsCertificateManagement.ProvisionRootCertificateRequest): TlsCertificateManagement.ProvisionRootCertificateResponse;
24
+ findRootCertificate(request: TlsCertificateManagement.FindRootCertificateRequest): TlsCertificateManagement.FindRootCertificateResponse;
25
+ lookupRootCertificate(request: TlsCertificateManagement.LookupRootCertificateRequest): TlsCertificateManagement.LookupRootCertificateResponse;
26
+ removeRootCertificate(request: TlsCertificateManagement.RemoveRootCertificateRequest): void;
27
+ clientCsr(request: TlsCertificateManagement.ClientCsrRequest): TlsCertificateManagement.ClientCsrResponse;
28
+ generateClientKey(): Uint8Array;
29
+ provisionClientCertificate(request: TlsCertificateManagement.ProvisionClientCertificateRequest): void;
30
+ findClientCertificate(request: TlsCertificateManagement.FindClientCertificateRequest): TlsCertificateManagement.FindClientCertificateResponse;
31
+ lookupClientCertificate(request: TlsCertificateManagement.LookupClientCertificateRequest): TlsCertificateManagement.LookupClientCertificateResponse;
32
+ removeClientCertificate(request: TlsCertificateManagement.RemoveClientCertificateRequest): void;
33
+ }
34
+ export declare namespace MatterbridgeTlsCertificateManagementServer {
35
+ interface RootCertificateEntry {
36
+ caid: number;
37
+ fabric: number;
38
+ certificate: Uint8Array;
39
+ }
40
+ interface ClientCertificateEntry {
41
+ ccdid: number;
42
+ fabric: number;
43
+ clientCertificate: Uint8Array | null;
44
+ intermediateCertificates: Uint8Array[];
45
+ privateKey: Uint8Array;
46
+ }
47
+ class State extends MatterbridgeTlsCertificateManagementServerBase.State {
48
+ rootCertificateStore: RootCertificateEntry[];
49
+ clientCertificateStore: ClientCertificateEntry[];
50
+ nextCaid: number;
51
+ nextCcdid: number;
52
+ [Val.properties](_owner: unknown, session: {
53
+ subject?: unknown;
54
+ largeMessage?: boolean;
55
+ }): Partial<State>;
56
+ }
57
+ }
58
+ export {};