@matterbridge/core 3.11.2 → 3.11.3-dev-20261109-ca46ffb

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.
package/dist/backend.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import EventEmitter from 'node:events';
2
- import { type ApiClusters, type ApiDevice, type ApiPlugin, type ApiSettings, type SharedMatterbridge, type ApiMatter } from '@matterbridge/types';
2
+ import { type ApiClusters, type ApiDevice, type ApiPlugin, type ApiSettings, type Device, type SharedMatterbridge, type ApiMatter } from '@matterbridge/types';
3
3
  import type { BackendExpress } from './backendExpress.js';
4
4
  import type { BackendWsServer } from './backendWsServer.js';
5
5
  interface BackendEvents {
@@ -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;
@@ -34,7 +35,8 @@ export declare class Backend extends EventEmitter<BackendEvents> {
34
35
  stop(): Promise<void>;
35
36
  getApiSettings(): Promise<ApiSettings>;
36
37
  getApiPlugins(): Promise<ApiPlugin[]>;
37
- getApiDevices(pluginName?: string, extended?: boolean): Promise<ApiDevice[]>;
38
+ getDevices(pluginName?: string): Promise<Device[]>;
39
+ getApiDevices(pluginName: string, extended?: boolean): Promise<ApiDevice[]>;
38
40
  getApiCluster(pluginName: string, number: number, serialNumber: string, uniqueId: string): Promise<ApiClusters>;
39
41
  generateDiagnostic(): Promise<void>;
40
42
  getApiMatter(id: string): Promise<ApiMatter | 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,21 +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
  }
345
+ async getDevices(pluginName) {
346
+ const start = performance.now();
347
+ const response = await this.server.fetch({ type: 'devices_array', src: 'frontend', dst: 'devices', params: { pluginName } }, this.serverFetchTimeout);
348
+ if (this.diagnostic)
349
+ writeDiagnostic('Backend', `getDevices() took ${(performance.now() - start).toFixed(2)} ms`);
350
+ return response.result.devices;
351
+ }
344
352
  async getApiDevices(pluginName, extended = false) {
345
353
  const start = performance.now();
346
- const response = await this.server.fetch({ type: 'devices_apidevicearray', src: 'frontend', dst: 'devices', params: { pluginName, extended } });
354
+ const response = await this.server.fetch({ type: 'platform_get_apidevices', src: 'frontend', dst: 'platform', params: { pluginName, extended } }, this.serverFetchTimeout);
347
355
  if (this.diagnostic)
348
356
  writeDiagnostic('Backend', `getApiDevices() took ${(performance.now() - start).toFixed(2)} ms`);
349
357
  return response.result.devices;
@@ -356,7 +364,7 @@ export class Backend extends EventEmitter {
356
364
  src: 'frontend',
357
365
  dst: 'platform',
358
366
  params: { pluginName, number, serialNumber, uniqueId },
359
- });
367
+ }, this.serverFetchTimeout);
360
368
  if (this.diagnostic)
361
369
  writeDiagnostic('Backend', `getApiCluster() took ${(performance.now() - start).toFixed(2)} ms`);
362
370
  return response.result.clusters;
@@ -368,7 +376,7 @@ export class Backend extends EventEmitter {
368
376
  }
369
377
  async getApiMatter(id) {
370
378
  const start = performance.now();
371
- 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);
372
380
  if (this.diagnostic)
373
381
  writeDiagnostic('Backend', `getApiMatter() took ${(performance.now() - start).toFixed(2)} ms`);
374
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');
@@ -160,7 +159,18 @@ export class BackendExpress {
160
159
  this.log.debug('The frontend sent /api/devices');
161
160
  if (!this.validateReq(req, res))
162
161
  return;
163
- res.json(await this.backend.getApiDevices());
162
+ res.json(await this.backend.getDevices());
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'));
164
174
  });
165
175
  this.expressApp.get('/api/view-mblog', async (req, res) => {
166
176
  this.log.debug('The frontend sent /api/view-mblog');
@@ -283,8 +293,8 @@ export class BackendExpress {
283
293
  }
284
294
  });
285
295
  });
