@attraccess/plugin-matter 0.5.0-nightly.1197.2 → 0.5.0-nightly.1200.1

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/index.js CHANGED
@@ -542,7 +542,7 @@ var require_parse = __commonJS({
542
542
  "../../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/parse.js"(exports2, module2) {
543
543
  "use strict";
544
544
  var SemVer = require_semver();
545
- var parse7 = (version2, options, throwErrors = false) => {
545
+ var parse8 = (version2, options, throwErrors = false) => {
546
546
  if (version2 instanceof SemVer) {
547
547
  return version2;
548
548
  }
@@ -555,7 +555,7 @@ var require_parse = __commonJS({
555
555
  throw er;
556
556
  }
557
557
  };
558
- module2.exports = parse7;
558
+ module2.exports = parse8;
559
559
  }
560
560
  });
561
561
 
@@ -563,9 +563,9 @@ var require_parse = __commonJS({
563
563
  var require_valid = __commonJS({
564
564
  "../../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/valid.js"(exports2, module2) {
565
565
  "use strict";
566
- var parse7 = require_parse();
566
+ var parse8 = require_parse();
567
567
  var valid = (version2, options) => {
568
- const v = parse7(version2, options);
568
+ const v = parse8(version2, options);
569
569
  return v ? v.version : null;
570
570
  };
571
571
  module2.exports = valid;
@@ -576,9 +576,9 @@ var require_valid = __commonJS({
576
576
  var require_clean = __commonJS({
577
577
  "../../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/clean.js"(exports2, module2) {
578
578
  "use strict";
579
- var parse7 = require_parse();
579
+ var parse8 = require_parse();
580
580
  var clean = (version2, options) => {
581
- const s = parse7(version2.trim().replace(/^[=v]+/, ""), options);
581
+ const s = parse8(version2.trim().replace(/^[=v]+/, ""), options);
582
582
  return s ? s.version : null;
583
583
  };
584
584
  module2.exports = clean;
@@ -613,10 +613,10 @@ var require_inc = __commonJS({
613
613
  var require_diff = __commonJS({
614
614
  "../../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/diff.js"(exports2, module2) {
615
615
  "use strict";
616
- var parse7 = require_parse();
616
+ var parse8 = require_parse();
617
617
  var diff = (version1, version2) => {
618
- const v1 = parse7(version1, null, true);
619
- const v2 = parse7(version2, null, true);
618
+ const v1 = parse8(version1, null, true);
619
+ const v2 = parse8(version2, null, true);
620
620
  const comparison = v1.compare(v2);
621
621
  if (comparison === 0) {
622
622
  return null;
@@ -687,9 +687,9 @@ var require_patch = __commonJS({
687
687
  var require_prerelease = __commonJS({
688
688
  "../../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/prerelease.js"(exports2, module2) {
689
689
  "use strict";
690
- var parse7 = require_parse();
690
+ var parse8 = require_parse();
691
691
  var prerelease = (version2, options) => {
692
- const parsed = parse7(version2, options);
692
+ const parsed = parse8(version2, options);
693
693
  return parsed && parsed.prerelease.length ? parsed.prerelease : null;
694
694
  };
695
695
  module2.exports = prerelease;
@@ -875,7 +875,7 @@ var require_coerce = __commonJS({
875
875
  "../../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/coerce.js"(exports2, module2) {
876
876
  "use strict";
877
877
  var SemVer = require_semver();
878
- var parse7 = require_parse();
878
+ var parse8 = require_parse();
879
879
  var { safeRe: re, t } = require_re();
880
880
  var coerce2 = (version2, options) => {
881
881
  if (version2 instanceof SemVer) {
@@ -910,7 +910,7 @@ var require_coerce = __commonJS({
910
910
  const patch = match[4] || "0";
911
911
  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
912
912
  const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
913
- return parse7(`${major}.${minor}.${patch}${prerelease}${build}`, options);
913
+ return parse8(`${major}.${minor}.${patch}${prerelease}${build}`, options);
914
914
  };
915
915
  module2.exports = coerce2;
916
916
  }
@@ -920,7 +920,7 @@ var require_coerce = __commonJS({
920
920
  var require_truncate = __commonJS({
921
921
  "../../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/truncate.js"(exports2, module2) {
922
922
  "use strict";
923
- var parse7 = require_parse();
923
+ var parse8 = require_parse();
924
924
  var constants = require_constants();
925
925
  var SemVer = require_semver();
926
926
  var truncate = (version2, truncation, options) => {
@@ -932,7 +932,7 @@ var require_truncate = __commonJS({
932
932
  };
933
933
  var cloneInputVersion = (version2, options) => {
934
934
  const versionStringToParse = version2 instanceof SemVer ? version2.version : version2;
935
- return parse7(versionStringToParse, options);
935
+ return parse8(versionStringToParse, options);
936
936
  };
937
937
  var doTruncation = (version2, truncation) => {
938
938
  if (isPrerelease(truncation)) {
@@ -2167,7 +2167,7 @@ var require_semver2 = __commonJS({
2167
2167
  var constants = require_constants();
2168
2168
  var SemVer = require_semver();
2169
2169
  var identifiers = require_identifiers();
2170
- var parse7 = require_parse();
2170
+ var parse8 = require_parse();
2171
2171
  var valid = require_valid();
2172
2172
  var clean = require_clean();
2173
2173
  var inc = require_inc();
@@ -2206,7 +2206,7 @@ var require_semver2 = __commonJS({
2206
2206
  var simplifyRange = require_simplify();
2207
2207
  var subset = require_subset();
2208
2208
  module2.exports = {
2209
- parse: parse7,
2209
+ parse: parse8,
2210
2210
  valid,
2211
2211
  clean,
2212
2212
  inc,
@@ -4356,7 +4356,7 @@ var require_extension = __commonJS({
4356
4356
  if (dest[name] === void 0) dest[name] = [elem];
4357
4357
  else dest[name].push(elem);
4358
4358
  }
4359
- function parse7(header) {
4359
+ function parse8(header) {
4360
4360
  const offers = /* @__PURE__ */ Object.create(null);
4361
4361
  let params = /* @__PURE__ */ Object.create(null);
4362
4362
  let mustUnescape = false;
@@ -4496,7 +4496,7 @@ var require_extension = __commonJS({
4496
4496
  }).join(", ");
4497
4497
  }).join(", ");
4498
4498
  }
4499
- module2.exports = { format, parse: parse7 };
4499
+ module2.exports = { format, parse: parse8 };
4500
4500
  }
4501
4501
  });
4502
4502
 
@@ -4531,7 +4531,7 @@ var require_websocket = __commonJS({
4531
4531
  var {
4532
4532
  EventTarget: { addEventListener, removeEventListener }
4533
4533
  } = require_event_target();
4534
- var { format, parse: parse7 } = require_extension();
4534
+ var { format, parse: parse8 } = require_extension();
4535
4535
  var { toBuffer } = require_buffer_util();
4536
4536
  var kAborted = /* @__PURE__ */ Symbol("kAborted");
4537
4537
  var protocolVersions = [8, 13];
@@ -5231,7 +5231,7 @@ var require_websocket = __commonJS({
5231
5231
  }
5232
5232
  let extensions;
5233
5233
  try {
5234
- extensions = parse7(secWebSocketExtensions);
5234
+ extensions = parse8(secWebSocketExtensions);
5235
5235
  } catch (err) {
5236
5236
  const message = "Invalid Sec-WebSocket-Extensions header";
5237
5237
  abortHandshake(websocket, socket, message);
@@ -5539,7 +5539,7 @@ var require_subprotocol = __commonJS({
5539
5539
  "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/subprotocol.js"(exports2, module2) {
5540
5540
  "use strict";
5541
5541
  var { tokenChars } = require_validation();
5542
- function parse7(header) {
5542
+ function parse8(header) {
5543
5543
  const protocols = /* @__PURE__ */ new Set();
5544
5544
  let start = -1;
5545
5545
  let end = -1;
@@ -5575,7 +5575,7 @@ var require_subprotocol = __commonJS({
5575
5575
  protocols.add(protocol);
5576
5576
  return protocols;
5577
5577
  }
5578
- module2.exports = { parse: parse7 };
5578
+ module2.exports = { parse: parse8 };
5579
5579
  }
5580
5580
  });
5581
5581
 
@@ -15508,11 +15508,13 @@ var MATTER_OPERATIONS = {
15508
15508
  nodeForceRemove: [MATTER_MANAGE],
15509
15509
  endpointUpdate: [MATTER_MANAGE],
15510
15510
  reconciliationRun: [MATTER_MANAGE],
15511
- // Future: commissioning (ATT-1002).
15511
+ // Commissioning (ATT-1002): start, cancel and name a session; read it; share and remove a node.
15512
+ /** Start, cancel and finish (name) a commissioning session. */
15512
15513
  commissioningStart: [MATTER_COMMISSION],
15513
15514
  commissioningStatus: [MATTER_COMMISSION],
15514
- /** Opens a commissioning window so another controller can join. */
15515
+ /** Opens (and closes) a commissioning window so another controller can join. */
15515
15516
  commissioningShare: [MATTER_COMMISSION],
15517
+ /** Normal and forced removal from the fabric through the sidecar. */
15516
15518
  commissioningRemoveFromFabric: [MATTER_COMMISSION],
15517
15519
  attestationOverride: [MATTER_COMMISSION, MATTER_MANAGE],
15518
15520
  // Future: direct commands (ATT-1011). See REQUIRES_CONFIRMATION.
@@ -17401,18 +17403,18 @@ var validateAsync = async (schema, value, _ctx) => {
17401
17403
  return result.issues.length === 0;
17402
17404
  };
17403
17405
  var _encode = (_Err) => {
17404
- const parse7 = _parse(_Err);
17406
+ const parse8 = _parse(_Err);
17405
17407
  const fn = (schema, value, _ctx, _params) => {
17406
17408
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
17407
- return parse7(schema, value, ctx, finalizeParams(fn, _params));
17409
+ return parse8(schema, value, ctx, finalizeParams(fn, _params));
17408
17410
  };
17409
17411
  return fn;
17410
17412
  };
17411
17413
  var encode = /* @__PURE__ */ _encode($ZodRealError);
17412
17414
  var _decode = (_Err) => {
17413
- const parse7 = _parse(_Err);
17415
+ const parse8 = _parse(_Err);
17414
17416
  const fn = (schema, value, _ctx, _params) => {
17415
- return parse7(schema, value, _ctx, finalizeParams(fn, _params));
17417
+ return parse8(schema, value, _ctx, finalizeParams(fn, _params));
17416
17418
  };
17417
17419
  return fn;
17418
17420
  };
@@ -18907,7 +18909,7 @@ function capSize(inst, size) {
18907
18909
  if (!caps.length)
18908
18910
  return;
18909
18911
  const cap = Math.min(...caps.map((c) => c[0]));
18910
- const parse7 = inst._zod.parse;
18912
+ const parse8 = inst._zod.parse;
18911
18913
  inst._zod.parse = (payload, ctx) => {
18912
18914
  const n = size(payload.value);
18913
18915
  if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
@@ -18921,7 +18923,7 @@ function capSize(inst, size) {
18921
18923
  }
18922
18924
  }
18923
18925
  }
18924
- return parse7(payload, ctx);
18926
+ return parse8(payload, ctx);
18925
18927
  };
18926
18928
  }
18927
18929
  var arraySize = (input2) => Array.isArray(input2) ? input2.length : -1;
@@ -35388,6 +35390,9 @@ var ERROR_STATUS = {
35388
35390
  fabric_absent: 409,
35389
35391
  recovery_required: 409,
35390
35392
  busy: 409,
35393
+ already_commissioned: 409,
35394
+ device_unreachable: 409,
35395
+ attestation_override_disabled: 403,
35391
35396
  restore_failed: 409,
35392
35397
  payload_too_large: 413,
35393
35398
  unsupported_wire_version: 426,
@@ -35497,16 +35502,97 @@ var backupRestoreResultSchema = external_exports.strictObject({
35497
35502
  state: external_exports.enum(["committed", "rolled_back", "finalized", "aborted"]),
35498
35503
  fabric: fabricStatusSchema
35499
35504
  });
35505
+ var commissioningStepSchema = external_exports.enum([
35506
+ "discovering",
35507
+ "pase",
35508
+ "reading_device",
35509
+ "attestation",
35510
+ "adding_fabric",
35511
+ /** Not used for devices already on an IP network; reserved for Thread. */
35512
+ "network_setup",
35513
+ "case",
35514
+ "interrogating",
35515
+ "completed"
35516
+ ]);
35517
+ var commissioningFailureCodeSchema = external_exports.enum([
35518
+ "invalid_code",
35519
+ "device_not_found",
35520
+ /** The passcode was wrong, or the device refused the pairing. */
35521
+ "pase_failed",
35522
+ "attestation_failed",
35523
+ "already_commissioned",
35524
+ "fabric_full",
35525
+ "case_failed",
35526
+ "timeout",
35527
+ "cancelled",
35528
+ "interrupted",
35529
+ "internal"
35530
+ ]);
35531
+ var attestationFindingTypeSchema = external_exports.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,63}$/);
35532
+ var commissioningFailureSchema = external_exports.strictObject({
35533
+ code: commissioningFailureCodeSchema,
35534
+ /** Present for `attestation_failed`. */
35535
+ attestationFindings: external_exports.array(attestationFindingTypeSchema).max(32).optional(),
35536
+ /** Present for `already_commissioned`: the node the device already is in this fabric. */
35537
+ existingNodeId: matterId64Schema.optional()
35538
+ });
35500
35539
  var commissioningRequestSchema = external_exports.strictObject({
35501
- setupCode: external_exports.string().regex(/^[0-9]{11}$|^[0-9]{21}$|^MT:[A-Z0-9.-]{10,}$/),
35540
+ /** An 11- or 21-digit manual code, or a QR payload (`MT:` and at most 512 base38 characters, as the plugin caps it). */
35541
+ setupCode: external_exports.string().regex(/^[0-9]{11}$|^[0-9]{21}$|^MT:[A-Z0-9.-]{10,512}$/),
35542
+ /**
35543
+ * A new session that proceeds although attestation fails. Refused with `attestation_override_disabled` unless the
35544
+ * sidecar runs with `MATTER_SIDECAR_ALLOW_ATTESTATION_OVERRIDE=true`.
35545
+ */
35546
+ attestationOverride: external_exports.strictObject({ confirmed: external_exports.literal(true) }).optional(),
35502
35547
  deadlineMs: deadlineSchema.optional()
35503
35548
  });
35504
35549
  var commissioningSessionSchema = external_exports.strictObject({
35505
35550
  sessionId: uuidSchema,
35506
35551
  state: external_exports.enum(["pending", "running", "succeeded", "failed"]),
35552
+ step: commissioningStepSchema.nullable(),
35507
35553
  nodeId: matterId64Schema.nullable(),
35508
- outcome: outcomeSchema
35554
+ outcome: outcomeSchema,
35555
+ /** Set when `state` is `failed`. */
35556
+ failure: commissioningFailureSchema.nullable(),
35557
+ /** The attestation result so far: finding types only. `overridden` means a failure was accepted by an override. */
35558
+ attestation: external_exports.strictObject({
35559
+ status: external_exports.enum(["verified", "failed", "overridden"]),
35560
+ findings: external_exports.array(attestationFindingTypeSchema).max(32)
35561
+ }).nullable(),
35562
+ /** Whether this sidecar offers the attestation override at all. */
35563
+ attestationOverrideAllowed: external_exports.boolean(),
35564
+ startedAt: timestampSchema,
35565
+ updatedAt: timestampSchema,
35566
+ finishedAt: timestampSchema.nullable()
35567
+ });
35568
+ var commissioningProgressPayloadSchema = external_exports.strictObject({
35569
+ sessionId: uuidSchema,
35570
+ step: commissioningStepSchema.nullable(),
35571
+ state: external_exports.enum(["pending", "running", "succeeded", "failed"]),
35572
+ nodeId: matterId64Schema.nullable(),
35573
+ failure: commissioningFailureSchema.nullable()
35509
35574
  });
35575
+ var nodeRemoveRequestSchema = external_exports.strictObject({ force: external_exports.boolean(), deadlineMs: deadlineSchema.optional() });
35576
+ var nodeRemoveResultSchema = external_exports.strictObject({
35577
+ nodeId: matterId64Schema,
35578
+ /** `removed_from_fabric`: the device confirmed. `forgotten`: forced, the device was not contacted. */
35579
+ result: external_exports.enum(["removed_from_fabric", "forgotten"]),
35580
+ fabricGeneration: external_exports.int().min(0)
35581
+ });
35582
+ var SHARE_WINDOW_MIN_SEC = 180;
35583
+ var SHARE_WINDOW_MAX_SEC = 900;
35584
+ var shareOpenRequestSchema = external_exports.strictObject({
35585
+ timeoutSec: external_exports.int().min(SHARE_WINDOW_MIN_SEC).max(SHARE_WINDOW_MAX_SEC).default(SHARE_WINDOW_MIN_SEC),
35586
+ deadlineMs: deadlineSchema.optional()
35587
+ });
35588
+ var shareWindowSchema = external_exports.strictObject({
35589
+ nodeId: matterId64Schema,
35590
+ manualCode: external_exports.string().regex(/^[0-9]{11}$|^[0-9]{21}$/),
35591
+ qrCode: external_exports.string().regex(/^MT:[A-Z0-9.-]{10,}$/),
35592
+ expiresAt: timestampSchema
35593
+ });
35594
+ var shareCloseRequestSchema = external_exports.strictObject({ deadlineMs: deadlineSchema.optional() });
35595
+ var shareCloseResultSchema = external_exports.strictObject({ nodeId: matterId64Schema, closed: external_exports.boolean() });
35510
35596
  var deviceTypeSchema = external_exports.strictObject({
35511
35597
  deviceTypeId: deviceTypeIdSchema,
35512
35598
  revision: external_exports.int().min(0).max(65535)
@@ -35537,6 +35623,13 @@ var endpointSchema = external_exports.strictObject({
35537
35623
  bridged: bridgedInfoSchema.nullable()
35538
35624
  });
35539
35625
  var attestationStatusSchema = external_exports.enum(["verified", "unverified", "failed", "unknown"]);
35626
+ var administratorSchema = external_exports.strictObject({
35627
+ fabricIndex: external_exports.int().min(1).max(254),
35628
+ vendorId: external_exports.int().min(0).max(65535).nullable(),
35629
+ fabricLabel: external_exports.string().max(32).nullable(),
35630
+ /** True for the Attraccess fabric itself. */
35631
+ isOwn: external_exports.boolean()
35632
+ });
35540
35633
  var nodeSchema = external_exports.strictObject({
35541
35634
  nodeId: matterId64Schema,
35542
35635
  reachable: external_exports.boolean(),
@@ -35551,6 +35644,8 @@ var nodeSchema = external_exports.strictObject({
35551
35644
  softwareVersionString: external_exports.string().max(64).nullable(),
35552
35645
  attestation: external_exports.strictObject({ status: attestationStatusSchema, checkedAt: timestampSchema.nullable() }),
35553
35646
  endpoints: external_exports.array(endpointSchema).max(256),
35647
+ /** Every fabric the device is joined to, Attraccess's own included. */
35648
+ administrators: external_exports.array(administratorSchema).max(254).default([]),
35554
35649
  /** When this inventory view was last confirmed by the device. */
35555
35650
  observedAt: timestampSchema.nullable()
35556
35651
  });
@@ -35668,6 +35763,7 @@ var commandOutcomePayloadSchema = commandResultSchema.extend({
35668
35763
  failureCode: external_exports.string().min(1).max(64).optional()
35669
35764
  });
35670
35765
  var TYPED_PAYLOADS = {
35766
+ "commissioning.progress": commissioningProgressPayloadSchema,
35671
35767
  "device.state": deviceStatePayloadSchema,
35672
35768
  "command.outcome": commandOutcomePayloadSchema
35673
35769
  };
@@ -35682,6 +35778,7 @@ var eventEnvelopeSchema = external_exports.strictObject({
35682
35778
  payload: external_exports.union([
35683
35779
  lifecyclePayloadSchema,
35684
35780
  capabilityReportSchema,
35781
+ commissioningProgressPayloadSchema,
35685
35782
  deviceStatePayloadSchema,
35686
35783
  commandOutcomePayloadSchema,
35687
35784
  opaquePayloadSchema
@@ -35819,10 +35916,12 @@ var DEFINITIONS = [
35819
35916
  method: "POST",
35820
35917
  path: "/v1/commissioning/sessions",
35821
35918
  versioned: true,
35822
- summary: "Start commissioning",
35919
+ summary: "Start commissioning; returns a pending session at once and reports progress by event",
35823
35920
  body: commissioningRequestSchema,
35824
35921
  response: commissioningSessionSchema,
35825
- physical: true
35922
+ physical: true,
35923
+ fabricMutating: true,
35924
+ secretsOnWire: true
35826
35925
  }),
35827
35926
  op({
35828
35927
  id: "commissioning.get",
@@ -35834,6 +35933,16 @@ var DEFINITIONS = [
35834
35933
  params: sessionParamsSchema,
35835
35934
  response: commissioningSessionSchema
35836
35935
  }),
35936
+ op({
35937
+ id: "commissioning.cancel",
35938
+ family: "commissioning",
35939
+ method: "DELETE",
35940
+ path: "/v1/commissioning/sessions/{sessionId}",
35941
+ versioned: true,
35942
+ summary: "Cancel a commissioning session",
35943
+ params: sessionParamsSchema,
35944
+ response: commissioningSessionSchema
35945
+ }),
35837
35946
  op({
35838
35947
  id: "inventory.list",
35839
35948
  family: "inventory",
@@ -35853,6 +35962,46 @@ var DEFINITIONS = [
35853
35962
  params: nodeParamsSchema,
35854
35963
  response: nodeSchema
35855
35964
  }),
35965
+ op({
35966
+ id: "nodes.remove",
35967
+ family: "commissioning",
35968
+ method: "DELETE",
35969
+ path: "/v1/nodes/{nodeId}",
35970
+ versioned: true,
35971
+ summary: "Remove a node from the fabric (RemoveFabric), or forget it without contacting the device",
35972
+ params: nodeParamsSchema,
35973
+ body: nodeRemoveRequestSchema,
35974
+ response: nodeRemoveResultSchema,
35975
+ physical: true,
35976
+ fabricMutating: true
35977
+ }),
35978
+ op({
35979
+ id: "nodes.share.open",
35980
+ family: "commissioning",
35981
+ method: "POST",
35982
+ path: "/v1/nodes/{nodeId}/commissioning-window",
35983
+ versioned: true,
35984
+ summary: "Open an Enhanced Commissioning Window to share the node with another controller",
35985
+ params: nodeParamsSchema,
35986
+ body: shareOpenRequestSchema,
35987
+ response: shareWindowSchema,
35988
+ physical: true,
35989
+ fabricMutating: true,
35990
+ secretsOnWire: true
35991
+ }),
35992
+ op({
35993
+ id: "nodes.share.revoke",
35994
+ family: "commissioning",
35995
+ method: "DELETE",
35996
+ path: "/v1/nodes/{nodeId}/commissioning-window",
35997
+ versioned: true,
35998
+ summary: "Close the commissioning window of a node",
35999
+ params: nodeParamsSchema,
36000
+ body: shareCloseRequestSchema,
36001
+ response: shareCloseResultSchema,
36002
+ physical: true,
36003
+ fabricMutating: true
36004
+ }),
35856
36005
  op({
35857
36006
  id: "commands.invoke",
35858
36007
  family: "commands",
@@ -36090,8 +36239,39 @@ function classifyNetworkError(error62, correlationId = null, outcome) {
36090
36239
  ...uncertain
36091
36240
  });
36092
36241
  }
36242
+ var SECRET_FIELDS = /* @__PURE__ */ new Set(["setupCode", "manualCode", "qrCode", "passcode", "attestationOverride"]);
36243
+ var ID_FIELDS = /* @__PURE__ */ new Set([
36244
+ "sessionId",
36245
+ "nodeId",
36246
+ "existingNodeId",
36247
+ "fabricId",
36248
+ "correlationId",
36249
+ "stageId",
36250
+ "backupId",
36251
+ "streamInstanceId",
36252
+ "storageInstanceId"
36253
+ ]);
36254
+ var SECRET_TEXT = /MT:[A-Z0-9.-]{6,}|(?<![0-9A-Za-z-])(?:[0-9]{21}|[0-9]{11})(?![0-9A-Za-z-])/g;
36255
+ function redactSecrets(text) {
36256
+ return text.replace(SECRET_TEXT, "[redacted]");
36257
+ }
36258
+ function redactValue(value) {
36259
+ if (typeof value === "string") return redactSecrets(value);
36260
+ if (Array.isArray(value)) return value.map(redactValue);
36261
+ if (value !== null && typeof value === "object") {
36262
+ return Object.fromEntries(
36263
+ Object.entries(value).map(([key, entry]) => [
36264
+ key,
36265
+ SECRET_FIELDS.has(key) ? "[redacted]" : ID_FIELDS.has(key) && typeof entry === "string" ? entry : redactValue(entry)
36266
+ ])
36267
+ );
36268
+ }
36269
+ return value;
36270
+ }
36093
36271
  function fromErrorEnvelope(error62, status) {
36094
- const { code, message, correlationId, retryable, outcome, details } = error62;
36272
+ const { code, correlationId, retryable, outcome } = error62;
36273
+ const message = redactSecrets(error62.message);
36274
+ const details = error62.details === void 0 ? void 0 : redactValue(error62.details);
36095
36275
  const init = { code, correlationId, retryable, outcome, details, status };
36096
36276
  if (code === "unauthorized") return new SidecarUnauthorizedError(message, init);
36097
36277
  if (code === "incompatible_release" || code === "unsupported_wire_version") {
@@ -36148,6 +36328,7 @@ function classifyHttpFailure(status, raw, headerCorrelationId, outcome) {
36148
36328
  // backend/fabric/errors.ts
36149
36329
  var conflict = (code, message) => new import_common.ConflictException({ code, message });
36150
36330
  var unprocessable = (code, message) => new import_common.UnprocessableEntityException({ code, message });
36331
+ var forbidden = (code, message) => new import_common.ForbiddenException({ code, message });
36151
36332
  var NOT_CONNECTED = "The Matter sidecar is not connected.";
36152
36333
  var INSECURE_MESSAGE = "The connection to the Matter sidecar is plain HTTP to another machine. Backups carry fabric secrets and are only made over HTTPS (or to a sidecar on this machine).";
36153
36334
  function sidecarCode(error62) {
@@ -36160,7 +36341,10 @@ function sidecarFailure(error62) {
36160
36341
  case "recovery_required":
36161
36342
  return conflict("recovery_required", "The sidecar needs recovery before it can create a fabric.");
36162
36343
  case "busy":
36163
- return conflict("busy", "The Matter sidecar is busy with another backup or restore. Try again shortly.");
36344
+ return conflict(
36345
+ "busy",
36346
+ "The Matter sidecar is busy with another operation (a backup, restore, commissioning, removal or share). Try again shortly."
36347
+ );
36164
36348
  case "sidecar_unavailable":
36165
36349
  case "timeout":
36166
36350
  case "network":
@@ -36178,6 +36362,12 @@ function sidecarFailure(error62) {
36178
36362
 
36179
36363
  // backend/fabric/guard.ts
36180
36364
  var import_common2 = require("@nestjs/common");
36365
+ function operationBusy(operation) {
36366
+ return conflict(
36367
+ "busy",
36368
+ operation === "commissioning" ? "A commissioning session is already running. Wait for it to finish or cancel it." : "Another fabric operation is in progress. Try again in a moment."
36369
+ );
36370
+ }
36181
36371
  var MatterFabricGuard = class {
36182
36372
  constructor() {
36183
36373
  this.current = null;
@@ -36189,6 +36379,17 @@ var MatterFabricGuard = class {
36189
36379
  * a reconnect instead of being recorded as the plugin's own change.
36190
36380
  */
36191
36381
  this.outcomeUnknown = false;
36382
+ /**
36383
+ * The commissioning session, removal or share that holds MatterOperationGate, or null. Set only by the gate. The
36384
+ * sidecar frees its own gate before the plugin wrote its registry rows: until then backups, restores and fabric
36385
+ * creation are refused here.
36386
+ */
36387
+ this.operation = null;
36388
+ /**
36389
+ * True while a restore confirmation runs (its preflight and pre-restore backup come before `busy` is set): a
36390
+ * commissioning session, removal or share must not start in that window.
36391
+ */
36392
+ this.restoreConfirming = false;
36192
36393
  this.restoringNow = false;
36193
36394
  this.restoreEpoch = 0;
36194
36395
  }
@@ -36219,7 +36420,8 @@ var MatterFabricGuard = class {
36219
36420
  }
36220
36421
  /**
36221
36422
  * The check every fabric-mutating plugin action makes first (fabric creation, commissioning, node removal, ...).
36222
- * Throws a 409 `recovery_required` while an administrator has to decide how to settle the fabric.
36423
+ * Throws a 409 `recovery_required` while an administrator has to decide how to settle the fabric, and a 409 `busy`
36424
+ * while the plugin changes the fabric (create, restore) or a commissioning session, removal or share runs.
36223
36425
  */
36224
36426
  assertFabricMutationAllowed() {
36225
36427
  if (this.current !== null) {
@@ -36228,7 +36430,8 @@ var MatterFabricGuard = class {
36228
36430
  "The Matter fabric needs recovery before it can be changed. Restore a backup, accept the sidecar, or start a new fabric."
36229
36431
  );
36230
36432
  }
36231
- if (this.busy) throw conflict("busy", "A fabric operation is in progress.");
36433
+ if (this.busy || this.restoreConfirming) throw conflict("busy", "A fabric operation is in progress.");
36434
+ if (this.operation !== null) throw operationBusy(this.operation);
36232
36435
  }
36233
36436
  };
36234
36437
  MatterFabricGuard = __decorateClass([
@@ -37239,6 +37442,11 @@ var LOOKUP_INDEXES = {
37239
37442
  endpoints: [{ fields: ["nodeRef", "endpointId"] }],
37240
37443
  endpointClusters: [{ fields: ["endpointRef", "clusterId", "role"] }]
37241
37444
  };
37445
+ var NODE_V3_FIELDS = {
37446
+ administrators: import_plugins_backend_sdk2.f.text().optional(),
37447
+ attestationOverridden: import_plugins_backend_sdk2.f.boolean({ column: "attestation_overridden" }).optional()
37448
+ };
37449
+ var withFields = (definition, fields) => ({ ...definition, fields: { ...definition.fields, ...fields } });
37242
37450
  var withIndexes = (definition, indexes) => ({
37243
37451
  ...definition,
37244
37452
  indexes: [...definition.indexes, ...indexes]
@@ -37246,7 +37454,7 @@ var withIndexes = (definition, indexes) => ({
37246
37454
  var MATTER_TABLES = {
37247
37455
  ...MATTER_BASELINE_TABLES,
37248
37456
  fabrics: withIndexes(fabrics, LOOKUP_INDEXES.fabrics),
37249
- nodes: withIndexes(nodes, LOOKUP_INDEXES.nodes),
37457
+ nodes: withIndexes(withFields(nodes, NODE_V3_FIELDS), LOOKUP_INDEXES.nodes),
37250
37458
  endpoints: withIndexes(endpoints, LOOKUP_INDEXES.endpoints),
37251
37459
  endpointClusters: withIndexes(endpointClusters, LOOKUP_INDEXES.endpointClusters)
37252
37460
  };
@@ -37269,6 +37477,11 @@ var MATTER_STORAGE = (0, import_plugins_backend_sdk2.definePluginStorage)({
37269
37477
  steps: Object.entries(LOOKUP_INDEXES).flatMap(
37270
37478
  ([name, indexes]) => indexes.map((index) => import_plugins_backend_sdk2.step.addIndex(name, index))
37271
37479
  )
37480
+ },
37481
+ {
37482
+ version: 3,
37483
+ name: "node-administrators",
37484
+ steps: Object.entries(NODE_V3_FIELDS).map(([field, definition]) => import_plugins_backend_sdk2.step.addColumn("nodes", field, definition))
37272
37485
  }
37273
37486
  ],
37274
37487
  adoption: { legacyMigrations: LEGACY_MIGRATIONS }
@@ -37461,9 +37674,11 @@ MatterSettingsService = __decorateClass([
37461
37674
  ], MatterSettingsService);
37462
37675
 
37463
37676
  // backend/connection/connection.service.ts
37677
+ var STOP_GRACE_MS = 3e3;
37464
37678
  var MatterConnectionService = class {
37465
37679
  constructor(context, settings) {
37466
37680
  this.settings = settings;
37681
+ this.beforeStop = /* @__PURE__ */ new Set();
37467
37682
  const logger = context.logger;
37468
37683
  this.connection = new SidecarConnection({
37469
37684
  hostVersion: context.hostVersion,
@@ -37472,6 +37687,14 @@ var MatterConnectionService = class {
37472
37687
  });
37473
37688
  this.logger = logger;
37474
37689
  }
37690
+ /**
37691
+ * Work that still needs the sidecar when the plugin stops, such as cancelling a running commissioning session. It
37692
+ * runs before the connection closes, for at most STOP_GRACE_MS. Returns the function that withdraws it.
37693
+ */
37694
+ beforeStopping(task) {
37695
+ this.beforeStop.add(task);
37696
+ return () => this.beforeStop.delete(task);
37697
+ }
37475
37698
  async onModuleInit() {
37476
37699
  try {
37477
37700
  await this.reload();
@@ -37490,7 +37713,18 @@ var MatterConnectionService = class {
37490
37713
  this.connection.misconfigure(error62.message);
37491
37714
  }
37492
37715
  }
37493
- onModuleDestroy() {
37716
+ async onModuleDestroy() {
37717
+ const tasks = [...this.beforeStop];
37718
+ this.beforeStop.clear();
37719
+ if (tasks.length > 0) {
37720
+ let timer;
37721
+ const grace = new Promise((resolve) => {
37722
+ timer = setTimeout(resolve, STOP_GRACE_MS);
37723
+ timer.unref();
37724
+ });
37725
+ await Promise.race([Promise.allSettled(tasks.map((task) => Promise.resolve().then(task))), grace]);
37726
+ clearTimeout(timer);
37727
+ }
37494
37728
  this.connection.stop();
37495
37729
  }
37496
37730
  onApplicationShutdown() {
@@ -38122,6 +38356,10 @@ var BackupIncompatibleError = class extends Error {
38122
38356
  this.name = "BackupIncompatibleError";
38123
38357
  }
38124
38358
  };
38359
+ var RESTORABLE_OLDER_LAYOUTS = {
38360
+ // ATT-1002: `administrators` and `attestation_overridden` on nodes.
38361
+ "v3:node-administrators": ["CreateMatterBackup1793900002000"]
38362
+ };
38125
38363
  function assertCompatible(header, local) {
38126
38364
  if (header.storageSchemaVersion !== STORAGE_SCHEMA_VERSION) {
38127
38365
  throw new BackupIncompatibleError(
@@ -38129,7 +38367,8 @@ function assertCompatible(header, local) {
38129
38367
  "The backup uses a different Matter storage layout than this installation."
38130
38368
  );
38131
38369
  }
38132
- if (local.pluginMigration === null || header.pluginMigration !== local.pluginMigration) {
38370
+ const accepted = local.pluginMigration === null ? [] : [local.pluginMigration, ...RESTORABLE_OLDER_LAYOUTS[local.pluginMigration] ?? []];
38371
+ if (!accepted.includes(header.pluginMigration)) {
38133
38372
  throw new BackupIncompatibleError(
38134
38373
  "incompatible_migration",
38135
38374
  "The backup was made with a different database layout of the Matter plugin than the installed one."
@@ -38167,7 +38406,7 @@ var ALLOWED_VALUES = {
38167
38406
  nodes: {
38168
38407
  lifecycleState: ["unclaimed", "claimed", "detached", "archived", "removed"],
38169
38408
  detachedReason: ["absent_from_sidecar", "fabric_mismatch", "fabric_absent"],
38170
- removalReason: ["force_removed", "merged", "replaced"],
38409
+ removalReason: ["force_removed", "merged", "replaced", "removed_from_fabric", "forced_from_fabric"],
38171
38410
  attestationStatus: ["verified", "unverified", "failed", "unknown"]
38172
38411
  },
38173
38412
  endpoints: { removalReason: ["absent_from_sidecar", "replaced", "force_removed", "merged"] },
@@ -38276,7 +38515,7 @@ var BACKUP_TIMEOUT_MS = 6e4;
38276
38515
  var FAILURE_TEXT = {
38277
38516
  inconsistent: "The sidecar and the plugin disagree about the fabric (identity or generation), so no consistent backup can be made.",
38278
38517
  sidecar_unavailable: "The Matter sidecar could not be reached.",
38279
- sidecar_busy: "The Matter sidecar is busy with another backup or restore. Try again shortly.",
38518
+ sidecar_busy: "The Matter sidecar is busy with another operation (a backup, restore, commissioning, removal or share). Try again shortly.",
38280
38519
  insecure_transport: INSECURE_MESSAGE,
38281
38520
  no_recovery_key: "There is no recovery key yet. Generate one first.",
38282
38521
  recovery_key_unreadable: "The stored recovery key cannot be read by this installation.",
@@ -38337,6 +38576,7 @@ var MatterBackupService = class {
38337
38576
  */
38338
38577
  async backup(trigger, by = null, options = {}) {
38339
38578
  if (this.guard.busy) throw conflict("busy", "A restore is in progress.");
38579
+ if (this.guard.operation !== null) throw operationBusy(this.guard.operation);
38340
38580
  const own2 = options.fresh === true || trigger === "pre_restore" || trigger === "restore";
38341
38581
  while (this.inFlight) {
38342
38582
  if (!own2) return this.inFlight;
@@ -38749,6 +38989,7 @@ var NODE_IDENTITY_COLUMNS = [
38749
38989
  "attestationStatus",
38750
38990
  "attestationCheckedAt",
38751
38991
  "reachable",
38992
+ "administrators",
38752
38993
  "lastSeenAt"
38753
38994
  ];
38754
38995
  var ENDPOINT_PROTOCOL_COLUMNS = [
@@ -38783,6 +39024,7 @@ function identityOf(view, fallbackLastSeen) {
38783
39024
  attestationStatus: view.attestation.status,
38784
39025
  attestationCheckedAt: view.attestation.checkedAt,
38785
39026
  reachable: view.reachable,
39027
+ administrators: JSON.stringify(view.administrators),
38786
39028
  lastSeenAt: view.observedAt ?? fallbackLastSeen
38787
39029
  };
38788
39030
  }
@@ -39216,6 +39458,7 @@ var MatterReconciliationService = class {
39216
39458
  removedBy: null,
39217
39459
  removalReason: null,
39218
39460
  mergedInto: null,
39461
+ attestationOverridden: null,
39219
39462
  createdAt: now,
39220
39463
  updatedAt: now,
39221
39464
  ...identityOf(view, now)
@@ -39978,7 +40221,7 @@ var MatterRestoreService = class {
39978
40221
  const audited = { ref: (0, import_node_crypto13.randomUUID)() };
39979
40222
  const actor = this.audit.actorFor(principal);
39980
40223
  const refuse = (code) => this.refused(code, audited.ref, actor, unprocessable(code, RESTORE_MESSAGES[code]));
39981
- if (this.running) await this.refuseBusy(audited.ref, actor);
40224
+ if (this.running || this.guard.operation !== null) await this.refuseBusy(audited.ref, actor);
39982
40225
  const status = this.connection.status();
39983
40226
  if (status.state !== "connected") return refuse("sidecar_unavailable");
39984
40227
  if (status.insecureTransport) return refuse("insecure_transport");
@@ -39987,7 +40230,7 @@ var MatterRestoreService = class {
39987
40230
  const opened = await this.open(file2, recoveryKey, audited, refuse);
39988
40231
  if (!tablesAreAcceptable(opened.body.tables)) return refuse("incompatible_schema");
39989
40232
  const preflight = await this.preflight(opened.header.fabricId);
39990
- if (this.running) await this.refuseBusy(audited.ref, actor);
40233
+ if (this.running || this.guard.operation !== null) await this.refuseBusy(audited.ref, actor);
39991
40234
  this.running = true;
39992
40235
  let validation;
39993
40236
  try {
@@ -40027,12 +40270,14 @@ var MatterRestoreService = class {
40027
40270
  );
40028
40271
  throw error62;
40029
40272
  }
40273
+ /** A restore is running, or a commissioning session, removal or share is changing the fabric. */
40030
40274
  refuseBusy(ref, actor) {
40275
+ const operation = this.guard.operation;
40031
40276
  return this.refused(
40032
40277
  "busy",
40033
40278
  ref,
40034
40279
  actor,
40035
- conflict("busy", "A restore is in progress. Check the backup again once it has finished.")
40280
+ !this.running && operation !== null ? operationBusy(operation) : conflict("busy", "A restore is in progress. Check the backup again once it has finished.")
40036
40281
  );
40037
40282
  }
40038
40283
  async load(source) {
@@ -40138,6 +40383,7 @@ var MatterRestoreService = class {
40138
40383
  throw conflict("validation_expired", "This restore check has expired. Check the backup again.");
40139
40384
  }
40140
40385
  if (this.running) throw conflict("busy", "A restore is already in progress.");
40386
+ if (this.guard.operation !== null) throw operationBusy(this.guard.operation);
40141
40387
  const ref = pending.header.backupId;
40142
40388
  const actor = this.audit.actorFor(principal, validationId);
40143
40389
  const refuse = async (code, message) => {
@@ -40151,6 +40397,7 @@ var MatterRestoreService = class {
40151
40397
  return conflict(code, message);
40152
40398
  };
40153
40399
  this.running = true;
40400
+ this.guard.restoreConfirming = true;
40154
40401
  try {
40155
40402
  const now = await this.preflight(pending.header.fabricId).catch(() => null);
40156
40403
  if (!now || now.sidecarState !== pending.preflight.sidecarState || now.currentFabricId !== pending.preflight.currentFabricId) {
@@ -40178,6 +40425,7 @@ var MatterRestoreService = class {
40178
40425
  }
40179
40426
  } finally {
40180
40427
  this.running = false;
40428
+ this.guard.restoreConfirming = false;
40181
40429
  }
40182
40430
  }
40183
40431
  async apply(pending, preflight, actor, refuse) {
@@ -40347,6 +40595,11 @@ MatterBackupController = __decorateClass([
40347
40595
  var import_common16 = require("@nestjs/common");
40348
40596
  var DEFAULT_TIMING = { intervalMs: 24 * 36e5, checkMs: 15 * 6e4, debounceMs: 3e4 };
40349
40597
  var SCHEDULER_TIMING = /* @__PURE__ */ Symbol.for("attraccess.matter.backup-timing");
40598
+ var BUSY_RETRIES = 5;
40599
+ var isBusy = (error62) => {
40600
+ const response = error62?.getResponse?.();
40601
+ return typeof response === "object" && response !== null && response.code === "busy";
40602
+ };
40350
40603
  var MatterBackupSchedulerService = class {
40351
40604
  constructor(context, connectionService, fabric, backups2, guard, timing = {}) {
40352
40605
  this.context = context;
@@ -40355,6 +40608,9 @@ var MatterBackupSchedulerService = class {
40355
40608
  this.backups = backups2;
40356
40609
  this.guard = guard;
40357
40610
  this.unsubscribe = [];
40611
+ /** Retries left for a `fabric_changed` backup the sidecar refused as busy (its own gate can outlive the plugin's). */
40612
+ this.busyRetries = BUSY_RETRIES;
40613
+ this.destroyed = false;
40358
40614
  this.timing = { ...DEFAULT_TIMING, ...timing };
40359
40615
  }
40360
40616
  get connection() {
@@ -40374,6 +40630,7 @@ var MatterBackupSchedulerService = class {
40374
40630
  if (this.connection.status().state === "connected") this.start();
40375
40631
  }
40376
40632
  onModuleDestroy() {
40633
+ this.destroyed = true;
40377
40634
  for (const stop of this.unsubscribe.splice(0)) stop();
40378
40635
  this.stop();
40379
40636
  clearTimeout(this.debounceTimer);
@@ -40423,6 +40680,7 @@ var MatterBackupSchedulerService = class {
40423
40680
  return status.sidecar.state === "initialized" && status.recorded !== null && status.recoveryKey.present;
40424
40681
  }
40425
40682
  scheduleAfterChange() {
40683
+ if (this.destroyed) return;
40426
40684
  clearTimeout(this.debounceTimer);
40427
40685
  this.debounceTimer = setTimeout(() => this.safely(() => this.backupAfterChange()), this.timing.debounceMs);
40428
40686
  this.debounceTimer.unref();
@@ -40435,7 +40693,18 @@ var MatterBackupSchedulerService = class {
40435
40693
  if (generation === void 0 || !status.recoveryKey.present) return;
40436
40694
  const latest = status.backups.stored[0]?.fabricGeneration ?? -1;
40437
40695
  if (generation <= latest) return;
40438
- await this.backups.backup("fabric_changed").catch(() => void 0);
40696
+ if (this.guard.operation !== null) return this.scheduleAfterChange();
40697
+ try {
40698
+ await this.backups.backup("fabric_changed");
40699
+ this.busyRetries = BUSY_RETRIES;
40700
+ } catch (error62) {
40701
+ if (!isBusy(error62) || this.busyRetries <= 0) {
40702
+ this.busyRetries = BUSY_RETRIES;
40703
+ return;
40704
+ }
40705
+ this.busyRetries -= 1;
40706
+ this.scheduleAfterChange();
40707
+ }
40439
40708
  }
40440
40709
  };
40441
40710
  MatterBackupSchedulerService = __decorateClass([
@@ -40449,254 +40718,27 @@ MatterBackupSchedulerService = __decorateClass([
40449
40718
  __decorateParam(5, (0, import_common16.Inject)(SCHEDULER_TIMING))
40450
40719
  ], MatterBackupSchedulerService);
40451
40720
 
40452
- // backend/connection/audit.ts
40453
- var UUID_FIELD = { type: "string", pattern: "[0-9a-f-]{36}" };
40454
- var DECIMAL_ID_FIELD = { type: "string", pattern: "[0-9]{1,20}" };
40455
- var NODE_REF = { nodeRef: UUID_FIELD };
40456
- var FABRIC_ID = { fabricId: DECIMAL_ID_FIELD };
40457
- var NODE_ID = { nodeId: DECIMAL_ID_FIELD };
40458
- var DETACHED_REASONS = ["absent_from_sidecar", "fabric_mismatch", "fabric_absent"];
40459
- var INITIATOR = { initiator: { type: "string", oneOf: ["system", "administrator"] } };
40460
- var KEY_ID_FIELD = { keyId: { type: "string", pattern: "[0-9a-f-]{16}" } };
40461
- var BACKUP_REF = { backupRef: UUID_FIELD };
40462
- var GENERATION = { fabricGeneration: { type: "number", integer: true, min: 0 } };
40463
- var BACKUP_TRIGGERS = ["manual", "fabric_created", "restore", "daily", "fabric_changed", "pre_restore"];
40464
- var BACKUP_FAILURES = [
40465
- "inconsistent",
40466
- "sidecar_unavailable",
40467
- "sidecar_busy",
40468
- "insecure_transport",
40469
- "no_recovery_key",
40470
- "recovery_key_unreadable",
40471
- "recovery_required",
40472
- "no_fabric",
40473
- "sidecar_error",
40474
- "internal"
40475
- ];
40476
- var RESTORE_REFUSALS = [
40477
- "key_required",
40478
- "wrong_key",
40479
- "corrupt",
40480
- "truncated",
40481
- "incompatible_format",
40482
- "incompatible_schema",
40483
- "incompatible_migration",
40484
- "incompatible_version",
40485
- "stage_failed",
40486
- "insecure_transport",
40487
- "sidecar_unavailable",
40488
- "confirmation_required",
40489
- "preflight_changed",
40490
- "pre_restore_backup_failed",
40491
- "validation_expired",
40492
- "busy"
40493
- ];
40494
- var RESTORE_KINDS = ["plain", "rollback", "replacement"];
40495
- var MISMATCHES = [
40496
- "sidecar_uninitialized",
40497
- "fabric_changed",
40498
- "generation_behind",
40499
- "generation_ahead",
40500
- "storage_instance_changed",
40501
- "sidecar_recovery_required"
40502
- ];
40503
- var METADATA_FLAGS = {
40504
- displayNameChanged: { type: "boolean" },
40505
- descriptionChanged: { type: "boolean" },
40506
- locationChanged: { type: "boolean" }
40507
- };
40508
- var MATTER_AUDIT_DOMAIN = {
40509
- domain: "matter",
40510
- labels: { en: "Matter", de: "Matter" },
40511
- actions: [
40512
- {
40513
- action: "matter.connection_saved",
40514
- subjectTypes: ["matter.connection"],
40515
- // Flags and a scheme only: never the URL, the credential or the certificate.
40516
- details: {
40517
- credentialChanged: { type: "boolean" },
40518
- caChanged: { type: "boolean" },
40519
- scheme: { type: "string", oneOf: ["http", "https"] }
40520
- }
40521
- },
40522
- { action: "matter.connection_removed", subjectTypes: ["matter.connection"] },
40523
- { action: "matter.connection_reconnect_requested", subjectTypes: ["matter.connection"] },
40524
- // Device model (ATT-996). Subject IDs are numeric (a host rule), so the plugin UUID travels in `nodeRef` /
40525
- // `endpointRef` / `fabricRef`. Details are bounded IDs, enums and flags: never device free text.
40526
- {
40527
- action: "matter.node_quarantined",
40528
- subjectTypes: ["matter.node"],
40529
- details: { ...NODE_REF, ...FABRIC_ID, ...NODE_ID, ...INITIATOR }
40530
- },
40531
- {
40532
- action: "matter.node_detached",
40533
- subjectTypes: ["matter.node"],
40534
- details: {
40535
- ...NODE_REF,
40536
- ...FABRIC_ID,
40537
- ...NODE_ID,
40538
- reason: { type: "string", oneOf: DETACHED_REASONS },
40539
- ...INITIATOR
40540
- }
40541
- },
40542
- {
40543
- action: "matter.node_reattached",
40544
- subjectTypes: ["matter.node"],
40545
- details: {
40546
- ...NODE_REF,
40547
- ...FABRIC_ID,
40548
- ...NODE_ID,
40549
- resultingState: { type: "string", oneOf: ["claimed", "unclaimed"] },
40550
- ...INITIATOR
40551
- }
40552
- },
40553
- {
40554
- action: "matter.node_claimed",
40555
- subjectTypes: ["matter.node"],
40556
- details: { ...NODE_REF, nameSet: { type: "boolean" } }
40557
- },
40558
- {
40559
- action: "matter.node_relinked",
40560
- subjectTypes: ["matter.node"],
40561
- details: {
40562
- ...NODE_REF,
40563
- sourceNodeRef: UUID_FIELD,
40564
- identityMismatchConfirmed: { type: "boolean" }
40565
- }
40566
- },
40567
- {
40568
- action: "matter.node_repaired",
40569
- subjectTypes: ["matter.node"],
40570
- details: { ...NODE_REF, reattached: { type: "boolean" } }
40571
- },
40572
- {
40573
- action: "matter.node_archived",
40574
- subjectTypes: ["matter.node"],
40575
- details: { ...NODE_REF, previousState: { type: "string", oneOf: ["detached", "unclaimed"] } }
40576
- },
40577
- { action: "matter.node_restored", subjectTypes: ["matter.node"], details: { ...NODE_REF } },
40578
- {
40579
- action: "matter.node_force_removed",
40580
- subjectTypes: ["matter.node"],
40581
- details: {
40582
- ...NODE_REF,
40583
- previousState: { type: "string", oneOf: ["unclaimed", "claimed", "detached", "archived"] }
40584
- }
40585
- },
40586
- {
40587
- action: "matter.node_metadata_updated",
40588
- subjectTypes: ["matter.node"],
40589
- details: { ...NODE_REF, ...METADATA_FLAGS }
40590
- },
40591
- {
40592
- action: "matter.endpoint_metadata_updated",
40593
- subjectTypes: ["matter.endpoint"],
40594
- details: {
40595
- endpointRef: UUID_FIELD,
40596
- endpointId: { type: "number", integer: true, min: 0, max: 65534 },
40597
- ...METADATA_FLAGS
40598
- }
40599
- },
40600
- {
40601
- action: "matter.fabric_mismatch_detected",
40602
- subjectTypes: ["matter.fabric"],
40603
- details: {
40604
- fabricRef: UUID_FIELD,
40605
- previousFabricId: DECIMAL_ID_FIELD,
40606
- detachedNodes: { type: "number", integer: true, min: 0 },
40607
- quarantinedNodes: { type: "number", integer: true, min: 0 },
40608
- ...INITIATOR
40609
- }
40610
- },
40611
- // Fabric persistence and encrypted backups (ATT-998). Fabric ID and key ID are public identifiers; recovery keys,
40612
- // backup contents and the sidecar's secrets never appear. A backup by the plugin itself is recorded with the
40613
- // system principal. A restore's entries share its validation ID as their operation ID.
40614
- {
40615
- action: "matter.fabric_created",
40616
- subjectTypes: ["matter.fabric"],
40617
- details: { fabricRef: UUID_FIELD, ...FABRIC_ID, recoveryKeyCreated: { type: "boolean" } }
40618
- },
40619
- {
40620
- action: "matter.recovery_key_generated",
40621
- subjectTypes: ["matter.recovery_key"],
40622
- // `source: 'restore'`: the key a disaster-recovery restore was made with, kept on an installation without one.
40623
- details: { ...KEY_ID_FIELD, source: { type: "string", oneOf: ["restore"] } }
40624
- },
40625
- { action: "matter.recovery_key_acknowledged", subjectTypes: ["matter.recovery_key"], details: KEY_ID_FIELD },
40626
- {
40627
- action: "matter.recovery_key_rotated",
40628
- subjectTypes: ["matter.recovery_key"],
40629
- details: { ...KEY_ID_FIELD, previousKeyId: KEY_ID_FIELD.keyId }
40630
- },
40631
- {
40632
- action: "matter.backup_succeeded",
40633
- subjectTypes: ["matter.backup"],
40634
- details: {
40635
- ...BACKUP_REF,
40636
- trigger: { type: "string", oneOf: BACKUP_TRIGGERS },
40637
- ...GENERATION,
40638
- system: { type: "boolean" }
40639
- }
40640
- },
40641
- {
40642
- action: "matter.backup_failed",
40643
- subjectTypes: ["matter.backup"],
40644
- details: {
40645
- ...BACKUP_REF,
40646
- trigger: { type: "string", oneOf: BACKUP_TRIGGERS },
40647
- reason: { type: "string", oneOf: BACKUP_FAILURES },
40648
- system: { type: "boolean" }
40649
- }
40650
- },
40651
- {
40652
- action: "matter.restore_validated",
40653
- subjectTypes: ["matter.backup"],
40654
- details: { ...BACKUP_REF, ...GENERATION, kind: { type: "string", oneOf: RESTORE_KINDS } }
40655
- },
40656
- {
40657
- action: "matter.restore_refused",
40658
- subjectTypes: ["matter.backup"],
40659
- details: { ...BACKUP_REF, reason: { type: "string", oneOf: RESTORE_REFUSALS } }
40660
- },
40661
- {
40662
- action: "matter.restore_confirmed",
40663
- subjectTypes: ["matter.backup"],
40664
- details: {
40665
- ...BACKUP_REF,
40666
- kind: { type: "string", oneOf: RESTORE_KINDS },
40667
- typedConfirmation: { type: "boolean" },
40668
- preRestoreBackup: { type: "boolean" }
40669
- }
40670
- },
40671
- {
40672
- action: "matter.restore_succeeded",
40673
- subjectTypes: ["matter.backup"],
40674
- details: { ...BACKUP_REF, ...GENERATION }
40675
- },
40676
- // The encrypted file left the installation (ATT-1003). Never its content.
40677
- { action: "matter.backup_downloaded", subjectTypes: ["matter.backup"], details: { ...BACKUP_REF, ...GENERATION } },
40678
- { action: "matter.restore_cancelled", subjectTypes: ["matter.backup"], details: BACKUP_REF },
40679
- { action: "matter.restore_failed", subjectTypes: ["matter.backup"], details: BACKUP_REF },
40680
- { action: "matter.restore_rolled_back", subjectTypes: ["matter.backup"], details: BACKUP_REF },
40681
- {
40682
- action: "matter.fabric_recovery_required",
40683
- subjectTypes: ["matter.fabric"],
40684
- details: { fabricRef: UUID_FIELD, mismatch: { type: "string", oneOf: MISMATCHES } }
40685
- },
40686
- {
40687
- action: "matter.recovery_action_chosen",
40688
- subjectTypes: ["matter.fabric"],
40689
- details: { fabricRef: UUID_FIELD, choice: { type: "string", oneOf: ["accept_sidecar", "start_new", "restore"] } }
40690
- }
40691
- ]
40692
- };
40693
-
40694
- // backend/devices/controller.ts
40721
+ // backend/commissioning/controller.ts
40695
40722
  var import_plugins_backend_sdk7 = require("@attraccess/plugins-backend-sdk");
40696
- var import_common19 = require("@nestjs/common");
40723
+ var import_common24 = require("@nestjs/common");
40697
40724
 
40698
40725
  // backend/devices/lifecycle.service.ts
40699
40726
  var import_common17 = require("@nestjs/common");
40727
+
40728
+ // backend/devices/mark-removed.ts
40729
+ async function markNodeRemoved(tables, nodeRef, from, removal, now) {
40730
+ const changed = await tables.nodes.update(
40731
+ { id: nodeRef, lifecycleState: { in: [...from] } },
40732
+ { lifecycleState: "removed", removedAt: now, ...removal, updatedAt: now }
40733
+ );
40734
+ if (changed === 0) return false;
40735
+ for (const endpoint of await findLive(tables.endpoints, "nodeRef", nodeRef)) {
40736
+ await retireEndpoint(tables, endpoint, "force_removed", now);
40737
+ }
40738
+ return true;
40739
+ }
40740
+
40741
+ // backend/devices/lifecycle.service.ts
40700
40742
  var METADATA_FIELDS = ["displayName", "description", "location"];
40701
40743
  var MatterLifecycleService = class {
40702
40744
  constructor(context, connectionService, audit, changes) {
@@ -40921,17 +40963,11 @@ var MatterLifecycleService = class {
40921
40963
  this.expect(node3, ["unclaimed", "claimed", "detached", "archived"], "force-removed");
40922
40964
  previousState = node3.lifecycleState;
40923
40965
  const now = (/* @__PURE__ */ new Date()).toISOString();
40924
- await this.transition(tables, node3, ["unclaimed", "claimed", "detached", "archived"], {
40925
- lifecycleState: "removed",
40926
- removedAt: now,
40927
- removedBy: actor.userId,
40928
- removalReason: "force_removed",
40929
- updatedAt: now
40930
- });
40931
- for (const endpoint of await findLive(tables.endpoints, "nodeRef", node3.id)) {
40932
- await retireEndpoint(tables, endpoint, "force_removed", now);
40966
+ const removal = { removedBy: actor.userId, removalReason: "force_removed" };
40967
+ if (!await markNodeRemoved(tables, node3.id, ["unclaimed", "claimed", "detached", "archived"], removal, now)) {
40968
+ throw new import_common17.ConflictException("The node changed in the meantime. Nothing was changed.");
40933
40969
  }
40934
- return node3;
40970
+ return Object.assign(node3, removal, { lifecycleState: "removed", removedAt: now, updatedAt: now });
40935
40971
  });
40936
40972
  this.changes.inventoryChanged();
40937
40973
  await this.audit.record("matter.node_force_removed", actor, nodeSubject(node2), { nodeRef: node2.id, previousState });
@@ -41127,9 +41163,1697 @@ var listQuerySchema = external_exports.strictObject({
41127
41163
  includeInactive: external_exports.enum(["true", "false"]).transform((value) => value === "true").optional()
41128
41164
  });
41129
41165
 
41130
- // backend/devices/state.service.ts
41166
+ // backend/devices/views.ts
41167
+ function nodeView(node2) {
41168
+ return {
41169
+ id: node2.id,
41170
+ fabricRef: node2.fabricRef,
41171
+ nodeId: node2.nodeId,
41172
+ lifecycleState: node2.lifecycleState,
41173
+ detachedReason: node2.detachedReason,
41174
+ reachable: node2.reachable,
41175
+ /** Read-only: reported by the sidecar. */
41176
+ identity: {
41177
+ vendorId: node2.vendorId,
41178
+ productId: node2.productId,
41179
+ vendorName: node2.vendorName,
41180
+ productName: node2.productName,
41181
+ serialNumber: node2.serialNumber,
41182
+ uniqueId: node2.uniqueId,
41183
+ hardwareVersion: node2.hardwareVersion,
41184
+ softwareVersion: node2.softwareVersion,
41185
+ softwareVersionString: node2.softwareVersionString,
41186
+ attestation: { status: node2.attestationStatus, checkedAt: node2.attestationCheckedAt }
41187
+ },
41188
+ /** Editable by administrators; reconciliation never writes it. */
41189
+ metadata: { displayName: node2.displayName, description: node2.description, location: node2.location },
41190
+ firstSeenAt: node2.firstSeenAt,
41191
+ lastSeenAt: node2.lastSeenAt,
41192
+ claimedAt: node2.claimedAt,
41193
+ claimedBy: node2.claimedBy,
41194
+ detachedAt: node2.detachedAt,
41195
+ archivedAt: node2.archivedAt,
41196
+ archivedBy: node2.archivedBy,
41197
+ removedAt: node2.removedAt,
41198
+ removedBy: node2.removedBy,
41199
+ removalReason: node2.removalReason,
41200
+ mergedInto: node2.mergedInto,
41201
+ createdAt: node2.createdAt,
41202
+ updatedAt: node2.updatedAt
41203
+ };
41204
+ }
41205
+ function endpointView(endpoint) {
41206
+ return {
41207
+ id: endpoint.id,
41208
+ nodeRef: endpoint.nodeRef,
41209
+ endpointId: endpoint.endpointId,
41210
+ parentEndpointId: endpoint.parentEndpointId,
41211
+ deviceTypes: JSON.parse(endpoint.deviceTypes),
41212
+ profile: endpoint.profile,
41213
+ metadata: { displayName: endpoint.displayName, description: endpoint.description, location: endpoint.location },
41214
+ bridged: endpoint.bridged ? {
41215
+ uniqueId: endpoint.bridgedUniqueId,
41216
+ nodeLabel: endpoint.bridgedNodeLabel,
41217
+ vendorName: endpoint.bridgedVendorName,
41218
+ productName: endpoint.bridgedProductName,
41219
+ serialNumber: endpoint.bridgedSerialNumber,
41220
+ reachable: endpoint.bridgedReachable
41221
+ } : null,
41222
+ firstSeenAt: endpoint.firstSeenAt,
41223
+ lastSeenAt: endpoint.lastSeenAt,
41224
+ removedAt: endpoint.removedAt,
41225
+ removalReason: endpoint.removalReason
41226
+ };
41227
+ }
41228
+ function clusterView(cluster) {
41229
+ return {
41230
+ clusterId: cluster.clusterId,
41231
+ role: cluster.role,
41232
+ revision: cluster.revision,
41233
+ featureMap: cluster.featureMap,
41234
+ attributeIds: JSON.parse(cluster.attributeIds),
41235
+ acceptedCommandIds: JSON.parse(cluster.acceptedCommandIds)
41236
+ };
41237
+ }
41238
+ function capabilityView(capability) {
41239
+ return {
41240
+ capability: capability.capability,
41241
+ sourceClusterId: capability.sourceClusterId,
41242
+ details: JSON.parse(capability.details)
41243
+ };
41244
+ }
41245
+ function nodeDetailView(detail) {
41246
+ return {
41247
+ ...nodeView(detail.node),
41248
+ /** Every fabric the device is joined to, Attraccess's own included. Read-only: other ecosystems manage theirs. */
41249
+ administrators: parseAdministrators(detail.node.administrators),
41250
+ /** True when the node was commissioned although attestation failed (development override). */
41251
+ attestationOverridden: detail.node.attestationOverridden === true,
41252
+ fabric: detail.fabric && {
41253
+ id: detail.fabric.id,
41254
+ fabricId: detail.fabric.fabricId,
41255
+ status: detail.fabric.status,
41256
+ label: detail.fabric.label
41257
+ },
41258
+ endpoints: detail.endpoints.map(({ endpoint, clusters, capabilities }) => ({
41259
+ ...endpointView(endpoint),
41260
+ clusters: clusters.map(clusterView),
41261
+ capabilities: capabilities.map(capabilityView).sort((a, b) => a.capability.localeCompare(b.capability))
41262
+ }))
41263
+ };
41264
+ }
41265
+ function parseAdministrators(json2) {
41266
+ if (!json2) return [];
41267
+ try {
41268
+ const parsed = JSON.parse(json2);
41269
+ return Array.isArray(parsed) ? parsed : [];
41270
+ } catch {
41271
+ return [];
41272
+ }
41273
+ }
41274
+
41275
+ // backend/commissioning/commissioning.service.ts
41276
+ var import_common21 = require("@nestjs/common");
41277
+ var import_node_crypto17 = require("node:crypto");
41278
+
41279
+ // backend/commissioning/errors.ts
41131
41280
  var import_common18 = require("@nestjs/common");
41281
+ var INSECURE_SETUP_CODE = "The connection to the Matter sidecar is plain HTTP to another machine. Setup codes are secrets and are only sent over HTTPS (or to a sidecar on this machine).";
41282
+ var INSECURE_SHARING_CODE = "The connection to the Matter sidecar is plain HTTP to another machine. Sharing codes are secrets and are only received over HTTPS (or from a sidecar on this machine).";
41283
+ function startFailure(error62) {
41284
+ switch (sidecarCode(error62)) {
41285
+ case "validation_failed":
41286
+ return new import_common18.BadRequestException({ code: "invalid_code", message: "The setup code is not valid." });
41287
+ case "attestation_override_disabled":
41288
+ return forbidden(
41289
+ "attestation_override_disabled",
41290
+ "The Matter sidecar does not allow the attestation override. An operator enables it on a development install only."
41291
+ );
41292
+ case "insecure_transport":
41293
+ return forbidden("insecure_transport", INSECURE_SETUP_CODE);
41294
+ case "fabric_absent":
41295
+ return conflict("fabric_absent", "The sidecar has no fabric yet. Create the fabric first.");
41296
+ case "unsupported_capability":
41297
+ return new import_common18.ServiceUnavailableException({
41298
+ code: "unsupported_capability",
41299
+ message: "This Matter sidecar release cannot commission devices."
41300
+ });
41301
+ default:
41302
+ return sidecarFailure(error62);
41303
+ }
41304
+ }
41305
+ function failureReason(error62) {
41306
+ switch (sidecarCode(error62)) {
41307
+ case "device_unreachable":
41308
+ return "device_unreachable";
41309
+ case "timeout":
41310
+ return "timeout";
41311
+ case "busy":
41312
+ return "busy";
41313
+ case "not_found":
41314
+ return "not_found";
41315
+ case "sidecar_unavailable":
41316
+ case "network":
41317
+ return "sidecar_unavailable";
41318
+ default:
41319
+ return "internal";
41320
+ }
41321
+ }
41322
+ function removalFailure(error62, mode) {
41323
+ switch (failureReason(error62)) {
41324
+ case "device_unreachable":
41325
+ return conflict(
41326
+ "device_unreachable",
41327
+ "The device could not be reached, so it was not removed from the fabric. Nothing was changed. Force removal forgets the device here without contacting it."
41328
+ );
41329
+ case "timeout":
41330
+ return conflict(
41331
+ "timeout",
41332
+ "The device did not answer in time. Whether it left the fabric is uncertain: it may still complete the removal. A reconciliation was requested; check the device again shortly. Force removal forgets the device here without contacting it."
41333
+ );
41334
+ case "not_found":
41335
+ return conflict(
41336
+ "node_not_on_sidecar",
41337
+ mode === "force" ? 'The sidecar does not know this node. Use "force remove" of the record instead.' : "The sidecar does not know this node. Run a reconciliation, or force remove the record."
41338
+ );
41339
+ default:
41340
+ return sidecarFailure(error62);
41341
+ }
41342
+ }
41343
+
41344
+ // backend/commissioning/operation-gate.ts
41345
+ var import_common19 = require("@nestjs/common");
41346
+ var MatterOperationGate = class {
41347
+ constructor(guard) {
41348
+ this.guard = guard;
41349
+ /** The current holder; a release by anyone else is a no-op. */
41350
+ this.holder = null;
41351
+ }
41352
+ /** Takes the gate for `kind`, or throws 409 `busy`. Returns the function that releases it (idempotent). */
41353
+ enter(kind) {
41354
+ if (this.guard.operation !== null) throw operationBusy(this.guard.operation);
41355
+ this.guard.assertFabricMutationAllowed();
41356
+ const holder = {};
41357
+ this.holder = holder;
41358
+ this.guard.operation = kind;
41359
+ return () => {
41360
+ if (this.holder !== holder) return;
41361
+ this.holder = null;
41362
+ this.guard.operation = null;
41363
+ };
41364
+ }
41365
+ get busy() {
41366
+ return this.guard.operation !== null;
41367
+ }
41368
+ };
41369
+ MatterOperationGate = __decorateClass([
41370
+ (0, import_common19.Injectable)(),
41371
+ __decorateParam(0, (0, import_common19.Inject)(MatterFabricGuard))
41372
+ ], MatterOperationGate);
41373
+
41374
+ // backend/commissioning/session.ts
41375
+ var isActive = (session) => session.state === "pending" || session.state === "running";
41376
+ function sessionView(session) {
41377
+ return {
41378
+ id: session.id,
41379
+ state: session.state,
41380
+ step: session.step,
41381
+ failure: session.failure,
41382
+ attestation: session.attestation,
41383
+ overrideAvailable: session.overrideAvailable,
41384
+ nodeRecordId: session.nodeRecordId,
41385
+ endpoints: session.state === "succeeded" ? session.endpoints : [],
41386
+ finished: session.finished,
41387
+ startedAt: session.startedAt,
41388
+ updatedAt: session.updatedAt,
41389
+ finishedAt: session.finishedAt
41390
+ };
41391
+ }
41392
+
41393
+ // backend/commissioning/session-tracker.ts
41394
+ var import_common20 = require("@nestjs/common");
41132
41395
  var import_node_crypto14 = require("node:crypto");
41396
+ var COMMISSIONING_TIMING = /* @__PURE__ */ Symbol.for("attraccess.matter.commissioning-timing");
41397
+ var DEFAULT_TIMING2 = {
41398
+ pollMs: 1500,
41399
+ maxMs: 7 * 6e4,
41400
+ maxUnreachablePolls: 4,
41401
+ retainMs: 36e5
41402
+ };
41403
+ var ORPHAN_WAIT_MS = 15e3;
41404
+ var CommissioningSessionTracker = class {
41405
+ constructor(deps) {
41406
+ this.deps = deps;
41407
+ this.sessions = /* @__PURE__ */ new Map();
41408
+ this.polling = false;
41409
+ this.streamInstanceId = null;
41410
+ /** Sidecar sessions this plugin did not start (it restarted since), already handled. */
41411
+ this.orphans = /* @__PURE__ */ new Set();
41412
+ this.startsInFlight = 0;
41413
+ }
41414
+ get settlement() {
41415
+ return this.deps.settlement;
41416
+ }
41417
+ get currentStreamInstanceId() {
41418
+ return this.streamInstanceId;
41419
+ }
41420
+ /** Subscribes to the connection. Returns the functions that unsubscribe. */
41421
+ listen() {
41422
+ const connection2 = this.deps.connection();
41423
+ return [
41424
+ connection2.onEvent((event) => this.onEvent(event)),
41425
+ connection2.onStateChange((status) => {
41426
+ if (status.state === "connected") void this.settlement.flushCancels();
41427
+ else this.interruptAll("connection_lost");
41428
+ })
41429
+ ];
41430
+ }
41431
+ stop() {
41432
+ clearInterval(this.timer);
41433
+ this.timer = void 0;
41434
+ }
41435
+ /** A session that just started: kept, and followed until it ends. */
41436
+ track(session) {
41437
+ this.prune();
41438
+ this.sessions.set(session.id, session);
41439
+ this.startPolling();
41440
+ }
41441
+ owned(id, userId) {
41442
+ const session = this.sessions.get(id);
41443
+ if (!session || session.userId !== userId) throw new import_common20.NotFoundException("Unknown commissioning session.");
41444
+ return session;
41445
+ }
41446
+ /** Running sessions whose outcome is not being handled yet. */
41447
+ activeSessions() {
41448
+ return [...this.sessions.values()].filter((session) => isActive(session) && !session.settling);
41449
+ }
41450
+ // --- starting, and the sessions of an earlier plugin run -------------------------------------------------------
41451
+ /**
41452
+ * Asks the sidecar to start. A session the plugin no longer follows may hold the sidecar's gate: one of an earlier
41453
+ * plugin run, or one the plugin already ended (interrupted) whose cancel did not reach the sidecar. It is cancelled
41454
+ * (nothing resumes) and the start is tried once more. Only one of an earlier run is audited, as `plugin_restart`.
41455
+ */
41456
+ async requestStart(input2) {
41457
+ const body = {
41458
+ setupCode: input2.setupCode,
41459
+ ...input2.attestationOverride ? { attestationOverride: input2.attestationOverride } : {}
41460
+ };
41461
+ const connection2 = this.deps.connection();
41462
+ this.startsInFlight += 1;
41463
+ try {
41464
+ try {
41465
+ return await connection2.request("commissioning.start", { body });
41466
+ } catch (error62) {
41467
+ const orphan = this.orphanOf(error62);
41468
+ if (orphan === null) throw error62;
41469
+ await this.cancelOrphan(orphan.id, orphan.known);
41470
+ return await connection2.request("commissioning.start", { body });
41471
+ }
41472
+ } finally {
41473
+ this.startsInFlight -= 1;
41474
+ }
41475
+ }
41476
+ /** The sidecar session a `busy` refusal points at, when the plugin does not follow it; null for any other cause. */
41477
+ orphanOf(error62) {
41478
+ if (!(error62 instanceof SidecarClientError) || error62.code !== "busy") return null;
41479
+ const id = error62.details?.sessionId;
41480
+ if (typeof id !== "string" || this.activeSessions().length > 0) return null;
41481
+ const known = [...this.sessions.values()].find((entry) => entry.sidecarSessionId === id);
41482
+ if (known && isActive(known)) return null;
41483
+ return { id, known: known !== void 0 };
41484
+ }
41485
+ async cancelOrphan(sidecarSessionId, known) {
41486
+ if (!known) await this.noteOrphan(sidecarSessionId);
41487
+ const connection2 = this.deps.connection();
41488
+ await connection2.request("commissioning.cancel", { params: { sessionId: sidecarSessionId } });
41489
+ const deadline = Date.now() + ORPHAN_WAIT_MS;
41490
+ for (; ; ) {
41491
+ const state = await connection2.request("commissioning.get", { params: { sessionId: sidecarSessionId } }).then((view) => view.state).catch(() => "failed");
41492
+ if (state !== "pending" && state !== "running") return;
41493
+ if (Date.now() > deadline) return;
41494
+ await new Promise((resolve) => setTimeout(resolve, 200));
41495
+ }
41496
+ }
41497
+ /** A session of the sidecar this plugin has no record of: it was lost with a restart. Audited once. */
41498
+ async noteOrphan(sidecarSessionId) {
41499
+ if (this.orphans.has(sidecarSessionId)) return;
41500
+ this.orphans.add(sidecarSessionId);
41501
+ await this.settlement.record("matter.commissioning_interrupted", null, { reason: "plugin_restart" }, (0, import_node_crypto14.randomUUID)());
41502
+ }
41503
+ // --- following ----------------------------------------------------------------------------------------------------
41504
+ onEvent({ event }) {
41505
+ const previous = this.streamInstanceId;
41506
+ this.streamInstanceId = event.streamInstanceId;
41507
+ if (previous !== null && previous !== event.streamInstanceId) {
41508
+ this.interruptAll("sidecar_restart");
41509
+ }
41510
+ for (const session2 of this.activeSessions()) session2.streamInstanceId ??= event.streamInstanceId;
41511
+ if (event.type !== "commissioning.progress") return;
41512
+ const payload = event.payload;
41513
+ const session = [...this.sessions.values()].find((entry) => entry.sidecarSessionId === payload.sessionId);
41514
+ if (session) {
41515
+ if (isActive(session) && !session.settling) this.background(this.refresh(session));
41516
+ else if (session.state === "interrupted" && payload.state === "succeeded")
41517
+ this.settlement.requestReconciliation();
41518
+ } else if (payload.sessionId && this.startsInFlight === 0) {
41519
+ this.background(this.noteOrphan(payload.sessionId));
41520
+ if (payload.state === "succeeded") this.settlement.requestReconciliation();
41521
+ }
41522
+ }
41523
+ startPolling() {
41524
+ if (this.timer) return;
41525
+ this.timer = setInterval(() => this.background(this.poll()), this.deps.timing.pollMs);
41526
+ this.timer.unref();
41527
+ }
41528
+ async poll() {
41529
+ if (this.polling) return;
41530
+ this.polling = true;
41531
+ try {
41532
+ for (const session of this.activeSessions()) {
41533
+ try {
41534
+ if (Date.now() - Date.parse(session.startedAt) > this.deps.timing.maxMs) {
41535
+ await this.settlement.interrupt(session, "timeout");
41536
+ } else {
41537
+ await this.refresh(session);
41538
+ }
41539
+ } catch (error62) {
41540
+ this.deps.warn(`A Matter commissioning session could not be followed: ${describe3(error62)}`);
41541
+ }
41542
+ }
41543
+ } finally {
41544
+ this.polling = false;
41545
+ if (![...this.sessions.values()].some(isActive)) this.stop();
41546
+ }
41547
+ }
41548
+ /** Reads the session from the sidecar. `not_found` means the sidecar restarted since it started the session. */
41549
+ async refresh(session) {
41550
+ if (!isActive(session) || session.settling) return;
41551
+ let sidecar;
41552
+ try {
41553
+ sidecar = await this.deps.connection().request("commissioning.get", { params: { sessionId: session.sidecarSessionId } });
41554
+ } catch (error62) {
41555
+ if (error62 instanceof SidecarClientError && error62.code === "not_found") {
41556
+ return this.settlement.interrupt(session, "sidecar_restart");
41557
+ }
41558
+ session.unreachable += 1;
41559
+ if (session.unreachable >= this.deps.timing.maxUnreachablePolls) {
41560
+ return this.settlement.interrupt(session, "connection_lost");
41561
+ }
41562
+ return;
41563
+ }
41564
+ session.unreachable = 0;
41565
+ await this.settlement.apply(session, sidecar);
41566
+ }
41567
+ interruptAll(reason) {
41568
+ return this.activeSessions().map((session) => {
41569
+ const done = this.settlement.interrupt(session, reason);
41570
+ this.background(done);
41571
+ return done;
41572
+ });
41573
+ }
41574
+ /** Work nobody awaits must never end as an unhandled rejection (an audit or database error, for example). */
41575
+ background(work) {
41576
+ work.catch(
41577
+ (error62) => this.deps.warn(`A Matter commissioning session could not be followed: ${describe3(error62)}`)
41578
+ );
41579
+ }
41580
+ prune() {
41581
+ const limit = Date.now() - this.deps.timing.retainMs;
41582
+ for (const [id, session] of this.sessions) {
41583
+ if (session.finishedAt !== null && Date.parse(session.finishedAt) < limit) this.sessions.delete(id);
41584
+ }
41585
+ }
41586
+ };
41587
+ var describe3 = (error62) => error62 instanceof Error ? error62.name : "unknown error";
41588
+
41589
+ // backend/commissioning/settlement.ts
41590
+ var import_node_crypto16 = require("node:crypto");
41591
+
41592
+ // backend/commissioning/registry-writer.ts
41593
+ var import_node_crypto15 = require("node:crypto");
41594
+ var RegistryConflictError = class extends Error {
41595
+ };
41596
+ async function registerCommissionedNode(tables, input2) {
41597
+ const { fabricId, view, userId, overridden, now } = input2;
41598
+ let fabric = await tables.fabrics.findOne({ where: { fabricId, retiredAt: null } });
41599
+ if (!fabric) {
41600
+ fabric = await tables.fabrics.insert({
41601
+ id: (0, import_node_crypto15.randomUUID)(),
41602
+ fabricId,
41603
+ label: null,
41604
+ firstSeenAt: now,
41605
+ lastSeenAt: now,
41606
+ status: "active",
41607
+ retiredAt: null,
41608
+ fabricGeneration: null,
41609
+ storageInstanceId: null,
41610
+ rootCertFingerprint: null,
41611
+ recordedAt: null
41612
+ });
41613
+ } else if (fabric.status !== "active") {
41614
+ throw new RegistryConflictError("The fabric is not the active one.");
41615
+ }
41616
+ const attestation = {
41617
+ attestationStatus: overridden ? "unverified" : view.attestation.status,
41618
+ attestationOverridden: overridden
41619
+ };
41620
+ const live = await tables.nodes.findOne({ where: { fabricRef: fabric.id, nodeId: view.nodeId, removedAt: null } });
41621
+ let node2;
41622
+ if (live) {
41623
+ if (live.lifecycleState !== "unclaimed") throw new RegistryConflictError("The node already has a record.");
41624
+ const patch = {
41625
+ lifecycleState: "claimed",
41626
+ claimedAt: now,
41627
+ claimedBy: userId,
41628
+ updatedAt: now,
41629
+ ...attestation
41630
+ };
41631
+ const changed = await tables.nodes.update({ id: live.id, lifecycleState: "unclaimed" }, patch);
41632
+ if (changed === 0) throw new RegistryConflictError("The node changed in the meantime.");
41633
+ node2 = Object.assign(live, patch);
41634
+ } else {
41635
+ node2 = {
41636
+ id: (0, import_node_crypto15.randomUUID)(),
41637
+ fabricRef: fabric.id,
41638
+ nodeId: view.nodeId,
41639
+ displayName: null,
41640
+ description: null,
41641
+ location: null,
41642
+ lifecycleState: "claimed",
41643
+ detachedReason: null,
41644
+ firstSeenAt: now,
41645
+ claimedAt: now,
41646
+ claimedBy: userId,
41647
+ detachedAt: null,
41648
+ archivedAt: null,
41649
+ archivedBy: null,
41650
+ removedAt: null,
41651
+ removedBy: null,
41652
+ removalReason: null,
41653
+ mergedInto: null,
41654
+ createdAt: now,
41655
+ updatedAt: now,
41656
+ ...identityOf(view, now),
41657
+ ...attestation
41658
+ };
41659
+ await tables.nodes.insert(node2);
41660
+ }
41661
+ await syncNode(tables, node2, view, now, newCounters());
41662
+ if (overridden && node2.attestationStatus !== "unverified") {
41663
+ node2.attestationStatus = "unverified";
41664
+ await tables.nodes.update({ id: node2.id }, { attestationStatus: "unverified" });
41665
+ }
41666
+ const endpoints2 = await findLive(tables.endpoints, "nodeRef", node2.id);
41667
+ endpoints2.sort((a, b) => a.endpointId - b.endpointId);
41668
+ return { node: node2, endpoints: endpoints2 };
41669
+ }
41670
+
41671
+ // backend/commissioning/settlement.ts
41672
+ var SUBJECT = "matter.commissioning_session";
41673
+ var RECONCILE_AFTER = /* @__PURE__ */ new Set([
41674
+ "internal",
41675
+ "case_failed",
41676
+ "timeout",
41677
+ "needs_reconciliation",
41678
+ "registry_failed"
41679
+ ]);
41680
+ var CANCEL_ON = /* @__PURE__ */ new Set(["connection_lost", "timeout"]);
41681
+ var CANCEL_TIMEOUT_MS = 5e3;
41682
+ var MAX_UNCONFIRMED_CANCELS = 16;
41683
+ var CommissioningSettlement = class {
41684
+ constructor(deps) {
41685
+ this.deps = deps;
41686
+ this.releaseGate = null;
41687
+ /** Sidecar sessions the plugin ended whose cancel the sidecar has not confirmed yet. */
41688
+ this.unconfirmedCancels = /* @__PURE__ */ new Set();
41689
+ }
41690
+ get storage() {
41691
+ return matterStorage(this.deps.context);
41692
+ }
41693
+ /** The release of the operation gate the running session holds. One session at a time. */
41694
+ holdGate(release) {
41695
+ this.releaseGate = release;
41696
+ }
41697
+ /** Takes over what the sidecar says about the session. Terminal outcomes are handled once. */
41698
+ async apply(session, sidecar) {
41699
+ if (!isActive(session) || session.settling) return;
41700
+ try {
41701
+ await this.take(session, sidecar);
41702
+ } catch (error62) {
41703
+ await this.abandon(session, error62);
41704
+ }
41705
+ }
41706
+ async take(session, sidecar) {
41707
+ session.step = sidecar.step;
41708
+ session.overrideAvailable = sidecar.attestationOverrideAllowed;
41709
+ const overriddenBefore = session.attestation?.status === "overridden";
41710
+ session.attestation = sidecar.attestation;
41711
+ session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
41712
+ if (sidecar.attestation?.status === "overridden" && !overriddenBefore) {
41713
+ await this.record("matter.commissioning_attestation_overridden", session, {
41714
+ findings: sidecar.attestation.findings.join(",")
41715
+ });
41716
+ if (!isActive(session) || session.settling) return;
41717
+ }
41718
+ if (sidecar.state === "pending" || sidecar.state === "running") {
41719
+ session.state = sidecar.state;
41720
+ return;
41721
+ }
41722
+ session.settling = true;
41723
+ if (sidecar.state === "failed") return this.settleFailure(session, sidecar);
41724
+ if (sidecar.nodeId === null) return this.fail(session, { code: "internal" });
41725
+ await this.register(session, sidecar.nodeId);
41726
+ }
41727
+ /**
41728
+ * The session could not be handled to its end (a database or audit error). It ends as `internal` failure, its
41729
+ * sidecar session is cancelled and the gate is freed; a device that joined meanwhile surfaces as unclaimed.
41730
+ */
41731
+ async abandon(session, error62) {
41732
+ const reason = error62 instanceof Error ? redactSecrets(error62.message) : "unknown error";
41733
+ this.deps.context.logger.warn?.(`A Matter commissioning session could not be settled: ${reason}`);
41734
+ if (!isActive(session)) return;
41735
+ session.state = "failed";
41736
+ session.failure = { code: "internal" };
41737
+ this.finishSession(session);
41738
+ void this.cancelOnSidecar(session.sidecarSessionId);
41739
+ this.requestReconciliation();
41740
+ await this.record("matter.commissioning_failed", session, {
41741
+ failure: "internal",
41742
+ ...session.step ? { step: session.step } : {}
41743
+ }).catch(() => void 0);
41744
+ }
41745
+ async settleFailure(session, sidecar) {
41746
+ const failure2 = sidecar.failure ?? { code: "internal" };
41747
+ if (failure2.code === "interrupted") return this.interrupt(session, "sidecar_restart", true);
41748
+ if (failure2.code === "already_commissioned") {
41749
+ const existing = await this.existingRecord(failure2.existingNodeId);
41750
+ return this.fail(session, { code: failure2.code, existing }, failure2.existingNodeId);
41751
+ }
41752
+ await this.fail(session, {
41753
+ code: failure2.code,
41754
+ ...failure2.attestationFindings ? { attestationFindings: failure2.attestationFindings } : {}
41755
+ });
41756
+ }
41757
+ /** The registry's record of a node the device already is, and what the administrator can do about it. */
41758
+ async existingRecord(nodeId) {
41759
+ const none = { nodeRecordId: null, lifecycleState: null, action: "reconcile" };
41760
+ if (nodeId === void 0) return none;
41761
+ const { tables } = this.storage;
41762
+ const recorded = await recordedFabricRow(tables);
41763
+ const fabrics2 = recorded ? [recorded] : await tables.fabrics.find({ where: { retiredAt: null } });
41764
+ const rows = await tables.nodes.find({
41765
+ where: { nodeId, fabricRef: { in: fabrics2.map((entry) => entry.id) } },
41766
+ orderBy: [{ field: "createdAt", direction: "desc" }]
41767
+ });
41768
+ const record2 = rows.find((row) => row.lifecycleState !== "removed") ?? null;
41769
+ if (!record2) return none;
41770
+ const action = {
41771
+ claimed: "open",
41772
+ unclaimed: "open",
41773
+ detached: "repair",
41774
+ archived: "restore"
41775
+ };
41776
+ return {
41777
+ nodeRecordId: record2.id,
41778
+ lifecycleState: record2.lifecycleState,
41779
+ action: action[record2.lifecycleState] ?? "reconcile"
41780
+ };
41781
+ }
41782
+ /**
41783
+ * The sidecar reported success. The session counts as succeeded only after the plugin read the node itself, the
41784
+ * fabric matches the one it recorded, and the rows were written in one transaction.
41785
+ */
41786
+ async register(session, nodeId) {
41787
+ const outcome = await this.write(session, nodeId);
41788
+ if ("code" in outcome) return this.fail(session, { code: outcome.code });
41789
+ const { registered, fabricId } = outcome;
41790
+ session.nodeRecordId = registered.node.id;
41791
+ session.endpoints = registered.endpoints.map((endpoint) => ({
41792
+ endpointId: endpoint.endpointId,
41793
+ id: endpoint.id,
41794
+ displayName: endpoint.displayName
41795
+ }));
41796
+ session.state = "succeeded";
41797
+ session.step = "completed";
41798
+ this.finishSession(session);
41799
+ this.deps.changes.inventoryChanged();
41800
+ const findings = session.attestation?.findings ?? [];
41801
+ await this.deps.audit.record(
41802
+ "matter.node_commissioned",
41803
+ session.principal,
41804
+ { type: "matter.node", ref: registered.node.id },
41805
+ {
41806
+ nodeRef: registered.node.id,
41807
+ fabricId,
41808
+ nodeId: registered.node.nodeId,
41809
+ sessionRef: session.id,
41810
+ attestation: session.attestation?.status === "overridden" ? "overridden" : "verified",
41811
+ ...findings.length > 0 ? { findings: findings.join(",") } : {}
41812
+ }
41813
+ );
41814
+ }
41815
+ /** Reads the node and writes its rows. A failure here means the device joined but the registry did not follow. */
41816
+ async write(session, nodeId) {
41817
+ const connection2 = this.deps.connection();
41818
+ try {
41819
+ const sidecarFabric = await connection2.request("fabric.get");
41820
+ const view = await connection2.request("inventory.get", { params: { nodeId } });
41821
+ await this.deps.fabric.detect("event").catch(() => void 0);
41822
+ const recorded = await recordedFabricRow(this.storage.tables);
41823
+ const fabricId = sidecarFabric.fabricId;
41824
+ if (fabricId === null || recorded && recorded.fabricId !== fabricId) return { code: "needs_reconciliation" };
41825
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41826
+ const registered = await this.storage.transaction(
41827
+ (tables) => registerCommissionedNode(tables, {
41828
+ fabricId,
41829
+ view,
41830
+ userId: session.userId,
41831
+ overridden: session.attestation?.status === "overridden",
41832
+ now
41833
+ })
41834
+ );
41835
+ return { registered, fabricId };
41836
+ } catch (error62) {
41837
+ return { code: error62 instanceof RegistryConflictError ? "needs_reconciliation" : "registry_failed" };
41838
+ }
41839
+ }
41840
+ async fail(session, failure2, existingNodeId) {
41841
+ session.state = "failed";
41842
+ session.failure = failure2;
41843
+ this.finishSession(session);
41844
+ if (RECONCILE_AFTER.has(failure2.code)) this.requestReconciliation();
41845
+ if (failure2.code === "cancelled") {
41846
+ await this.record("matter.commissioning_cancelled", session, {});
41847
+ return;
41848
+ }
41849
+ await this.record("matter.commissioning_failed", session, {
41850
+ failure: failure2.code,
41851
+ ...session.step ? { step: session.step } : {},
41852
+ ...failure2.attestationFindings ? { findings: failure2.attestationFindings.join(",") } : {},
41853
+ ...existingNodeId === void 0 ? {} : { existingNodeId }
41854
+ });
41855
+ }
41856
+ /**
41857
+ * Ends the session as `interrupted`. Where the sidecar may still run it, it is cancelled there too (best effort, and
41858
+ * again after a reconnect), so "Start again" is not refused as busy. `force`: the caller already holds the session's
41859
+ * terminal handling (the sidecar itself reported the interruption).
41860
+ */
41861
+ async interrupt(session, reason, force = false) {
41862
+ if (!isActive(session) || session.settling && !force) return;
41863
+ session.settling = true;
41864
+ session.state = "interrupted";
41865
+ session.failure = { code: "interrupted" };
41866
+ this.finishSession(session);
41867
+ const cancelled = CANCEL_ON.has(reason) ? this.cancelOnSidecar(session.sidecarSessionId) : Promise.resolve();
41868
+ if (reason !== "plugin_restart") this.requestReconciliation();
41869
+ try {
41870
+ await this.record("matter.commissioning_interrupted", session, { reason });
41871
+ } finally {
41872
+ await cancelled;
41873
+ }
41874
+ }
41875
+ /** Asks the sidecar to cancel a session. Never throws; an unconfirmed cancel is sent again after a reconnect. */
41876
+ async cancelOnSidecar(sidecarSessionId, timeoutMs = CANCEL_TIMEOUT_MS) {
41877
+ try {
41878
+ await this.deps.connection().request("commissioning.cancel", { params: { sessionId: sidecarSessionId }, timeoutMs });
41879
+ this.unconfirmedCancels.delete(sidecarSessionId);
41880
+ } catch (error62) {
41881
+ if (error62 instanceof SidecarClientError && error62.kind === "request") {
41882
+ this.unconfirmedCancels.delete(sidecarSessionId);
41883
+ return;
41884
+ }
41885
+ this.unconfirmedCancels.add(sidecarSessionId);
41886
+ if (this.unconfirmedCancels.size > MAX_UNCONFIRMED_CANCELS) {
41887
+ const [oldest] = this.unconfirmedCancels;
41888
+ this.unconfirmedCancels.delete(oldest);
41889
+ }
41890
+ }
41891
+ }
41892
+ /** Sends the cancels the sidecar could not confirm while it was unreachable. Never throws. */
41893
+ async flushCancels() {
41894
+ for (const id of [...this.unconfirmedCancels]) await this.cancelOnSidecar(id);
41895
+ }
41896
+ requestReconciliation() {
41897
+ void this.deps.reconciliation.request().catch(() => void 0);
41898
+ }
41899
+ finishSession(session) {
41900
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41901
+ session.updatedAt = now;
41902
+ session.finishedAt = now;
41903
+ session.settling = false;
41904
+ this.releaseGate?.();
41905
+ this.releaseGate = null;
41906
+ }
41907
+ record(action, session, details, ref = session?.id ?? (0, import_node_crypto16.randomUUID)()) {
41908
+ return this.deps.audit.record(
41909
+ action,
41910
+ session?.principal ?? null,
41911
+ { type: SUBJECT, ref },
41912
+ { sessionRef: ref, ...details }
41913
+ );
41914
+ }
41915
+ };
41916
+
41917
+ // backend/commissioning/commissioning.service.ts
41918
+ var SHUTDOWN_CANCEL_TIMEOUT_MS = 2e3;
41919
+ var MatterCommissioningService = class {
41920
+ constructor(context, connectionService, guard, audit, changes, gate, fabric, reconciliation, timing) {
41921
+ this.context = context;
41922
+ this.connectionService = connectionService;
41923
+ this.guard = guard;
41924
+ this.audit = audit;
41925
+ this.changes = changes;
41926
+ this.gate = gate;
41927
+ this.unsubscribe = [];
41928
+ const connection2 = () => this.connectionService.connection;
41929
+ this.settlement = new CommissioningSettlement({ context, connection: connection2, audit, changes, fabric, reconciliation });
41930
+ this.tracker = new CommissioningSessionTracker({
41931
+ connection: connection2,
41932
+ settlement: this.settlement,
41933
+ timing: timing ?? DEFAULT_TIMING2,
41934
+ warn: (message) => context.logger.warn?.(message)
41935
+ });
41936
+ }
41937
+ get connection() {
41938
+ return this.connectionService.connection;
41939
+ }
41940
+ get storage() {
41941
+ return matterStorage(this.context);
41942
+ }
41943
+ onModuleInit() {
41944
+ this.unsubscribe.push(...this.tracker.listen());
41945
+ this.connectionService.beforeStopping?.(() => this.shutdown());
41946
+ }
41947
+ /** Ends running sessions as interrupted (`plugin_restart`) and cancels them on the sidecar. Bounded. */
41948
+ async onModuleDestroy() {
41949
+ for (const stop of this.unsubscribe.splice(0)) stop();
41950
+ this.tracker.stop();
41951
+ let timer;
41952
+ const grace = new Promise((resolve) => {
41953
+ timer = setTimeout(resolve, STOP_GRACE_MS);
41954
+ timer.unref();
41955
+ });
41956
+ await Promise.race([this.shutdown(), grace]);
41957
+ clearTimeout(timer);
41958
+ }
41959
+ async shutdown() {
41960
+ const active = [...this.tracker.sessions.values()].filter((session) => isActive(session) && !session.settling);
41961
+ await Promise.allSettled(
41962
+ active.map(async (session) => {
41963
+ const cancelled = this.settlement.cancelOnSidecar(session.sidecarSessionId, SHUTDOWN_CANCEL_TIMEOUT_MS);
41964
+ await this.settlement.interrupt(session, "plugin_restart");
41965
+ await cancelled;
41966
+ })
41967
+ );
41968
+ }
41969
+ // --- the REST operations -----------------------------------------------------------------------------------------
41970
+ /** Starts a session on the sidecar. `input.setupCode` is passed on and dropped: nothing keeps it. */
41971
+ async start(input2, principal) {
41972
+ this.guard.assertFabricMutationAllowed();
41973
+ const release = this.gate.enter("commissioning");
41974
+ let sidecar;
41975
+ try {
41976
+ const status = this.connection.status();
41977
+ if (status.state !== "connected") {
41978
+ throw conflict("sidecar_unavailable", "The Matter sidecar is not connected.");
41979
+ }
41980
+ if (status.insecureTransport) throw forbidden("insecure_transport", INSECURE_SETUP_CODE);
41981
+ sidecar = await this.tracker.requestStart(input2);
41982
+ } catch (error62) {
41983
+ release();
41984
+ throw error62 instanceof SidecarClientError ? startFailure(error62) : error62;
41985
+ }
41986
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41987
+ const session = {
41988
+ id: (0, import_node_crypto17.randomUUID)(),
41989
+ userId: principal.userId,
41990
+ principal,
41991
+ state: "pending",
41992
+ step: null,
41993
+ failure: null,
41994
+ attestation: null,
41995
+ overrideRequested: input2.attestationOverride !== void 0,
41996
+ overrideAvailable: sidecar.attestationOverrideAllowed,
41997
+ nodeRecordId: null,
41998
+ endpoints: [],
41999
+ finished: false,
42000
+ finishing: false,
42001
+ startedAt: now,
42002
+ updatedAt: now,
42003
+ finishedAt: null,
42004
+ sidecarSessionId: sidecar.sessionId,
42005
+ streamInstanceId: this.tracker.currentStreamInstanceId,
42006
+ settling: false,
42007
+ unreachable: 0
42008
+ };
42009
+ this.settlement.holdGate(release);
42010
+ this.tracker.track(session);
42011
+ try {
42012
+ await this.settlement.record("matter.commissioning_started", session, {
42013
+ attestationOverride: session.overrideRequested
42014
+ });
42015
+ } catch (error62) {
42016
+ await this.settlement.abandon(session, error62);
42017
+ return sessionView(session);
42018
+ }
42019
+ await this.settlement.apply(session, sidecar);
42020
+ return sessionView(session);
42021
+ }
42022
+ get(id, userId) {
42023
+ return sessionView(this.tracker.owned(id, userId));
42024
+ }
42025
+ /** The caller's newest session that is running, or succeeded and not yet named. Null when there is none. */
42026
+ current(userId) {
42027
+ const mine = [...this.tracker.sessions.values()].filter((session) => session.userId === userId).filter((session) => isActive(session) || session.state === "succeeded" && !session.finished).sort((a, b) => b.startedAt.localeCompare(a.startedAt));
42028
+ return mine[0] ? sessionView(mine[0]) : null;
42029
+ }
42030
+ async cancel(id, userId) {
42031
+ const session = this.tracker.owned(id, userId);
42032
+ if (!isActive(session) || session.settling) return sessionView(session);
42033
+ try {
42034
+ const sidecar = await this.connection.request("commissioning.cancel", {
42035
+ params: { sessionId: session.sidecarSessionId }
42036
+ });
42037
+ await this.settlement.apply(session, sidecar);
42038
+ } catch (error62) {
42039
+ if (error62 instanceof SidecarClientError && error62.code === "not_found") {
42040
+ await this.settlement.interrupt(session, "sidecar_restart");
42041
+ } else if (isActive(session) && !session.settling) {
42042
+ await this.settlement.interrupt(session, "connection_lost");
42043
+ }
42044
+ }
42045
+ return sessionView(session);
42046
+ }
42047
+ /** The naming step: names the node and its endpoints. Only the user who commissioned, once, after success. */
42048
+ async finish(id, userId, input2) {
42049
+ const session = this.tracker.owned(id, userId);
42050
+ if (session.state !== "succeeded" || session.nodeRecordId === null) {
42051
+ throw conflict("not_succeeded", "Only a commissioning session that succeeded can be finished.");
42052
+ }
42053
+ if (session.finished || session.finishing) {
42054
+ throw conflict("already_finished", "This session was already finished.");
42055
+ }
42056
+ const nodeRef = session.nodeRecordId;
42057
+ const owned = new Set(session.endpoints.map((endpoint) => endpoint.id));
42058
+ for (const entry of input2.endpoints ?? []) {
42059
+ if (!owned.has(entry.id)) throw new import_common21.NotFoundException("Unknown endpoint of this node.");
42060
+ }
42061
+ session.finishing = true;
42062
+ let node2;
42063
+ const now = (/* @__PURE__ */ new Date()).toISOString();
42064
+ try {
42065
+ node2 = await this.name(nodeRef, input2, now);
42066
+ } catch (error62) {
42067
+ session.finishing = false;
42068
+ throw error62;
42069
+ }
42070
+ session.finished = true;
42071
+ session.finishing = false;
42072
+ session.updatedAt = now;
42073
+ this.changes.inventoryChanged();
42074
+ await this.audit.record(
42075
+ "matter.commissioning_finished",
42076
+ session.principal,
42077
+ { type: "matter.node", ref: nodeRef },
42078
+ {
42079
+ nodeRef,
42080
+ sessionRef: session.id,
42081
+ nameSet: input2.displayName !== void 0,
42082
+ locationSet: input2.location !== void 0,
42083
+ endpointNames: input2.endpoints?.length ?? 0
42084
+ }
42085
+ );
42086
+ return node2;
42087
+ }
42088
+ name(nodeRef, input2, now) {
42089
+ return this.storage.transaction(async (tables) => {
42090
+ const node2 = await tables.nodes.get(nodeRef);
42091
+ if (!node2 || node2.lifecycleState === "removed") {
42092
+ throw conflict("node_removed", "The node is no longer in the registry.");
42093
+ }
42094
+ const patch = {
42095
+ ...input2.displayName === void 0 ? {} : { displayName: input2.displayName },
42096
+ ...input2.location === void 0 ? {} : { location: input2.location }
42097
+ };
42098
+ if (Object.keys(patch).length > 0) {
42099
+ await tables.nodes.update({ id: node2.id }, { ...patch, updatedAt: now });
42100
+ Object.assign(node2, patch, { updatedAt: now });
42101
+ }
42102
+ for (const entry of input2.endpoints ?? []) {
42103
+ await tables.endpoints.update({ id: entry.id, nodeRef }, { displayName: entry.displayName });
42104
+ }
42105
+ return node2;
42106
+ });
42107
+ }
42108
+ };
42109
+ MatterCommissioningService = __decorateClass([
42110
+ (0, import_common21.Injectable)(),
42111
+ __decorateParam(0, (0, import_common21.Inject)(PLUGIN_CONTEXT)),
42112
+ __decorateParam(1, (0, import_common21.Inject)(MatterConnectionService)),
42113
+ __decorateParam(2, (0, import_common21.Inject)(MatterFabricGuard)),
42114
+ __decorateParam(3, (0, import_common21.Inject)(DeviceAuditService)),
42115
+ __decorateParam(4, (0, import_common21.Inject)(MatterChangeBus)),
42116
+ __decorateParam(5, (0, import_common21.Inject)(MatterOperationGate)),
42117
+ __decorateParam(6, (0, import_common21.Inject)(MatterFabricService)),
42118
+ __decorateParam(7, (0, import_common21.Inject)(MatterReconciliationService)),
42119
+ __decorateParam(8, (0, import_common21.Optional)()),
42120
+ __decorateParam(8, (0, import_common21.Inject)(COMMISSIONING_TIMING))
42121
+ ], MatterCommissioningService);
42122
+
42123
+ // backend/commissioning/removal.service.ts
42124
+ var import_common22 = require("@nestjs/common");
42125
+ var REMOVABLE = ["unclaimed", "claimed", "detached", "archived"];
42126
+ var DEVICE_TIMEOUT_MS = 3e4;
42127
+ var LATE_RECONCILIATION_MS = 35e3;
42128
+ var MatterNodeRemovalService = class {
42129
+ constructor(context, connectionService, guard, audit, changes, gate, fabric, reconciliation) {
42130
+ this.context = context;
42131
+ this.connectionService = connectionService;
42132
+ this.guard = guard;
42133
+ this.audit = audit;
42134
+ this.changes = changes;
42135
+ this.gate = gate;
42136
+ this.fabric = fabric;
42137
+ this.reconciliation = reconciliation;
42138
+ }
42139
+ get storage() {
42140
+ return matterStorage(this.context);
42141
+ }
42142
+ async remove(id, input2, principal) {
42143
+ this.guard.assertFabricMutationAllowed();
42144
+ const { tables } = this.storage;
42145
+ const node2 = await tables.nodes.get(id);
42146
+ if (!node2) throw new import_common22.NotFoundException("Unknown Matter node.");
42147
+ if (!REMOVABLE.includes(node2.lifecycleState)) {
42148
+ throw conflict("not_removable", `The node is ${node2.lifecycleState} and cannot be removed from the fabric.`);
42149
+ }
42150
+ const fabric = await tables.fabrics.get(node2.fabricRef);
42151
+ const release = this.gate.enter("removal");
42152
+ try {
42153
+ const connection2 = this.connectionService.connection;
42154
+ if (connection2.status().state !== "connected") {
42155
+ throw conflict("sidecar_unavailable", "The Matter sidecar is not connected.");
42156
+ }
42157
+ const sidecarFabric = await connection2.request("fabric.get").catch((error62) => {
42158
+ throw removalFailure(error62, input2.mode);
42159
+ });
42160
+ if (!fabric || fabric.status !== "active" || sidecarFabric.fabricId !== fabric.fabricId) {
42161
+ throw conflict("fabric_mismatch", "The node does not belong to the sidecar's fabric. Nothing was changed.");
42162
+ }
42163
+ const generation = await this.removeOnSidecar(node2, input2.mode, principal);
42164
+ return await this.record(node2, input2.mode, generation, principal);
42165
+ } finally {
42166
+ release();
42167
+ }
42168
+ }
42169
+ /** `nodes.remove` on the sidecar. A failure is audited; one of uncertain outcome also asks for a reconciliation. */
42170
+ async removeOnSidecar(node2, mode, principal) {
42171
+ try {
42172
+ const { fabricGeneration } = await this.connectionService.connection.request("nodes.remove", {
42173
+ params: { nodeId: node2.nodeId },
42174
+ body: { force: mode === "force" },
42175
+ timeoutMs: DEVICE_TIMEOUT_MS
42176
+ });
42177
+ return fabricGeneration;
42178
+ } catch (error62) {
42179
+ if (!(error62 instanceof SidecarClientError)) throw error62;
42180
+ if (error62.code === "timeout" || error62.outcome === "uncertain") {
42181
+ void this.reconciliation.request().catch(() => void 0);
42182
+ setTimeout(() => void this.reconciliation.request().catch(() => void 0), LATE_RECONCILIATION_MS).unref();
42183
+ }
42184
+ await this.audit.record(
42185
+ "matter.node_removal_failed",
42186
+ principal,
42187
+ subjectOf(node2),
42188
+ { nodeRef: node2.id, mode, reason: failureReason(error62) },
42189
+ "failed"
42190
+ );
42191
+ throw removalFailure(error62, mode);
42192
+ }
42193
+ }
42194
+ /**
42195
+ * The sidecar removed the node: the record follows. The audit entry is written whatever the plugin's own write
42196
+ * does, since the fabric changed. A row that is already `removed` counts as done. A write that fails is reported
42197
+ * clearly and a reconciliation is asked for, which then finds the node gone from the sidecar.
42198
+ */
42199
+ async record(node2, mode, generation, principal) {
42200
+ const force = mode === "force";
42201
+ const now = (/* @__PURE__ */ new Date()).toISOString();
42202
+ const removal = {
42203
+ removedBy: principal.userId,
42204
+ removalReason: force ? "forced_from_fabric" : "removed_from_fabric"
42205
+ };
42206
+ let written = false;
42207
+ try {
42208
+ written = await this.storage.transaction((scoped) => markNodeRemoved(scoped, node2.id, REMOVABLE, removal, now));
42209
+ } catch (error62) {
42210
+ this.context.logger.warn?.(
42211
+ `The Matter node removed from the fabric could not be marked removed: ${error62 instanceof Error ? error62.name : "unknown error"}`
42212
+ );
42213
+ }
42214
+ await this.fabric.detect("event").catch(() => void 0);
42215
+ this.changes.inventoryChanged();
42216
+ const current = await this.storage.tables.nodes.get(node2.id).catch(() => null);
42217
+ const registryUpdated = written || current?.lifecycleState === "removed";
42218
+ await this.audit.record(
42219
+ force ? "matter.node_force_removed_from_fabric" : "matter.node_removed_from_fabric",
42220
+ principal,
42221
+ subjectOf(node2),
42222
+ { nodeRef: node2.id, previousState: node2.lifecycleState, fabricGeneration: generation, registryUpdated }
42223
+ );
42224
+ if (!registryUpdated || !current) {
42225
+ void this.reconciliation.request().catch(() => void 0);
42226
+ throw new import_common22.InternalServerErrorException({
42227
+ code: "registry_failed",
42228
+ message: "The device was removed from the fabric, but its record could not be updated. A reconciliation was requested; it marks the device as missing. Force remove the record if it stays."
42229
+ });
42230
+ }
42231
+ return current;
42232
+ }
42233
+ };
42234
+ MatterNodeRemovalService = __decorateClass([
42235
+ (0, import_common22.Injectable)(),
42236
+ __decorateParam(0, (0, import_common22.Inject)(PLUGIN_CONTEXT)),
42237
+ __decorateParam(1, (0, import_common22.Inject)(MatterConnectionService)),
42238
+ __decorateParam(2, (0, import_common22.Inject)(MatterFabricGuard)),
42239
+ __decorateParam(3, (0, import_common22.Inject)(DeviceAuditService)),
42240
+ __decorateParam(4, (0, import_common22.Inject)(MatterChangeBus)),
42241
+ __decorateParam(5, (0, import_common22.Inject)(MatterOperationGate)),
42242
+ __decorateParam(6, (0, import_common22.Inject)(MatterFabricService)),
42243
+ __decorateParam(7, (0, import_common22.Inject)(MatterReconciliationService))
42244
+ ], MatterNodeRemovalService);
42245
+ var subjectOf = (node2) => ({ type: "matter.node", ref: node2.id });
42246
+
42247
+ // backend/commissioning/schemas.ts
42248
+ var optionalText2 = (max) => external_exports.string().trim().max(max).transform((value) => value === "" ? null : value).nullable();
42249
+ var startSchema = external_exports.strictObject({
42250
+ setupCode: external_exports.string().regex(/^[0-9]{11}$|^[0-9]{21}$|^MT:[A-Z0-9.-]{10,512}$/, "must be a Matter setup code"),
42251
+ attestationOverride: external_exports.strictObject({ confirmed: external_exports.literal(true) }).optional()
42252
+ });
42253
+ var finishSchema = external_exports.strictObject({
42254
+ displayName: optionalText2(100).optional(),
42255
+ location: optionalText2(100).optional(),
42256
+ endpoints: external_exports.array(external_exports.strictObject({ id: external_exports.uuid(), displayName: external_exports.string().trim().min(1).max(100) })).max(256).optional()
42257
+ });
42258
+ var removeSchema = external_exports.strictObject({ mode: external_exports.enum(["normal", "force"]), confirm: external_exports.literal(true) });
42259
+ var shareSchema = external_exports.strictObject({
42260
+ timeoutSec: external_exports.int().min(SHARE_WINDOW_MIN_SEC).max(SHARE_WINDOW_MAX_SEC).optional()
42261
+ });
42262
+
42263
+ // backend/commissioning/sharing.service.ts
42264
+ var import_common23 = require("@nestjs/common");
42265
+ var DEVICE_TIMEOUT_MS2 = 3e4;
42266
+ var MatterNodeSharingService = class {
42267
+ constructor(context, connectionService, guard, audit, gate) {
42268
+ this.context = context;
42269
+ this.connectionService = connectionService;
42270
+ this.guard = guard;
42271
+ this.audit = audit;
42272
+ this.gate = gate;
42273
+ /** Windows this plugin opened and the timers that audit their expiry. Holds no code. */
42274
+ this.windows = /* @__PURE__ */ new Map();
42275
+ }
42276
+ onModuleDestroy() {
42277
+ for (const timer of this.windows.values()) clearTimeout(timer);
42278
+ this.windows.clear();
42279
+ }
42280
+ async liveNode(id) {
42281
+ const node2 = await matterStorage(this.context).tables.nodes.get(id);
42282
+ if (!node2) throw new import_common23.NotFoundException("Unknown Matter node.");
42283
+ if (node2.lifecycleState !== "claimed" && node2.lifecycleState !== "unclaimed") {
42284
+ throw conflict("not_shareable", `The node is ${node2.lifecycleState}; only a node in the fabric can be shared.`);
42285
+ }
42286
+ return node2;
42287
+ }
42288
+ /** The node ID addresses a device in the sidecar's fabric: the node's own fabric must be that one. */
42289
+ async assertSameFabric(node2) {
42290
+ const fabric = await matterStorage(this.context).tables.fabrics.get(node2.fabricRef);
42291
+ const sidecarFabric = await this.call(() => this.connectionService.connection.request("fabric.get"));
42292
+ if (!fabric || fabric.status !== "active" || sidecarFabric.fabricId !== fabric.fabricId) {
42293
+ throw conflict("fabric_mismatch", "The node does not belong to the sidecar's fabric. Nothing was changed.");
42294
+ }
42295
+ }
42296
+ /** A sidecar call; its contract errors become our own wording. */
42297
+ async call(request) {
42298
+ try {
42299
+ return await request();
42300
+ } catch (error62) {
42301
+ if (error62 instanceof SidecarClientError) throw this.failure(error62);
42302
+ throw error62;
42303
+ }
42304
+ }
42305
+ async open(id, input2, principal) {
42306
+ this.guard.assertFabricMutationAllowed();
42307
+ const node2 = await this.liveNode(id);
42308
+ const release = this.gate.enter("sharing");
42309
+ try {
42310
+ if (this.connectionService.connection.status().insecureTransport) {
42311
+ throw forbidden("insecure_transport", INSECURE_SHARING_CODE);
42312
+ }
42313
+ await this.assertSameFabric(node2);
42314
+ const timeoutSec = input2.timeoutSec ?? SHARE_WINDOW_MIN_SEC;
42315
+ const window = await this.call(
42316
+ () => this.connectionService.connection.request("nodes.share.open", {
42317
+ params: { nodeId: node2.nodeId },
42318
+ body: input2.timeoutSec === void 0 ? {} : { timeoutSec: input2.timeoutSec },
42319
+ timeoutMs: DEVICE_TIMEOUT_MS2
42320
+ })
42321
+ );
42322
+ this.track(node2.id, window.expiresAt);
42323
+ await this.audit.record(
42324
+ "matter.node_shared",
42325
+ principal,
42326
+ { type: "matter.node", ref: node2.id },
42327
+ { nodeRef: node2.id, timeoutSec }
42328
+ );
42329
+ return { manualCode: window.manualCode, qrCode: window.qrCode, expiresAt: window.expiresAt };
42330
+ } finally {
42331
+ release();
42332
+ }
42333
+ }
42334
+ async revoke(id, principal) {
42335
+ this.guard.assertFabricMutationAllowed();
42336
+ const node2 = await this.liveNode(id);
42337
+ const release = this.gate.enter("sharing");
42338
+ try {
42339
+ await this.assertSameFabric(node2);
42340
+ const { closed } = await this.call(
42341
+ () => this.connectionService.connection.request("nodes.share.revoke", {
42342
+ params: { nodeId: node2.nodeId },
42343
+ body: {},
42344
+ timeoutMs: DEVICE_TIMEOUT_MS2
42345
+ })
42346
+ );
42347
+ clearTimeout(this.windows.get(node2.id));
42348
+ this.windows.delete(node2.id);
42349
+ await this.audit.record(
42350
+ "matter.node_share_revoked",
42351
+ principal,
42352
+ { type: "matter.node", ref: node2.id },
42353
+ { nodeRef: node2.id, closed }
42354
+ );
42355
+ return { closed };
42356
+ } finally {
42357
+ release();
42358
+ }
42359
+ }
42360
+ failure(error62) {
42361
+ if (error62.code === "insecure_transport") return forbidden("insecure_transport", INSECURE_SHARING_CODE);
42362
+ if (failureReason(error62) === "device_unreachable") {
42363
+ return conflict("device_unreachable", "The device could not be reached. Nothing was changed.");
42364
+ }
42365
+ if (failureReason(error62) === "timeout") {
42366
+ return conflict(
42367
+ "timeout",
42368
+ "The device did not answer in time. The window may or may not be open; close it to be sure."
42369
+ );
42370
+ }
42371
+ return sidecarFailure(error62);
42372
+ }
42373
+ /** Audits the end of the window by itself, as the system. */
42374
+ track(nodeRef, expiresAt) {
42375
+ clearTimeout(this.windows.get(nodeRef));
42376
+ const timer = setTimeout(
42377
+ () => {
42378
+ this.windows.delete(nodeRef);
42379
+ void this.audit.record("matter.node_share_expired", null, { type: "matter.node", ref: nodeRef }, { nodeRef });
42380
+ },
42381
+ Math.max(0, Date.parse(expiresAt) - Date.now())
42382
+ );
42383
+ timer.unref();
42384
+ this.windows.set(nodeRef, timer);
42385
+ }
42386
+ };
42387
+ MatterNodeSharingService = __decorateClass([
42388
+ (0, import_common23.Injectable)(),
42389
+ __decorateParam(0, (0, import_common23.Inject)(PLUGIN_CONTEXT)),
42390
+ __decorateParam(1, (0, import_common23.Inject)(MatterConnectionService)),
42391
+ __decorateParam(2, (0, import_common23.Inject)(MatterFabricGuard)),
42392
+ __decorateParam(3, (0, import_common23.Inject)(DeviceAuditService)),
42393
+ __decorateParam(4, (0, import_common23.Inject)(MatterOperationGate))
42394
+ ], MatterNodeSharingService);
42395
+
42396
+ // backend/commissioning/controller.ts
42397
+ function parse5(schema, value, where = "body") {
42398
+ const parsed = schema.safeParse(value);
42399
+ if (!parsed.success) throw new import_common24.BadRequestException(validationMessages(parsed.error, where));
42400
+ return parsed.data;
42401
+ }
42402
+ var parseId = (id) => parse5(idParamSchema2, id, "id");
42403
+ var mayOverride = (request) => MATTER_OPERATIONS.attestationOverride.every((key) => request.user.effectivePermissions?.has(key) === true);
42404
+ var MatterCommissioningController = class {
42405
+ constructor(commissioning, removal, sharing, lifecycle) {
42406
+ this.commissioning = commissioning;
42407
+ this.removal = removal;
42408
+ this.sharing = sharing;
42409
+ this.lifecycle = lifecycle;
42410
+ }
42411
+ async start(body, request) {
42412
+ const input2 = parse5(startSchema, body);
42413
+ if (input2.attestationOverride && !mayOverride(request)) {
42414
+ throw forbidden(
42415
+ "attestation_override_forbidden",
42416
+ "The attestation override needs the permissions to commission and to manage Matter devices."
42417
+ );
42418
+ }
42419
+ return this.commissioning.start(input2, principalOf(request));
42420
+ }
42421
+ current(request) {
42422
+ return this.commissioning.current(request.user.id);
42423
+ }
42424
+ get(id, request) {
42425
+ return this.commissioning.get(parseId(id), request.user.id);
42426
+ }
42427
+ cancel(id, request) {
42428
+ return this.commissioning.cancel(parseId(id), request.user.id);
42429
+ }
42430
+ async finish(id, body, request) {
42431
+ const node2 = await this.commissioning.finish(parseId(id), request.user.id, parse5(finishSchema, body ?? {}));
42432
+ return { node: nodeDetailView(await this.lifecycle.getNode(node2.id)) };
42433
+ }
42434
+ async remove(id, body, request) {
42435
+ return nodeView(await this.removal.remove(parseId(id), parse5(removeSchema, body), principalOf(request)));
42436
+ }
42437
+ async share(id, body, request) {
42438
+ return this.sharing.open(parseId(id), parse5(shareSchema, body ?? {}), principalOf(request));
42439
+ }
42440
+ async revokeShare(id, request) {
42441
+ return this.sharing.revoke(parseId(id), principalOf(request));
42442
+ }
42443
+ };
42444
+ __decorateClass([
42445
+ (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.commissioningStart),
42446
+ (0, import_common24.Post)("commissioning/sessions"),
42447
+ __decorateParam(0, (0, import_common24.Body)()),
42448
+ __decorateParam(1, (0, import_common24.Req)())
42449
+ ], MatterCommissioningController.prototype, "start", 1);
42450
+ __decorateClass([
42451
+ (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.commissioningStatus),
42452
+ (0, import_common24.Get)("commissioning/sessions/current"),
42453
+ __decorateParam(0, (0, import_common24.Req)())
42454
+ ], MatterCommissioningController.prototype, "current", 1);
42455
+ __decorateClass([
42456
+ (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.commissioningStatus),
42457
+ (0, import_common24.Get)("commissioning/sessions/:id"),
42458
+ __decorateParam(0, (0, import_common24.Param)("id")),
42459
+ __decorateParam(1, (0, import_common24.Req)())
42460
+ ], MatterCommissioningController.prototype, "get", 1);
42461
+ __decorateClass([
42462
+ (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.commissioningStart),
42463
+ (0, import_common24.Delete)("commissioning/sessions/:id"),
42464
+ __decorateParam(0, (0, import_common24.Param)("id")),
42465
+ __decorateParam(1, (0, import_common24.Req)())
42466
+ ], MatterCommissioningController.prototype, "cancel", 1);
42467
+ __decorateClass([
42468
+ (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.commissioningStart),
42469
+ (0, import_common24.Post)("commissioning/sessions/:id/finish"),
42470
+ (0, import_common24.HttpCode)(200),
42471
+ __decorateParam(0, (0, import_common24.Param)("id")),
42472
+ __decorateParam(1, (0, import_common24.Body)()),
42473
+ __decorateParam(2, (0, import_common24.Req)())
42474
+ ], MatterCommissioningController.prototype, "finish", 1);
42475
+ __decorateClass([
42476
+ (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.commissioningRemoveFromFabric),
42477
+ (0, import_common24.Post)("nodes/:id/remove"),
42478
+ (0, import_common24.HttpCode)(200),
42479
+ __decorateParam(0, (0, import_common24.Param)("id")),
42480
+ __decorateParam(1, (0, import_common24.Body)()),
42481
+ __decorateParam(2, (0, import_common24.Req)())
42482
+ ], MatterCommissioningController.prototype, "remove", 1);
42483
+ __decorateClass([
42484
+ (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.commissioningShare),
42485
+ (0, import_common24.Post)("nodes/:id/share"),
42486
+ (0, import_common24.HttpCode)(200),
42487
+ (0, import_common24.Header)("Cache-Control", "no-store"),
42488
+ __decorateParam(0, (0, import_common24.Param)("id")),
42489
+ __decorateParam(1, (0, import_common24.Body)()),
42490
+ __decorateParam(2, (0, import_common24.Req)())
42491
+ ], MatterCommissioningController.prototype, "share", 1);
42492
+ __decorateClass([
42493
+ (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.commissioningShare),
42494
+ (0, import_common24.Delete)("nodes/:id/share"),
42495
+ __decorateParam(0, (0, import_common24.Param)("id")),
42496
+ __decorateParam(1, (0, import_common24.Req)())
42497
+ ], MatterCommissioningController.prototype, "revokeShare", 1);
42498
+ MatterCommissioningController = __decorateClass([
42499
+ (0, import_common24.Controller)("matter"),
42500
+ __decorateParam(0, (0, import_common24.Inject)(MatterCommissioningService)),
42501
+ __decorateParam(1, (0, import_common24.Inject)(MatterNodeRemovalService)),
42502
+ __decorateParam(2, (0, import_common24.Inject)(MatterNodeSharingService)),
42503
+ __decorateParam(3, (0, import_common24.Inject)(MatterLifecycleService))
42504
+ ], MatterCommissioningController);
42505
+
42506
+ // backend/connection/audit.ts
42507
+ var UUID_FIELD = { type: "string", pattern: "[0-9a-f-]{36}" };
42508
+ var DECIMAL_ID_FIELD = { type: "string", pattern: "[0-9]{1,20}" };
42509
+ var NODE_REF = { nodeRef: UUID_FIELD };
42510
+ var FABRIC_ID = { fabricId: DECIMAL_ID_FIELD };
42511
+ var NODE_ID = { nodeId: DECIMAL_ID_FIELD };
42512
+ var DETACHED_REASONS = ["absent_from_sidecar", "fabric_mismatch", "fabric_absent"];
42513
+ var INITIATOR = { initiator: { type: "string", oneOf: ["system", "administrator"] } };
42514
+ var KEY_ID_FIELD = { keyId: { type: "string", pattern: "[0-9a-f-]{16}" } };
42515
+ var BACKUP_REF = { backupRef: UUID_FIELD };
42516
+ var GENERATION = { fabricGeneration: { type: "number", integer: true, min: 0 } };
42517
+ var BACKUP_TRIGGERS = ["manual", "fabric_created", "restore", "daily", "fabric_changed", "pre_restore"];
42518
+ var BACKUP_FAILURES = [
42519
+ "inconsistent",
42520
+ "sidecar_unavailable",
42521
+ "sidecar_busy",
42522
+ "insecure_transport",
42523
+ "no_recovery_key",
42524
+ "recovery_key_unreadable",
42525
+ "recovery_required",
42526
+ "no_fabric",
42527
+ "sidecar_error",
42528
+ "internal"
42529
+ ];
42530
+ var RESTORE_REFUSALS = [
42531
+ "key_required",
42532
+ "wrong_key",
42533
+ "corrupt",
42534
+ "truncated",
42535
+ "incompatible_format",
42536
+ "incompatible_schema",
42537
+ "incompatible_migration",
42538
+ "incompatible_version",
42539
+ "stage_failed",
42540
+ "insecure_transport",
42541
+ "sidecar_unavailable",
42542
+ "confirmation_required",
42543
+ "preflight_changed",
42544
+ "pre_restore_backup_failed",
42545
+ "validation_expired",
42546
+ "busy"
42547
+ ];
42548
+ var RESTORE_KINDS = ["plain", "rollback", "replacement"];
42549
+ var MISMATCHES = [
42550
+ "sidecar_uninitialized",
42551
+ "fabric_changed",
42552
+ "generation_behind",
42553
+ "generation_ahead",
42554
+ "storage_instance_changed",
42555
+ "sidecar_recovery_required"
42556
+ ];
42557
+ var SESSION_REF = { sessionRef: UUID_FIELD };
42558
+ var COMMISSIONING_STEPS = commissioningStepSchema.options;
42559
+ var PLUGIN_FAILURE_CODES = ["needs_reconciliation", "registry_failed"];
42560
+ var COMMISSIONING_FAILURES = [...commissioningFailureCodeSchema.options, ...PLUGIN_FAILURE_CODES];
42561
+ var FINDINGS = { findings: { type: "string", pattern: "[A-Za-z0-9_,]{0,512}", maxLength: 512 } };
42562
+ var INTERRUPT_REASONS = ["sidecar_restart", "connection_lost", "timeout", "plugin_restart"];
42563
+ var REMOVAL_STATES = ["unclaimed", "claimed", "detached", "archived"];
42564
+ var REMOVED_FROM_FABRIC = {
42565
+ ...NODE_REF,
42566
+ previousState: { type: "string", oneOf: REMOVAL_STATES },
42567
+ ...GENERATION,
42568
+ registryUpdated: { type: "boolean" }
42569
+ };
42570
+ var COMMISSIONING_ACTIONS = [
42571
+ {
42572
+ action: "matter.commissioning_started",
42573
+ subjectTypes: ["matter.commissioning_session"],
42574
+ details: { ...SESSION_REF, attestationOverride: { type: "boolean" } }
42575
+ },
42576
+ {
42577
+ action: "matter.commissioning_failed",
42578
+ subjectTypes: ["matter.commissioning_session"],
42579
+ details: {
42580
+ ...SESSION_REF,
42581
+ failure: { type: "string", oneOf: COMMISSIONING_FAILURES },
42582
+ step: { type: "string", oneOf: COMMISSIONING_STEPS },
42583
+ ...FINDINGS,
42584
+ existingNodeId: DECIMAL_ID_FIELD
42585
+ }
42586
+ },
42587
+ {
42588
+ action: "matter.commissioning_interrupted",
42589
+ subjectTypes: ["matter.commissioning_session"],
42590
+ details: { ...SESSION_REF, reason: { type: "string", oneOf: INTERRUPT_REASONS } }
42591
+ },
42592
+ { action: "matter.commissioning_cancelled", subjectTypes: ["matter.commissioning_session"], details: SESSION_REF },
42593
+ {
42594
+ // The dangerous development override: the attempt went on although attestation failed.
42595
+ action: "matter.commissioning_attestation_overridden",
42596
+ subjectTypes: ["matter.commissioning_session"],
42597
+ details: { ...SESSION_REF, ...FINDINGS }
42598
+ },
42599
+ {
42600
+ action: "matter.node_commissioned",
42601
+ subjectTypes: ["matter.node"],
42602
+ details: {
42603
+ ...NODE_REF,
42604
+ ...FABRIC_ID,
42605
+ ...NODE_ID,
42606
+ ...SESSION_REF,
42607
+ attestation: { type: "string", oneOf: ["verified", "overridden"] },
42608
+ // The warning- and info-level finding types a verified attestation still reported.
42609
+ ...FINDINGS
42610
+ }
42611
+ },
42612
+ {
42613
+ action: "matter.commissioning_finished",
42614
+ subjectTypes: ["matter.node"],
42615
+ details: {
42616
+ ...NODE_REF,
42617
+ ...SESSION_REF,
42618
+ nameSet: { type: "boolean" },
42619
+ locationSet: { type: "boolean" },
42620
+ endpointNames: { type: "number", integer: true, min: 0, max: 256 }
42621
+ }
42622
+ },
42623
+ {
42624
+ action: "matter.node_removed_from_fabric",
42625
+ subjectTypes: ["matter.node"],
42626
+ details: REMOVED_FROM_FABRIC
42627
+ },
42628
+ {
42629
+ action: "matter.node_force_removed_from_fabric",
42630
+ subjectTypes: ["matter.node"],
42631
+ details: REMOVED_FROM_FABRIC
42632
+ },
42633
+ {
42634
+ action: "matter.node_removal_failed",
42635
+ subjectTypes: ["matter.node"],
42636
+ details: {
42637
+ ...NODE_REF,
42638
+ mode: { type: "string", oneOf: ["normal", "force"] },
42639
+ reason: {
42640
+ type: "string",
42641
+ oneOf: ["device_unreachable", "timeout", "busy", "sidecar_unavailable", "not_found", "internal"]
42642
+ }
42643
+ }
42644
+ },
42645
+ {
42646
+ // The sharing code itself is never recorded: only that a window was opened, and for how long.
42647
+ action: "matter.node_shared",
42648
+ subjectTypes: ["matter.node"],
42649
+ details: { ...NODE_REF, timeoutSec: { type: "number", integer: true, min: 180, max: 900 } }
42650
+ },
42651
+ {
42652
+ action: "matter.node_share_revoked",
42653
+ subjectTypes: ["matter.node"],
42654
+ details: { ...NODE_REF, closed: { type: "boolean" } }
42655
+ },
42656
+ { action: "matter.node_share_expired", subjectTypes: ["matter.node"], details: NODE_REF }
42657
+ ];
42658
+ var METADATA_FLAGS = {
42659
+ displayNameChanged: { type: "boolean" },
42660
+ descriptionChanged: { type: "boolean" },
42661
+ locationChanged: { type: "boolean" }
42662
+ };
42663
+ var MATTER_AUDIT_DOMAIN = {
42664
+ domain: "matter",
42665
+ labels: { en: "Matter", de: "Matter" },
42666
+ actions: [
42667
+ {
42668
+ action: "matter.connection_saved",
42669
+ subjectTypes: ["matter.connection"],
42670
+ // Flags and a scheme only: never the URL, the credential or the certificate.
42671
+ details: {
42672
+ credentialChanged: { type: "boolean" },
42673
+ caChanged: { type: "boolean" },
42674
+ scheme: { type: "string", oneOf: ["http", "https"] }
42675
+ }
42676
+ },
42677
+ { action: "matter.connection_removed", subjectTypes: ["matter.connection"] },
42678
+ { action: "matter.connection_reconnect_requested", subjectTypes: ["matter.connection"] },
42679
+ // Device model (ATT-996). Subject IDs are numeric (a host rule), so the plugin UUID travels in `nodeRef` /
42680
+ // `endpointRef` / `fabricRef`. Details are bounded IDs, enums and flags: never device free text.
42681
+ {
42682
+ action: "matter.node_quarantined",
42683
+ subjectTypes: ["matter.node"],
42684
+ details: { ...NODE_REF, ...FABRIC_ID, ...NODE_ID, ...INITIATOR }
42685
+ },
42686
+ {
42687
+ action: "matter.node_detached",
42688
+ subjectTypes: ["matter.node"],
42689
+ details: {
42690
+ ...NODE_REF,
42691
+ ...FABRIC_ID,
42692
+ ...NODE_ID,
42693
+ reason: { type: "string", oneOf: DETACHED_REASONS },
42694
+ ...INITIATOR
42695
+ }
42696
+ },
42697
+ {
42698
+ action: "matter.node_reattached",
42699
+ subjectTypes: ["matter.node"],
42700
+ details: {
42701
+ ...NODE_REF,
42702
+ ...FABRIC_ID,
42703
+ ...NODE_ID,
42704
+ resultingState: { type: "string", oneOf: ["claimed", "unclaimed"] },
42705
+ ...INITIATOR
42706
+ }
42707
+ },
42708
+ {
42709
+ action: "matter.node_claimed",
42710
+ subjectTypes: ["matter.node"],
42711
+ details: { ...NODE_REF, nameSet: { type: "boolean" } }
42712
+ },
42713
+ {
42714
+ action: "matter.node_relinked",
42715
+ subjectTypes: ["matter.node"],
42716
+ details: {
42717
+ ...NODE_REF,
42718
+ sourceNodeRef: UUID_FIELD,
42719
+ identityMismatchConfirmed: { type: "boolean" }
42720
+ }
42721
+ },
42722
+ {
42723
+ action: "matter.node_repaired",
42724
+ subjectTypes: ["matter.node"],
42725
+ details: { ...NODE_REF, reattached: { type: "boolean" } }
42726
+ },
42727
+ {
42728
+ action: "matter.node_archived",
42729
+ subjectTypes: ["matter.node"],
42730
+ details: { ...NODE_REF, previousState: { type: "string", oneOf: ["detached", "unclaimed"] } }
42731
+ },
42732
+ { action: "matter.node_restored", subjectTypes: ["matter.node"], details: { ...NODE_REF } },
42733
+ {
42734
+ action: "matter.node_force_removed",
42735
+ subjectTypes: ["matter.node"],
42736
+ details: {
42737
+ ...NODE_REF,
42738
+ previousState: { type: "string", oneOf: ["unclaimed", "claimed", "detached", "archived"] }
42739
+ }
42740
+ },
42741
+ {
42742
+ action: "matter.node_metadata_updated",
42743
+ subjectTypes: ["matter.node"],
42744
+ details: { ...NODE_REF, ...METADATA_FLAGS }
42745
+ },
42746
+ {
42747
+ action: "matter.endpoint_metadata_updated",
42748
+ subjectTypes: ["matter.endpoint"],
42749
+ details: {
42750
+ endpointRef: UUID_FIELD,
42751
+ endpointId: { type: "number", integer: true, min: 0, max: 65534 },
42752
+ ...METADATA_FLAGS
42753
+ }
42754
+ },
42755
+ {
42756
+ action: "matter.fabric_mismatch_detected",
42757
+ subjectTypes: ["matter.fabric"],
42758
+ details: {
42759
+ fabricRef: UUID_FIELD,
42760
+ previousFabricId: DECIMAL_ID_FIELD,
42761
+ detachedNodes: { type: "number", integer: true, min: 0 },
42762
+ quarantinedNodes: { type: "number", integer: true, min: 0 },
42763
+ ...INITIATOR
42764
+ }
42765
+ },
42766
+ // Fabric persistence and encrypted backups (ATT-998). Fabric ID and key ID are public identifiers; recovery keys,
42767
+ // backup contents and the sidecar's secrets never appear. A backup by the plugin itself is recorded with the
42768
+ // system principal. A restore's entries share its validation ID as their operation ID.
42769
+ {
42770
+ action: "matter.fabric_created",
42771
+ subjectTypes: ["matter.fabric"],
42772
+ details: { fabricRef: UUID_FIELD, ...FABRIC_ID, recoveryKeyCreated: { type: "boolean" } }
42773
+ },
42774
+ {
42775
+ action: "matter.recovery_key_generated",
42776
+ subjectTypes: ["matter.recovery_key"],
42777
+ // `source: 'restore'`: the key a disaster-recovery restore was made with, kept on an installation without one.
42778
+ details: { ...KEY_ID_FIELD, source: { type: "string", oneOf: ["restore"] } }
42779
+ },
42780
+ { action: "matter.recovery_key_acknowledged", subjectTypes: ["matter.recovery_key"], details: KEY_ID_FIELD },
42781
+ {
42782
+ action: "matter.recovery_key_rotated",
42783
+ subjectTypes: ["matter.recovery_key"],
42784
+ details: { ...KEY_ID_FIELD, previousKeyId: KEY_ID_FIELD.keyId }
42785
+ },
42786
+ {
42787
+ action: "matter.backup_succeeded",
42788
+ subjectTypes: ["matter.backup"],
42789
+ details: {
42790
+ ...BACKUP_REF,
42791
+ trigger: { type: "string", oneOf: BACKUP_TRIGGERS },
42792
+ ...GENERATION,
42793
+ system: { type: "boolean" }
42794
+ }
42795
+ },
42796
+ {
42797
+ action: "matter.backup_failed",
42798
+ subjectTypes: ["matter.backup"],
42799
+ details: {
42800
+ ...BACKUP_REF,
42801
+ trigger: { type: "string", oneOf: BACKUP_TRIGGERS },
42802
+ reason: { type: "string", oneOf: BACKUP_FAILURES },
42803
+ system: { type: "boolean" }
42804
+ }
42805
+ },
42806
+ {
42807
+ action: "matter.restore_validated",
42808
+ subjectTypes: ["matter.backup"],
42809
+ details: { ...BACKUP_REF, ...GENERATION, kind: { type: "string", oneOf: RESTORE_KINDS } }
42810
+ },
42811
+ {
42812
+ action: "matter.restore_refused",
42813
+ subjectTypes: ["matter.backup"],
42814
+ details: { ...BACKUP_REF, reason: { type: "string", oneOf: RESTORE_REFUSALS } }
42815
+ },
42816
+ {
42817
+ action: "matter.restore_confirmed",
42818
+ subjectTypes: ["matter.backup"],
42819
+ details: {
42820
+ ...BACKUP_REF,
42821
+ kind: { type: "string", oneOf: RESTORE_KINDS },
42822
+ typedConfirmation: { type: "boolean" },
42823
+ preRestoreBackup: { type: "boolean" }
42824
+ }
42825
+ },
42826
+ {
42827
+ action: "matter.restore_succeeded",
42828
+ subjectTypes: ["matter.backup"],
42829
+ details: { ...BACKUP_REF, ...GENERATION }
42830
+ },
42831
+ // The encrypted file left the installation (ATT-1003). Never its content.
42832
+ { action: "matter.backup_downloaded", subjectTypes: ["matter.backup"], details: { ...BACKUP_REF, ...GENERATION } },
42833
+ { action: "matter.restore_cancelled", subjectTypes: ["matter.backup"], details: BACKUP_REF },
42834
+ { action: "matter.restore_failed", subjectTypes: ["matter.backup"], details: BACKUP_REF },
42835
+ { action: "matter.restore_rolled_back", subjectTypes: ["matter.backup"], details: BACKUP_REF },
42836
+ {
42837
+ action: "matter.fabric_recovery_required",
42838
+ subjectTypes: ["matter.fabric"],
42839
+ details: { fabricRef: UUID_FIELD, mismatch: { type: "string", oneOf: MISMATCHES } }
42840
+ },
42841
+ {
42842
+ action: "matter.recovery_action_chosen",
42843
+ subjectTypes: ["matter.fabric"],
42844
+ details: { fabricRef: UUID_FIELD, choice: { type: "string", oneOf: ["accept_sidecar", "start_new", "restore"] } }
42845
+ },
42846
+ ...COMMISSIONING_ACTIONS
42847
+ ]
42848
+ };
42849
+
42850
+ // backend/devices/controller.ts
42851
+ var import_plugins_backend_sdk8 = require("@attraccess/plugins-backend-sdk");
42852
+ var import_common26 = require("@nestjs/common");
42853
+
42854
+ // backend/devices/state.service.ts
42855
+ var import_common25 = require("@nestjs/common");
42856
+ var import_node_crypto18 = require("node:crypto");
41133
42857
 
41134
42858
  // backend/devices/state-machine.ts
41135
42859
  var DEFAULT_STALE_AFTER_MS = 6e5;
@@ -41255,7 +42979,7 @@ function applyReport(row, report, receivedAt) {
41255
42979
  }
41256
42980
  return next;
41257
42981
  }
41258
- var parse5 = (text) => text === null ? null : JSON.parse(text);
42982
+ var parse6 = (text) => text === null ? null : JSON.parse(text);
41259
42983
  function freshnessOf(row, now) {
41260
42984
  if (row.reportedAt === null) return "unknown";
41261
42985
  return now - Date.parse(row.reportedAt) > row.staleAfterMs ? "stale" : "fresh";
@@ -41266,7 +42990,7 @@ function toView(row, now = Date.now()) {
41266
42990
  return {
41267
42991
  stateKey: row.stateKey,
41268
42992
  reported: {
41269
- value: parse5(row.reportedValue),
42993
+ value: parse6(row.reportedValue),
41270
42994
  observedAt: row.reportedAt,
41271
42995
  receivedAt: row.receivedAt,
41272
42996
  source: row.source,
@@ -41275,7 +42999,7 @@ function toView(row, now = Date.now()) {
41275
42999
  freshness: freshnessOf(row, now),
41276
43000
  staleAfterMs: row.staleAfterMs,
41277
43001
  requested: {
41278
- value: parse5(row.requestedValue),
43002
+ value: parse6(row.requestedValue),
41279
43003
  requestedAt: row.requestedAt,
41280
43004
  requestedBy: row.requestedBy,
41281
43005
  requestId: row.requestId,
@@ -41283,7 +43007,7 @@ function toView(row, now = Date.now()) {
41283
43007
  },
41284
43008
  command: { state: row.commandState, acceptedAt: row.acceptedAt, reportedAt: row.commandReportedAt },
41285
43009
  confirmed,
41286
- externalChange: row.externalChangeAt ? { at: row.externalChangeAt, value: parse5(row.externalChangeValue) } : null,
43010
+ externalChange: row.externalChangeAt ? { at: row.externalChangeAt, value: parse6(row.externalChangeValue) } : null,
41287
43011
  fault: row.faultCode && row.faultAt ? { code: row.faultCode, message: row.faultMessage ?? "", at: row.faultAt } : null,
41288
43012
  uncertainActuation: row.commandState === "uncertain"
41289
43013
  };
@@ -41338,9 +43062,9 @@ var MatterStateService = class {
41338
43062
  where: { endpointRef: input2.endpointRef, stateKey: input2.stateKey }
41339
43063
  });
41340
43064
  if (await tables.commands.get(input2.requestId)) {
41341
- return toView(current ?? emptyState(input2.endpointRef, input2.stateKey, (0, import_node_crypto14.randomUUID)(), now));
43065
+ return toView(current ?? emptyState(input2.endpointRef, input2.stateKey, (0, import_node_crypto18.randomUUID)(), now));
41342
43066
  }
41343
- const next = applyRequest(current ?? emptyState(input2.endpointRef, input2.stateKey, (0, import_node_crypto14.randomUUID)(), now), {
43067
+ const next = applyRequest(current ?? emptyState(input2.endpointRef, input2.stateKey, (0, import_node_crypto18.randomUUID)(), now), {
41344
43068
  value: input2.value,
41345
43069
  requestedAt: now,
41346
43070
  requestedBy: input2.requestedBy,
@@ -41445,7 +43169,7 @@ var MatterStateService = class {
41445
43169
  if (!fitsValueBound(payload.value)) return void (delta.oversizedValue += 1);
41446
43170
  const resolved = await this.resolve(tables, fabrics2, payload);
41447
43171
  if ("ignored" in resolved) return void (delta[resolved.ignored] += 1);
41448
- const row = await tables.endpointState.findOne({ where: { endpointRef: resolved.endpoint.id, stateKey } }) ?? emptyState(resolved.endpoint.id, stateKey, (0, import_node_crypto14.randomUUID)(), receivedAt);
43172
+ const row = await tables.endpointState.findOne({ where: { endpointRef: resolved.endpoint.id, stateKey } }) ?? emptyState(resolved.endpoint.id, stateKey, (0, import_node_crypto18.randomUUID)(), receivedAt);
41449
43173
  const next = applyReport(
41450
43174
  row,
41451
43175
  {
@@ -41540,9 +43264,9 @@ var MatterStateService = class {
41540
43264
  }
41541
43265
  };
41542
43266
  MatterStateService = __decorateClass([
41543
- (0, import_common18.Injectable)(),
41544
- __decorateParam(0, (0, import_common18.Inject)(PLUGIN_CONTEXT)),
41545
- __decorateParam(1, (0, import_common18.Inject)(MatterChangeBus))
43267
+ (0, import_common25.Injectable)(),
43268
+ __decorateParam(0, (0, import_common25.Inject)(PLUGIN_CONTEXT)),
43269
+ __decorateParam(1, (0, import_common25.Inject)(MatterChangeBus))
41546
43270
  ], MatterStateService);
41547
43271
  function fitsValueBound(value) {
41548
43272
  try {
@@ -41552,109 +43276,13 @@ function fitsValueBound(value) {
41552
43276
  }
41553
43277
  }
41554
43278
 
41555
- // backend/devices/views.ts
41556
- function nodeView(node2) {
41557
- return {
41558
- id: node2.id,
41559
- fabricRef: node2.fabricRef,
41560
- nodeId: node2.nodeId,
41561
- lifecycleState: node2.lifecycleState,
41562
- detachedReason: node2.detachedReason,
41563
- reachable: node2.reachable,
41564
- /** Read-only: reported by the sidecar. */
41565
- identity: {
41566
- vendorId: node2.vendorId,
41567
- productId: node2.productId,
41568
- vendorName: node2.vendorName,
41569
- productName: node2.productName,
41570
- serialNumber: node2.serialNumber,
41571
- uniqueId: node2.uniqueId,
41572
- hardwareVersion: node2.hardwareVersion,
41573
- softwareVersion: node2.softwareVersion,
41574
- softwareVersionString: node2.softwareVersionString,
41575
- attestation: { status: node2.attestationStatus, checkedAt: node2.attestationCheckedAt }
41576
- },
41577
- /** Editable by administrators; reconciliation never writes it. */
41578
- metadata: { displayName: node2.displayName, description: node2.description, location: node2.location },
41579
- firstSeenAt: node2.firstSeenAt,
41580
- lastSeenAt: node2.lastSeenAt,
41581
- claimedAt: node2.claimedAt,
41582
- claimedBy: node2.claimedBy,
41583
- detachedAt: node2.detachedAt,
41584
- archivedAt: node2.archivedAt,
41585
- archivedBy: node2.archivedBy,
41586
- removedAt: node2.removedAt,
41587
- removedBy: node2.removedBy,
41588
- removalReason: node2.removalReason,
41589
- mergedInto: node2.mergedInto,
41590
- createdAt: node2.createdAt,
41591
- updatedAt: node2.updatedAt
41592
- };
41593
- }
41594
- function endpointView(endpoint) {
41595
- return {
41596
- id: endpoint.id,
41597
- nodeRef: endpoint.nodeRef,
41598
- endpointId: endpoint.endpointId,
41599
- parentEndpointId: endpoint.parentEndpointId,
41600
- deviceTypes: JSON.parse(endpoint.deviceTypes),
41601
- profile: endpoint.profile,
41602
- metadata: { displayName: endpoint.displayName, description: endpoint.description, location: endpoint.location },
41603
- bridged: endpoint.bridged ? {
41604
- uniqueId: endpoint.bridgedUniqueId,
41605
- nodeLabel: endpoint.bridgedNodeLabel,
41606
- vendorName: endpoint.bridgedVendorName,
41607
- productName: endpoint.bridgedProductName,
41608
- serialNumber: endpoint.bridgedSerialNumber,
41609
- reachable: endpoint.bridgedReachable
41610
- } : null,
41611
- firstSeenAt: endpoint.firstSeenAt,
41612
- lastSeenAt: endpoint.lastSeenAt,
41613
- removedAt: endpoint.removedAt,
41614
- removalReason: endpoint.removalReason
41615
- };
41616
- }
41617
- function clusterView(cluster) {
41618
- return {
41619
- clusterId: cluster.clusterId,
41620
- role: cluster.role,
41621
- revision: cluster.revision,
41622
- featureMap: cluster.featureMap,
41623
- attributeIds: JSON.parse(cluster.attributeIds),
41624
- acceptedCommandIds: JSON.parse(cluster.acceptedCommandIds)
41625
- };
41626
- }
41627
- function capabilityView(capability) {
41628
- return {
41629
- capability: capability.capability,
41630
- sourceClusterId: capability.sourceClusterId,
41631
- details: JSON.parse(capability.details)
41632
- };
41633
- }
41634
- function nodeDetailView(detail) {
41635
- return {
41636
- ...nodeView(detail.node),
41637
- fabric: detail.fabric && {
41638
- id: detail.fabric.id,
41639
- fabricId: detail.fabric.fabricId,
41640
- status: detail.fabric.status,
41641
- label: detail.fabric.label
41642
- },
41643
- endpoints: detail.endpoints.map(({ endpoint, clusters, capabilities }) => ({
41644
- ...endpointView(endpoint),
41645
- clusters: clusters.map(clusterView),
41646
- capabilities: capabilities.map(capabilityView).sort((a, b) => a.capability.localeCompare(b.capability))
41647
- }))
41648
- };
41649
- }
41650
-
41651
43279
  // backend/devices/controller.ts
41652
- function parse6(schema, value, where = "body") {
43280
+ function parse7(schema, value, where = "body") {
41653
43281
  const parsed = schema.safeParse(value);
41654
- if (!parsed.success) throw new import_common19.BadRequestException(validationMessages(parsed.error, where));
43282
+ if (!parsed.success) throw new import_common26.BadRequestException(validationMessages(parsed.error, where));
41655
43283
  return parsed.data;
41656
43284
  }
41657
- var parseId = (id) => parse6(idParamSchema2, id, "id");
43285
+ var parseId2 = (id) => parse7(idParamSchema2, id, "id");
41658
43286
  var MatterDevicesController = class {
41659
43287
  constructor(lifecycle, reconciliation, state) {
41660
43288
  this.lifecycle = lifecycle;
@@ -41662,43 +43290,43 @@ var MatterDevicesController = class {
41662
43290
  this.state = state;
41663
43291
  }
41664
43292
  async listNodes(query) {
41665
- const filter2 = parse6(listQuerySchema, query, "query");
43293
+ const filter2 = parse7(listQuerySchema, query, "query");
41666
43294
  const nodes2 = await this.lifecycle.listNodes(filter2);
41667
43295
  const counts = await this.lifecycle.endpointCounts(nodes2.map((node2) => node2.id));
41668
43296
  return nodes2.map((node2) => ({ ...nodeView(node2), endpointCount: counts.get(node2.id) ?? 0 }));
41669
43297
  }
41670
43298
  async getNode(id) {
41671
- return nodeDetailView(await this.lifecycle.getNode(parseId(id)));
43299
+ return nodeDetailView(await this.lifecycle.getNode(parseId2(id)));
41672
43300
  }
41673
43301
  async updateNode(id, body, request) {
41674
- return nodeView(await this.lifecycle.updateNode(parseId(id), parse6(metadataSchema, body), principalOf(request)));
43302
+ return nodeView(await this.lifecycle.updateNode(parseId2(id), parse7(metadataSchema, body), principalOf(request)));
41675
43303
  }
41676
43304
  async claim(id, body, request) {
41677
- return nodeView(await this.lifecycle.claim(parseId(id), parse6(claimSchema, body ?? {}), principalOf(request)));
43305
+ return nodeView(await this.lifecycle.claim(parseId2(id), parse7(claimSchema, body ?? {}), principalOf(request)));
41678
43306
  }
41679
43307
  async relink(id, body, request) {
41680
- return nodeView(await this.lifecycle.relink(parseId(id), parse6(relinkSchema, body), principalOf(request)));
43308
+ return nodeView(await this.lifecycle.relink(parseId2(id), parse7(relinkSchema, body), principalOf(request)));
41681
43309
  }
41682
43310
  async repair(id, request) {
41683
- return nodeView(await this.lifecycle.repair(parseId(id), principalOf(request)));
43311
+ return nodeView(await this.lifecycle.repair(parseId2(id), principalOf(request)));
41684
43312
  }
41685
43313
  async archive(id, request) {
41686
- return nodeView(await this.lifecycle.archive(parseId(id), principalOf(request)));
43314
+ return nodeView(await this.lifecycle.archive(parseId2(id), principalOf(request)));
41687
43315
  }
41688
43316
  async restore(id, request) {
41689
- return nodeView(await this.lifecycle.restore(parseId(id), principalOf(request)));
43317
+ return nodeView(await this.lifecycle.restore(parseId2(id), principalOf(request)));
41690
43318
  }
41691
43319
  async forceRemove(id, body, request) {
41692
- parse6(forceRemoveSchema, body);
41693
- return nodeView(await this.lifecycle.forceRemove(parseId(id), principalOf(request)));
43320
+ parse7(forceRemoveSchema, body);
43321
+ return nodeView(await this.lifecycle.forceRemove(parseId2(id), principalOf(request)));
41694
43322
  }
41695
43323
  async updateEndpoint(id, body, request) {
41696
43324
  return endpointView(
41697
- await this.lifecycle.updateEndpoint(parseId(id), parse6(metadataSchema, body), principalOf(request))
43325
+ await this.lifecycle.updateEndpoint(parseId2(id), parse7(metadataSchema, body), principalOf(request))
41698
43326
  );
41699
43327
  }
41700
43328
  async endpointState(id) {
41701
- const endpoint = await this.lifecycle.getEndpoint(parseId(id));
43329
+ const endpoint = await this.lifecycle.getEndpoint(parseId2(id));
41702
43330
  return { endpointRef: endpoint.id, states: await this.state.read(endpoint.id) };
41703
43331
  }
41704
43332
  async reconciliationStatus() {
@@ -41709,98 +43337,98 @@ var MatterDevicesController = class {
41709
43337
  }
41710
43338
  };
41711
43339
  __decorateClass([
41712
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeList),
41713
- (0, import_common19.Get)("nodes"),
41714
- __decorateParam(0, (0, import_common19.Query)())
43340
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeList),
43341
+ (0, import_common26.Get)("nodes"),
43342
+ __decorateParam(0, (0, import_common26.Query)())
41715
43343
  ], MatterDevicesController.prototype, "listNodes", 1);
41716
43344
  __decorateClass([
41717
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeGet),
41718
- (0, import_common19.Get)("nodes/:id"),
41719
- __decorateParam(0, (0, import_common19.Param)("id"))
43345
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeGet),
43346
+ (0, import_common26.Get)("nodes/:id"),
43347
+ __decorateParam(0, (0, import_common26.Param)("id"))
41720
43348
  ], MatterDevicesController.prototype, "getNode", 1);
41721
43349
  __decorateClass([
41722
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeUpdate),
41723
- (0, import_common19.Patch)("nodes/:id"),
41724
- __decorateParam(0, (0, import_common19.Param)("id")),
41725
- __decorateParam(1, (0, import_common19.Body)()),
41726
- __decorateParam(2, (0, import_common19.Req)())
43350
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeUpdate),
43351
+ (0, import_common26.Patch)("nodes/:id"),
43352
+ __decorateParam(0, (0, import_common26.Param)("id")),
43353
+ __decorateParam(1, (0, import_common26.Body)()),
43354
+ __decorateParam(2, (0, import_common26.Req)())
41727
43355
  ], MatterDevicesController.prototype, "updateNode", 1);
41728
43356
  __decorateClass([
41729
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeClaim),
41730
- (0, import_common19.Post)("nodes/:id/claim"),
41731
- (0, import_common19.HttpCode)(200),
41732
- __decorateParam(0, (0, import_common19.Param)("id")),
41733
- __decorateParam(1, (0, import_common19.Body)()),
41734
- __decorateParam(2, (0, import_common19.Req)())
43357
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeClaim),
43358
+ (0, import_common26.Post)("nodes/:id/claim"),
43359
+ (0, import_common26.HttpCode)(200),
43360
+ __decorateParam(0, (0, import_common26.Param)("id")),
43361
+ __decorateParam(1, (0, import_common26.Body)()),
43362
+ __decorateParam(2, (0, import_common26.Req)())
41735
43363
  ], MatterDevicesController.prototype, "claim", 1);
41736
43364
  __decorateClass([
41737
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeRelink),
41738
- (0, import_common19.Post)("nodes/:id/relink"),
41739
- (0, import_common19.HttpCode)(200),
41740
- __decorateParam(0, (0, import_common19.Param)("id")),
41741
- __decorateParam(1, (0, import_common19.Body)()),
41742
- __decorateParam(2, (0, import_common19.Req)())
43365
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeRelink),
43366
+ (0, import_common26.Post)("nodes/:id/relink"),
43367
+ (0, import_common26.HttpCode)(200),
43368
+ __decorateParam(0, (0, import_common26.Param)("id")),
43369
+ __decorateParam(1, (0, import_common26.Body)()),
43370
+ __decorateParam(2, (0, import_common26.Req)())
41743
43371
  ], MatterDevicesController.prototype, "relink", 1);
41744
43372
  __decorateClass([
41745
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeRepair),
41746
- (0, import_common19.Post)("nodes/:id/repair"),
41747
- (0, import_common19.HttpCode)(200),
41748
- __decorateParam(0, (0, import_common19.Param)("id")),
41749
- __decorateParam(1, (0, import_common19.Req)())
43373
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeRepair),
43374
+ (0, import_common26.Post)("nodes/:id/repair"),
43375
+ (0, import_common26.HttpCode)(200),
43376
+ __decorateParam(0, (0, import_common26.Param)("id")),
43377
+ __decorateParam(1, (0, import_common26.Req)())
41750
43378
  ], MatterDevicesController.prototype, "repair", 1);
41751
43379
  __decorateClass([
41752
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeArchive),
41753
- (0, import_common19.Post)("nodes/:id/archive"),
41754
- (0, import_common19.HttpCode)(200),
41755
- __decorateParam(0, (0, import_common19.Param)("id")),
41756
- __decorateParam(1, (0, import_common19.Req)())
43380
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeArchive),
43381
+ (0, import_common26.Post)("nodes/:id/archive"),
43382
+ (0, import_common26.HttpCode)(200),
43383
+ __decorateParam(0, (0, import_common26.Param)("id")),
43384
+ __decorateParam(1, (0, import_common26.Req)())
41757
43385
  ], MatterDevicesController.prototype, "archive", 1);
41758
43386
  __decorateClass([
41759
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeRestore),
41760
- (0, import_common19.Post)("nodes/:id/restore"),
41761
- (0, import_common19.HttpCode)(200),
41762
- __decorateParam(0, (0, import_common19.Param)("id")),
41763
- __decorateParam(1, (0, import_common19.Req)())
43387
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeRestore),
43388
+ (0, import_common26.Post)("nodes/:id/restore"),
43389
+ (0, import_common26.HttpCode)(200),
43390
+ __decorateParam(0, (0, import_common26.Param)("id")),
43391
+ __decorateParam(1, (0, import_common26.Req)())
41764
43392
  ], MatterDevicesController.prototype, "restore", 1);
41765
43393
  __decorateClass([
41766
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.nodeForceRemove),
41767
- (0, import_common19.Post)("nodes/:id/force-remove"),
41768
- (0, import_common19.HttpCode)(200),
41769
- __decorateParam(0, (0, import_common19.Param)("id")),
41770
- __decorateParam(1, (0, import_common19.Body)()),
41771
- __decorateParam(2, (0, import_common19.Req)())
43394
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.nodeForceRemove),
43395
+ (0, import_common26.Post)("nodes/:id/force-remove"),
43396
+ (0, import_common26.HttpCode)(200),
43397
+ __decorateParam(0, (0, import_common26.Param)("id")),
43398
+ __decorateParam(1, (0, import_common26.Body)()),
43399
+ __decorateParam(2, (0, import_common26.Req)())
41772
43400
  ], MatterDevicesController.prototype, "forceRemove", 1);
41773
43401
  __decorateClass([
41774
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.endpointUpdate),
41775
- (0, import_common19.Patch)("endpoints/:id"),
41776
- __decorateParam(0, (0, import_common19.Param)("id")),
41777
- __decorateParam(1, (0, import_common19.Body)()),
41778
- __decorateParam(2, (0, import_common19.Req)())
43402
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.endpointUpdate),
43403
+ (0, import_common26.Patch)("endpoints/:id"),
43404
+ __decorateParam(0, (0, import_common26.Param)("id")),
43405
+ __decorateParam(1, (0, import_common26.Body)()),
43406
+ __decorateParam(2, (0, import_common26.Req)())
41779
43407
  ], MatterDevicesController.prototype, "updateEndpoint", 1);
41780
43408
  __decorateClass([
41781
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.endpointState),
41782
- (0, import_common19.Get)("endpoints/:id/state"),
41783
- __decorateParam(0, (0, import_common19.Param)("id"))
43409
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.endpointState),
43410
+ (0, import_common26.Get)("endpoints/:id/state"),
43411
+ __decorateParam(0, (0, import_common26.Param)("id"))
41784
43412
  ], MatterDevicesController.prototype, "endpointState", 1);
41785
43413
  __decorateClass([
41786
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.reconciliationStatus),
41787
- (0, import_common19.Get)("reconciliation")
43414
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.reconciliationStatus),
43415
+ (0, import_common26.Get)("reconciliation")
41788
43416
  ], MatterDevicesController.prototype, "reconciliationStatus", 1);
41789
43417
  __decorateClass([
41790
- (0, import_plugins_backend_sdk7.Auth)(...MATTER_OPERATIONS.reconciliationRun),
41791
- (0, import_common19.Post)("reconciliation"),
41792
- (0, import_common19.HttpCode)(200),
41793
- __decorateParam(0, (0, import_common19.Req)())
43418
+ (0, import_plugins_backend_sdk8.Auth)(...MATTER_OPERATIONS.reconciliationRun),
43419
+ (0, import_common26.Post)("reconciliation"),
43420
+ (0, import_common26.HttpCode)(200),
43421
+ __decorateParam(0, (0, import_common26.Req)())
41794
43422
  ], MatterDevicesController.prototype, "trigger", 1);
41795
43423
  MatterDevicesController = __decorateClass([
41796
- (0, import_common19.Controller)("matter"),
41797
- __decorateParam(0, (0, import_common19.Inject)(MatterLifecycleService)),
41798
- __decorateParam(1, (0, import_common19.Inject)(MatterReconciliationService)),
41799
- __decorateParam(2, (0, import_common19.Inject)(MatterStateService))
43424
+ (0, import_common26.Controller)("matter"),
43425
+ __decorateParam(0, (0, import_common26.Inject)(MatterLifecycleService)),
43426
+ __decorateParam(1, (0, import_common26.Inject)(MatterReconciliationService)),
43427
+ __decorateParam(2, (0, import_common26.Inject)(MatterStateService))
41800
43428
  ], MatterDevicesController);
41801
43429
 
41802
43430
  // backend/devices/ingestion.service.ts
41803
- var import_common20 = require("@nestjs/common");
43431
+ var import_common27 = require("@nestjs/common");
41804
43432
  var MAX_PENDING_EVENTS = 1e4;
41805
43433
  var INGEST_BATCH_SIZE = 200;
41806
43434
  var MatterIngestionService = class {
@@ -41872,13 +43500,13 @@ var MatterIngestionService = class {
41872
43500
  }
41873
43501
  };
41874
43502
  MatterIngestionService = __decorateClass([
41875
- (0, import_common20.Injectable)(),
41876
- __decorateParam(0, (0, import_common20.Inject)(PLUGIN_CONTEXT)),
41877
- __decorateParam(1, (0, import_common20.Inject)(MatterConnectionService)),
41878
- __decorateParam(2, (0, import_common20.Inject)(MatterReconciliationService)),
41879
- __decorateParam(3, (0, import_common20.Inject)(MatterStateService)),
41880
- __decorateParam(4, (0, import_common20.Optional)()),
41881
- __decorateParam(4, (0, import_common20.Inject)(MatterFabricService))
43503
+ (0, import_common27.Injectable)(),
43504
+ __decorateParam(0, (0, import_common27.Inject)(PLUGIN_CONTEXT)),
43505
+ __decorateParam(1, (0, import_common27.Inject)(MatterConnectionService)),
43506
+ __decorateParam(2, (0, import_common27.Inject)(MatterReconciliationService)),
43507
+ __decorateParam(3, (0, import_common27.Inject)(MatterStateService)),
43508
+ __decorateParam(4, (0, import_common27.Optional)()),
43509
+ __decorateParam(4, (0, import_common27.Inject)(MatterFabricService))
41882
43510
  ], MatterIngestionService);
41883
43511
  function parseStateEvent(type, payload) {
41884
43512
  if (type === "device.state") {
@@ -41893,7 +43521,7 @@ function parseStateEvent(type, payload) {
41893
43521
  }
41894
43522
 
41895
43523
  // backend/devices/live-updates.service.ts
41896
- var import_common21 = require("@nestjs/common");
43524
+ var import_common28 = require("@nestjs/common");
41897
43525
  var import_rxjs2 = __toESM(require_cjs());
41898
43526
  var LIVE_COALESCE_MS = 1e3;
41899
43527
  var allowed = (user, keys) => keys.every((key) => user.effectivePermissions?.has(key));
@@ -41915,7 +43543,7 @@ var MatterLiveUpdatesService = class {
41915
43543
  topic: "devices",
41916
43544
  identifier: "none",
41917
43545
  authorize: (_subscription, user) => {
41918
- if (!allowed(user, MATTER_OPERATIONS.liveDeviceInventory)) throw new import_common21.ForbiddenException();
43546
+ if (!allowed(user, MATTER_OPERATIONS.liveDeviceInventory)) throw new import_common28.ForbiddenException();
41919
43547
  },
41920
43548
  source: () => this.signals((change) => change.kind === "inventory")
41921
43549
  }),
@@ -41923,8 +43551,8 @@ var MatterLiveUpdatesService = class {
41923
43551
  topic: "device-state",
41924
43552
  identifier: "required",
41925
43553
  authorize: async ({ identifier }, user) => {
41926
- if (!allowed(user, MATTER_OPERATIONS.liveDeviceState)) throw new import_common21.ForbiddenException();
41927
- if (!idParamSchema2.safeParse(identifier).success) throw new import_common21.NotFoundException();
43554
+ if (!allowed(user, MATTER_OPERATIONS.liveDeviceState)) throw new import_common28.ForbiddenException();
43555
+ if (!idParamSchema2.safeParse(identifier).success) throw new import_common28.NotFoundException();
41928
43556
  await this.lifecycle.getEndpoint(identifier);
41929
43557
  },
41930
43558
  source: ({ identifier }) => this.signals((change) => change.kind === "state" && change.endpointRef === identifier)
@@ -41946,10 +43574,10 @@ var MatterLiveUpdatesService = class {
41946
43574
  }
41947
43575
  };
41948
43576
  MatterLiveUpdatesService = __decorateClass([
41949
- (0, import_common21.Injectable)(),
41950
- __decorateParam(0, (0, import_common21.Inject)(PLUGIN_CONTEXT)),
41951
- __decorateParam(1, (0, import_common21.Inject)(MatterChangeBus)),
41952
- __decorateParam(2, (0, import_common21.Inject)(MatterLifecycleService))
43577
+ (0, import_common28.Injectable)(),
43578
+ __decorateParam(0, (0, import_common28.Inject)(PLUGIN_CONTEXT)),
43579
+ __decorateParam(1, (0, import_common28.Inject)(MatterChangeBus)),
43580
+ __decorateParam(2, (0, import_common28.Inject)(MatterLifecycleService))
41953
43581
  ], MatterLiveUpdatesService);
41954
43582
 
41955
43583
  // backend/fabric/migration-reader.ts
@@ -41981,6 +43609,7 @@ var plugin = {
41981
43609
  controllers: [
41982
43610
  MatterConnectionController,
41983
43611
  MatterDevicesController,
43612
+ MatterCommissioningController,
41984
43613
  MatterFabricController,
41985
43614
  MatterBackupController
41986
43615
  ],
@@ -42002,7 +43631,12 @@ var plugin = {
42002
43631
  MatterBackupService,
42003
43632
  MatterFabricService,
42004
43633
  MatterRestoreService,
42005
- MatterBackupSchedulerService
43634
+ MatterBackupSchedulerService,
43635
+ // ATT-1002: commissioning, removal from the fabric and sharing.
43636
+ MatterOperationGate,
43637
+ MatterCommissioningService,
43638
+ MatterNodeRemovalService,
43639
+ MatterNodeSharingService
42006
43640
  ]
42007
43641
  };
42008
43642
  }