286
- this.expressApp.get('/api/viewhistory', async (req, res) => {
287
- this.log.debug('The frontend sent /api/viewhistory');
296
+ this.expressApp.get('/api/view-history', async (req, res) => {
297
+ this.log.debug('The frontend sent /api/view-history');
288
298
  if (!this.validateReq(req, res))
289
299
  return;
290
300
  try {
@@ -294,12 +304,12 @@ export class BackendExpress {
294
304
  res.send(data);
295
305
  }
296
306
  catch (error) {
297
- this.log.error(`Error in /api/viewhistory reading history file ${MATTERBRIDGE_HISTORY_FILE}: ${getErrorMessage(error)}`);
307
+ this.log.error(`Error in /api/view-history reading history file ${MATTERBRIDGE_HISTORY_FILE}: ${getErrorMessage(error)}`);
298
308
  res.status(500).send('Error reading history file.');
299
309
  }
300
310
  });
301
- this.expressApp.get('/api/downloadhistory', this.fileLimiter, async (req, res) => {
302
- this.log.debug(`The frontend sent /api/downloadhistory`);
311
+ this.expressApp.get('/api/download-history', this.fileLimiter, async (req, res) => {
312
+ this.log.debug(`The frontend sent /api/download-history`);
303
313
  if (!this.validateReq(req, res))
304
314
  return;
305
315
  try {
@@ -310,7 +320,7 @@ export class BackendExpress {
310
320
  res.type('text/html; charset=utf-8');
311
321
  res.download(path.join(os.tmpdir(), MATTERBRIDGE_HISTORY_FILE), MATTERBRIDGE_HISTORY_FILE, (error) => {
312
322
  if (error) {
313
- this.log.error(`Error in /api/downloadhistory downloading history file ${MATTERBRIDGE_HISTORY_FILE}: ${getErrorMessage(error)}`);
323
+ this.log.error(`Error in /api/download-history downloading history file ${MATTERBRIDGE_HISTORY_FILE}: ${getErrorMessage(error)}`);
314
324
  sendDownloadError(res, error, 'Error downloading history file');
315
325
  }
316
326
  else {
@@ -319,7 +329,7 @@ export class BackendExpress {
319
329
  });
320
330
  }
321
331
  catch (error) {
322
- this.log.error(`Error in /api/downloadhistory reading history file ${MATTERBRIDGE_HISTORY_FILE}: ${getErrorMessage(error)}`);
332
+ this.log.error(`Error in /api/download-history reading history file ${MATTERBRIDGE_HISTORY_FILE}: ${getErrorMessage(error)}`);
323
333
  res.status(500).send('Error reading history file.');
324
334
  }
325
335
  });
@@ -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') {
@@ -209,11 +242,22 @@ export class BackendWsServer {
209
242
  }
210
243
  else if (data.method === '/api/devices') {
211
244
  const start = performance.now();
212
- const devices = await this.backend.getApiDevices(isValidString(data.params.pluginName) ? data.params.pluginName : undefined, data.params.extended);
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}`, `getApiDevices() 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
  }
250
+ else if (data.method === '/api/platform-devices') {
251
+ if (!isValidString(data.params.pluginName, 10)) {
252
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, error: 'Wrong parameter pluginName in /api/platform-devices' });
253
+ return;
254
+ }
255
+ const start = performance.now();
256
+ const devices = await this.backend.getApiDevices(data.params.pluginName, data.params.extended);
257
+ if (this.diagnostic)
258
+ writeDiagnostic(`Frontend:${data.sender}`, `getApiDevices(${data.params.pluginName}) took ${(performance.now() - start).toFixed(2)} ms`);
259
+ sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true, pluginName: data.params.pluginName, response: devices });
260
+ }
217
261
  else if (data.method === '/api/clusters') {
218
262
  if (!isValidString(data.params.pluginName, 10)) {
219
263
  sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, error: 'Wrong parameter pluginName in /api/clusters' });
@@ -295,6 +339,72 @@ export class BackendWsServer {
295
339
  this.server.request({ type: 'platform_rename_device', src: 'frontend', dst: 'platform', params: { pluginName, serialNumber, uniqueId, label } });
296
340
  sendResponse({ id: data.id, method: data.method, src: 'Matterbridge', dst: data.src, success: true });
297
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
+ }
298
408
  }
299
409
  catch (error) {
300
410
  inspectError(this.log, `Error parsing message from websocket client`, error);
@@ -423,4 +533,12 @@ export class BackendWsServer {
423
533
  response: { plugin, serialNumber, uniqueId, number, id, cluster, attribute, value },
424
534
  });
425
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
+ }
426
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';
@@ -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 = {}));