@attraccess/plugin-wago 0.1.0 → 0.2.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
@@ -863,7 +863,7 @@ __export(plugin_exports, {
863
863
  module.exports = __toCommonJS(plugin_exports);
864
864
 
865
865
  // backend/controllers/controller.ts
866
- var import_plugins_backend_sdk16 = require("@attraccess/plugins-backend-sdk");
866
+ var import_plugins_backend_sdk13 = require("@attraccess/plugins-backend-sdk");
867
867
  var import_common32 = require("@nestjs/common");
868
868
 
869
869
  // backend/audit/index.ts
@@ -1250,8 +1250,8 @@ function validateConnections(config, validation) {
1250
1250
  // modbus/validate-profiles.ts
1251
1251
  function validateProfiles(config, validation) {
1252
1252
  const { fail, object, integer, name, keys } = validation;
1253
- const format = (f, path) => {
1254
- if (![0, 1].includes(f.addressBase) || !Number.isSafeInteger(f.address) || !integer(f.address - f.addressBase, 0, 65536 - registerCount(f)) || !["uint16", "int16", "uint32", "int32", "float32"].includes(f.dataType) || !["big", "little"].includes(f.byteOrder) || !["big", "little"].includes(f.wordOrder) || !Number.isFinite(f.scale) || f.scale === 0 || !Number.isFinite(f.offset))
1253
+ const format = (f2, path) => {
1254
+ if (![0, 1].includes(f2.addressBase) || !Number.isSafeInteger(f2.address) || !integer(f2.address - f2.addressBase, 0, 65536 - registerCount(f2)) || !["uint16", "int16", "uint32", "int32", "float32"].includes(f2.dataType) || !["big", "little"].includes(f2.byteOrder) || !["big", "little"].includes(f2.wordOrder) || !Number.isFinite(f2.scale) || f2.scale === 0 || !Number.isFinite(f2.offset))
1255
1255
  fail(path, "invalid address, dtype, order or transform");
1256
1256
  };
1257
1257
  config.profiles.forEach((p, i) => {
@@ -1264,15 +1264,15 @@ function validateProfiles(config, validation) {
1264
1264
  return;
1265
1265
  }
1266
1266
  const ids = /* @__PURE__ */ new Set();
1267
- [...p.measurements, ...p.actions].forEach((f, j) => {
1268
- if (!object(f) || !name(f.id) || !name(f.name) || ids.has(f.id)) {
1267
+ [...p.measurements, ...p.actions].forEach((f2, j) => {
1268
+ if (!object(f2) || !name(f2.id) || !name(f2.name) || ids.has(f2.id)) {
1269
1269
  fail(`${path}[${j}]`, "unique named entry required");
1270
1270
  return;
1271
1271
  }
1272
- ids.add(f.id);
1273
- format(f, `${path}.${f.id}`);
1272
+ ids.add(f2.id);
1273
+ format(f2, `${path}.${f2.id}`);
1274
1274
  keys(
1275
- f,
1275
+ f2,
1276
1276
  [
1277
1277
  "id",
1278
1278
  "name",
@@ -1284,7 +1284,7 @@ function validateProfiles(config, validation) {
1284
1284
  "scale",
1285
1285
  "offset",
1286
1286
  "functionCode",
1287
- ...p.measurements.includes(f) ? [
1287
+ ...p.measurements.includes(f2) ? [
1288
1288
  "unit",
1289
1289
  "kind",
1290
1290
  "pollIntervalMs",
@@ -1296,7 +1296,7 @@ function validateProfiles(config, validation) {
1296
1296
  "valueLabels"
1297
1297
  ] : ["onValue", "offValue"]
1298
1298
  ],
1299
- `${path}.${f.id}`
1299
+ `${path}.${f2.id}`
1300
1300
  );
1301
1301
  });
1302
1302
  p.measurements.forEach((m) => {
@@ -2451,7 +2451,7 @@ function parseManagementInspection(output) {
2451
2451
  // backend/commissioning/service.ts
2452
2452
  var import_common30 = require("@nestjs/common");
2453
2453
  var import_promises10 = require("node:fs/promises");
2454
- var import_plugins_backend_sdk14 = require("@attraccess/plugins-backend-sdk");
2454
+ var import_plugins_backend_sdk11 = require("@attraccess/plugins-backend-sdk");
2455
2455
 
2456
2456
  // backend/controllers/service.ts
2457
2457
  var import_common10 = require("@nestjs/common");
@@ -3151,6 +3151,9 @@ function requireRuntimeSupport(snapshot, capabilities) {
3151
3151
  if (errors.length) throw new import_common4.ConflictException({ message: errors[0].message, code: errors[0].code, errors });
3152
3152
  }
3153
3153
 
3154
+ // backend/controllers/subscriptions.ts
3155
+ var import_plugins_backend_sdk5 = require("@attraccess/plugins-backend-sdk");
3156
+
3154
3157
  // backend/controllers/enrollment.ts
3155
3158
  var import_common9 = require("@nestjs/common");
3156
3159
  var import_node_crypto7 = require("node:crypto");
@@ -3158,9 +3161,6 @@ var import_node_crypto7 = require("node:crypto");
3158
3161
  // backend/configuration/revisions.ts
3159
3162
  var import_common8 = require("@nestjs/common");
3160
3163
 
3161
- // backend/configuration/flow-references.ts
3162
- var import_plugins_backend_sdk = require("@attraccess/plugins-backend-sdk");
3163
-
3164
3164
  // backend/configuration/digital.ts
3165
3165
  var DIGITAL_TERMINALS = [
3166
3166
  ...Array.from({ length: 4 }, (_, channel) => ({ channel, label: `DO${channel + 1}`, direction: "output" })),
@@ -3316,7 +3316,10 @@ async function configurationFlowImpacts(context, controllerId, previous, current
3316
3316
  impacts.push({ channelId: channel.id, message: "An input used by this channel as a guard or feedback changed." });
3317
3317
  }
3318
3318
  }
3319
- const nodes = await context.dataSource.getRepository(import_plugins_backend_sdk.ResourceFlowNode).createQueryBuilder("node").select(["node.id", "node.resourceId", "node.flowId", "node.type", "node.data"]).leftJoin("node.flow", "flow").addSelect(["flow.id", "flow.name"]).where("node.type LIKE :type", { type: "plugin.wago.%" }).andWhere("node.data ->> 'controllerId' = :controllerId", { controllerId }).getMany();
3319
+ const nodes = await context.hostData.flows.findNodes({
3320
+ typePrefix: "plugin.wago.",
3321
+ dataEquals: { controllerId }
3322
+ });
3320
3323
  for (const node of nodes) {
3321
3324
  const channelId2 = node.data?.channelId;
3322
3325
  if (String(node.type) !== "plugin.wago.command" || typeof channelId2 !== "string" || !channelId2) continue;
@@ -3331,165 +3334,316 @@ async function configurationFlowImpacts(context, controllerId, previous, current
3331
3334
  references: nodes.filter((node) => node.data?.channelId === impact.channelId).map((node) => ({
3332
3335
  resourceId: node.resourceId ?? null,
3333
3336
  flowId: node.flowId ?? null,
3334
- flowName: node.flowId != null ? node.flow?.name ?? null : null,
3337
+ flowName: node.flowId != null ? node.flowName : null,
3335
3338
  nodeId: node.id,
3336
3339
  nodeType: node.type
3337
3340
  }))
3338
3341
  }));
3339
3342
  }
3340
3343
 
3344
+ // backend/configuration/revisions.ts
3345
+ var import_plugins_backend_sdk4 = require("@attraccess/plugins-backend-sdk");
3346
+
3341
3347
  // backend/configuration/drafts.ts
3342
3348
  var import_common7 = require("@nestjs/common");
3343
3349
 
3344
- // backend/controllers/settings.entity.ts
3350
+ // backend/controllers/registry.ts
3351
+ var import_plugins_backend_sdk3 = require("@attraccess/plugins-backend-sdk");
3352
+
3353
+ // backend/storage/index.ts
3345
3354
  var import_plugins_backend_sdk2 = require("@attraccess/plugins-backend-sdk");
3346
- var WagoSettings = class {
3347
- constructor() {
3348
- __publicField(this, "id");
3349
- __publicField(this, "defaultMqttServerId");
3350
- __publicField(this, "operationalPrefix");
3351
- }
3355
+
3356
+ // backend/storage/legacy-migrations.ts
3357
+ var WAGO_LEGACY_MIGRATIONS = [
3358
+ "CreateWagoControllers1780000000000",
3359
+ "AddWagoEnrollmentRevocation1780000000001",
3360
+ "AddWagoConfigurationRevisions1780000000002",
3361
+ "AddWagoPresetProvenance1780000000003",
3362
+ "AddWagoCommissioningSessions1780000000004",
3363
+ "AddWagoCommissioningEnrollment1780000000005",
3364
+ "AddWagoCommissioningClaimDetails1780000000006",
3365
+ "AddWagoCommissioningProgress1780000000007",
3366
+ "AddWagoCommissioningDeliveryToken1780000000008",
3367
+ "AddWagoCommissioningPrincipal1780000000009",
3368
+ "WagoManagement1780000000010",
3369
+ "WagoCommissioningLease1780000000011",
3370
+ "AddWagoRevisionEditorMetadata1780010580000",
3371
+ "AddWagoClaimIntent1780010600000",
3372
+ "WagoCredentialRotation1780010610000",
3373
+ "AddWagoRejectionAcknowledgement1780010630000",
3374
+ "DropWagoCommissioningLease1780010640000",
3375
+ "WagoManagedUpdates1780010650000",
3376
+ "WagoNetworkChanges1780010660000"
3377
+ ];
3378
+
3379
+ // backend/storage/tables.ts
3380
+ var import_plugins_backend_sdk = require("@attraccess/plugins-backend-sdk");
3381
+ var wagoTables = {
3382
+ controllers: (0, import_plugins_backend_sdk.table)(
3383
+ {
3384
+ id: import_plugins_backend_sdk.f.id(),
3385
+ /** Reported by the controller without a length limit. */
3386
+ hardwareId: import_plugins_backend_sdk.f.text({ column: "hardware_id" }),
3387
+ trustState: import_plugins_backend_sdk.f.string({ column: "trust_state" }),
3388
+ name: import_plugins_backend_sdk.f.text().optional(),
3389
+ mqttServerId: import_plugins_backend_sdk.f.integer({ column: "mqtt_server_id" }).optional(),
3390
+ /** Durable permanent-identity provisioning intent, retained until confirmed revocation. */
3391
+ credentialMqttServerId: import_plugins_backend_sdk.f.integer({ column: "credential_mqtt_server_id" }).optional(),
3392
+ /** Changes whenever permanent broker credentials are issued, binding later rotations to that claim. */
3393
+ credentialEpoch: import_plugins_backend_sdk.f.string({ column: "credential_epoch" }).optional(),
3394
+ enrollmentId: import_plugins_backend_sdk.f.integer({ column: "enrollment_id" }).optional(),
3395
+ pairingCodeHash: import_plugins_backend_sdk.f.string({ column: "pairing_code_hash" }),
3396
+ /** Fingerprint, protocol and runtime version come from the controller's announcement, without a length limit. */
3397
+ fingerprint: import_plugins_backend_sdk.f.text().optional(),
3398
+ protocolVersion: import_plugins_backend_sdk.f.text({ column: "protocol_version" }),
3399
+ runtimeVersion: import_plugins_backend_sdk.f.text({ column: "runtime_version" }),
3400
+ /** JSON array of capability names. */
3401
+ capabilities: import_plugins_backend_sdk.f.text(),
3402
+ lastSequence: import_plugins_backend_sdk.f.integer({ column: "last_sequence" }).withDefault(0),
3403
+ lastHeartbeatAt: import_plugins_backend_sdk.f.string({ column: "last_heartbeat_at" }).optional(),
3404
+ lastSeenAt: import_plugins_backend_sdk.f.string({ column: "last_seen_at" }),
3405
+ compatibilityError: import_plugins_backend_sdk.f.text({ column: "compatibility_error" }).optional(),
3406
+ createdAt: import_plugins_backend_sdk.f.string({ column: "created_at" }),
3407
+ updatedAt: import_plugins_backend_sdk.f.string({ column: "updated_at" })
3408
+ },
3409
+ {
3410
+ physicalName: "plugin_wago_controllers",
3411
+ indexes: [{ name: "UQ_plugin_wago_controllers_hardware_id", fields: ["hardwareId"], unique: true }]
3412
+ }
3413
+ ),
3414
+ settings: (0, import_plugins_backend_sdk.table)(
3415
+ {
3416
+ id: import_plugins_backend_sdk.f.id(),
3417
+ defaultMqttServerId: import_plugins_backend_sdk.f.integer({ column: "default_mqtt_server_id" }).optional(),
3418
+ /** Set by an administrator; only its MQTT segments are validated. */
3419
+ operationalPrefix: import_plugins_backend_sdk.f.text({ column: "operational_prefix" }).withDefault("attraccess/wago")
3420
+ },
3421
+ { physicalName: "plugin_wago_settings" }
3422
+ ),
3423
+ enrollments: (0, import_plugins_backend_sdk.table)(
3424
+ {
3425
+ id: import_plugins_backend_sdk.f.id(),
3426
+ mqttServerId: import_plugins_backend_sdk.f.integer({ column: "mqtt_server_id" }),
3427
+ hardwareId: import_plugins_backend_sdk.f.text({ column: "hardware_id" }),
3428
+ secretHash: import_plugins_backend_sdk.f.string({ column: "secret_hash" }),
3429
+ identity: import_plugins_backend_sdk.f.string(),
3430
+ createdAt: import_plugins_backend_sdk.f.string({ column: "created_at" }),
3431
+ expiresAt: import_plugins_backend_sdk.f.string({ column: "expires_at" }),
3432
+ consumedAt: import_plugins_backend_sdk.f.string({ column: "consumed_at" }).optional(),
3433
+ revokedAt: import_plugins_backend_sdk.f.string({ column: "revoked_at" }).optional()
3434
+ },
3435
+ {
3436
+ physicalName: "plugin_wago_enrollments",
3437
+ indexes: [
3438
+ { name: "UQ_plugin_wago_enrollments_secret_hash", fields: ["secretHash"], unique: true },
3439
+ { name: "IDX_plugin_wago_enrollments_active", fields: ["consumedAt", "expiresAt"] }
3440
+ ]
3441
+ }
3442
+ ),
3443
+ configurationDrafts: (0, import_plugins_backend_sdk.table)(
3444
+ {
3445
+ id: import_plugins_backend_sdk.f.id(),
3446
+ controllerId: import_plugins_backend_sdk.f.integer({ column: "controller_id" }),
3447
+ snapshot: import_plugins_backend_sdk.f.text(),
3448
+ reviewedHash: import_plugins_backend_sdk.f.string({ column: "reviewed_hash" }).optional(),
3449
+ presetProvenance: import_plugins_backend_sdk.f.text({ column: "preset_provenance" }).optional(),
3450
+ updatedAt: import_plugins_backend_sdk.f.string({ column: "updated_at" })
3451
+ },
3452
+ {
3453
+ physicalName: "plugin_wago_configuration_drafts",
3454
+ indexes: [{ name: "UQ_plugin_wago_configuration_drafts_controller_id", fields: ["controllerId"], unique: true }]
3455
+ }
3456
+ ),
3457
+ configurationRevisions: (0, import_plugins_backend_sdk.table)(
3458
+ {
3459
+ id: import_plugins_backend_sdk.f.id(),
3460
+ controllerId: import_plugins_backend_sdk.f.integer({ column: "controller_id" }),
3461
+ revision: import_plugins_backend_sdk.f.integer(),
3462
+ snapshot: import_plugins_backend_sdk.f.text(),
3463
+ presetProvenance: import_plugins_backend_sdk.f.text({ column: "preset_provenance" }).optional(),
3464
+ contentHash: import_plugins_backend_sdk.f.string({ column: "content_hash" }),
3465
+ state: import_plugins_backend_sdk.f.string(),
3466
+ rejectionErrors: import_plugins_backend_sdk.f.text({ column: "rejection_errors" }).optional(),
3467
+ rejectionAcknowledgedAt: import_plugins_backend_sdk.f.string({ column: "rejection_acknowledged_at" }).optional(),
3468
+ /** Core user id of the acknowledging user. */
3469
+ rejectionAcknowledgedBy: import_plugins_backend_sdk.f.integer({ column: "rejection_acknowledged_by" }).optional(),
3470
+ publishedAt: import_plugins_backend_sdk.f.string({ column: "published_at" }),
3471
+ reportedAt: import_plugins_backend_sdk.f.string({ column: "reported_at" }).optional()
3472
+ },
3473
+ {
3474
+ physicalName: "plugin_wago_configuration_revisions",
3475
+ indexes: [
3476
+ {
3477
+ name: "UQ_plugin_wago_configuration_revisions_controller_revision",
3478
+ fields: ["controllerId", "revision"],
3479
+ unique: true
3480
+ },
3481
+ { name: "IDX_plugin_wago_configuration_revisions_controller", fields: ["controllerId", "revision"] }
3482
+ ]
3483
+ }
3484
+ ),
3485
+ commissioningSessions: (0, import_plugins_backend_sdk.table)(
3486
+ {
3487
+ id: import_plugins_backend_sdk.f.id(),
3488
+ hardwareId: import_plugins_backend_sdk.f.string({ column: "hardware_id" }),
3489
+ mqttServerId: import_plugins_backend_sdk.f.integer({ column: "mqtt_server_id" }),
3490
+ targetHost: import_plugins_backend_sdk.f.string({ column: "target_host" }),
3491
+ hostKeyFingerprint: import_plugins_backend_sdk.f.string({ column: "host_key_fingerprint" }),
3492
+ /** From the operator's WAGO_CC100_FIRMWARE_BASELINE setting. */
3493
+ firmwareBaseline: import_plugins_backend_sdk.f.text({ column: "firmware_baseline" }),
3494
+ controllerName: import_plugins_backend_sdk.f.text({ column: "controller_name" }).optional(),
3495
+ state: import_plugins_backend_sdk.f.string(),
3496
+ enrollmentExpiresAt: import_plugins_backend_sdk.f.string({ column: "enrollment_expires_at" }).optional(),
3497
+ enrollmentId: import_plugins_backend_sdk.f.integer({ column: "enrollment_id" }).optional(),
3498
+ pairingCode: import_plugins_backend_sdk.f.string({ column: "pairing_code" }).optional(),
3499
+ deliveryToken: import_plugins_backend_sdk.f.string({ column: "delivery_token" }).optional(),
3500
+ /** JSON document of the initiating principal. */
3501
+ initiatingPrincipal: import_plugins_backend_sdk.f.text({ column: "initiating_principal" }).optional(),
3502
+ /** Last attempted delivery's digest for observation only; never used to choose the next bundle. */
3503
+ runtimeArtifactDigest: import_plugins_backend_sdk.f.string({ column: "runtime_artifact_digest" }).optional(),
3504
+ managementControllerId: import_plugins_backend_sdk.f.integer({ column: "management_controller_id" }).optional(),
3505
+ dockerProvisionToken: import_plugins_backend_sdk.f.string({ column: "docker_provision_token" }).optional(),
3506
+ dockerProvisionState: import_plugins_backend_sdk.f.string({ column: "docker_provision_state" }).optional(),
3507
+ platformReport: import_plugins_backend_sdk.f.text({ column: "platform_report" }).optional(),
3508
+ codesysState: import_plugins_backend_sdk.f.string({ column: "codesys_state" }).optional(),
3509
+ progressPercent: import_plugins_backend_sdk.f.integer({ column: "progress_percent" }).optional(),
3510
+ progressStep: import_plugins_backend_sdk.f.string({ column: "progress_step" }).optional(),
3511
+ progressDetail: import_plugins_backend_sdk.f.text({ column: "progress_detail" }).optional(),
3512
+ auditLog: import_plugins_backend_sdk.f.text({ column: "audit_log" }),
3513
+ failureReason: import_plugins_backend_sdk.f.text({ column: "failure_reason" }).optional(),
3514
+ createdAt: import_plugins_backend_sdk.f.string({ column: "created_at" }),
3515
+ updatedAt: import_plugins_backend_sdk.f.string({ column: "updated_at" })
3516
+ },
3517
+ { physicalName: "plugin_wago_commissioning_sessions" }
3518
+ ),
3519
+ /** New enrolments only. Never serialize this row or its encrypted envelope. */
3520
+ managedAccess: (0, import_plugins_backend_sdk.table)(
3521
+ {
3522
+ sessionId: import_plugins_backend_sdk.f.integer({ column: "session_id" }),
3523
+ controllerId: import_plugins_backend_sdk.f.integer({ column: "controller_id" }).optional(),
3524
+ host: import_plugins_backend_sdk.f.string(),
3525
+ fingerprint: import_plugins_backend_sdk.f.string(),
3526
+ token: import_plugins_backend_sdk.f.string(),
3527
+ state: import_plugins_backend_sdk.f.string(),
3528
+ encryptedCredentials: import_plugins_backend_sdk.f.text({ column: "encrypted_credentials" }),
3529
+ keyFingerprint: import_plugins_backend_sdk.f.string({ column: "key_fingerprint" })
3530
+ },
3531
+ {
3532
+ physicalName: "plugin_wago_managed_access",
3533
+ primaryKey: ["sessionId"],
3534
+ indexes: [{ name: "wago_managed_controller", fields: ["controllerId"] }]
3535
+ }
3536
+ ),
3537
+ runtimeUpdates: (0, import_plugins_backend_sdk.table)(
3538
+ {
3539
+ controllerId: import_plugins_backend_sdk.f.integer({ column: "controller_id" }),
3540
+ metadata: import_plugins_backend_sdk.f.text().optional()
3541
+ },
3542
+ { physicalName: "plugin_wago_runtime_updates", primaryKey: ["controllerId"] }
3543
+ ),
3544
+ /** Shared by commissioning, managed SSH and updates; keyed by pinned device identity. */
3545
+ deviceOperations: (0, import_plugins_backend_sdk.table)(
3546
+ {
3547
+ fingerprint: import_plugins_backend_sdk.f.string(),
3548
+ owner: import_plugins_backend_sdk.f.string().optional(),
3549
+ leaseUntil: import_plugins_backend_sdk.f.integer({ column: "lease_until" }).withDefault(0)
3550
+ },
3551
+ { physicalName: "plugin_wago_device_operations", primaryKey: ["fingerprint"] }
3552
+ ),
3553
+ /** Never return this row from an API. */
3554
+ management: (0, import_plugins_backend_sdk.table)(
3555
+ {
3556
+ controllerId: import_plugins_backend_sdk.f.integer({ column: "controller_id" }),
3557
+ metadataJson: import_plugins_backend_sdk.f.text({ column: "metadata_json" }).optional(),
3558
+ encryptedPrivateKey: import_plugins_backend_sdk.f.text({ column: "encrypted_private_key" }).optional(),
3559
+ leaseOwner: import_plugins_backend_sdk.f.string({ column: "lease_owner" }).optional(),
3560
+ leaseUntil: import_plugins_backend_sdk.f.integer({ column: "lease_until" }).withDefault(0)
3561
+ },
3562
+ { physicalName: "plugin_wago_management", primaryKey: ["controllerId"] }
3563
+ ),
3564
+ /** Never expose this recovery record through an API. */
3565
+ credentialRotations: (0, import_plugins_backend_sdk.table)(
3566
+ {
3567
+ controllerId: import_plugins_backend_sdk.f.integer({ column: "controller_id" }),
3568
+ revision: import_plugins_backend_sdk.f.integer(),
3569
+ credentialEpoch: import_plugins_backend_sdk.f.string({ column: "credential_epoch" }),
3570
+ phase: import_plugins_backend_sdk.f.string(),
3571
+ mqttServerId: import_plugins_backend_sdk.f.integer({ column: "mqtt_server_id" }),
3572
+ /** The operational prefix the rotation was issued for. */
3573
+ prefix: import_plugins_backend_sdk.f.text(),
3574
+ token: import_plugins_backend_sdk.f.string(),
3575
+ encryptedCredentials: import_plugins_backend_sdk.f.text({ column: "encrypted_credentials" }).optional()
3576
+ },
3577
+ {
3578
+ physicalName: "plugin_wago_credential_rotations",
3579
+ primaryKey: ["controllerId"],
3580
+ foreignKeys: [
3581
+ { fields: ["controllerId"], references: "controllers", referencedFields: ["id"], onDelete: "cascade" }
3582
+ ]
3583
+ }
3584
+ ),
3585
+ /** Durable roll-forward intent. Only an explicit public projection may leave the backend. */
3586
+ networkChanges: (0, import_plugins_backend_sdk.table)(
3587
+ {
3588
+ controllerId: import_plugins_backend_sdk.f.integer({ column: "controller_id" }),
3589
+ sessionId: import_plugins_backend_sdk.f.integer({ column: "session_id" }),
3590
+ fingerprint: import_plugins_backend_sdk.f.string(),
3591
+ targetHost: import_plugins_backend_sdk.f.string({ column: "target_host" }),
3592
+ mqttServerId: import_plugins_backend_sdk.f.integer({ column: "mqtt_server_id" }).optional(),
3593
+ phase: import_plugins_backend_sdk.f.string(),
3594
+ failure: import_plugins_backend_sdk.f.text().optional(),
3595
+ encryptedPayload: import_plugins_backend_sdk.f.text({ column: "encrypted_payload" }).optional(),
3596
+ updatedAt: import_plugins_backend_sdk.f.string({ column: "updated_at" })
3597
+ },
3598
+ {
3599
+ physicalName: "plugin_wago_network_changes",
3600
+ primaryKey: ["controllerId"],
3601
+ foreignKeys: [
3602
+ { fields: ["controllerId"], references: "controllers", referencedFields: ["id"], onDelete: "cascade" }
3603
+ ]
3604
+ }
3605
+ ),
3606
+ /**
3607
+ * Retain the old identity's broker association when it cannot be contacted. Migration success never relies on
3608
+ * revocation through an unreachable broker.
3609
+ */
3610
+ mqttCredentialRetirements: (0, import_plugins_backend_sdk.table)(
3611
+ {
3612
+ controllerId: import_plugins_backend_sdk.f.integer({ column: "controller_id" }),
3613
+ mqttServerId: import_plugins_backend_sdk.f.integer({ column: "mqtt_server_id" })
3614
+ },
3615
+ {
3616
+ physicalName: "plugin_wago_mqtt_credential_retirements",
3617
+ primaryKey: ["controllerId", "mqttServerId"],
3618
+ foreignKeys: [
3619
+ { fields: ["controllerId"], references: "controllers", referencedFields: ["id"], onDelete: "cascade" }
3620
+ ]
3621
+ }
3622
+ )
3352
3623
  };
3353
- __decorateClass([
3354
- (0, import_plugins_backend_sdk2.PrimaryGeneratedColumn)({ type: "integer" })
3355
- ], WagoSettings.prototype, "id", 2);
3356
- __decorateClass([
3357
- (0, import_plugins_backend_sdk2.Column)({ type: "integer", name: "default_mqtt_server_id", nullable: true })
3358
- ], WagoSettings.prototype, "defaultMqttServerId", 2);
3359
- __decorateClass([
3360
- (0, import_plugins_backend_sdk2.Column)({ type: "varchar", name: "operational_prefix", default: "attraccess/wago" })
3361
- ], WagoSettings.prototype, "operationalPrefix", 2);
3362
- WagoSettings = __decorateClass([
3363
- (0, import_plugins_backend_sdk2.Entity)({ name: "plugin_wago_settings" })
3364
- ], WagoSettings);
3624
+
3625
+ // backend/storage/index.ts
3626
+ var wagoStorage = (0, import_plugins_backend_sdk2.definePluginStorage)({
3627
+ tables: wagoTables,
3628
+ migrations: [
3629
+ {
3630
+ version: 1,
3631
+ name: "baseline",
3632
+ steps: Object.entries(wagoTables).map(([name, definition]) => import_plugins_backend_sdk2.step.createTable(name, definition))
3633
+ }
3634
+ ],
3635
+ adoption: { legacyMigrations: WAGO_LEGACY_MIGRATIONS }
3636
+ });
3637
+ function openWagoStorage(context) {
3638
+ return context.storage.open(wagoStorage);
3639
+ }
3365
3640
 
3366
3641
  // backend/controllers/registry.ts
3367
3642
  var import_common6 = require("@nestjs/common");
3368
3643
 
3369
- // backend/controllers/entity.ts
3370
- var import_plugins_backend_sdk3 = require("@attraccess/plugins-backend-sdk");
3371
- var WagoController = class {
3372
- constructor() {
3373
- __publicField(this, "id");
3374
- __publicField(this, "hardwareId");
3375
- __publicField(this, "trustState");
3376
- __publicField(this, "name");
3377
- __publicField(this, "mqttServerId");
3378
- __publicField(this, "credentialMqttServerId");
3379
- __publicField(this, "credentialEpoch");
3380
- __publicField(this, "enrollmentId");
3381
- __publicField(this, "pairingCodeHash");
3382
- __publicField(this, "fingerprint");
3383
- __publicField(this, "protocolVersion");
3384
- __publicField(this, "runtimeVersion");
3385
- __publicField(this, "capabilities");
3386
- __publicField(this, "lastSequence");
3387
- __publicField(this, "lastHeartbeatAt");
3388
- __publicField(this, "lastSeenAt");
3389
- __publicField(this, "compatibilityError");
3390
- __publicField(this, "createdAt");
3391
- __publicField(this, "updatedAt");
3392
- }
3393
- };
3394
- __decorateClass([
3395
- (0, import_plugins_backend_sdk3.PrimaryGeneratedColumn)({ type: "integer" })
3396
- ], WagoController.prototype, "id", 2);
3397
- __decorateClass([
3398
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "hardware_id", unique: true })
3399
- ], WagoController.prototype, "hardwareId", 2);
3400
- __decorateClass([
3401
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "trust_state" })
3402
- ], WagoController.prototype, "trustState", 2);
3403
- __decorateClass([
3404
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", nullable: true })
3405
- ], WagoController.prototype, "name", 2);
3406
- __decorateClass([
3407
- (0, import_plugins_backend_sdk3.Column)({ type: "integer", name: "mqtt_server_id", nullable: true })
3408
- ], WagoController.prototype, "mqttServerId", 2);
3409
- __decorateClass([
3410
- (0, import_plugins_backend_sdk3.Column)({ type: "integer", name: "credential_mqtt_server_id", nullable: true })
3411
- ], WagoController.prototype, "credentialMqttServerId", 2);
3412
- __decorateClass([
3413
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "credential_epoch", nullable: true })
3414
- ], WagoController.prototype, "credentialEpoch", 2);
3415
- __decorateClass([
3416
- (0, import_plugins_backend_sdk3.Column)({ type: "integer", name: "enrollment_id", nullable: true })
3417
- ], WagoController.prototype, "enrollmentId", 2);
3418
- __decorateClass([
3419
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "pairing_code_hash" })
3420
- ], WagoController.prototype, "pairingCodeHash", 2);
3421
- __decorateClass([
3422
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", nullable: true })
3423
- ], WagoController.prototype, "fingerprint", 2);
3424
- __decorateClass([
3425
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "protocol_version" })
3426
- ], WagoController.prototype, "protocolVersion", 2);
3427
- __decorateClass([
3428
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "runtime_version" })
3429
- ], WagoController.prototype, "runtimeVersion", 2);
3430
- __decorateClass([
3431
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar" })
3432
- ], WagoController.prototype, "capabilities", 2);
3433
- __decorateClass([
3434
- (0, import_plugins_backend_sdk3.Column)({ type: "integer", name: "last_sequence", default: 0 })
3435
- ], WagoController.prototype, "lastSequence", 2);
3436
- __decorateClass([
3437
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "last_heartbeat_at", nullable: true })
3438
- ], WagoController.prototype, "lastHeartbeatAt", 2);
3439
- __decorateClass([
3440
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "last_seen_at" })
3441
- ], WagoController.prototype, "lastSeenAt", 2);
3442
- __decorateClass([
3443
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "compatibility_error", nullable: true })
3444
- ], WagoController.prototype, "compatibilityError", 2);
3445
- __decorateClass([
3446
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "created_at" })
3447
- ], WagoController.prototype, "createdAt", 2);
3448
- __decorateClass([
3449
- (0, import_plugins_backend_sdk3.Column)({ type: "varchar", name: "updated_at" })
3450
- ], WagoController.prototype, "updatedAt", 2);
3451
- WagoController = __decorateClass([
3452
- (0, import_plugins_backend_sdk3.Entity)({ name: "plugin_wago_controllers" })
3453
- ], WagoController);
3454
-
3455
3644
  // backend/commands/handler.ts
3456
- var import_plugins_backend_sdk5 = require("@attraccess/plugins-backend-sdk");
3457
3645
  var import_node_crypto5 = require("node:crypto");
3458
3646
 
3459
- // backend/configuration/draft.entity.ts
3460
- var import_plugins_backend_sdk4 = require("@attraccess/plugins-backend-sdk");
3461
- var WagoConfigurationDraft = class {
3462
- constructor() {
3463
- __publicField(this, "id");
3464
- __publicField(this, "controllerId");
3465
- __publicField(this, "snapshot");
3466
- __publicField(this, "reviewedHash");
3467
- __publicField(this, "presetProvenance");
3468
- __publicField(this, "updatedAt");
3469
- }
3470
- };
3471
- __decorateClass([
3472
- (0, import_plugins_backend_sdk4.PrimaryGeneratedColumn)({ type: "integer" })
3473
- ], WagoConfigurationDraft.prototype, "id", 2);
3474
- __decorateClass([
3475
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", name: "controller_id", unique: true })
3476
- ], WagoConfigurationDraft.prototype, "controllerId", 2);
3477
- __decorateClass([
3478
- (0, import_plugins_backend_sdk4.Column)({ type: "text" })
3479
- ], WagoConfigurationDraft.prototype, "snapshot", 2);
3480
- __decorateClass([
3481
- (0, import_plugins_backend_sdk4.Column)({ type: "varchar", name: "reviewed_hash", nullable: true })
3482
- ], WagoConfigurationDraft.prototype, "reviewedHash", 2);
3483
- __decorateClass([
3484
- (0, import_plugins_backend_sdk4.Column)({ type: "text", name: "preset_provenance", nullable: true })
3485
- ], WagoConfigurationDraft.prototype, "presetProvenance", 2);
3486
- __decorateClass([
3487
- (0, import_plugins_backend_sdk4.Column)({ type: "varchar", name: "updated_at" })
3488
- ], WagoConfigurationDraft.prototype, "updatedAt", 2);
3489
- WagoConfigurationDraft = __decorateClass([
3490
- (0, import_plugins_backend_sdk4.Entity)({ name: "plugin_wago_configuration_drafts" })
3491
- ], WagoConfigurationDraft);
3492
-
3493
3647
  // backend/flow/preview.ts
3494
3648
  var WAGO_FLOW_PREVIEW_SCHEMA = { dynamic: true, type: "object", properties: {}, preview: [] };
3495
3649
  function wagoFlowPreview(config, kind, controller, snapshot, names) {
@@ -3686,15 +3840,13 @@ var WagoCommandHandler = class {
3686
3840
  * resource, a global flow by itself. NULL owner columns must be matched explicitly: `<>` skips them.
3687
3841
  */
3688
3842
  async references(controllerId, channelId2, resourceId, flowId = null) {
3689
- const query = this.dependencies.context.dataSource.getRepository(import_plugins_backend_sdk5.ResourceFlowNode).createQueryBuilder("node").select(["node.id", "node.resourceId", "node.flowId"]).leftJoin("node.flow", "flow").addSelect(["flow.id", "flow.name"]).where("node.type = :type", { type: "plugin.wago.command" }).andWhere("node.data ->> 'controllerId' = :controllerId", { controllerId }).andWhere("node.data ->> 'channelId' = :channelId", { channelId: channelId2 });
3690
- if (flowId !== null) {
3691
- query.andWhere("(node.flowId IS NULL OR node.flowId <> :flowId)", { flowId });
3692
- } else if (resourceId !== null) {
3693
- query.andWhere("(node.resourceId IS NULL OR node.resourceId <> :resourceId)", { resourceId });
3694
- }
3695
- const nodes = await query.getMany();
3843
+ const nodes = await this.dependencies.context.hostData.flows.findNodes({
3844
+ type: "plugin.wago.command",
3845
+ dataEquals: { controllerId, channelId: channelId2 },
3846
+ ...flowId !== null ? { excludeFlowId: flowId } : resourceId !== null ? { excludeResourceId: resourceId } : {}
3847
+ });
3696
3848
  return nodes.map(
3697
- (node) => node.flowId !== null && node.flowId !== void 0 ? `global flow ${node.flow?.name ? JSON.stringify(node.flow.name) : node.flowId} / node ${node.id}` : `resource ${node.resourceId} / node ${node.id}`
3849
+ (node) => node.flowId !== null && node.flowId !== void 0 ? `global flow ${node.flowName ? JSON.stringify(node.flowName) : node.flowId} / node ${node.id}` : `resource ${node.resourceId} / node ${node.id}`
3698
3850
  );
3699
3851
  }
3700
3852
  destroy() {
@@ -3797,7 +3949,7 @@ var WagoCommandHandler = class {
3797
3949
  const controller = await this.cached(
3798
3950
  validationContext,
3799
3951
  `wago-controller:${controllerId}`,
3800
- () => this.dependencies.controllers().findOneBy({ id: controllerId })
3952
+ () => this.dependencies.controllers().get(controllerId)
3801
3953
  );
3802
3954
  if (!controller || controller.trustState !== "claimed")
3803
3955
  return [{ field: "controllerId", message: "Select a claimed WAGO controller." }];
@@ -3832,7 +3984,7 @@ var WagoCommandHandler = class {
3832
3984
  const controllerId = positiveInteger2(config.controllerId);
3833
3985
  const controllers = previewOnly && !controllerId ? [] : await this.dependencies.controllers().find({
3834
3986
  where: { trustState: "claimed", ...previewOnly ? { id: controllerId } : {} },
3835
- order: { name: "ASC" }
3987
+ orderBy: [{ field: "name", direction: "asc" }]
3836
3988
  });
3837
3989
  const revision2 = controllerId ? await this.dependencies.appliedRevision(controllerId) : null;
3838
3990
  const snapshot = revision2 ? JSON.parse(revision2.snapshot) : null;
@@ -3953,7 +4105,7 @@ var WagoCommandHandler = class {
3953
4105
  async channelNames(controllerId, revision2, appliedOnly = false) {
3954
4106
  let names = {};
3955
4107
  if (controllerId) {
3956
- const draft = appliedOnly ? null : await this.dependencies.context.getRepository(WagoConfigurationDraft).findOneBy({ controllerId });
4108
+ const draft = appliedOnly ? null : await openWagoStorage(this.dependencies.context).configurationDrafts.findOne({ where: { controllerId } });
3957
4109
  try {
3958
4110
  const storedNames = JSON.parse(revision2?.presetProvenance ?? draft?.presetProvenance ?? "null")?.editor?.names;
3959
4111
  if (storedNames && typeof storedNames === "object" && !Array.isArray(storedNames)) names = storedNames;
@@ -3967,116 +4119,14 @@ var WagoCommandHandler = class {
3967
4119
  // backend/controllers/registry.ts
3968
4120
  var import_node_crypto6 = require("node:crypto");
3969
4121
 
3970
- // backend/controllers/enrollment.entity.ts
3971
- var import_plugins_backend_sdk6 = require("@attraccess/plugins-backend-sdk");
3972
- var WagoEnrollment = class {
3973
- constructor() {
3974
- __publicField(this, "id");
3975
- __publicField(this, "mqttServerId");
3976
- __publicField(this, "hardwareId");
3977
- __publicField(this, "secretHash");
3978
- __publicField(this, "identity");
3979
- __publicField(this, "createdAt");
3980
- __publicField(this, "expiresAt");
3981
- __publicField(this, "revokedAt");
3982
- __publicField(this, "consumedAt");
3983
- }
3984
- };
3985
- __decorateClass([
3986
- (0, import_plugins_backend_sdk6.PrimaryGeneratedColumn)({ type: "integer" })
3987
- ], WagoEnrollment.prototype, "id", 2);
3988
- __decorateClass([
3989
- (0, import_plugins_backend_sdk6.Column)({ type: "integer", name: "mqtt_server_id" })
3990
- ], WagoEnrollment.prototype, "mqttServerId", 2);
3991
- __decorateClass([
3992
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar", name: "hardware_id" })
3993
- ], WagoEnrollment.prototype, "hardwareId", 2);
3994
- __decorateClass([
3995
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar", name: "secret_hash", unique: true })
3996
- ], WagoEnrollment.prototype, "secretHash", 2);
3997
- __decorateClass([
3998
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar" })
3999
- ], WagoEnrollment.prototype, "identity", 2);
4000
- __decorateClass([
4001
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar", name: "created_at" })
4002
- ], WagoEnrollment.prototype, "createdAt", 2);
4003
- __decorateClass([
4004
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar", name: "expires_at" })
4005
- ], WagoEnrollment.prototype, "expiresAt", 2);
4006
- __decorateClass([
4007
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar", name: "revoked_at", nullable: true })
4008
- ], WagoEnrollment.prototype, "revokedAt", 2);
4009
- __decorateClass([
4010
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar", name: "consumed_at", nullable: true })
4011
- ], WagoEnrollment.prototype, "consumedAt", 2);
4012
- WagoEnrollment = __decorateClass([
4013
- (0, import_plugins_backend_sdk6.Entity)({ name: "plugin_wago_enrollments" })
4014
- ], WagoEnrollment);
4015
-
4016
- // backend/configuration/revision.entity.ts
4017
- var import_plugins_backend_sdk7 = require("@attraccess/plugins-backend-sdk");
4018
- var WagoConfigurationRevision = class {
4019
- constructor() {
4020
- __publicField(this, "id");
4021
- __publicField(this, "controllerId");
4022
- __publicField(this, "revision");
4023
- __publicField(this, "snapshot");
4024
- __publicField(this, "presetProvenance");
4025
- __publicField(this, "contentHash");
4026
- __publicField(this, "state");
4027
- __publicField(this, "rejectionErrors");
4028
- __publicField(this, "rejectionAcknowledgedAt");
4029
- __publicField(this, "rejectionAcknowledgedBy");
4030
- __publicField(this, "publishedAt");
4031
- __publicField(this, "reportedAt");
4032
- }
4033
- };
4034
- __decorateClass([
4035
- (0, import_plugins_backend_sdk7.PrimaryGeneratedColumn)({ type: "integer" })
4036
- ], WagoConfigurationRevision.prototype, "id", 2);
4037
- __decorateClass([
4038
- (0, import_plugins_backend_sdk7.Column)({ type: "integer", name: "controller_id" })
4039
- ], WagoConfigurationRevision.prototype, "controllerId", 2);
4040
- __decorateClass([
4041
- (0, import_plugins_backend_sdk7.Column)({ type: "integer" })
4042
- ], WagoConfigurationRevision.prototype, "revision", 2);
4043
- __decorateClass([
4044
- (0, import_plugins_backend_sdk7.Column)({ type: "text" })
4045
- ], WagoConfigurationRevision.prototype, "snapshot", 2);
4046
- __decorateClass([
4047
- (0, import_plugins_backend_sdk7.Column)({ type: "text", name: "preset_provenance", nullable: true })
4048
- ], WagoConfigurationRevision.prototype, "presetProvenance", 2);
4049
- __decorateClass([
4050
- (0, import_plugins_backend_sdk7.Column)({ type: "varchar", name: "content_hash" })
4051
- ], WagoConfigurationRevision.prototype, "contentHash", 2);
4052
- __decorateClass([
4053
- (0, import_plugins_backend_sdk7.Column)({ type: "varchar" })
4054
- ], WagoConfigurationRevision.prototype, "state", 2);
4055
- __decorateClass([
4056
- (0, import_plugins_backend_sdk7.Column)({ type: "text", name: "rejection_errors", nullable: true })
4057
- ], WagoConfigurationRevision.prototype, "rejectionErrors", 2);
4058
- __decorateClass([
4059
- (0, import_plugins_backend_sdk7.Column)({ type: "varchar", name: "rejection_acknowledged_at", nullable: true })
4060
- ], WagoConfigurationRevision.prototype, "rejectionAcknowledgedAt", 2);
4061
- __decorateClass([
4062
- (0, import_plugins_backend_sdk7.Column)({ type: "integer", name: "rejection_acknowledged_by", nullable: true })
4063
- ], WagoConfigurationRevision.prototype, "rejectionAcknowledgedBy", 2);
4064
- __decorateClass([
4065
- (0, import_plugins_backend_sdk7.Column)({ type: "varchar", name: "published_at" })
4066
- ], WagoConfigurationRevision.prototype, "publishedAt", 2);
4067
- __decorateClass([
4068
- (0, import_plugins_backend_sdk7.Column)({ type: "varchar", name: "reported_at", nullable: true })
4069
- ], WagoConfigurationRevision.prototype, "reportedAt", 2);
4070
- WagoConfigurationRevision = __decorateClass([
4071
- (0, import_plugins_backend_sdk7.Entity)({ name: "plugin_wago_configuration_revisions" })
4072
- ], WagoConfigurationRevision);
4073
-
4074
4122
  // backend/controllers/state.ts
4075
4123
  var import_common5 = require("@nestjs/common");
4076
4124
  var WagoServiceState = class {
4077
4125
  constructor(context) {
4078
4126
  __publicField(this, "context", context);
4079
4127
  __publicField(this, "diagnostics", new WagoDiagnosticsStore());
4128
+ /** The record port of every WAGO table; opened when the application has bootstrapped. */
4129
+ __publicField(this, "storage");
4080
4130
  __publicField(this, "controllers");
4081
4131
  __publicField(this, "networkSubscriptions", /* @__PURE__ */ new Map());
4082
4132
  __publicField(this, "networkSubscriptionRevision", 0);
@@ -4131,28 +4181,34 @@ var WagoRegistry = class extends WagoServiceState {
4131
4181
  throw new import_common6.NotFoundException(`MQTT server ${serverId} not found`);
4132
4182
  const save = async () => {
4133
4183
  const settings2 = await this.getSettings();
4134
- if (serverId !== void 0) settings2.defaultMqttServerId = serverId;
4184
+ const patch = {};
4185
+ if (serverId !== void 0) patch.defaultMqttServerId = serverId;
4135
4186
  if (operationalPrefix !== void 0) {
4136
4187
  const normalizedPrefix = normalizeOperationalPrefix(operationalPrefix);
4137
4188
  if (normalizedPrefix !== settings2.operationalPrefix) {
4138
- const controllers = await this.controllers.find({ where: { trustState: "claimed" } });
4139
- if (controllers.length)
4189
+ if (await this.controllers.count({ trustState: "claimed" }))
4140
4190
  throw new import_common6.ConflictException("operational MQTT prefix cannot change after a controller has been claimed");
4141
- settings2.operationalPrefix = normalizedPrefix;
4191
+ patch.operationalPrefix = normalizedPrefix;
4142
4192
  }
4143
4193
  }
4144
- await this.settings.save(settings2);
4145
- return settings2;
4194
+ if (Object.keys(patch).length) await this.settings.update({ id: settings2.id }, patch);
4195
+ return { ...settings2, ...patch };
4146
4196
  };
4147
4197
  const settings = operationalPrefix === void 0 ? await save() : await this.withClaimConfigurationLock(save);
4148
4198
  await this.subscribeConfiguredServers();
4149
4199
  return settings;
4150
4200
  }
4151
4201
  async getSettings() {
4152
- const settings = await this.settings.findOneBy({ id: 1 });
4202
+ const settings = await this.settings.get(1);
4153
4203
  if (settings) return settings;
4154
- await this.settings.createQueryBuilder().insert().values({ id: 1, defaultMqttServerId: null, operationalPrefix: "attraccess/wago" }).orIgnore().execute();
4155
- return this.settings.findOneByOrFail({ id: 1 });
4204
+ try {
4205
+ return await this.settings.insert({ id: 1, defaultMqttServerId: null, operationalPrefix: "attraccess/wago" });
4206
+ } catch (error) {
4207
+ if (!(error instanceof import_plugins_backend_sdk3.PluginStorageUniqueViolation)) throw error;
4208
+ const existing = await this.settings.get(1);
4209
+ if (!existing) throw error;
4210
+ return existing;
4211
+ }
4156
4212
  }
4157
4213
  async setRuntimePolicy(controllerId, desired, observed, runtimePolicyToken) {
4158
4214
  const previous = this.runtimePolicies.get(controllerId);
@@ -4169,7 +4225,10 @@ var WagoRegistry = class extends WagoServiceState {
4169
4225
  JSON.stringify({ runtimeImageId: desired, runtimePolicyToken }),
4170
4226
  { qos: 1, retain: false }
4171
4227
  );
4172
- const [revision2] = await this.revisions.find({ where: { controllerId }, order: { revision: "DESC" }, take: 1 });
4228
+ const revision2 = await this.revisions.findOne({
4229
+ where: { controllerId },
4230
+ orderBy: [{ field: "revision", direction: "desc" }]
4231
+ });
4173
4232
  const replay = revision2 && (revision2.state === "published" || revision2.state === "applied") ? revision2 : null;
4174
4233
  const unsupported = replay ? runtimeSupportErrors(JSON.parse(replay.snapshot), controller.capabilities) : [];
4175
4234
  if (replay && unsupported.length)
@@ -4207,7 +4266,7 @@ var WagoRegistry = class extends WagoServiceState {
4207
4266
  this.commissioningDiscoveryHandler = handler;
4208
4267
  }
4209
4268
  async list() {
4210
- const controllers = await this.controllers.find({ order: { hardwareId: "ASC" } });
4269
+ const controllers = await this.controllers.find({ orderBy: [{ field: "hardwareId" }] });
4211
4270
  return controllers.map((controller) => ({
4212
4271
  id: controller.id,
4213
4272
  hardwareId: controller.hardwareId,
@@ -4280,12 +4339,13 @@ var WagoRegistry = class extends WagoServiceState {
4280
4339
  this.commands.destroy();
4281
4340
  }
4282
4341
  async onApplicationBootstrap() {
4283
- this.controllers = this.context.getRepository(WagoController);
4284
- this.settings = this.context.getRepository(WagoSettings);
4285
- this.enrollments = this.context.getRepository(WagoEnrollment);
4286
- this.drafts = this.context.getRepository(WagoConfigurationDraft);
4287
- this.revisions = this.context.getRepository(WagoConfigurationRevision);
4288
- const enrollments = await this.enrollments.createQueryBuilder("enrollment").where("enrollment.consumedAt IS NULL").getMany();
4342
+ this.storage = openWagoStorage(this.context);
4343
+ this.controllers = this.storage.controllers;
4344
+ this.settings = this.storage.settings;
4345
+ this.enrollments = this.storage.enrollments;
4346
+ this.drafts = this.storage.configurationDrafts;
4347
+ this.revisions = this.storage.configurationRevisions;
4348
+ const enrollments = await this.enrollments.find({ where: { consumedAt: null } });
4289
4349
  for (const enrollment of enrollments) this.scheduleEnrollmentExpiry(enrollment);
4290
4350
  try {
4291
4351
  await this.subscribeConfiguredServers();
@@ -4353,24 +4413,15 @@ var WagoDrafts = class extends WagoRegistry {
4353
4413
  await this.claimedController(controllerId);
4354
4414
  const pageOffset = Number.isSafeInteger(offset) && offset > 0 ? offset : 0;
4355
4415
  const pageLimit = Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, 100) : 20;
4356
- const revisions = await this.revisions.find({
4416
+ const rows = await this.revisions.find({
4357
4417
  where: { controllerId },
4358
- order: { revision: "DESC" },
4359
- select: [
4360
- "id",
4361
- "controllerId",
4362
- "revision",
4363
- "contentHash",
4364
- "state",
4365
- "rejectionErrors",
4366
- "rejectionAcknowledgedAt",
4367
- "rejectionAcknowledgedBy",
4368
- "publishedAt",
4369
- "reportedAt",
4370
- "presetProvenance"
4371
- ],
4372
- skip: pageOffset,
4373
- take: pageLimit
4418
+ orderBy: [{ field: "revision", direction: "desc" }],
4419
+ offset: pageOffset,
4420
+ limit: pageLimit
4421
+ });
4422
+ const revisions = rows.map(({ snapshot: _snapshot, ...summary }) => {
4423
+ void _snapshot;
4424
+ return summary;
4374
4425
  });
4375
4426
  return { revisions, offset: pageOffset, limit: pageLimit };
4376
4427
  }
@@ -4433,7 +4484,7 @@ var WagoDrafts = class extends WagoRegistry {
4433
4484
  }
4434
4485
  ]);
4435
4486
  draft.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4436
- return this.drafts.save(draft);
4487
+ return this.storeDraft(draft);
4437
4488
  };
4438
4489
  return principal ? new WagoAudit(this.context).run(
4439
4490
  principal,
@@ -4447,7 +4498,7 @@ var WagoDrafts = class extends WagoRegistry {
4447
4498
  }
4448
4499
  async draftForPreset(controllerId) {
4449
4500
  await this.claimedController(controllerId);
4450
- const draft = await this.drafts.findOneBy({ controllerId });
4501
+ const draft = await this.drafts.findOne({ where: { controllerId } });
4451
4502
  if (!draft) throw new import_common7.NotFoundException(`WAGO controller ${controllerId} has no configuration draft`);
4452
4503
  return draft;
4453
4504
  }
@@ -4536,21 +4587,33 @@ var WagoDrafts = class extends WagoRegistry {
4536
4587
  await this.claimedController(controllerId);
4537
4588
  const [revision2] = await this.revisions.find({
4538
4589
  where: { controllerId, state: "applied" },
4539
- order: { revision: "DESC" },
4540
- take: 1
4590
+ orderBy: [{ field: "revision", direction: "desc" }],
4591
+ limit: 1
4541
4592
  });
4542
4593
  return revision2 ?? null;
4543
4594
  }
4595
+ /** Stores the draft: one per controller, created on first save. */
4596
+ storeDraft(draft, scope) {
4597
+ return this.drafts.upsert(draft, {
4598
+ conflictOn: ["controllerId"],
4599
+ update: ["snapshot", "reviewedHash", "presetProvenance", "updatedAt"],
4600
+ scope
4601
+ });
4602
+ }
4544
4603
  async getDraft(controllerId) {
4545
4604
  await this.claimedController(controllerId);
4546
- return this.drafts.findOneBy({ controllerId });
4605
+ return this.drafts.findOne({ where: { controllerId } });
4547
4606
  }
4548
4607
  };
4549
4608
 
4550
4609
  // backend/configuration/revisions.ts
4551
4610
  var WagoRevisions = class extends WagoDrafts {
4552
4611
  async latestRevision(controllerId) {
4553
- const [revision2] = await this.revisions.find({ where: { controllerId }, order: { revision: "DESC" }, take: 1 });
4612
+ const [revision2] = await this.revisions.find({
4613
+ where: { controllerId },
4614
+ orderBy: [{ field: "revision", direction: "desc" }],
4615
+ limit: 1
4616
+ });
4554
4617
  return revision2 ?? null;
4555
4618
  }
4556
4619
  async auditRevision(lifecycle, operation, allocated) {
@@ -4567,7 +4630,7 @@ var WagoRevisions = class extends WagoDrafts {
4567
4630
  async publishDraftWhileLocked(controllerId, force = false, reviewedHash, principal, preparedDraft, onAllocated) {
4568
4631
  const controller = await this.claimedController(controllerId);
4569
4632
  this.requireConfigurationCompatibility(controller);
4570
- const draft = preparedDraft ?? await this.drafts.findOneBy({ controllerId });
4633
+ const draft = preparedDraft ?? await this.drafts.findOne({ where: { controllerId } });
4571
4634
  if (!draft) throw new import_common8.NotFoundException(`WAGO controller ${controllerId} has no configuration draft`);
4572
4635
  const validation = validateEditorSnapshot(JSON.parse(draft.snapshot));
4573
4636
  if (validation.length)
@@ -4596,21 +4659,32 @@ var WagoRevisions = class extends WagoDrafts {
4596
4659
  };
4597
4660
  const lifecycle = principal ? new WagoAudit(this.context).begin(principal, controllerId, force ? "forced_publication" : "publication") : void 0;
4598
4661
  const persist = async () => {
4599
- if (preparedDraft) await this.drafts.save(preparedDraft);
4600
- if (previous?.state === "pending" && previous.contentHash === contentHash && (previous.presetProvenance ?? null) === (draft.presetProvenance ?? null))
4601
- return dispatch(previous);
4602
- const revision2 = this.revisions.create({
4603
- controllerId,
4604
- revision: (previous?.revision ?? 0) + 1,
4605
- snapshot: draft.snapshot,
4606
- presetProvenance: draft.presetProvenance ?? null,
4607
- contentHash,
4608
- state: "pending",
4609
- rejectionErrors: null,
4610
- publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
4611
- reportedAt: null
4662
+ const stored = await this.context.persistence.transaction(async (scope) => {
4663
+ if (preparedDraft) await this.storeDraft(preparedDraft, scope);
4664
+ if (previous?.state === "pending" && previous.contentHash === contentHash && (previous.presetProvenance ?? null) === (draft.presetProvenance ?? null))
4665
+ return previous;
4666
+ try {
4667
+ return await this.revisions.insert(
4668
+ {
4669
+ controllerId,
4670
+ revision: (previous?.revision ?? 0) + 1,
4671
+ snapshot: draft.snapshot,
4672
+ presetProvenance: draft.presetProvenance ?? null,
4673
+ contentHash,
4674
+ state: "pending",
4675
+ rejectionErrors: null,
4676
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
4677
+ reportedAt: null
4678
+ },
4679
+ { scope }
4680
+ );
4681
+ } catch (error) {
4682
+ if (error instanceof import_plugins_backend_sdk4.PluginStorageUniqueViolation)
4683
+ throw new import_common8.ConflictException("configuration changed while publishing; review it again");
4684
+ throw error;
4685
+ }
4612
4686
  });
4613
- return dispatch(await this.revisions.save(revision2));
4687
+ return dispatch(stored);
4614
4688
  };
4615
4689
  return this.auditRevision(lifecycle, persist, () => allocatedRevision);
4616
4690
  }
@@ -4623,7 +4697,7 @@ var WagoRevisions = class extends WagoDrafts {
4623
4697
  }
4624
4698
  async reviewDraftWhileLocked(controllerId) {
4625
4699
  await this.claimedController(controllerId);
4626
- const draft = await this.drafts.findOneBy({ controllerId });
4700
+ const draft = await this.drafts.findOne({ where: { controllerId } });
4627
4701
  if (!draft) throw new import_common8.NotFoundException(`WAGO controller ${controllerId} has no configuration draft`);
4628
4702
  const previous = await this.latestRevision(controllerId);
4629
4703
  const impacts = await configurationFlowImpacts(
@@ -4633,7 +4707,7 @@ var WagoRevisions = class extends WagoDrafts {
4633
4707
  JSON.parse(draft.snapshot)
4634
4708
  );
4635
4709
  draft.reviewedHash = this.reviewIdentity(draft, previous, impacts);
4636
- await this.drafts.save(draft);
4710
+ await this.drafts.update({ id: draft.id }, { reviewedHash: draft.reviewedHash });
4637
4711
  const diff = configurationDiff(previous ? JSON.parse(previous.snapshot) : null, JSON.parse(draft.snapshot));
4638
4712
  const metadataDiff = configurationDiff(
4639
4713
  this.metadataFromProvenance(previous?.presetProvenance),
@@ -4659,19 +4733,19 @@ var WagoRevisions = class extends WagoDrafts {
4659
4733
  }
4660
4734
  }
4661
4735
  const serialized = canonicalSnapshot(snapshot);
4662
- const existing = await this.drafts.findOneBy({ controllerId });
4663
- const draft = existing ?? this.drafts.create({
4736
+ const existing = await this.drafts.findOne({ where: { controllerId } });
4737
+ const draft = existing ?? {
4664
4738
  controllerId,
4665
4739
  snapshot: serialized,
4666
4740
  reviewedHash: null,
4667
4741
  presetProvenance: null,
4668
4742
  updatedAt: ""
4669
- });
4743
+ };
4670
4744
  draft.snapshot = serialized;
4671
4745
  if (provenance !== void 0) draft.presetProvenance = provenance;
4672
4746
  draft.reviewedHash = null;
4673
4747
  draft.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4674
- return this.drafts.save(draft);
4748
+ return this.storeDraft(draft);
4675
4749
  }
4676
4750
  metadataFromProvenance(provenance) {
4677
4751
  if (!provenance) return { names: {}, presets: [] };
@@ -4713,10 +4787,14 @@ var WagoRevisions = class extends WagoDrafts {
4713
4787
  async previewRevision(controllerId, revision2) {
4714
4788
  return this.withConfigurationLock(controllerId, async () => {
4715
4789
  const controller = await this.claimedController(controllerId);
4716
- const selected = await this.revisions.findOneBy({ controllerId, revision: revision2 });
4790
+ const selected = await this.revisions.findOne({ where: { controllerId, revision: revision2 } });
4717
4791
  if (!selected) throw new import_common8.NotFoundException(`WAGO configuration revision ${revision2} not found`);
4718
- const [current] = await this.revisions.find({ where: { controllerId }, order: { revision: "DESC" }, take: 1 });
4719
- const draft = await this.drafts.findOneBy({ controllerId });
4792
+ const [current] = await this.revisions.find({
4793
+ where: { controllerId },
4794
+ orderBy: [{ field: "revision", direction: "desc" }],
4795
+ limit: 1
4796
+ });
4797
+ const draft = await this.drafts.findOne({ where: { controllerId } });
4720
4798
  const snapshot = JSON.parse(selected.snapshot);
4721
4799
  const impacts = await configurationFlowImpacts(
4722
4800
  this.context,
@@ -4742,7 +4820,7 @@ var WagoRevisions = class extends WagoDrafts {
4742
4820
  async acknowledgeRejection(controllerId, revision2, expected, principal) {
4743
4821
  return this.withConfigurationLock(controllerId, async () => {
4744
4822
  await this.claimedController(controllerId);
4745
- const rejected = await this.revisions.findOneBy({ controllerId, revision: revision2 });
4823
+ const rejected = await this.revisions.findOne({ where: { controllerId, revision: revision2 } });
4746
4824
  if (!rejected) throw new import_common8.NotFoundException(`WAGO configuration revision ${revision2} not found`);
4747
4825
  if (rejected.state !== "rejected" || !rejected.reportedAt || expected.contentHash !== rejected.contentHash || expected.reportedAt !== rejected.reportedAt)
4748
4826
  throw new import_common8.ConflictException("rejection changed; refresh and review it before acknowledging");
@@ -4753,11 +4831,21 @@ var WagoRevisions = class extends WagoDrafts {
4753
4831
  "rejection_acknowledgement",
4754
4832
  { revision: revision2 },
4755
4833
  async () => {
4756
- return this.revisions.save({
4757
- ...rejected,
4834
+ const acknowledged = {
4758
4835
  rejectionAcknowledgedAt: (/* @__PURE__ */ new Date()).toISOString(),
4759
4836
  rejectionAcknowledgedBy: principal.userId
4760
- });
4837
+ };
4838
+ const changed = await this.revisions.update(
4839
+ {
4840
+ id: rejected.id,
4841
+ state: "rejected",
4842
+ reportedAt: rejected.reportedAt,
4843
+ rejectionAcknowledgedAt: { isNull: true }
4844
+ },
4845
+ acknowledged
4846
+ );
4847
+ if (!changed) throw new import_common8.ConflictException("rejection changed; refresh and review it before acknowledging");
4848
+ return { ...rejected, ...acknowledged };
4761
4849
  }
4762
4850
  );
4763
4851
  });
@@ -4766,10 +4854,10 @@ var WagoRevisions = class extends WagoDrafts {
4766
4854
  return this.withConfigurationLock(controllerId, async () => {
4767
4855
  const controller = await this.claimedController(controllerId);
4768
4856
  this.requireConfigurationCompatibility(controller);
4769
- const source = await this.revisions.findOneBy({ controllerId, revision: revision2 });
4857
+ const source = await this.revisions.findOne({ where: { controllerId, revision: revision2 } });
4770
4858
  if (!source) throw new import_common8.NotFoundException(`WAGO configuration revision ${revision2} not found`);
4771
4859
  const current = await this.latestRevision(controllerId);
4772
- const draft = await this.drafts.findOneBy({ controllerId });
4860
+ const draft = await this.drafts.findOne({ where: { controllerId } });
4773
4861
  const snapshot = JSON.parse(source.snapshot);
4774
4862
  const errors = validateEditorSnapshot(snapshot);
4775
4863
  if (errors.length) throw new import_common8.ConflictException({ message: "rollback configuration is invalid", errors });
@@ -4801,7 +4889,7 @@ var WagoRevisions = class extends WagoDrafts {
4801
4889
  snapshot
4802
4890
  )
4803
4891
  );
4804
- const replacement = this.drafts.create({
4892
+ const replacement = {
4805
4893
  ...draft,
4806
4894
  controllerId,
4807
4895
  snapshot: canonicalSnapshot(snapshot),
@@ -4815,7 +4903,7 @@ var WagoRevisions = class extends WagoDrafts {
4815
4903
  }),
4816
4904
  reviewedHash: null,
4817
4905
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4818
- });
4906
+ };
4819
4907
  const approvedHash = this.reviewIdentity(replacement, current, approvedImpacts);
4820
4908
  replacement.reviewedHash = approvedHash;
4821
4909
  return this.publishDraftWhileLocked(controllerId, force, approvedHash, void 0, replacement, (value) => {
@@ -4845,6 +4933,8 @@ var WagoControllerEnrollment = class extends WagoRevisions {
4845
4933
  previousController
4846
4934
  }, assertOwned = async () => void 0) {
4847
4935
  await assertOwned();
4936
+ const epoch = controller.credentialEpoch;
4937
+ if (!epoch || await this.claimTakenOver(controller, epoch)) return;
4848
4938
  const manual = await this.context.getMqttCredentialProvisioning().revoke({ mqttServerId, identity, username: identity, vhost: "/" });
4849
4939
  if (manual) throw new import_common9.ConflictException("Manual permanent credential revocation is required.");
4850
4940
  await assertOwned();
@@ -4852,12 +4942,29 @@ var WagoControllerEnrollment = class extends WagoRevisions {
4852
4942
  controller.credentialEpoch = null;
4853
4943
  Object.assign(controller, previousController);
4854
4944
  await assertOwned();
4855
- await this.controllers.save(controller).catch((rollbackError) => {
4945
+ await this.controllers.update(
4946
+ { id: controller.id, credentialEpoch: epoch },
4947
+ { credentialMqttServerId: null, credentialEpoch: null, ...previousController }
4948
+ ).catch((rollbackError) => {
4856
4949
  this.context.logger.warn(
4857
4950
  `Could not restore WAGO controller ${controller.id} after claim failure: ${String(rollbackError)}`
4858
4951
  );
4859
4952
  });
4860
4953
  }
4954
+ /**
4955
+ * Whether another claim owns the broker identity now. When the row is gone (removed while this claim ran), the
4956
+ * identity this claim provisioned is still revoked, unless a new registration of the hardware already carries a
4957
+ * claim of its own.
4958
+ */
4959
+ async claimTakenOver(controller, epoch) {
4960
+ const current = await this.controllers.get(controller.id);
4961
+ if (current) return current.credentialEpoch !== epoch;
4962
+ const reclaimed = await this.controllers.count({
4963
+ hardwareId: controller.hardwareId,
4964
+ credentialEpoch: { isNull: false }
4965
+ });
4966
+ return reclaimed > 0;
4967
+ }
4861
4968
  async restoreUnclaimedController({
4862
4969
  controller,
4863
4970
  mqttServerId,
@@ -4876,8 +4983,17 @@ var WagoControllerEnrollment = class extends WagoRevisions {
4876
4983
  )
4877
4984
  );
4878
4985
  }
4986
+ /**
4987
+ * Writes claim fields of a controller that is still untrusted and still carries `credentialEpoch` (the epoch this
4988
+ * claim read, or the one it wrote). A controller claimed meanwhile, or taken over by a concurrent claim on another
4989
+ * instance, is a conflict; the caller then owns nothing to roll back.
4990
+ */
4991
+ async requireUnclaimedUpdate(id, credentialEpoch, patch) {
4992
+ if (!await this.controllers.update({ id, trustState: "untrusted", credentialEpoch }, patch))
4993
+ throw new import_common9.ConflictException("controller has already been claimed");
4994
+ }
4879
4995
  async prepareClaim(id, name, verifier, mqttServerId, assertOwned = async () => void 0, manualCredentials) {
4880
- const controller = await this.controllers.findOneBy({ id });
4996
+ const controller = await this.controllers.get(id);
4881
4997
  if (!controller) throw new import_common9.NotFoundException(`WAGO controller ${id} not found`);
4882
4998
  if (controller.trustState === "claimed") throw new import_common9.ConflictException("controller has already been claimed");
4883
4999
  if (!name.trim()) throw new import_common9.ConflictException("a controller name is required");
@@ -4907,9 +5023,13 @@ var WagoControllerEnrollment = class extends WagoRevisions {
4907
5023
  "Remove the controller registration to revoke its unfinished permanent credential before claiming again."
4908
5024
  );
4909
5025
  await assertOwned();
5026
+ const readEpoch = controller.credentialEpoch;
4910
5027
  controller.credentialMqttServerId = selectedServerId;
4911
5028
  controller.credentialEpoch = (0, import_node_crypto7.randomUUID)();
4912
- await this.controllers.save(controller);
5029
+ await this.requireUnclaimedUpdate(controller.id, readEpoch, {
5030
+ credentialMqttServerId: controller.credentialMqttServerId,
5031
+ credentialEpoch: controller.credentialEpoch
5032
+ });
4913
5033
  await assertOwned();
4914
5034
  const provisioned = manualCredentials ?? await this.context.getMqttCredentialProvisioning().provision({
4915
5035
  mqttServerId: selectedServerId,
@@ -4940,7 +5060,12 @@ var WagoControllerEnrollment = class extends WagoRevisions {
4940
5060
  controller.name = name.trim();
4941
5061
  controller.mqttServerId = selectedServerId;
4942
5062
  controller.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4943
- await this.controllers.save(controller);
5063
+ await this.requireUnclaimedUpdate(controller.id, controller.credentialEpoch, {
5064
+ trustState: "claimed",
5065
+ name: controller.name,
5066
+ mqttServerId: controller.mqttServerId,
5067
+ updatedAt: controller.updatedAt
5068
+ });
4944
5069
  return {
4945
5070
  controller,
4946
5071
  enrollment,
@@ -5021,7 +5146,7 @@ var WagoControllerEnrollment = class extends WagoRevisions {
5021
5146
  });
5022
5147
  }
5023
5148
  async completeManualCredentials(id, input, principal, assertOwned = async () => void 0) {
5024
- const controller = await this.controllers.findOneBy({ id });
5149
+ const controller = await this.controllers.get(id);
5025
5150
  if (!controller) throw new import_common9.NotFoundException("controller not found");
5026
5151
  if (input.username !== `wago-controller-${controller.hardwareId}` || !input.password || input.password.length > 4096)
5027
5152
  throw new import_common9.BadRequestException("Supply the controller identity and provisioned password");
@@ -5084,7 +5209,7 @@ var WagoControllerEnrollment = class extends WagoRevisions {
5084
5209
  return this.withClaimLock(
5085
5210
  id,
5086
5211
  () => this.withClaimConfigurationLock(async () => {
5087
- const controller = await this.controllers.findOneBy({ id });
5212
+ const controller = await this.controllers.get(id);
5088
5213
  if (!controller) throw new import_common9.NotFoundException(`WAGO controller ${id} not found`);
5089
5214
  const credentialServerId = controller.credentialMqttServerId ?? (controller.trustState === "claimed" ? controller.mqttServerId : null);
5090
5215
  if (credentialServerId) {
@@ -5101,9 +5226,11 @@ var WagoControllerEnrollment = class extends WagoRevisions {
5101
5226
  }
5102
5227
  if (controller.enrollmentId) await this.revokeEnrollmentById(controller.enrollmentId, assertOwned);
5103
5228
  await assertOwned();
5104
- await Promise.all([this.drafts.delete({ controllerId: id }), this.revisions.delete({ controllerId: id })]);
5105
- await assertOwned();
5106
- await this.controllers.delete(id);
5229
+ await this.context.persistence.transaction(async (scope) => {
5230
+ await this.drafts.delete({ controllerId: id }, { scope });
5231
+ await this.revisions.delete({ controllerId: id }, { scope });
5232
+ await this.controllers.delete({ id }, { scope });
5233
+ });
5107
5234
  this.configurationReportQueues.delete(id);
5108
5235
  await this.subscribeConfiguredServers().catch((error) => {
5109
5236
  this.context.logger.warn(
@@ -5117,11 +5244,11 @@ var WagoControllerEnrollment = class extends WagoRevisions {
5117
5244
  }
5118
5245
  async deleteEnrollmentById(id, assertOwned = async () => void 0) {
5119
5246
  await assertOwned();
5120
- await this.enrollments.delete(id);
5247
+ await this.enrollments.delete({ id });
5121
5248
  }
5122
5249
  /** Server-side commissioning revokes the enrollment it created without exposing credentials to a browser. */
5123
5250
  async revokeEnrollmentById(id, assertOwned = async () => void 0) {
5124
- const enrollment = await this.enrollments.findOneBy({ id });
5251
+ const enrollment = await this.enrollments.get(id);
5125
5252
  if (enrollment && !enrollment.consumedAt) await this.revokeEnrollment(enrollment, assertOwned);
5126
5253
  }
5127
5254
  async createEnrollment(hardwareId, mqttServerId, manualCredentials, assertOwned = async () => void 0) {
@@ -5136,16 +5263,14 @@ var WagoControllerEnrollment = class extends WagoRevisions {
5136
5263
  const identity = `wago-enrollment-${(0, import_node_crypto7.randomBytes)(8).toString("hex")}`;
5137
5264
  const expiresAt = new Date(Date.now() + 15 * 6e4).toISOString();
5138
5265
  await assertOwned();
5139
- const enrollment = await this.enrollments.save(
5140
- this.enrollments.create({
5141
- mqttServerId: selectedServerId,
5142
- hardwareId: normalizedHardwareId,
5143
- secretHash: hash(claimSecret),
5144
- identity,
5145
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
5146
- expiresAt
5147
- })
5148
- );
5266
+ const enrollment = await this.enrollments.insert({
5267
+ mqttServerId: selectedServerId,
5268
+ hardwareId: normalizedHardwareId,
5269
+ secretHash: hash(claimSecret),
5270
+ identity,
5271
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
5272
+ expiresAt
5273
+ });
5149
5274
  this.scheduleEnrollmentExpiry(enrollment);
5150
5275
  await assertOwned();
5151
5276
  const provisionedCredential = await this.context.getMqttCredentialProvisioning().provision({
@@ -5163,7 +5288,7 @@ var WagoControllerEnrollment = class extends WagoRevisions {
5163
5288
  const timer = this.enrollmentExpiryTimers.get(enrollment.id);
5164
5289
  if (timer) clearTimeout(timer);
5165
5290
  this.enrollmentExpiryTimers.delete(enrollment.id);
5166
- await this.enrollments.delete(enrollment.id);
5291
+ await this.enrollments.delete({ id: enrollment.id });
5167
5292
  throw new import_common9.ConflictException(
5168
5293
  `Manual discovery credentials are required: ${provisionedCredential.instructions.join(" ")}`
5169
5294
  );
@@ -5174,7 +5299,7 @@ var WagoControllerEnrollment = class extends WagoRevisions {
5174
5299
  await assertOwned();
5175
5300
  if (!("password" in provisionedCredential)) {
5176
5301
  enrollment.identity = credential.username;
5177
- await this.enrollments.save(enrollment);
5302
+ await this.enrollments.update({ id: enrollment.id }, { identity: enrollment.identity });
5178
5303
  }
5179
5304
  await this.subscribeConfiguredServers().catch((error) => {
5180
5305
  this.context.logger.warn(`Could not refresh WAGO MQTT subscriptions after enrollment: ${String(error)}`);
@@ -5201,7 +5326,7 @@ var WagoSubscriptions = class extends WagoControllerEnrollment {
5201
5326
  if (!parsed) return;
5202
5327
  const { heartbeat, rawHeartbeat } = parsed;
5203
5328
  const canonical = canonicalEnvelope(rawHeartbeat, "heartbeat");
5204
- const controller = await this.controllers.findOneBy({ hardwareId });
5329
+ const controller = await this.controllers.findOne({ where: { hardwareId } });
5205
5330
  if (!controller || controller.trustState !== "claimed" || !canonical && heartbeat.sequence !== void 0 && heartbeat.sequence < controller.lastSequence)
5206
5331
  return;
5207
5332
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -5254,26 +5379,40 @@ var WagoSubscriptions = class extends WagoControllerEnrollment {
5254
5379
  controller.lastSequence = this.diagnostics.read(controller.id).legacyHeartbeatSequence ?? controller.lastSequence;
5255
5380
  controller.lastHeartbeatAt = now;
5256
5381
  } else {
5257
- controller.lastHeartbeatAt = heartbeatAt;
5382
+ controller.lastHeartbeatAt = heartbeatAt ?? controller.lastHeartbeatAt;
5258
5383
  }
5259
5384
  controller.lastSeenAt = now;
5260
5385
  controller.compatibilityError = compatibilityError(heartbeat);
5261
5386
  controller.updatedAt = now;
5262
- await this.controllers.save({
5263
- id: controller.id,
5264
- protocolVersion: controller.protocolVersion,
5265
- runtimeVersion: controller.runtimeVersion,
5266
- capabilities: controller.capabilities,
5267
- lastSequence: controller.lastSequence,
5268
- lastHeartbeatAt: controller.lastHeartbeatAt,
5269
- lastSeenAt: controller.lastSeenAt,
5270
- compatibilityError: controller.compatibilityError,
5271
- updatedAt: controller.updatedAt
5272
- });
5387
+ await this.controllers.update(
5388
+ { id: controller.id },
5389
+ {
5390
+ protocolVersion: controller.protocolVersion,
5391
+ runtimeVersion: controller.runtimeVersion,
5392
+ capabilities: controller.capabilities,
5393
+ lastSequence: controller.lastSequence,
5394
+ lastHeartbeatAt: controller.lastHeartbeatAt,
5395
+ lastSeenAt: controller.lastSeenAt,
5396
+ compatibilityError: controller.compatibilityError,
5397
+ updatedAt: controller.updatedAt
5398
+ }
5399
+ );
5273
5400
  }
5274
5401
  async onDiscovery(serverId, topic, payload) {
5275
5402
  const hardwareId = topic.slice(`${DISCOVERY_ROOT}/`.length);
5276
5403
  if (!isValidHardwareId(hardwareId)) return;
5404
+ const announcement = this.readAnnouncement(topic, hardwareId, payload);
5405
+ if (!announcement) return;
5406
+ const enrollment = await this.announcedEnrollment(announcement, serverId, hardwareId, topic);
5407
+ if (!enrollment) return;
5408
+ const existing = await this.controllers.findOne({ where: { hardwareId } });
5409
+ if (existing?.trustState === "claimed") return;
5410
+ const stored = await this.storeDiscovered(existing, announcement, enrollment, serverId);
5411
+ if (stored === "raced") return this.onDiscovery(serverId, topic, payload);
5412
+ if (stored) await this.offerDiscoveredController(stored);
5413
+ }
5414
+ /** The valid announcement of a discovery message, or null (with a warning) when it must be ignored. */
5415
+ readAnnouncement(topic, hardwareId, payload) {
5277
5416
  let announcement;
5278
5417
  try {
5279
5418
  announcement = parseAnnouncement(payload);
@@ -5281,58 +5420,68 @@ var WagoSubscriptions = class extends WagoControllerEnrollment {
5281
5420
  this.context.logger.warn(
5282
5421
  `Ignoring invalid WAGO announcement: ${error instanceof Error ? error.message : String(error)}`
5283
5422
  );
5284
- return;
5285
- }
5286
- if (announcement.hardwareId !== hardwareId) {
5287
- this.context.logger.warn(`Ignoring WAGO announcement with mismatched hardware ID on ${topic}`);
5288
- return;
5423
+ return null;
5289
5424
  }
5425
+ if (announcement.hardwareId === hardwareId) return announcement;
5426
+ this.context.logger.warn(`Ignoring WAGO announcement with mismatched hardware ID on ${topic}`);
5427
+ return null;
5428
+ }
5429
+ async announcedEnrollment(announcement, serverId, hardwareId, topic) {
5290
5430
  const enrollment = announcement.enrollmentSecret ? await this.validEnrollment(announcement.enrollmentSecret, serverId, hardwareId) : null;
5291
5431
  if (!enrollment) {
5292
5432
  this.context.logger.warn(`Ignoring WAGO announcement without a valid enrollment secret on ${topic}`);
5293
- return;
5294
5433
  }
5295
- const existing = await this.controllers.findOneBy({ hardwareId });
5296
- if (existing?.trustState === "claimed") return;
5434
+ return enrollment;
5435
+ }
5436
+ /**
5437
+ * Records the announcement as an untrusted controller. Returns the stored controller, null when a concurrent claim
5438
+ * won the race, or 'raced' when a concurrent announcement inserted the controller first.
5439
+ */
5440
+ async storeDiscovered(existing, announcement, enrollment, serverId) {
5297
5441
  const now = (/* @__PURE__ */ new Date()).toISOString();
5298
- const candidate = existing ?? this.controllers.create({
5299
- hardwareId,
5300
- trustState: "untrusted",
5301
- name: null,
5442
+ const discovered = {
5302
5443
  mqttServerId: serverId,
5303
5444
  enrollmentId: enrollment.id,
5304
- pairingCodeHash: "",
5305
- fingerprint: null,
5306
- protocolVersion: "",
5307
- runtimeVersion: "",
5308
- capabilities: "[]",
5309
- lastSequence: 0,
5310
- lastHeartbeatAt: null,
5445
+ pairingCodeHash: hash(announcement.pairingCode),
5446
+ fingerprint: announcement.fingerprint ?? null,
5447
+ protocolVersion: announcement.protocolVersion,
5448
+ runtimeVersion: announcement.runtimeVersion,
5449
+ capabilities: JSON.stringify(announcement.capabilities),
5311
5450
  lastSeenAt: now,
5312
- compatibilityError: null,
5313
- createdAt: now,
5451
+ compatibilityError: compatibilityError(announcement),
5314
5452
  updatedAt: now
5315
- });
5316
- candidate.mqttServerId = serverId;
5317
- candidate.enrollmentId = enrollment.id;
5318
- candidate.pairingCodeHash = hash(announcement.pairingCode);
5319
- candidate.fingerprint = announcement.fingerprint ?? null;
5320
- candidate.protocolVersion = announcement.protocolVersion;
5321
- candidate.runtimeVersion = announcement.runtimeVersion;
5322
- candidate.capabilities = JSON.stringify(announcement.capabilities);
5323
- candidate.lastSequence = announcement.sequence ?? candidate.lastSequence;
5324
- candidate.lastSeenAt = now;
5325
- candidate.compatibilityError = compatibilityError(announcement);
5326
- candidate.updatedAt = now;
5327
- await this.controllers.save(candidate);
5328
- if (this.commissioningDiscoveryHandler) {
5329
- try {
5330
- await this.commissioningDiscoveryHandler(candidate);
5331
- } catch (error) {
5332
- this.context.logger.warn(
5333
- `Could not automatically claim commissioned WAGO controller ${candidate.hardwareId}: ${String(error)}`
5334
- );
5335
- }
5453
+ };
5454
+ if (existing) {
5455
+ const lastSequence = announcement.sequence ?? existing.lastSequence;
5456
+ const updated = await this.controllers.update(
5457
+ { id: existing.id, trustState: "untrusted" },
5458
+ { ...discovered, lastSequence }
5459
+ );
5460
+ return updated ? { ...existing, ...discovered, lastSequence } : null;
5461
+ }
5462
+ try {
5463
+ return await this.controllers.insert({
5464
+ ...discovered,
5465
+ hardwareId: announcement.hardwareId,
5466
+ trustState: "untrusted",
5467
+ name: null,
5468
+ lastSequence: announcement.sequence ?? 0,
5469
+ lastHeartbeatAt: null,
5470
+ createdAt: now
5471
+ });
5472
+ } catch (error) {
5473
+ if (error instanceof import_plugins_backend_sdk5.PluginStorageUniqueViolation) return "raced";
5474
+ throw error;
5475
+ }
5476
+ }
5477
+ async offerDiscoveredController(candidate) {
5478
+ if (!this.commissioningDiscoveryHandler) return;
5479
+ try {
5480
+ await this.commissioningDiscoveryHandler(candidate);
5481
+ } catch (error) {
5482
+ this.context.logger.warn(
5483
+ `Could not automatically claim commissioned WAGO controller ${candidate.hardwareId}: ${String(error)}`
5484
+ );
5336
5485
  }
5337
5486
  }
5338
5487
  isActiveSubscriptionGeneration(generation) {
@@ -5522,7 +5671,7 @@ var WagoService = class extends WagoSubscriptions {
5522
5671
  }
5523
5672
  }
5524
5673
  async claimedController(id) {
5525
- const controller = await this.controllers.findOneBy({ id });
5674
+ const controller = await this.controllers.get(id);
5526
5675
  if (!controller || controller.trustState !== "claimed")
5527
5676
  throw new import_common10.NotFoundException(`claimed WAGO controller ${id} not found`);
5528
5677
  if (!controller.mqttServerId) throw new import_common10.ConflictException(`WAGO controller ${id} has no MQTT server`);
@@ -5575,11 +5724,11 @@ var WagoService = class extends WagoSubscriptions {
5575
5724
  throw new import_common10.ConflictException(`Manual credential revocation is required: ${manual.instructions.join(" ")}`);
5576
5725
  await assertOwned();
5577
5726
  enrollment.revokedAt = (/* @__PURE__ */ new Date()).toISOString();
5578
- await this.enrollments.save(enrollment);
5727
+ await this.enrollments.update({ id: enrollment.id }, { revokedAt: enrollment.revokedAt });
5579
5728
  }
5580
5729
  await assertOwned();
5581
5730
  enrollment.consumedAt = (/* @__PURE__ */ new Date()).toISOString();
5582
- await this.enrollments.save(enrollment);
5731
+ await this.enrollments.update({ id: enrollment.id }, { consumedAt: enrollment.consumedAt });
5583
5732
  const timer = this.enrollmentExpiryTimers.get(enrollment.id);
5584
5733
  if (timer) clearTimeout(timer);
5585
5734
  this.enrollmentExpiryTimers.delete(enrollment.id);
@@ -5609,18 +5758,18 @@ var WagoService = class extends WagoSubscriptions {
5609
5758
  return !enrollment.consumedAt && !enrollment.revokedAt && Date.parse(enrollment.expiresAt) > Date.now();
5610
5759
  }
5611
5760
  activeEnrollments() {
5612
- return this.enrollments.createQueryBuilder("enrollment").where("enrollment.consumedAt IS NULL").andWhere("enrollment.revokedAt IS NULL").andWhere("enrollment.expiresAt > :now", { now: (/* @__PURE__ */ new Date()).toISOString() }).getMany();
5761
+ return this.enrollments.find({
5762
+ where: { consumedAt: null, revokedAt: null, expiresAt: { gt: (/* @__PURE__ */ new Date()).toISOString() } }
5763
+ });
5613
5764
  }
5614
5765
  async activeEnrollment(id) {
5615
5766
  if (!id) return null;
5616
- const enrollment = await this.enrollments.findOneBy({ id });
5767
+ const enrollment = await this.enrollments.get(id);
5617
5768
  return enrollment && this.isActiveEnrollment(enrollment) ? enrollment : null;
5618
5769
  }
5619
5770
  async validEnrollment(secret, serverId, hardwareId) {
5620
- const enrollment = await this.enrollments.findOneBy({
5621
- secretHash: hash(secret),
5622
- mqttServerId: serverId,
5623
- hardwareId
5771
+ const enrollment = await this.enrollments.findOne({
5772
+ where: { secretHash: hash(secret), mqttServerId: serverId, hardwareId }
5624
5773
  });
5625
5774
  return enrollment && this.isActiveEnrollment(enrollment) ? enrollment : null;
5626
5775
  }
@@ -5629,12 +5778,10 @@ var WagoService = class extends WagoSubscriptions {
5629
5778
  return Boolean(value) && Boolean(controller.fingerprint) && safeEqual(hash(value), hash(controller.fingerprint)) || safeEqual(hash(value), controller.pairingCodeHash);
5630
5779
  }
5631
5780
  async appliedRevision(controllerId) {
5632
- const [revision2] = await this.revisions.find({
5781
+ return this.revisions.findOne({
5633
5782
  where: { controllerId, state: "applied" },
5634
- order: { revision: "DESC" },
5635
- take: 1
5783
+ orderBy: [{ field: "revision", direction: "desc" }]
5636
5784
  });
5637
- return revision2 ?? null;
5638
5785
  }
5639
5786
  connectivity(controller) {
5640
5787
  if (controller.trustState === "untrusted") return "untrusted";
@@ -5671,8 +5818,12 @@ var WagoService = class extends WagoSubscriptions {
5671
5818
  }),
5672
5819
  { qos: 1, retain: true }
5673
5820
  );
5674
- revision2.state = "published";
5675
- return this.revisions.save(revision2);
5821
+ const published = await this.revisions.update(
5822
+ { id: revision2.id, state: { in: ["pending", "published"] } },
5823
+ { state: "published" }
5824
+ );
5825
+ if (published) return { ...revision2, state: "published" };
5826
+ return await this.revisions.get(revision2.id) ?? revision2;
5676
5827
  }
5677
5828
  /** Revision a queued report acknowledges; throws for a report outside the controller payload limits. */
5678
5829
  configurationReportRevision(payload) {
@@ -5737,13 +5888,17 @@ var WagoService = class extends WagoSubscriptions {
5737
5888
  return;
5738
5889
  }
5739
5890
  await this.withConfigurationLock(controllerId, async () => {
5740
- const revision2 = await this.revisions.findOneBy({ controllerId, revision: report.revision });
5891
+ const revision2 = await this.revisions.findOne({ where: { controllerId, revision: report.revision } });
5741
5892
  if (!revision2 || revision2.contentHash !== report.contentHash) return;
5742
5893
  if (revision2.state !== "published") return;
5743
- revision2.state = report.errors.length ? "rejected" : "applied";
5744
- revision2.rejectionErrors = report.errors.length ? JSON.stringify(report.errors) : null;
5745
- revision2.reportedAt = (/* @__PURE__ */ new Date()).toISOString();
5746
- await this.revisions.save(revision2);
5894
+ await this.revisions.update(
5895
+ { id: revision2.id, state: "published" },
5896
+ {
5897
+ state: report.errors.length ? "rejected" : "applied",
5898
+ rejectionErrors: report.errors.length ? JSON.stringify(report.errors) : null,
5899
+ reportedAt: (/* @__PURE__ */ new Date()).toISOString()
5900
+ }
5901
+ );
5747
5902
  });
5748
5903
  }
5749
5904
  async watchClaimAcknowledgement(prepared, acknowledgementToken, manual) {
@@ -6107,9 +6262,10 @@ var WagoRuntimeArtifactCatalog = class {
6107
6262
  } catch (error) {
6108
6263
  if (!["EEXIST", "ENOTEMPTY"].includes(error.code ?? "")) throw error;
6109
6264
  const existing = await (0, import_promises.lstat)(destination);
6110
- if (!existing.isDirectory() || existing.isSymbolicLink()) throw new Error("Invalid catalog object");
6265
+ if (!existing.isDirectory() || existing.isSymbolicLink())
6266
+ throw new Error("Invalid catalog object", { cause: error });
6111
6267
  const existingMetadata = await this.verify(destination);
6112
- if (existingMetadata.digest !== metadata2.digest) throw new Error("Invalid catalog object");
6268
+ if (existingMetadata.digest !== metadata2.digest) throw new Error("Invalid catalog object", { cause: error });
6113
6269
  await this.backfillMetadata(destination, existingMetadata);
6114
6270
  }
6115
6271
  const objectsHandle = await (0, import_promises.open)((0, import_node_path.join)(root, "objects"), import_node_fs.constants.O_RDONLY | import_node_fs.constants.O_NOFOLLOW);
@@ -6404,7 +6560,7 @@ WagoRuntimeArtifactsService = __decorateClass([
6404
6560
 
6405
6561
  // backend/commissioning/readiness/readiness.ts
6406
6562
  var import_common15 = require("@nestjs/common");
6407
- var import_plugins_backend_sdk8 = require("@attraccess/plugins-backend-sdk");
6563
+ var import_plugins_backend_sdk6 = require("@attraccess/plugins-backend-sdk");
6408
6564
  function isReadiness(value) {
6409
6565
  return !!value && typeof value === "object" && "configurationAccepted" in value && typeof value.configurationAccepted === "boolean" && "hardwareAvailable" in value && typeof value.hardwareAvailable === "boolean" && "ready" in value && typeof value.ready === "boolean";
6410
6566
  }
@@ -6488,10 +6644,11 @@ var WagoCommissioningReadiness = class {
6488
6644
  };
6489
6645
  WagoCommissioningReadiness = __decorateClass([
6490
6646
  (0, import_common15.Injectable)(),
6491
- __decorateParam(0, (0, import_common15.Inject)(import_plugins_backend_sdk8.PLUGIN_CONTEXT))
6647
+ __decorateParam(0, (0, import_common15.Inject)(import_plugins_backend_sdk6.PLUGIN_CONTEXT))
6492
6648
  ], WagoCommissioningReadiness);
6493
6649
 
6494
6650
  // backend/runtime/managed/service.ts
6651
+ var import_plugins_backend_sdk8 = require("@attraccess/plugins-backend-sdk");
6495
6652
  var import_common20 = require("@nestjs/common");
6496
6653
  var import_node_crypto17 = require("node:crypto");
6497
6654
 
@@ -9918,14 +10075,14 @@ var import_common19 = require("@nestjs/common");
9918
10075
 
9919
10076
  // backend/commissioning/sessions/verification.ts
9920
10077
  async function commissioningVerification(context, session, runtime) {
9921
- const controller = await context.getRepository(WagoController).findOneBy({
9922
- hardwareId: session.hardwareId,
9923
- mqttServerId: session.mqttServerId
10078
+ const tables = openWagoStorage(context);
10079
+ const controller = await tables.controllers.findOne({
10080
+ where: { hardwareId: session.hardwareId, mqttServerId: session.mqttServerId }
9924
10081
  });
9925
- const enrollment = session.enrollmentId === null ? null : await context.getRepository(WagoEnrollment).findOneBy({ id: session.enrollmentId });
9926
- const revision2 = controller ? await context.getRepository(WagoConfigurationRevision).findOne({
10082
+ const enrollment = session.enrollmentId === null ? null : await tables.enrollments.get(session.enrollmentId);
10083
+ const revision2 = controller ? await tables.configurationRevisions.findOne({
9927
10084
  where: { controllerId: controller.id },
9928
- order: { revision: "DESC" }
10085
+ orderBy: [{ field: "revision", direction: "desc" }]
9929
10086
  }) : null;
9930
10087
  const heartbeat = controller?.lastHeartbeatAt ? Date.parse(controller.lastHeartbeatAt) : NaN;
9931
10088
  const permanentConnection = Boolean(
@@ -10145,172 +10302,35 @@ async function managedSsh(access, privateKey, header, signal, file) {
10145
10302
  "-o",
10146
10303
  "ServerAliveCountMax=3",
10147
10304
  `${MANAGEMENT_USERNAME}@${access.host}`,
10148
- "true"
10149
- ],
10150
- header + "\n",
10151
- signal,
10152
- {},
10153
- file
10154
- );
10155
- } finally {
10156
- const ownedAgent = agent;
10157
- if (ownedAgent?.pid) {
10158
- try {
10159
- process.kill(-ownedAgent.pid, "SIGKILL");
10160
- } catch {
10161
- }
10162
- await new Promise((resolve2) => {
10163
- if (ownedAgent.exitCode !== null || ownedAgent.signalCode !== null) resolve2();
10164
- else ownedAgent.once("close", () => resolve2());
10165
- });
10166
- }
10167
- await (0, import_promises4.rm)(directory, { recursive: true, force: true });
10168
- }
10169
- }
10170
-
10171
- // backend/runtime/managed/access.ts
10172
- var import_common18 = require("@nestjs/common");
10173
-
10174
- // backend/runtime/managed/enrollment.ts
10175
- var import_node_crypto15 = require("node:crypto");
10176
- var import_common17 = require("@nestjs/common");
10177
-
10178
- // backend/network/entity.ts
10179
- var import_plugins_backend_sdk9 = require("@attraccess/plugins-backend-sdk");
10180
- var WagoNetworkChange = class {
10181
- constructor() {
10182
- __publicField(this, "controllerId");
10183
- __publicField(this, "sessionId");
10184
- __publicField(this, "fingerprint");
10185
- __publicField(this, "targetHost");
10186
- __publicField(this, "mqttServerId");
10187
- __publicField(this, "phase");
10188
- __publicField(this, "failure");
10189
- __publicField(this, "encryptedPayload");
10190
- __publicField(this, "updatedAt");
10191
- }
10192
- };
10193
- __decorateClass([
10194
- (0, import_plugins_backend_sdk9.PrimaryColumn)({ type: "integer", name: "controller_id" })
10195
- ], WagoNetworkChange.prototype, "controllerId", 2);
10196
- __decorateClass([
10197
- (0, import_plugins_backend_sdk9.Column)({ type: "integer", name: "session_id" })
10198
- ], WagoNetworkChange.prototype, "sessionId", 2);
10199
- __decorateClass([
10200
- (0, import_plugins_backend_sdk9.Column)({ type: "varchar" })
10201
- ], WagoNetworkChange.prototype, "fingerprint", 2);
10202
- __decorateClass([
10203
- (0, import_plugins_backend_sdk9.Column)({ type: "varchar", name: "target_host" })
10204
- ], WagoNetworkChange.prototype, "targetHost", 2);
10205
- __decorateClass([
10206
- (0, import_plugins_backend_sdk9.Column)({ type: "integer", name: "mqtt_server_id", nullable: true })
10207
- ], WagoNetworkChange.prototype, "mqttServerId", 2);
10208
- __decorateClass([
10209
- (0, import_plugins_backend_sdk9.Column)({ type: "varchar" })
10210
- ], WagoNetworkChange.prototype, "phase", 2);
10211
- __decorateClass([
10212
- (0, import_plugins_backend_sdk9.Column)({ type: "varchar", nullable: true })
10213
- ], WagoNetworkChange.prototype, "failure", 2);
10214
- __decorateClass([
10215
- (0, import_plugins_backend_sdk9.Column)({ type: "text", name: "encrypted_payload", nullable: true, select: false })
10216
- ], WagoNetworkChange.prototype, "encryptedPayload", 2);
10217
- __decorateClass([
10218
- (0, import_plugins_backend_sdk9.Column)({ type: "varchar", name: "updated_at" })
10219
- ], WagoNetworkChange.prototype, "updatedAt", 2);
10220
- WagoNetworkChange = __decorateClass([
10221
- (0, import_plugins_backend_sdk9.Entity)({ name: "plugin_wago_network_changes" })
10222
- ], WagoNetworkChange);
10223
- var WagoMqttCredentialRetirement = class {
10224
- constructor() {
10225
- __publicField(this, "controllerId");
10226
- __publicField(this, "mqttServerId");
10227
- }
10228
- };
10229
- __decorateClass([
10230
- (0, import_plugins_backend_sdk9.PrimaryColumn)({ type: "integer", name: "controller_id" })
10231
- ], WagoMqttCredentialRetirement.prototype, "controllerId", 2);
10232
- __decorateClass([
10233
- (0, import_plugins_backend_sdk9.PrimaryColumn)({ type: "integer", name: "mqtt_server_id" })
10234
- ], WagoMqttCredentialRetirement.prototype, "mqttServerId", 2);
10235
- WagoMqttCredentialRetirement = __decorateClass([
10236
- (0, import_plugins_backend_sdk9.Entity)({ name: "plugin_wago_mqtt_credential_retirements" })
10237
- ], WagoMqttCredentialRetirement);
10238
-
10239
- // backend/runtime/managed/access.entity.ts
10240
- var import_plugins_backend_sdk10 = require("@attraccess/plugins-backend-sdk");
10241
- var WagoManagedAccess = class {
10242
- constructor() {
10243
- __publicField(this, "sessionId");
10244
- __publicField(this, "controllerId");
10245
- __publicField(this, "host");
10246
- __publicField(this, "fingerprint");
10247
- __publicField(this, "token");
10248
- __publicField(this, "state");
10249
- __publicField(this, "encryptedCredentials");
10250
- __publicField(this, "keyFingerprint");
10251
- }
10252
- };
10253
- __decorateClass([
10254
- (0, import_plugins_backend_sdk10.PrimaryColumn)({ type: "integer", name: "session_id" })
10255
- ], WagoManagedAccess.prototype, "sessionId", 2);
10256
- __decorateClass([
10257
- (0, import_plugins_backend_sdk10.Column)({ type: "integer", name: "controller_id", nullable: true })
10258
- ], WagoManagedAccess.prototype, "controllerId", 2);
10259
- __decorateClass([
10260
- (0, import_plugins_backend_sdk10.Column)({ type: "varchar" })
10261
- ], WagoManagedAccess.prototype, "host", 2);
10262
- __decorateClass([
10263
- (0, import_plugins_backend_sdk10.Column)({ type: "varchar" })
10264
- ], WagoManagedAccess.prototype, "fingerprint", 2);
10265
- __decorateClass([
10266
- (0, import_plugins_backend_sdk10.Column)({ type: "varchar" })
10267
- ], WagoManagedAccess.prototype, "token", 2);
10268
- __decorateClass([
10269
- (0, import_plugins_backend_sdk10.Column)({ type: "varchar" })
10270
- ], WagoManagedAccess.prototype, "state", 2);
10271
- __decorateClass([
10272
- (0, import_plugins_backend_sdk10.Column)({ type: "text", name: "encrypted_credentials", select: false })
10273
- ], WagoManagedAccess.prototype, "encryptedCredentials", 2);
10274
- __decorateClass([
10275
- (0, import_plugins_backend_sdk10.Column)({ type: "varchar", name: "key_fingerprint" })
10276
- ], WagoManagedAccess.prototype, "keyFingerprint", 2);
10277
- WagoManagedAccess = __decorateClass([
10278
- (0, import_plugins_backend_sdk10.Entity)({ name: "plugin_wago_managed_access" })
10279
- ], WagoManagedAccess);
10280
- var WagoRuntimeUpdateEntity = class {
10281
- constructor() {
10282
- __publicField(this, "controllerId");
10283
- __publicField(this, "metadata");
10284
- }
10285
- };
10286
- __decorateClass([
10287
- (0, import_plugins_backend_sdk10.PrimaryColumn)({ type: "integer", name: "controller_id" })
10288
- ], WagoRuntimeUpdateEntity.prototype, "controllerId", 2);
10289
- __decorateClass([
10290
- (0, import_plugins_backend_sdk10.Column)({ type: "text", nullable: true })
10291
- ], WagoRuntimeUpdateEntity.prototype, "metadata", 2);
10292
- WagoRuntimeUpdateEntity = __decorateClass([
10293
- (0, import_plugins_backend_sdk10.Entity)({ name: "plugin_wago_runtime_updates" })
10294
- ], WagoRuntimeUpdateEntity);
10295
- var WagoDeviceOperation = class {
10296
- constructor() {
10297
- __publicField(this, "fingerprint");
10298
- __publicField(this, "owner");
10299
- __publicField(this, "leaseUntil");
10305
+ "true"
10306
+ ],
10307
+ header + "\n",
10308
+ signal,
10309
+ {},
10310
+ file
10311
+ );
10312
+ } finally {
10313
+ const ownedAgent = agent;
10314
+ if (ownedAgent?.pid) {
10315
+ try {
10316
+ process.kill(-ownedAgent.pid, "SIGKILL");
10317
+ } catch {
10318
+ }
10319
+ await new Promise((resolve2) => {
10320
+ if (ownedAgent.exitCode !== null || ownedAgent.signalCode !== null) resolve2();
10321
+ else ownedAgent.once("close", () => resolve2());
10322
+ });
10323
+ }
10324
+ await (0, import_promises4.rm)(directory, { recursive: true, force: true });
10300
10325
  }
10301
- };
10302
- __decorateClass([
10303
- (0, import_plugins_backend_sdk10.PrimaryColumn)({ type: "varchar" })
10304
- ], WagoDeviceOperation.prototype, "fingerprint", 2);
10305
- __decorateClass([
10306
- (0, import_plugins_backend_sdk10.Column)({ type: "varchar", nullable: true })
10307
- ], WagoDeviceOperation.prototype, "owner", 2);
10308
- __decorateClass([
10309
- (0, import_plugins_backend_sdk10.Column)({ type: "bigint", name: "lease_until", default: 0 })
10310
- ], WagoDeviceOperation.prototype, "leaseUntil", 2);
10311
- WagoDeviceOperation = __decorateClass([
10312
- (0, import_plugins_backend_sdk10.Entity)({ name: "plugin_wago_device_operations" })
10313
- ], WagoDeviceOperation);
10326
+ }
10327
+
10328
+ // backend/runtime/managed/access.ts
10329
+ var import_common18 = require("@nestjs/common");
10330
+
10331
+ // backend/runtime/managed/enrollment.ts
10332
+ var import_node_crypto15 = require("node:crypto");
10333
+ var import_common17 = require("@nestjs/common");
10314
10334
 
10315
10335
  // backend/runtime/managed/provisioning/provisioning-error.ts
10316
10336
  var reasons3 = {
@@ -10338,136 +10358,32 @@ function managedProvisioningError(output) {
10338
10358
  return stage && Object.hasOwn(reasons3, stage) ? new WagoManagedProvisioningError(stage) : null;
10339
10359
  }
10340
10360
 
10341
- // backend/commissioning/sessions/session.entity.ts
10342
- var import_plugins_backend_sdk11 = require("@attraccess/plugins-backend-sdk");
10343
- var WagoCommissioningSession = class {
10344
- constructor() {
10345
- __publicField(this, "id");
10346
- __publicField(this, "hardwareId");
10347
- __publicField(this, "mqttServerId");
10348
- __publicField(this, "targetHost");
10349
- __publicField(this, "hostKeyFingerprint");
10350
- __publicField(this, "firmwareBaseline");
10351
- __publicField(this, "controllerName");
10352
- __publicField(this, "state");
10353
- __publicField(this, "enrollmentExpiresAt");
10354
- __publicField(this, "enrollmentId");
10355
- __publicField(this, "pairingCode");
10356
- __publicField(this, "deliveryToken");
10357
- __publicField(this, "initiatingPrincipal");
10358
- __publicField(this, "runtimeArtifactDigest");
10359
- __publicField(this, "managementControllerId");
10360
- __publicField(this, "dockerProvisionToken");
10361
- __publicField(this, "dockerProvisionState");
10362
- __publicField(this, "platformReport");
10363
- __publicField(this, "codesysState");
10364
- __publicField(this, "progressPercent");
10365
- __publicField(this, "progressStep");
10366
- __publicField(this, "progressDetail");
10367
- __publicField(this, "auditLog");
10368
- __publicField(this, "failureReason");
10369
- __publicField(this, "createdAt");
10370
- __publicField(this, "updatedAt");
10371
- }
10372
- };
10373
- __decorateClass([
10374
- (0, import_plugins_backend_sdk11.PrimaryGeneratedColumn)({ type: "integer" })
10375
- ], WagoCommissioningSession.prototype, "id", 2);
10376
- __decorateClass([
10377
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "hardware_id" })
10378
- ], WagoCommissioningSession.prototype, "hardwareId", 2);
10379
- __decorateClass([
10380
- (0, import_plugins_backend_sdk11.Column)({ type: "integer", name: "mqtt_server_id" })
10381
- ], WagoCommissioningSession.prototype, "mqttServerId", 2);
10382
- __decorateClass([
10383
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "target_host" })
10384
- ], WagoCommissioningSession.prototype, "targetHost", 2);
10385
- __decorateClass([
10386
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "host_key_fingerprint" })
10387
- ], WagoCommissioningSession.prototype, "hostKeyFingerprint", 2);
10388
- __decorateClass([
10389
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "firmware_baseline" })
10390
- ], WagoCommissioningSession.prototype, "firmwareBaseline", 2);
10391
- __decorateClass([
10392
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "controller_name", nullable: true })
10393
- ], WagoCommissioningSession.prototype, "controllerName", 2);
10394
- __decorateClass([
10395
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar" })
10396
- ], WagoCommissioningSession.prototype, "state", 2);
10397
- __decorateClass([
10398
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "enrollment_expires_at", nullable: true })
10399
- ], WagoCommissioningSession.prototype, "enrollmentExpiresAt", 2);
10400
- __decorateClass([
10401
- (0, import_plugins_backend_sdk11.Column)({ type: "integer", name: "enrollment_id", nullable: true })
10402
- ], WagoCommissioningSession.prototype, "enrollmentId", 2);
10403
- __decorateClass([
10404
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "pairing_code", nullable: true })
10405
- ], WagoCommissioningSession.prototype, "pairingCode", 2);
10406
- __decorateClass([
10407
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "delivery_token", nullable: true })
10408
- ], WagoCommissioningSession.prototype, "deliveryToken", 2);
10409
- __decorateClass([
10410
- (0, import_plugins_backend_sdk11.Column)({ type: "text", name: "initiating_principal", nullable: true })
10411
- ], WagoCommissioningSession.prototype, "initiatingPrincipal", 2);
10412
- __decorateClass([
10413
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "runtime_artifact_digest", nullable: true })
10414
- ], WagoCommissioningSession.prototype, "runtimeArtifactDigest", 2);
10415
- __decorateClass([
10416
- (0, import_plugins_backend_sdk11.Column)({ type: "integer", name: "management_controller_id", nullable: true })
10417
- ], WagoCommissioningSession.prototype, "managementControllerId", 2);
10418
- __decorateClass([
10419
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "docker_provision_token", nullable: true })
10420
- ], WagoCommissioningSession.prototype, "dockerProvisionToken", 2);
10421
- __decorateClass([
10422
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "docker_provision_state", nullable: true })
10423
- ], WagoCommissioningSession.prototype, "dockerProvisionState", 2);
10424
- __decorateClass([
10425
- (0, import_plugins_backend_sdk11.Column)({ type: "text", name: "platform_report", nullable: true })
10426
- ], WagoCommissioningSession.prototype, "platformReport", 2);
10427
- __decorateClass([
10428
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "codesys_state", nullable: true })
10429
- ], WagoCommissioningSession.prototype, "codesysState", 2);
10430
- __decorateClass([
10431
- (0, import_plugins_backend_sdk11.Column)({ type: "integer", name: "progress_percent", nullable: true })
10432
- ], WagoCommissioningSession.prototype, "progressPercent", 2);
10433
- __decorateClass([
10434
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "progress_step", nullable: true })
10435
- ], WagoCommissioningSession.prototype, "progressStep", 2);
10436
- __decorateClass([
10437
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "progress_detail", nullable: true })
10438
- ], WagoCommissioningSession.prototype, "progressDetail", 2);
10439
- __decorateClass([
10440
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "audit_log" })
10441
- ], WagoCommissioningSession.prototype, "auditLog", 2);
10442
- __decorateClass([
10443
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "failure_reason", nullable: true })
10444
- ], WagoCommissioningSession.prototype, "failureReason", 2);
10445
- __decorateClass([
10446
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "created_at" })
10447
- ], WagoCommissioningSession.prototype, "createdAt", 2);
10448
- __decorateClass([
10449
- (0, import_plugins_backend_sdk11.Column)({ type: "varchar", name: "updated_at" })
10450
- ], WagoCommissioningSession.prototype, "updatedAt", 2);
10451
- WagoCommissioningSession = __decorateClass([
10452
- (0, import_plugins_backend_sdk11.Entity)({ name: "plugin_wago_commissioning_sessions" })
10453
- ], WagoCommissioningSession);
10454
-
10455
10361
  // backend/runtime/device-operations.ts
10362
+ var import_plugins_backend_sdk7 = require("@attraccess/plugins-backend-sdk");
10456
10363
  var WagoDeviceOperations = class {
10457
- constructor(repository) {
10458
- __publicField(this, "repository", repository);
10364
+ constructor(table2) {
10365
+ __publicField(this, "table", table2);
10459
10366
  }
10460
10367
  async acquire(fingerprint2, owner, now, until) {
10461
- await this.repository.createQueryBuilder().insert().values({ fingerprint: fingerprint2, leaseUntil: 0 }).orIgnore().execute();
10462
- const result = await this.repository.createQueryBuilder().update().set({ owner, leaseUntil: until }).where("fingerprint = :fingerprint AND (owner IS NULL OR lease_until < :now)", { fingerprint: fingerprint2, now }).execute();
10463
- return result.affected === 1;
10368
+ if (!await this.table.get(fingerprint2)) {
10369
+ try {
10370
+ await this.table.insert({ fingerprint: fingerprint2, leaseUntil: 0 });
10371
+ } catch (error) {
10372
+ if (!(error instanceof import_plugins_backend_sdk7.PluginStorageUniqueViolation)) throw error;
10373
+ }
10374
+ }
10375
+ const claimed = await this.table.update(
10376
+ { and: [{ fingerprint: fingerprint2 }, { or: [{ owner: null }, { leaseUntil: { lt: now } }] }] },
10377
+ { owner, leaseUntil: until }
10378
+ );
10379
+ return claimed === 1;
10464
10380
  }
10465
10381
  async assertOwned(fingerprint2, owner, now = Date.now()) {
10466
- const row = await this.repository.findOneBy({ fingerprint: fingerprint2, owner });
10382
+ const row = await this.table.findOne({ where: { fingerprint: fingerprint2, owner } });
10467
10383
  if (!row || Number(row.leaseUntil) <= now) throw new Error("Controller operation ownership lost");
10468
10384
  }
10469
10385
  async release(fingerprint2, owner) {
10470
- await this.repository.createQueryBuilder().update().set({ owner: null, leaseUntil: 0 }).where("fingerprint = :fingerprint AND owner = :owner", { fingerprint: fingerprint2, owner }).execute();
10386
+ await this.table.update({ fingerprint: fingerprint2, owner }, { owner: null, leaseUntil: 0 });
10471
10387
  }
10472
10388
  };
10473
10389
 
@@ -10479,10 +10395,7 @@ var WagoManagedRuntimeServiceState = class {
10479
10395
  __publicField(this, "wago", wago);
10480
10396
  __publicField(this, "artifacts", artifacts);
10481
10397
  __publicField(this, "readiness", readiness);
10482
- __publicField(this, "access");
10483
- __publicField(this, "updates");
10484
- __publicField(this, "sessions");
10485
- __publicField(this, "controllers");
10398
+ __publicField(this, "storage");
10486
10399
  __publicField(this, "operations");
10487
10400
  __publicField(this, "coordinator");
10488
10401
  __publicField(this, "heartbeats", /* @__PURE__ */ new Map());
@@ -10501,6 +10414,22 @@ var WagoManagedRuntimeServiceState = class {
10501
10414
  __publicField(this, "retirementProbe");
10502
10415
  __publicField(this, "connections", /* @__PURE__ */ new Set());
10503
10416
  }
10417
+ get access() {
10418
+ return this.storage.managedAccess;
10419
+ }
10420
+ get updates() {
10421
+ return this.storage.runtimeUpdates;
10422
+ }
10423
+ get sessions() {
10424
+ return this.storage.commissioningSessions;
10425
+ }
10426
+ get controllers() {
10427
+ return this.storage.controllers;
10428
+ }
10429
+ /** The newest managed access bound to the controller. */
10430
+ latestAccess(controllerId) {
10431
+ return this.access.findOne({ where: { controllerId }, orderBy: [{ field: "sessionId", direction: "desc" }] });
10432
+ }
10504
10433
  };
10505
10434
  WagoManagedRuntimeServiceState = __decorateClass([
10506
10435
  __decorateParam(0, (0, import_common16.Inject)(/* @__PURE__ */ Symbol.for("attraccess.plugin.context"))),
@@ -10524,7 +10453,7 @@ var WagoManagedRuntimeEnrollment = class extends WagoManagedRuntimeServiceState
10524
10453
  async networkManagement(controllerId, targetHost, signal) {
10525
10454
  const access = await this.required(controllerId);
10526
10455
  const credentials = this.credentials(access);
10527
- const session = await this.sessions.findOneBy({ id: access.sessionId });
10456
+ const session = await this.sessions.get(access.sessionId);
10528
10457
  if (!session || session.state !== "completed" || session.targetHost !== access.host || session.hostKeyFingerprint !== access.fingerprint || session.hardwareId !== credentials.hardwareId)
10529
10458
  throw new RuntimeUpdateError("management_required");
10530
10459
  const command = (header, payload) => this.connection(access, header, signal, payload, targetHost);
@@ -10567,21 +10496,23 @@ var WagoManagedRuntimeEnrollment = class extends WagoManagedRuntimeServiceState
10567
10496
  }
10568
10497
  async assertNetworkSettled(controllerId, fingerprint2) {
10569
10498
  if (controllerId === null && !fingerprint2) return;
10570
- const change = await this.context.getRepository(WagoNetworkChange).findOneBy(controllerId === null ? { fingerprint: fingerprint2 } : { controllerId });
10499
+ const change = await this.storage.networkChanges.findOne({
10500
+ where: controllerId === null ? { fingerprint: fingerprint2 } : { controllerId }
10501
+ });
10571
10502
  if (change && change.phase !== "completed")
10572
10503
  throw new import_common17.ConflictException("Finish the pending MQTT/address change before another controller operation.");
10573
10504
  }
10574
10505
  async assertUpdateSettled(controllerId) {
10575
10506
  await this.assertNetworkSettled(controllerId);
10576
- const row = await this.updates.findOneBy({ controllerId });
10507
+ const row = await this.updates.get(controllerId);
10577
10508
  const update = row?.metadata ? JSON.parse(row.metadata) : null;
10578
10509
  if (update?.token) throw new import_common17.ConflictException("Finish runtime update recovery before removing this controller");
10579
10510
  }
10580
10511
  async assertRemovable(controllerId) {
10581
10512
  await this.assertUpdateSettled(controllerId);
10582
- if (await this.context.getRepository(WagoMqttCredentialRetirement).countBy({ controllerId }))
10513
+ if (await this.storage.mqttCredentialRetirements.count({ controllerId }))
10583
10514
  throw new import_common17.ConflictException("Retire previous broker credentials before removing this controller.");
10584
- const access = await this.access.findOne({ where: { controllerId }, order: { sessionId: "DESC" } });
10515
+ const access = await this.latestAccess(controllerId);
10585
10516
  if (access && access.state !== "retired")
10586
10517
  throw new import_common17.ConflictException("Restore bootstrap SSH and retire managed access before removing this controller");
10587
10518
  }
@@ -10606,12 +10537,12 @@ var WagoManagedRuntimeEnrollment = class extends WagoManagedRuntimeServiceState
10606
10537
  }
10607
10538
  async publicStatus(access, requestedControllerId) {
10608
10539
  access = await this.revalidatedAccess(access);
10609
- const row = access?.controllerId ? await this.updates.findOneBy({ controllerId: access.controllerId }) : null;
10540
+ const row = access?.controllerId ? await this.updates.get(access.controllerId) : null;
10610
10541
  const controllerId = requestedControllerId ?? access?.controllerId;
10611
- const controller = controllerId ? await this.controllers.findOneBy({ id: controllerId }) : null;
10542
+ const controller = controllerId ? await this.controllers.get(controllerId) : null;
10612
10543
  const desired = controller ? await this.artifacts.current().catch(() => null) : null;
10613
10544
  const managementSetup = access?.state === "verified" ? await this.managementSetup(access, controller, controllerId) : void 0;
10614
- const managementFailure = access && ["verified", "recovery_required"].includes(access.state) ? (await this.sessions.findOneBy({ id: access.sessionId }))?.failureReason : null;
10545
+ const managementFailure = access && ["verified", "recovery_required"].includes(access.state) ? (await this.sessions.get(access.sessionId))?.failureReason : null;
10615
10546
  return {
10616
10547
  ...managementFailure ? { managementFailure } : {},
10617
10548
  sessionId: access?.sessionId ?? null,
@@ -10634,14 +10565,14 @@ var WagoManagedRuntimeEnrollment = class extends WagoManagedRuntimeServiceState
10634
10565
  return access;
10635
10566
  } catch {
10636
10567
  await this.setActiveState(access.sessionId, "recovery_required").catch(() => void 0);
10637
- return this.access.findOneBy({ sessionId: access.sessionId });
10568
+ return this.access.get(access.sessionId);
10638
10569
  }
10639
10570
  }
10640
10571
  /** Live automatic SSH-completion progress, or the prerequisite it is still waiting for. */
10641
10572
  async managementSetup(access, controller, controllerId) {
10642
10573
  return this.enrolmentProgress.get(controllerId ?? 0) ?? {
10643
10574
  state: "waiting",
10644
- reason: controller ? await this.enrolmentWaitReason(controller, await this.sessions.findOneBy({ id: access.sessionId })) ?? "scheduled" : "connection"
10575
+ reason: controller ? await this.enrolmentWaitReason(controller, await this.sessions.get(access.sessionId)) ?? "scheduled" : "connection"
10645
10576
  };
10646
10577
  }
10647
10578
  /** Running versus desired runtime image for the controller's latest heartbeat. */
@@ -10665,11 +10596,10 @@ var WagoManagedRuntimeEnrollment = class extends WagoManagedRuntimeServiceState
10665
10596
  };
10666
10597
  }
10667
10598
  async sessionStatus(sessionId) {
10668
- return this.publicStatus(await this.access.findOneBy({ sessionId }));
10599
+ return this.publicStatus(await this.access.get(sessionId));
10669
10600
  }
10670
10601
  async status(controllerId) {
10671
- const access = await this.access.findOne({ where: { controllerId }, order: { sessionId: "DESC" } });
10672
- return this.publicStatus(access, controllerId);
10602
+ return this.publicStatus(await this.latestAccess(controllerId), controllerId);
10673
10603
  }
10674
10604
  /** Called inside the commissioning device lease, with fresh bootstrap credentials.
10675
10605
  * DB encryption/storage completes before account/password mutation. The generated
@@ -10696,18 +10626,16 @@ var WagoManagedRuntimeEnrollment = class extends WagoManagedRuntimeServiceState
10696
10626
  const encryptedCredentials = this.context.secrets.encrypt(plaintext);
10697
10627
  if (!encryptedCredentials || encryptedCredentials === plaintext || this.context.secrets.decrypt(encryptedCredentials) !== plaintext)
10698
10628
  throw new import_common17.ConflictException("Managed credential encryption failed.");
10699
- access = await this.access.save(
10700
- this.access.create({
10701
- sessionId: session.id,
10702
- controllerId: null,
10703
- host: session.targetHost,
10704
- fingerprint: session.hostKeyFingerprint,
10705
- token: credentials2.token,
10706
- state: "pending",
10707
- encryptedCredentials,
10708
- keyFingerprint: key.fingerprint
10709
- })
10710
- );
10629
+ await this.access.insert({
10630
+ sessionId: session.id,
10631
+ controllerId: null,
10632
+ host: session.targetHost,
10633
+ fingerprint: session.hostKeyFingerprint,
10634
+ token: credentials2.token,
10635
+ state: "pending",
10636
+ encryptedCredentials,
10637
+ keyFingerprint: key.fingerprint
10638
+ });
10711
10639
  key.privateKey = "";
10712
10640
  access = await this.loadSession(session.id);
10713
10641
  if (!access) throw new import_common17.ConflictException("Managed credential storage verification failed.");
@@ -10750,7 +10678,7 @@ var WagoManagedRuntimeEnrollment = class extends WagoManagedRuntimeServiceState
10750
10678
  if (!access) return;
10751
10679
  if (access.state !== "verified" || access.controllerId !== null && access.controllerId !== controllerId)
10752
10680
  throw new import_common17.ConflictException("Managed enrolment is not verified for this controller");
10753
- await this.access.update(sessionId, { controllerId });
10681
+ await this.access.update({ sessionId }, { controllerId });
10754
10682
  }
10755
10683
  registerRetirementProbe(probe) {
10756
10684
  this.retirementProbe = probe;
@@ -10762,11 +10690,8 @@ var WagoManagedRuntimeEnrollment = class extends WagoManagedRuntimeServiceState
10762
10690
  this.rootProbe = probe;
10763
10691
  }
10764
10692
  onApplicationBootstrap() {
10765
- this.access = this.context.getRepository(WagoManagedAccess);
10766
- this.updates = this.context.getRepository(WagoRuntimeUpdateEntity);
10767
- this.sessions = this.context.getRepository(WagoCommissioningSession);
10768
- this.controllers = this.context.getRepository(WagoController);
10769
- this.operations = new WagoDeviceOperations(this.context.getRepository(WagoDeviceOperation));
10693
+ this.storage = openWagoStorage(this.context);
10694
+ this.operations = new WagoDeviceOperations(this.storage.deviceOperations);
10770
10695
  this.coordinator = new WagoRuntimeUpdateCoordinator(
10771
10696
  this.updateStore(),
10772
10697
  () => this.desired(),
@@ -10857,12 +10782,15 @@ var WagoManagedRuntimeAccess = class extends WagoManagedRuntimeEnrollment {
10857
10782
  }
10858
10783
  }
10859
10784
  async required(controllerId) {
10860
- const row = await this.access.createQueryBuilder("access").addSelect("access.encryptedCredentials").where("access.controllerId = :controllerId AND access.state = :state", { controllerId, state: "managed" }).orderBy("access.sessionId", "DESC").getOne();
10785
+ const row = await this.access.findOne({
10786
+ where: { controllerId, state: "managed" },
10787
+ orderBy: [{ field: "sessionId", direction: "desc" }]
10788
+ });
10861
10789
  if (!row) throw new RuntimeUpdateError("management_required");
10862
10790
  return row;
10863
10791
  }
10864
10792
  loadSession(sessionId) {
10865
- return this.access.createQueryBuilder("access").addSelect("access.encryptedCredentials").where("access.sessionId = :sessionId", { sessionId }).getOne();
10793
+ return this.access.get(sessionId);
10866
10794
  }
10867
10795
  async desired() {
10868
10796
  const value = await this.artifacts.current();
@@ -10879,11 +10807,8 @@ var WagoManagedRuntimeAccess = class extends WagoManagedRuntimeEnrollment {
10879
10807
  throw new import_common18.ConflictException("Controller is busy; retry after its current operation finishes");
10880
10808
  }
10881
10809
  async setActiveState(sessionId, state) {
10882
- const result = await this.access.createQueryBuilder().update().set({ state }).where("session_id = :sessionId AND state NOT IN (:...retired)", {
10883
- sessionId,
10884
- retired: ["retiring", "retired"]
10885
- }).execute();
10886
- if (result.affected !== 1) throw new import_common18.ConflictException("Managed access is being retired");
10810
+ const affected = await this.access.update({ sessionId, state: { notIn: ["retiring", "retired"] } }, { state });
10811
+ if (affected !== 1) throw new import_common18.ConflictException("Managed access is being retired");
10887
10812
  }
10888
10813
  async retryAccess(sessionId) {
10889
10814
  let access = await this.loadSession(sessionId);
@@ -10935,7 +10860,7 @@ var WagoManagedRuntimeAccess = class extends WagoManagedRuntimeEnrollment {
10935
10860
  if (access.controllerId) await this.assertUpdateSettled(access.controllerId);
10936
10861
  await this.securityAudit(sessionId, "security_recover", principal, operationId, "attempted");
10937
10862
  attempted = true;
10938
- await this.access.update(sessionId, { state: "retiring" });
10863
+ await this.access.update({ sessionId }, { state: "retiring" });
10939
10864
  const password = this.credentials(access).recoveryPassword;
10940
10865
  if (!await this.retirementProbe(access.host, access.fingerprint, password)) {
10941
10866
  await this.connection(access, `access-restore ${access.token}`, operation.signal);
@@ -10957,7 +10882,7 @@ var WagoManagedRuntimeAccess = class extends WagoManagedRuntimeEnrollment {
10957
10882
  if (!await this.retirementProbe(access.host, access.fingerprint, password))
10958
10883
  throw new import_common18.ConflictException("Managed key retirement is unverified; retry administrator recovery");
10959
10884
  await this.operations.assertOwned(access.fingerprint, owner);
10960
- await this.access.update(sessionId, { state: "retired" });
10885
+ await this.access.update({ sessionId }, { state: "retired" });
10961
10886
  await this.securityAudit(sessionId, "security_recover", principal, operationId, "succeeded");
10962
10887
  } catch (error) {
10963
10888
  if (attempted)
@@ -10984,7 +10909,7 @@ var WagoManagedRuntimeAccess = class extends WagoManagedRuntimeEnrollment {
10984
10909
  return await this.rootProbe(access.host, access.fingerprint, credentials.recoveryPassword) ? credentials.recoveryPassword : null;
10985
10910
  }
10986
10911
  async hasAccess(sessionId) {
10987
- return !!await this.access.findOneBy({ sessionId });
10912
+ return !!await this.access.get(sessionId);
10988
10913
  }
10989
10914
  };
10990
10915
 
@@ -11003,15 +10928,18 @@ var WagoManagedRuntimeReconciliation = class extends WagoManagedRuntimeAccess {
11003
10928
  throw new import_common19.ConflictException("Durable audit is required for managed SSH recovery and transitions");
11004
10929
  }
11005
10930
  async finishSession(id) {
11006
- await this.sessions.update(id, {
11007
- deliveryToken: null,
11008
- dockerProvisionToken: null,
11009
- dockerProvisionState: null,
11010
- state: "completed",
11011
- progressStep: "Controller enrolled",
11012
- progressDetail: "Permanent runtime verified; encrypted managed SSH credentials retained for automatic updates.",
11013
- failureReason: null
11014
- });
10931
+ await this.sessions.update(
10932
+ { id },
10933
+ {
10934
+ deliveryToken: null,
10935
+ dockerProvisionToken: null,
10936
+ dockerProvisionState: null,
10937
+ state: "completed",
10938
+ progressStep: "Controller enrolled",
10939
+ progressDetail: "Permanent runtime verified; encrypted managed SSH credentials retained for automatic updates.",
10940
+ failureReason: null
10941
+ }
10942
+ );
11015
10943
  }
11016
10944
  async enrolmentWaitReason(controller, session) {
11017
10945
  if (!controller.mqttServerId || !session || !["awaiting_verification", "completed"].includes(session.state) || session.hardwareId !== controller.hardwareId || session.mqttServerId !== controller.mqttServerId)
@@ -11036,9 +10964,9 @@ var WagoManagedRuntimeReconciliation = class extends WagoManagedRuntimeAccess {
11036
10964
  for (let skip = 0; !this.destroyed; skip += 50) {
11037
10965
  const controllers = await this.controllers.find({
11038
10966
  where: { trustState: "claimed" },
11039
- order: { id: "ASC" },
11040
- skip,
11041
- take: 50
10967
+ orderBy: [{ field: "id", direction: "asc" }],
10968
+ offset: skip,
10969
+ limit: 50
11042
10970
  });
11043
10971
  for (let index = 0; index < controllers.length && !this.destroyed; index += 2)
11044
10972
  await Promise.all(
@@ -11068,7 +10996,7 @@ var WagoManagedRuntimeReconciliation = class extends WagoManagedRuntimeAccess {
11068
10996
  await this.assertNetworkSettled(id);
11069
10997
  const heartbeat = await this.refreshRuntimePolicy(id);
11070
10998
  if (!heartbeat) return;
11071
- const controller = await this.controllers.findOneBy({ id, trustState: "claimed" });
10999
+ const controller = await this.controllers.findOne({ where: { id, trustState: "claimed" } });
11072
11000
  if (controller && await this.completeEnrolment(controller))
11073
11001
  await this.coordinator.reconcile(id, true, heartbeat.imageId);
11074
11002
  }
@@ -11082,9 +11010,9 @@ var WagoManagedRuntimeReconciliation = class extends WagoManagedRuntimeAccess {
11082
11010
  }
11083
11011
  const heartbeat = this.heartbeats.get(id);
11084
11012
  if (!heartbeat || this.destroyed) return;
11085
- const access = await this.access.findOne({ where: { controllerId: id }, order: { sessionId: "DESC" } });
11013
+ const access = await this.latestAccess(id);
11086
11014
  const enrolling = access?.state === "verified" || access?.state === "recovery_required";
11087
- const controller = await this.controllers.findOneBy({ id, trustState: "claimed" });
11015
+ const controller = await this.controllers.findOne({ where: { id, trustState: "claimed" } });
11088
11016
  await this.wago.setRuntimePolicy?.(
11089
11017
  id,
11090
11018
  enrolling ? heartbeat.imageId : runtimeTargetImageId(desired, {
@@ -11168,9 +11096,9 @@ var WagoManagedRuntimeService = class extends WagoManagedRuntimeReconciliation {
11168
11096
  /** Bound, unretired access whose commissioning session still matches this controller. */
11169
11097
  async enrolmentCandidate(controller) {
11170
11098
  if (!controller.mqttServerId) return null;
11171
- const bound = await this.access.findOne({ where: { controllerId: controller.id }, order: { sessionId: "DESC" } });
11099
+ const bound = await this.latestAccess(controller.id);
11172
11100
  if (!bound) return null;
11173
- const session = await this.sessions.findOneBy({ id: bound.sessionId });
11101
+ const session = await this.sessions.get(bound.sessionId);
11174
11102
  if (!session || !["awaiting_verification", "completed"].includes(session.state)) return null;
11175
11103
  if (session.hardwareId !== controller.hardwareId || session.mqttServerId !== controller.mqttServerId) return null;
11176
11104
  const access = await this.loadSession(session.id);
@@ -11206,8 +11134,8 @@ var WagoManagedRuntimeService = class extends WagoManagedRuntimeReconciliation {
11206
11134
  if (!principal) throw new Error("Management audit initiator unavailable");
11207
11135
  await this.securityAudit(session.id, "security_apply", principal, operationId, "attempted");
11208
11136
  attempt.attempted = true;
11209
- await this.sessions.update(session.id, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
11210
- await this.access.update(access.sessionId, { controllerId: controller.id });
11137
+ await this.sessions.update({ id: session.id }, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
11138
+ await this.access.update({ sessionId: access.sessionId }, { controllerId: controller.id });
11211
11139
  if (remoteStatus === "cutover\n") {
11212
11140
  attempt.stage = "rollback";
11213
11141
  this.restartEnrolmentTimer(attempt, 5e4);
@@ -11301,16 +11229,19 @@ var WagoManagedRuntimeService = class extends WagoManagedRuntimeReconciliation {
11301
11229
  async failEnrolment(session, error, stage, attempted, principal, operationId, operation) {
11302
11230
  if (attempted && principal)
11303
11231
  await this.securityAudit(session.id, "security_apply", principal, operationId, "failed").catch(() => void 0);
11304
- await this.access.createQueryBuilder().update().set({ state: "recovery_required" }).where("session_id = :sessionId AND state NOT IN (:...retired)", {
11305
- sessionId: session.id,
11306
- retired: ["retiring", "retired"]
11307
- }).execute();
11232
+ await this.access.update(
11233
+ { sessionId: session.id, state: { notIn: ["retiring", "retired"] } },
11234
+ { state: "recovery_required" }
11235
+ );
11308
11236
  const transientOfflineProbe = stage === "status" && error instanceof RuntimeUpdateError && error.failure === "offline";
11309
11237
  if (attempted || !session.failureReason || !transientOfflineProbe)
11310
- await this.sessions.update(session.id, {
11311
- failureReason: managedSetupFailure(stage, error, operation.signal.aborted),
11312
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
11313
- });
11238
+ await this.sessions.update(
11239
+ { id: session.id },
11240
+ {
11241
+ failureReason: managedSetupFailure(stage, error, operation.signal.aborted),
11242
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
11243
+ }
11244
+ );
11314
11245
  return false;
11315
11246
  }
11316
11247
  async onModuleDestroy() {
@@ -11327,7 +11258,8 @@ var WagoManagedRuntimeService = class extends WagoManagedRuntimeReconciliation {
11327
11258
  }
11328
11259
  async auditUpdate(record2) {
11329
11260
  const access = await this.required(record2.controllerId);
11330
- const session = await this.sessions.findOneByOrFail({ id: access.sessionId });
11261
+ const session = await this.sessions.get(access.sessionId);
11262
+ if (!session) throw new RuntimeUpdateError("audit");
11331
11263
  const principal = JSON.parse(session.initiatingPrincipal ?? "null");
11332
11264
  if (!principal || !Number.isSafeInteger(principal.userId) || principal.userId <= 0)
11333
11265
  throw new RuntimeUpdateError("audit");
@@ -11352,7 +11284,7 @@ var WagoManagedRuntimeService = class extends WagoManagedRuntimeReconciliation {
11352
11284
  return {
11353
11285
  inspect: async (id, signal) => {
11354
11286
  const access = await this.required(id);
11355
- const controller = await this.controllers.findOneBy({ id, trustState: "claimed" });
11287
+ const controller = await this.controllers.findOne({ where: { id, trustState: "claimed" } });
11356
11288
  const output = await this.connection(access, `inspect ${access.token}`, signal);
11357
11289
  const match = new RegExp(
11358
11290
  `^${MANAGED_HELPER_PROTOCOL}\\n([a-f0-9]{64})\\n(sha256:[a-f0-9]{64}) (true|false)\\n$`
@@ -11418,7 +11350,8 @@ var WagoManagedRuntimeService = class extends WagoManagedRuntimeReconciliation {
11418
11350
  await command(id, "activate", token, signal);
11419
11351
  },
11420
11352
  verify: async (id, _token, imageId, since, signal) => {
11421
- const controller = await this.controllers.findOneByOrFail({ id, trustState: "claimed" });
11353
+ const controller = await this.controllers.findOne({ where: { id, trustState: "claimed" } });
11354
+ if (!controller) throw new RuntimeUpdateError("offline");
11422
11355
  if (!controller.mqttServerId) throw new RuntimeUpdateError("offline");
11423
11356
  const prefix = (await this.wago.getSettings()).operationalPrefix;
11424
11357
  const activation = _token === null ? void 0 : this.runtimeActivations.get(_token);
@@ -11454,6 +11387,15 @@ var WagoManagedRuntimeService = class extends WagoManagedRuntimeReconciliation {
11454
11387
  }
11455
11388
  };
11456
11389
  }
11390
+ /** Creates the update-state row of a controller once; a concurrent creator wins without error. */
11391
+ async ensureUpdateRow(controllerId) {
11392
+ if (await this.updates.get(controllerId)) return;
11393
+ try {
11394
+ await this.updates.insert({ controllerId });
11395
+ } catch (error) {
11396
+ if (!(error instanceof import_plugins_backend_sdk8.PluginStorageUniqueViolation)) throw error;
11397
+ }
11398
+ }
11457
11399
  updateStore() {
11458
11400
  const owners = /* @__PURE__ */ new Map();
11459
11401
  return {
@@ -11468,21 +11410,29 @@ var WagoManagedRuntimeService = class extends WagoManagedRuntimeReconciliation {
11468
11410
  throw error;
11469
11411
  }
11470
11412
  owners.set(owner, access.fingerprint);
11471
- await this.updates.createQueryBuilder().insert().values({ controllerId }).orIgnore().execute();
11413
+ await this.ensureUpdateRow(controllerId);
11472
11414
  return true;
11473
11415
  },
11474
11416
  load: async (controllerId) => {
11475
- const row = await this.updates.findOneBy({ controllerId });
11417
+ const row = await this.updates.get(controllerId);
11476
11418
  return row?.metadata ? JSON.parse(row.metadata) : null;
11477
11419
  },
11478
11420
  save: async (record2, owner, now) => {
11479
11421
  const fingerprint2 = owners.get(owner);
11480
11422
  if (!fingerprint2) throw new Error("Update lease lost");
11481
- const result = await this.updates.createQueryBuilder().update().set({ metadata: JSON.stringify(record2) }).where(
11482
- "controller_id = :controllerId AND EXISTS (SELECT 1 FROM plugin_wago_device_operations WHERE fingerprint = :fingerprint AND owner = :owner AND lease_until > :now)",
11483
- { controllerId: record2.controllerId, fingerprint: fingerprint2, owner, now }
11484
- ).execute();
11485
- if (result.affected !== 1) throw new Error("Update lease lost");
11423
+ const saved = await this.context.persistence.transaction(async (scope) => {
11424
+ const held = await this.storage.deviceOperations.count(
11425
+ { fingerprint: fingerprint2, owner, leaseUntil: { gt: now } },
11426
+ { scope }
11427
+ );
11428
+ if (held !== 1) return 0;
11429
+ return this.updates.update(
11430
+ { controllerId: record2.controllerId },
11431
+ { metadata: JSON.stringify(record2) },
11432
+ { scope }
11433
+ );
11434
+ });
11435
+ if (saved !== 1) throw new Error("Update lease lost");
11486
11436
  },
11487
11437
  release: async (_id, owner) => {
11488
11438
  const fingerprint2 = owners.get(owner);
@@ -12466,35 +12416,8 @@ echo 'docker-provision=started'
12466
12416
  var import_common24 = require("@nestjs/common");
12467
12417
  var import_node_crypto20 = require("node:crypto");
12468
12418
 
12469
- // backend/management/entity.ts
12470
- var import_plugins_backend_sdk12 = require("@attraccess/plugins-backend-sdk");
12471
- var WagoManagementEntity = class {
12472
- constructor() {
12473
- __publicField(this, "controllerId");
12474
- __publicField(this, "metadataJson");
12475
- __publicField(this, "encryptedPrivateKey");
12476
- __publicField(this, "leaseOwner");
12477
- __publicField(this, "leaseUntil");
12478
- }
12479
- };
12480
- __decorateClass([
12481
- (0, import_plugins_backend_sdk12.PrimaryColumn)({ type: "integer", name: "controller_id" })
12482
- ], WagoManagementEntity.prototype, "controllerId", 2);
12483
- __decorateClass([
12484
- (0, import_plugins_backend_sdk12.Column)({ type: "text", name: "metadata_json", nullable: true })
12485
- ], WagoManagementEntity.prototype, "metadataJson", 2);
12486
- __decorateClass([
12487
- (0, import_plugins_backend_sdk12.Column)({ type: "text", name: "encrypted_private_key", nullable: true, select: false })
12488
- ], WagoManagementEntity.prototype, "encryptedPrivateKey", 2);
12489
- __decorateClass([
12490
- (0, import_plugins_backend_sdk12.Column)({ type: "varchar", name: "lease_owner", nullable: true })
12491
- ], WagoManagementEntity.prototype, "leaseOwner", 2);
12492
- __decorateClass([
12493
- (0, import_plugins_backend_sdk12.Column)({ type: "bigint", name: "lease_until", default: 0 })
12494
- ], WagoManagementEntity.prototype, "leaseUntil", 2);
12495
- WagoManagementEntity = __decorateClass([
12496
- (0, import_plugins_backend_sdk12.Entity)({ name: "plugin_wago_management" })
12497
- ], WagoManagementEntity);
12419
+ // backend/management/store.ts
12420
+ var import_plugins_backend_sdk9 = require("@attraccess/plugins-backend-sdk");
12498
12421
 
12499
12422
  // backend/management/shell-helpers.ts
12500
12423
  function managementShellHelpers() {
@@ -12761,16 +12684,21 @@ var WagoManagementProvider = class {
12761
12684
 
12762
12685
  // backend/management/store.ts
12763
12686
  var RepositoryManagementStore = class {
12764
- constructor(repository) {
12765
- __publicField(this, "repository", repository);
12687
+ constructor(table2) {
12688
+ __publicField(this, "table", table2);
12766
12689
  }
12767
12690
  async acquire(controllerId, owner, now, until) {
12768
- await this.repository.createQueryBuilder().insert().values({ controllerId, leaseUntil: 0 }).orIgnore().execute();
12769
- const result = await this.repository.createQueryBuilder().update().set({ leaseOwner: owner, leaseUntil: until }).where("controller_id = :controllerId AND (lease_owner IS NULL OR lease_until < :now)", { controllerId, now }).execute();
12770
- return result.affected === 1;
12691
+ await this.table.insert({ controllerId, leaseUntil: 0 }).catch((error) => {
12692
+ if (!(error instanceof import_plugins_backend_sdk9.PluginStorageUniqueViolation)) throw error;
12693
+ });
12694
+ const affected = await this.table.update(
12695
+ { and: [{ controllerId }, { or: [{ leaseOwner: { isNull: true } }, { leaseUntil: { lt: now } }] }] },
12696
+ { leaseOwner: owner, leaseUntil: until }
12697
+ );
12698
+ return affected === 1;
12771
12699
  }
12772
12700
  async load(controllerId) {
12773
- const row = await this.repository.createQueryBuilder("management").addSelect("management.encryptedPrivateKey").where("management.controllerId = :controllerId", { controllerId }).getOne();
12701
+ const row = await this.table.get(controllerId);
12774
12702
  if (!row?.metadataJson) return null;
12775
12703
  if (row.metadataJson.length > 16384) throw new Error("invalid_metadata");
12776
12704
  return { ...JSON.parse(row.metadataJson), encryptedPrivateKey: row.encryptedPrivateKey };
@@ -12779,20 +12707,19 @@ var RepositoryManagementStore = class {
12779
12707
  const { encryptedPrivateKey, ...metadata2 } = record2;
12780
12708
  const metadataJson = JSON.stringify(metadata2);
12781
12709
  if (metadataJson.length > 16384) throw new Error("invalid_metadata");
12782
- const result = await this.repository.createQueryBuilder().update().set({ metadataJson, encryptedPrivateKey }).where("controller_id = :controllerId AND lease_owner = :owner AND lease_until >= :now", {
12783
- controllerId,
12784
- owner,
12785
- now
12786
- }).execute();
12787
- if (result.affected !== 1) throw new Error("lease_lost");
12710
+ const affected = await this.table.update(
12711
+ { controllerId, leaseOwner: owner, leaseUntil: { gte: now } },
12712
+ { metadataJson, encryptedPrivateKey }
12713
+ );
12714
+ if (affected !== 1) throw new Error("lease_lost");
12788
12715
  }
12789
12716
  async release(controllerId, owner) {
12790
- await this.repository.createQueryBuilder().update().set({ leaseOwner: null, leaseUntil: 0 }).where("controller_id = :controllerId AND lease_owner = :owner", { controllerId, owner }).execute();
12717
+ await this.table.update({ controllerId, leaseOwner: owner }, { leaseOwner: null, leaseUntil: 0 });
12791
12718
  }
12792
12719
  };
12793
12720
  function createWagoManagementService(context, ssh) {
12794
12721
  return new WagoManagementService(
12795
- new RepositoryManagementStore(context.getRepository(WagoManagementEntity)),
12722
+ new RepositoryManagementStore(openWagoStorage(context).management),
12796
12723
  context.secrets,
12797
12724
  new WagoManagementProvider(ssh)
12798
12725
  );
@@ -12801,7 +12728,7 @@ function createWagoManagementService(context, ssh) {
12801
12728
  // backend/commissioning/state.ts
12802
12729
  var import_common23 = require("@nestjs/common");
12803
12730
  var import_node_async_hooks = require("node:async_hooks");
12804
- var import_plugins_backend_sdk13 = require("@attraccess/plugins-backend-sdk");
12731
+ var import_plugins_backend_sdk10 = require("@attraccess/plugins-backend-sdk");
12805
12732
  var WagoCommissioningServiceState = class {
12806
12733
  constructor(context, wago, artifacts, readiness, managedRuntime) {
12807
12734
  __publicField(this, "context", context);
@@ -12819,7 +12746,7 @@ var WagoCommissioningServiceState = class {
12819
12746
  }
12820
12747
  };
12821
12748
  WagoCommissioningServiceState = __decorateClass([
12822
- __decorateParam(0, (0, import_common23.Inject)(import_plugins_backend_sdk13.PLUGIN_CONTEXT)),
12749
+ __decorateParam(0, (0, import_common23.Inject)(import_plugins_backend_sdk10.PLUGIN_CONTEXT)),
12823
12750
  __decorateParam(1, (0, import_common23.Inject)(WagoService)),
12824
12751
  __decorateParam(2, (0, import_common23.Optional)()),
12825
12752
  __decorateParam(2, (0, import_common23.Inject)(WagoRuntimeArtifactsService)),
@@ -12832,7 +12759,7 @@ WagoCommissioningServiceState = __decorateClass([
12832
12759
  // backend/commissioning/sessions/sessions.ts
12833
12760
  var WagoCommissioningSessions = class extends WagoCommissioningServiceState {
12834
12761
  async verification(id) {
12835
- const session = await this.sessions.findOneBy({ id });
12762
+ const session = await this.sessions.get(id);
12836
12763
  if (!session) throw new import_common24.NotFoundException("commissioning session not found");
12837
12764
  const settings = this.readiness ? await this.wago.getSettings() : null;
12838
12765
  const runtime = this.readiness?.observe(session.mqttServerId, session.hardwareId, settings.operationalPrefix);
@@ -12847,14 +12774,18 @@ var WagoCommissioningSessions = class extends WagoCommissioningServiceState {
12847
12774
  async list(limit = 50, offset = 0) {
12848
12775
  const take = Number.isSafeInteger(limit) ? Math.min(Math.max(limit, 1), 100) : 50;
12849
12776
  const skip = Number.isSafeInteger(offset) ? Math.max(offset, 0) : 0;
12850
- const sessions = await this.sessions.find({ order: { updatedAt: "DESC" }, take, skip });
12777
+ const sessions = await this.sessions.find({
12778
+ orderBy: [{ field: "updatedAt", direction: "desc" }],
12779
+ limit: take,
12780
+ offset: skip
12781
+ });
12851
12782
  return Promise.all(sessions.map((session) => this.toResponse(session)));
12852
12783
  }
12853
12784
  async confirmHostKey(id, hostKeyFingerprint, trustMethod = "trusted_inventory", physicalIdentityConfirmed = false) {
12854
12785
  if (!["trusted_inventory", "isolated_service_connection"].includes(trustMethod) || trustMethod === "isolated_service_connection" && physicalIdentityConfirmed !== true)
12855
12786
  throw new import_common24.ConflictException("Confirm the isolated service connection and physical controller identity.");
12856
12787
  return this.withDeliveryLock(id, async () => {
12857
- const session = await this.sessions.findOneBy({ id });
12788
+ const session = await this.sessions.get(id);
12858
12789
  if (!session) throw new import_common24.NotFoundException("commissioning session not found");
12859
12790
  if (session.state !== "awaiting_identity_confirmation")
12860
12791
  throw new import_common24.ConflictException("commissioning session identity cannot be confirmed in its current state");
@@ -12892,31 +12823,29 @@ var WagoCommissioningSessions = class extends WagoCommissioningServiceState {
12892
12823
  }
12893
12824
  const hardwareId = `cc100-${(0, import_node_crypto20.createHash)("sha256").update(hostKeyFingerprint).digest("hex").slice(0, 16)}`;
12894
12825
  const now = (/* @__PURE__ */ new Date()).toISOString();
12895
- const session = await this.sessions.save(
12896
- this.sessions.create({
12897
- hardwareId,
12898
- mqttServerId: input.mqttServerId,
12899
- targetHost: input.targetHost,
12900
- hostKeyFingerprint,
12901
- firmwareBaseline: configuredFirmwareBaseline,
12902
- controllerName: input.name.trim(),
12903
- state: "awaiting_identity_confirmation",
12904
- enrollmentExpiresAt: null,
12905
- enrollmentId: null,
12906
- // This verifier authenticates the first runtime announcement and is never exposed to an operator.
12907
- pairingCode: this.encryptVerifier((0, import_node_crypto20.randomBytes)(32).toString("base64url")),
12908
- initiatingPrincipal: principal ? JSON.stringify(principal) : null,
12909
- runtimeArtifactDigest: null,
12910
- codesysState: null,
12911
- progressPercent: 0,
12912
- progressStep: "Confirm controller identity",
12913
- progressDetail: "Verify the scanned SSH host-key fingerprint on the controller before delivery.",
12914
- auditLog: JSON.stringify([{ at: now, event: "host_key_scanned" }]),
12915
- failureReason: null,
12916
- createdAt: now,
12917
- updatedAt: now
12918
- })
12919
- );
12826
+ const session = await this.sessions.insert({
12827
+ hardwareId,
12828
+ mqttServerId: input.mqttServerId,
12829
+ targetHost: input.targetHost,
12830
+ hostKeyFingerprint,
12831
+ firmwareBaseline: configuredFirmwareBaseline,
12832
+ controllerName: input.name.trim(),
12833
+ state: "awaiting_identity_confirmation",
12834
+ enrollmentExpiresAt: null,
12835
+ enrollmentId: null,
12836
+ // This verifier authenticates the first runtime announcement and is never exposed to an operator.
12837
+ pairingCode: this.encryptVerifier((0, import_node_crypto20.randomBytes)(32).toString("base64url")),
12838
+ initiatingPrincipal: principal ? JSON.stringify(principal) : null,
12839
+ runtimeArtifactDigest: null,
12840
+ codesysState: null,
12841
+ progressPercent: 0,
12842
+ progressStep: "Confirm controller identity",
12843
+ progressDetail: "Verify the scanned SSH host-key fingerprint on the controller before delivery.",
12844
+ auditLog: JSON.stringify([{ at: now, event: "host_key_scanned" }]),
12845
+ failureReason: null,
12846
+ createdAt: now,
12847
+ updatedAt: now
12848
+ });
12920
12849
  return this.toResponse(session);
12921
12850
  }
12922
12851
  async support() {
@@ -12926,7 +12855,7 @@ var WagoCommissioningSessions = class extends WagoCommissioningServiceState {
12926
12855
  };
12927
12856
  }
12928
12857
  async onApplicationBootstrap() {
12929
- this.sessions = this.context.getRepository(WagoCommissioningSession);
12858
+ this.sessions = openWagoStorage(this.context).commissioningSessions;
12930
12859
  this.managedRuntime?.registerRootProbe(async (host, fingerprint2, password) => {
12931
12860
  try {
12932
12861
  return await this.run(host, fingerprint2, { username: "root", password }, "id -u", void 0, {
@@ -13073,12 +13002,14 @@ var WagoCommissioningPlatform = class extends WagoCommissioningSessions {
13073
13002
  return this.withControllerLock(
13074
13003
  id,
13075
13004
  () => this.withDeliveryLock(id, async () => {
13076
- const session = await this.sessions.findOneBy({ id });
13005
+ const session = await this.sessions.get(id);
13077
13006
  if (!session) throw new import_common25.NotFoundException("commissioning session not found");
13078
13007
  if (["awaiting_identity_confirmation", "delivering"].includes(session.state) || session.state === "revoked" && action !== "recover")
13079
13008
  throw new import_common25.ConflictException("Confirm controller identity and finish delivery before management changes.");
13080
13009
  if (!session.managementControllerId) {
13081
- const controller = await this.context.getRepository(WagoController).findOneBy({ hardwareId: session.hardwareId, mqttServerId: session.mqttServerId });
13010
+ const controller = await openWagoStorage(this.context).controllers.findOne({
13011
+ where: { hardwareId: session.hardwareId, mqttServerId: session.mqttServerId }
13012
+ });
13082
13013
  if (!controller) throw new import_common25.ConflictException("Wait for controller enrollment before management inspection.");
13083
13014
  session.managementControllerId = controller.id;
13084
13015
  await this.save(session, "management_subject_bound");
@@ -13134,7 +13065,7 @@ var WagoCommissioningPlatform = class extends WagoCommissioningSessions {
13134
13065
  );
13135
13066
  }
13136
13067
  async managementStatus(id) {
13137
- const session = await this.sessions.findOneBy({ id });
13068
+ const session = await this.sessions.get(id);
13138
13069
  if (!session) throw new import_common25.NotFoundException("commissioning session not found");
13139
13070
  return session.managementControllerId ? this.management.status(session.managementControllerId) : null;
13140
13071
  }
@@ -13222,7 +13153,7 @@ var WagoCommissioningPlatform = class extends WagoCommissioningSessions {
13222
13153
  () => this.withControllerLock(
13223
13154
  id,
13224
13155
  () => this.withDeliveryLock(id, async () => {
13225
- const session = await this.sessions.findOneBy({ id });
13156
+ const session = await this.sessions.get(id);
13226
13157
  if (!session) throw new import_common25.NotFoundException("commissioning session not found");
13227
13158
  if (["awaiting_identity_confirmation", "delivering"].includes(session.state) || session.state === "revoked" && action !== "recover")
13228
13159
  throw new import_common25.ConflictException("Finish identity confirmation and any active delivery first.");
@@ -13271,13 +13202,15 @@ var WagoCommissioningPlatform = class extends WagoCommissioningSessions {
13271
13202
  }
13272
13203
  async reconcileDiscovery() {
13273
13204
  for (let skip = 0; ; skip += 100) {
13274
- const page = await this.sessions.find({ order: { id: "ASC" }, take: 100, skip });
13205
+ const page = await this.sessions.find({ orderBy: [{ field: "id" }], limit: 100, offset: skip });
13275
13206
  for (const session of page) {
13276
13207
  if (session.state !== "awaiting_discovery" || session.enrollmentId === null) continue;
13277
- const controller = await this.context.getRepository(WagoController).findOneBy({
13278
- hardwareId: session.hardwareId,
13279
- mqttServerId: session.mqttServerId,
13280
- enrollmentId: session.enrollmentId
13208
+ const controller = await openWagoStorage(this.context).controllers.findOne({
13209
+ where: {
13210
+ hardwareId: session.hardwareId,
13211
+ mqttServerId: session.mqttServerId,
13212
+ enrollmentId: session.enrollmentId
13213
+ }
13281
13214
  });
13282
13215
  if (controller?.trustState === "untrusted") await this.claimDiscovered(controller);
13283
13216
  }
@@ -13289,7 +13222,7 @@ var WagoCommissioningPlatform = class extends WagoCommissioningSessions {
13289
13222
  // backend/commissioning/delivery/recovery.ts
13290
13223
  var WagoCommissioningRecovery = class extends WagoCommissioningPlatform {
13291
13224
  async withControllerLock(id, operation) {
13292
- const session = await this.sessions.findOneBy({ id });
13225
+ const session = await this.sessions.get(id);
13293
13226
  if (!session) throw new import_common26.NotFoundException("commissioning session not found");
13294
13227
  const key = session.hostKeyFingerprint || session.targetHost || session.hardwareId;
13295
13228
  const previous = this.controllerLocks.get(key) ?? Promise.resolve();
@@ -13313,7 +13246,7 @@ var WagoCommissioningRecovery = class extends WagoCommissioningPlatform {
13313
13246
  let deviceOperations;
13314
13247
  const owner = (0, import_node_crypto22.randomBytes)(16).toString("hex");
13315
13248
  if (this.managedRuntime) {
13316
- deviceOperations = new WagoDeviceOperations(this.context.getRepository(WagoDeviceOperation));
13249
+ deviceOperations = new WagoDeviceOperations(openWagoStorage(this.context).deviceOperations);
13317
13250
  if (!await deviceOperations.acquire(key, owner, Date.now(), deadline + 6e4))
13318
13251
  throw new import_common26.ConflictException("Another controller operation is active. Retry after it finishes.");
13319
13252
  }
@@ -13323,7 +13256,7 @@ var WagoCommissioningRecovery = class extends WagoCommissioningPlatform {
13323
13256
  await deviceOperations?.assertOwned(key, owner);
13324
13257
  };
13325
13258
  try {
13326
- const enrolled = session.hardwareId ? await this.context.getRepository(WagoController).findOneBy({ hardwareId: session.hardwareId }) : null;
13259
+ const enrolled = session.hardwareId ? await openWagoStorage(this.context).controllers.findOne({ where: { hardwareId: session.hardwareId } }) : null;
13327
13260
  await this.managedRuntime?.assertNetworkSettled(enrolled?.id ?? null, session.hostKeyFingerprint ?? void 0);
13328
13261
  this.activeDeadlines.set(id, deadline);
13329
13262
  return await this.operationContext.run(guard, operation);
@@ -13343,7 +13276,7 @@ var WagoCommissioningRecovery = class extends WagoCommissioningPlatform {
13343
13276
  return this.withControllerLock(
13344
13277
  id,
13345
13278
  () => this.withDeliveryLock(id, async () => {
13346
- const session = await this.sessions.findOneBy({ id });
13279
+ const session = await this.sessions.get(id);
13347
13280
  if (!session) throw new import_common26.NotFoundException("commissioning session not found");
13348
13281
  if (![
13349
13282
  "delivery_failed",
@@ -13440,7 +13373,7 @@ var WagoCommissioningRecovery = class extends WagoCommissioningPlatform {
13440
13373
  throw new import_common26.ConflictException("Build and install the bundled CC100 runtime before installation.");
13441
13374
  }
13442
13375
  async loadDeliverableSession(id) {
13443
- const session = await this.sessions.findOneBy({ id });
13376
+ const session = await this.sessions.get(id);
13444
13377
  if (!session) throw new import_common26.NotFoundException("commissioning session not found");
13445
13378
  if (!["awaiting_delivery", "delivering", "awaiting_codesys_confirmation", "delivery_failed"].includes(session.state))
13446
13379
  throw new import_common26.ConflictException("commissioning session cannot be delivered in its current state");
@@ -13465,16 +13398,18 @@ var WagoCommissioningRecovery = class extends WagoCommissioningPlatform {
13465
13398
  var WagoCommissioningOwnership = class extends WagoCommissioningRecovery {
13466
13399
  async claimDiscovered(controller) {
13467
13400
  if (!controller.mqttServerId || !controller.enrollmentId) return;
13468
- const session = await this.sessions.findOneBy({
13469
- hardwareId: controller.hardwareId,
13470
- mqttServerId: controller.mqttServerId,
13471
- enrollmentId: controller.enrollmentId
13401
+ const session = await this.sessions.findOne({
13402
+ where: {
13403
+ hardwareId: controller.hardwareId,
13404
+ mqttServerId: controller.mqttServerId,
13405
+ enrollmentId: controller.enrollmentId
13406
+ }
13472
13407
  });
13473
13408
  if (!session) return;
13474
13409
  await this.withControllerLock(
13475
13410
  session.id,
13476
13411
  () => this.withDeliveryLock(session.id, async () => {
13477
- const current = await this.sessions.findOneBy({ id: session.id });
13412
+ const current = await this.sessions.get(session.id);
13478
13413
  if (!current || current.state !== "awaiting_discovery" || current.hardwareId !== controller.hardwareId || current.mqttServerId !== controller.mqttServerId || current.enrollmentId !== controller.enrollmentId || !current.controllerName || !current.pairingCode)
13479
13414
  return;
13480
13415
  let pairingCode;
@@ -13539,9 +13474,12 @@ var WagoCommissioningOwnership = class extends WagoCommissioningRecovery {
13539
13474
  }
13540
13475
  /** The HTTP audit wrapper belongs inside remove(), so removal is audited once by ATT-983. */
13541
13476
  async removeControllerSafely(id, remove) {
13542
- const controller = await this.context.getRepository(WagoController).findOneBy({ id });
13477
+ const controller = await openWagoStorage(this.context).controllers.get(id);
13543
13478
  if (!controller) throw new import_common27.NotFoundException("controller not found");
13544
- const sessions = await this.sessions.find({ where: { hardwareId: controller.hardwareId }, order: { id: "DESC" } });
13479
+ const sessions = await this.sessions.find({
13480
+ where: { hardwareId: controller.hardwareId },
13481
+ orderBy: [{ field: "id", direction: "desc" }]
13482
+ });
13545
13483
  if (!sessions.length) {
13546
13484
  await remove(async () => void 0);
13547
13485
  return;
@@ -13556,7 +13494,7 @@ var WagoCommissioningOwnership = class extends WagoCommissioningRecovery {
13556
13494
  await this.managedRuntime?.retire(id);
13557
13495
  for (const candidate of await this.sessions.find({ where: { hardwareId } })) {
13558
13496
  await this.withDeliveryLock(candidate.id, async () => {
13559
- const session = await this.sessions.findOneBy({ id: candidate.id });
13497
+ const session = await this.sessions.get(candidate.id);
13560
13498
  if (!session) return;
13561
13499
  await this.revokeSessionEnrollment(session);
13562
13500
  if (session.managementControllerId) {
@@ -13572,16 +13510,19 @@ var WagoCommissioningOwnership = class extends WagoCommissioningRecovery {
13572
13510
  await this.save(session, "controller_removed_recovery_retained");
13573
13511
  } else {
13574
13512
  await assertOwned();
13575
- await this.sessions.delete(session.id);
13513
+ await this.sessions.delete({ id: session.id });
13576
13514
  }
13577
13515
  });
13578
13516
  }
13579
13517
  });
13580
13518
  }
13581
13519
  async operateControllerSafely(id, operation, requireCommissioningSession = false) {
13582
- const controller = await this.context.getRepository(WagoController).findOneBy({ id });
13520
+ const controller = await openWagoStorage(this.context).controllers.get(id);
13583
13521
  if (!controller) throw new import_common27.NotFoundException("controller not found");
13584
- const sessions = await this.sessions.find({ where: { hardwareId: controller.hardwareId }, order: { id: "DESC" } });
13522
+ const sessions = await this.sessions.find({
13523
+ where: { hardwareId: controller.hardwareId },
13524
+ orderBy: [{ field: "id", direction: "desc" }]
13525
+ });
13585
13526
  if (!sessions.length) {
13586
13527
  if (requireCommissioningSession)
13587
13528
  throw new import_common27.ConflictException("A commissioning session must remain pinned while rotating credentials.");
@@ -13614,7 +13555,7 @@ var WagoCommissioningOwnership = class extends WagoCommissioningRecovery {
13614
13555
  await this.withControllerLock(
13615
13556
  id,
13616
13557
  () => this.withDeliveryLock(id, async () => {
13617
- const session = await this.sessions.findOneBy({ id });
13558
+ const session = await this.sessions.get(id);
13618
13559
  if (!session) throw new import_common27.NotFoundException("commissioning session not found");
13619
13560
  if (session.deliveryToken)
13620
13561
  throw new import_common27.ConflictException("Clean up the retained runtime installation before deleting this session.");
@@ -13638,7 +13579,7 @@ var WagoCommissioningOwnership = class extends WagoCommissioningRecovery {
13638
13579
  }
13639
13580
  }
13640
13581
  await this.operationContext.getStore()?.assertOwned();
13641
- await this.sessions.delete(id);
13582
+ await this.sessions.delete({ id });
13642
13583
  })
13643
13584
  );
13644
13585
  }
@@ -13646,7 +13587,7 @@ var WagoCommissioningOwnership = class extends WagoCommissioningRecovery {
13646
13587
  return this.withControllerLock(
13647
13588
  id,
13648
13589
  () => this.withDeliveryLock(id, async () => {
13649
- const session = await this.sessions.findOneBy({ id });
13590
+ const session = await this.sessions.get(id);
13650
13591
  if (!session) throw new import_common27.NotFoundException("commissioning session not found");
13651
13592
  await this.revokeSessionEnrollment(session);
13652
13593
  session.state = "revoked";
@@ -13864,13 +13805,18 @@ var WagoCommissioningProgress = class extends WagoCommissioningTransport {
13864
13805
  }
13865
13806
  async retireSupersededSessions(hardwareId, completedSessionId) {
13866
13807
  for (let skip = 0; ; skip += 100) {
13867
- const sessions = await this.sessions.find({ where: { hardwareId }, order: { id: "ASC" }, take: 100, skip });
13808
+ const sessions = await this.sessions.find({
13809
+ where: { hardwareId },
13810
+ orderBy: [{ field: "id" }],
13811
+ limit: 100,
13812
+ offset: skip
13813
+ });
13868
13814
  await Promise.all(
13869
13815
  sessions.filter(
13870
13816
  (session) => session.id !== completedSessionId && session.state !== "completed" && session.state !== "revoked"
13871
13817
  ).map(
13872
13818
  (session) => this.withDeliveryLock(session.id, async () => {
13873
- const current = await this.sessions.findOneBy({ id: session.id });
13819
+ const current = await this.sessions.get(session.id);
13874
13820
  if (!current || current.state === "completed" || current.state === "revoked") return;
13875
13821
  await this.revokeSessionEnrollment(current);
13876
13822
  current.state = "revoked";
@@ -13887,7 +13833,12 @@ var WagoCommissioningProgress = class extends WagoCommissioningTransport {
13887
13833
  }
13888
13834
  async reconcileCompletedSessions() {
13889
13835
  for (let skip = 0; ; skip += 100) {
13890
- const page = await this.sessions.find({ where: { state: "completed" }, order: { id: "ASC" }, take: 100, skip });
13836
+ const page = await this.sessions.find({
13837
+ where: { state: "completed" },
13838
+ orderBy: [{ field: "id" }],
13839
+ limit: 100,
13840
+ offset: skip
13841
+ });
13891
13842
  for (const session of page) {
13892
13843
  if (session.state === "completed")
13893
13844
  await this.withControllerLock(
@@ -13901,13 +13852,13 @@ var WagoCommissioningProgress = class extends WagoCommissioningTransport {
13901
13852
  async recoverSessions() {
13902
13853
  let recoveryFailed = false;
13903
13854
  for (let skip = 0; ; skip += 100) {
13904
- const page = await this.sessions.find({ order: { id: "ASC" }, take: 100, skip });
13855
+ const page = await this.sessions.find({ orderBy: [{ field: "id" }], limit: 100, offset: skip });
13905
13856
  for (const candidate of page) {
13906
13857
  if (["completed", "awaiting_verification", "claim_interrupted"].includes(candidate.state) && !candidate.pairingCode && !(candidate.dockerProvisionToken && ["starting", "recovering"].includes(candidate.dockerProvisionState ?? "")))
13907
13858
  continue;
13908
13859
  try {
13909
13860
  await this.withControllerLock(candidate.id, async () => {
13910
- const session = await this.sessions.findOneBy({ id: candidate.id });
13861
+ const session = await this.sessions.get(candidate.id);
13911
13862
  if (!session || session.state === "recovery_revocation_pending") return;
13912
13863
  if (session.dockerProvisionToken && ["starting", "recovering"].includes(session.dockerProvisionState ?? "")) {
13913
13864
  session.dockerProvisionState = "recovery_required";
@@ -13927,10 +13878,12 @@ var WagoCommissioningProgress = class extends WagoCommissioningTransport {
13927
13878
  return;
13928
13879
  }
13929
13880
  if (session.state === "awaiting_claim") {
13930
- const controller = session.enrollmentId === null ? null : await this.context.getRepository(WagoController).findOneBy({
13931
- hardwareId: session.hardwareId,
13932
- mqttServerId: session.mqttServerId,
13933
- enrollmentId: session.enrollmentId
13881
+ const controller = session.enrollmentId === null ? null : await openWagoStorage(this.context).controllers.findOne({
13882
+ where: {
13883
+ hardwareId: session.hardwareId,
13884
+ mqttServerId: session.mqttServerId,
13885
+ enrollmentId: session.enrollmentId
13886
+ }
13934
13887
  });
13935
13888
  session.state = controller?.trustState === "claimed" ? "claim_interrupted" : "awaiting_discovery";
13936
13889
  session.progressStep = "Claim interrupted; recovery required";
@@ -13995,26 +13948,26 @@ var WagoCommissioningProgress = class extends WagoCommissioningTransport {
13995
13948
  }
13996
13949
  }
13997
13950
  reportPreparationProgress(session, checkpoint) {
13998
- const [percent, step, detail] = commissioningCheckpoints[checkpoint];
13999
- if (session.progressStep === step) return;
13951
+ const [percent, step2, detail] = commissioningCheckpoints[checkpoint];
13952
+ if (session.progressStep === step2) return;
14000
13953
  const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
14001
13954
  session.progressPercent = percent;
14002
- session.progressStep = step;
13955
+ session.progressStep = step2;
14003
13956
  session.progressDetail = detail;
14004
13957
  const audit = JSON.parse(session.auditLog);
14005
- audit.push({ at: updatedAt, event: `progress: ${step}` });
13958
+ audit.push({ at: updatedAt, event: `progress: ${step2}` });
14006
13959
  session.auditLog = JSON.stringify(audit.slice(-50));
14007
13960
  session.updatedAt = updatedAt;
14008
13961
  const update = {
14009
13962
  progressPercent: percent,
14010
- progressStep: step,
13963
+ progressStep: step2,
14011
13964
  progressDetail: detail,
14012
13965
  updatedAt,
14013
13966
  auditLog: session.auditLog
14014
13967
  };
14015
13968
  const write = (this.transferWrites.get(session.id) ?? Promise.resolve()).then(async () => {
14016
13969
  await this.operationContext.getStore()?.assertOwned();
14017
- await this.sessions.update(session.id, update);
13970
+ await this.sessions.update({ id: session.id }, update);
14018
13971
  }).catch(() => this.context.logger?.warn("Could not update WAGO controller preparation progress."));
14019
13972
  this.transferWrites.set(session.id, write);
14020
13973
  void write.then(() => {
@@ -14034,18 +13987,18 @@ var WagoCommissioningProgress = class extends WagoCommissioningTransport {
14034
13987
  };
14035
13988
  const write = (this.transferWrites.get(session.id) ?? Promise.resolve()).then(async () => {
14036
13989
  await this.operationContext.getStore()?.assertOwned();
14037
- await this.sessions.update(session.id, update);
13990
+ await this.sessions.update({ id: session.id }, update);
14038
13991
  }).catch(() => this.context.logger?.warn("Could not update WAGO runtime transfer progress."));
14039
13992
  this.transferWrites.set(session.id, write);
14040
13993
  void write.then(() => {
14041
13994
  if (this.transferWrites.get(session.id) === write) this.transferWrites.delete(session.id);
14042
13995
  });
14043
13996
  }
14044
- async updateProgress(session, percent, step, detail) {
13997
+ async updateProgress(session, percent, step2, detail) {
14045
13998
  session.progressPercent = percent;
14046
- session.progressStep = step;
13999
+ session.progressStep = step2;
14047
14000
  session.progressDetail = detail;
14048
- await this.save(session, `progress: ${step}`);
14001
+ await this.save(session, `progress: ${step2}`);
14049
14002
  }
14050
14003
  async save(session, event) {
14051
14004
  await this.operationContext.getStore()?.assertOwned();
@@ -14053,7 +14006,13 @@ var WagoCommissioningProgress = class extends WagoCommissioningTransport {
14053
14006
  audit.push({ at: (/* @__PURE__ */ new Date()).toISOString(), event });
14054
14007
  session.auditLog = JSON.stringify(audit.slice(-50));
14055
14008
  session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
14056
- return this.sessions.save(session);
14009
+ return this.persist(session);
14010
+ }
14011
+ /** Writes the whole session row. A removed session is never brought back. */
14012
+ async persist(session) {
14013
+ const { id, ...patch } = session;
14014
+ if (!await this.sessions.update({ id }, patch)) throw new import_common29.NotFoundException("commissioning session not found");
14015
+ return session;
14057
14016
  }
14058
14017
  };
14059
14018
 
@@ -14303,7 +14262,7 @@ var WagoCommissioningService = class extends WagoCommissioningProgress {
14303
14262
  };
14304
14263
  WagoCommissioningService = __decorateClass([
14305
14264
  (0, import_common30.Injectable)(),
14306
- __decorateParam(0, (0, import_common30.Inject)(import_plugins_backend_sdk14.PLUGIN_CONTEXT)),
14265
+ __decorateParam(0, (0, import_common30.Inject)(import_plugins_backend_sdk11.PLUGIN_CONTEXT)),
14307
14266
  __decorateParam(1, (0, import_common30.Inject)(WagoService)),
14308
14267
  __decorateParam(2, (0, import_common30.Optional)()),
14309
14268
  __decorateParam(2, (0, import_common30.Inject)(WagoRuntimeArtifactsService)),
@@ -14314,7 +14273,7 @@ WagoCommissioningService = __decorateClass([
14314
14273
  ], WagoCommissioningService);
14315
14274
 
14316
14275
  // backend/credentials/service.ts
14317
- var import_plugins_backend_sdk15 = require("@attraccess/plugins-backend-sdk");
14276
+ var import_plugins_backend_sdk12 = require("@attraccess/plugins-backend-sdk");
14318
14277
  var import_common31 = require("@nestjs/common");
14319
14278
  var import_node_crypto24 = require("node:crypto");
14320
14279
  var WagoCredentialRotationUncertainError = class extends import_common31.ConflictException {
@@ -14322,45 +14281,6 @@ var WagoCredentialRotationUncertainError = class extends import_common31.Conflic
14322
14281
  super("Credential rotation is incomplete. Inspect its recovery state and retry the pending handoff.");
14323
14282
  }
14324
14283
  };
14325
- var WagoCredentialRotationEntity = class {
14326
- constructor() {
14327
- __publicField(this, "controllerId");
14328
- __publicField(this, "revision");
14329
- __publicField(this, "credentialEpoch");
14330
- __publicField(this, "phase");
14331
- __publicField(this, "mqttServerId");
14332
- __publicField(this, "prefix");
14333
- __publicField(this, "token");
14334
- __publicField(this, "encryptedCredentials");
14335
- }
14336
- };
14337
- __decorateClass([
14338
- (0, import_plugins_backend_sdk15.PrimaryColumn)({ type: "integer", name: "controller_id" })
14339
- ], WagoCredentialRotationEntity.prototype, "controllerId", 2);
14340
- __decorateClass([
14341
- (0, import_plugins_backend_sdk15.Column)({ type: "integer" })
14342
- ], WagoCredentialRotationEntity.prototype, "revision", 2);
14343
- __decorateClass([
14344
- (0, import_plugins_backend_sdk15.Column)({ type: "varchar", name: "credential_epoch" })
14345
- ], WagoCredentialRotationEntity.prototype, "credentialEpoch", 2);
14346
- __decorateClass([
14347
- (0, import_plugins_backend_sdk15.Column)({ type: "varchar" })
14348
- ], WagoCredentialRotationEntity.prototype, "phase", 2);
14349
- __decorateClass([
14350
- (0, import_plugins_backend_sdk15.Column)({ type: "integer", name: "mqtt_server_id" })
14351
- ], WagoCredentialRotationEntity.prototype, "mqttServerId", 2);
14352
- __decorateClass([
14353
- (0, import_plugins_backend_sdk15.Column)({ type: "varchar" })
14354
- ], WagoCredentialRotationEntity.prototype, "prefix", 2);
14355
- __decorateClass([
14356
- (0, import_plugins_backend_sdk15.Column)({ type: "varchar" })
14357
- ], WagoCredentialRotationEntity.prototype, "token", 2);
14358
- __decorateClass([
14359
- (0, import_plugins_backend_sdk15.Column)({ type: "text", name: "encrypted_credentials", nullable: true, select: false })
14360
- ], WagoCredentialRotationEntity.prototype, "encryptedCredentials", 2);
14361
- WagoCredentialRotationEntity = __decorateClass([
14362
- (0, import_plugins_backend_sdk15.Entity)({ name: "plugin_wago_credential_rotations" })
14363
- ], WagoCredentialRotationEntity);
14364
14284
  var CAPABILITY = "credential-rotation-v1";
14365
14285
  var WAIT_MS = 3e4;
14366
14286
  function assertRotationController(controller, retry) {
@@ -14459,19 +14379,15 @@ var WagoCredentialRotationService = class {
14459
14379
  }
14460
14380
  async rotate(controllerId, prefix, principal, guard, retry = false) {
14461
14381
  await guard.assertOwned();
14462
- const controller = await this.context.getRepository(WagoController).findOneBy({ id: controllerId });
14382
+ const controller = await this.tables.controllers.get(controllerId);
14463
14383
  if (!controller) throw new import_common31.NotFoundException("WAGO controller not found");
14464
14384
  assertRotationController(controller, retry);
14465
- const [epochRow] = await this.repository.query(
14466
- "SELECT credential_epoch AS epoch FROM plugin_wago_controllers WHERE id = ?",
14467
- [controllerId]
14468
- );
14469
- const credentialEpoch = epochRow?.epoch;
14385
+ const credentialEpoch = controller.credentialEpoch;
14470
14386
  if (typeof credentialEpoch !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(credentialEpoch))
14471
14387
  throw new import_common31.ConflictException("Re-enroll this controller with a credential epoch before rotating credentials.");
14472
14388
  prefix = normalizeOperationalPrefix(prefix);
14473
14389
  const identity = `wago-controller-${controller.hardwareId}`;
14474
- const previous = await this.repository.createQueryBuilder("rotation").addSelect("rotation.encryptedCredentials").where("rotation.controllerId = :controllerId", { controllerId }).getOne();
14390
+ const previous = await this.tables.credentialRotations.get(controllerId);
14475
14391
  const completed = checkPendingRotation(previous, credentialEpoch, retry, controller.mqttServerId, prefix);
14476
14392
  if (completed) return completed;
14477
14393
  const lifecycle = new WagoAudit(this.context).begin(principal, controllerId, "credential_rotation");
@@ -14482,7 +14398,7 @@ var WagoCredentialRotationService = class {
14482
14398
  if (!retry) {
14483
14399
  const revision2 = (previous?.revision ?? 0) + 1;
14484
14400
  if (!Number.isSafeInteger(revision2)) throw new import_common31.ConflictException("Credential rotation revision exhausted.");
14485
- row = this.repository.create({
14401
+ row = {
14486
14402
  controllerId,
14487
14403
  revision: revision2,
14488
14404
  credentialEpoch,
@@ -14491,9 +14407,9 @@ var WagoCredentialRotationService = class {
14491
14407
  prefix,
14492
14408
  token: (0, import_node_crypto24.randomBytes)(32).toString("base64url"),
14493
14409
  encryptedCredentials: null
14494
- });
14410
+ };
14495
14411
  await guard.assertOwned();
14496
- await this.repository.save(row);
14412
+ await this.tables.credentialRotations.upsert(row, { conflictOn: ["controllerId"] });
14497
14413
  await guard.assertOwned();
14498
14414
  const root = `${prefix}/v1/controllers/${controller.hardwareId}`;
14499
14415
  uncertain = true;
@@ -14510,8 +14426,8 @@ var WagoCredentialRotationService = class {
14510
14426
  await guard.assertOwned();
14511
14427
  if (!("password" in credential2)) {
14512
14428
  uncertain = false;
14513
- if (previous) await this.repository.save(previous);
14514
- else await this.repository.delete(controllerId);
14429
+ if (previous) await this.tables.credentialRotations.upsert(previous, { conflictOn: ["controllerId"] });
14430
+ else await this.tables.credentialRotations.delete({ controllerId });
14515
14431
  throw new import_common31.ConflictException("Automatic broker credential rotation is unavailable.");
14516
14432
  }
14517
14433
  if (credential2.username !== identity || !credential2.password || credential2.password.length > 4096)
@@ -14520,10 +14436,13 @@ var WagoCredentialRotationService = class {
14520
14436
  const encrypted = this.context.secrets.encrypt(plaintext);
14521
14437
  if (!encrypted || encrypted === plaintext || this.context.secrets.decrypt(encrypted) !== plaintext)
14522
14438
  throw new import_common31.ConflictException("Credential recovery storage is unavailable.");
14523
- row.encryptedCredentials = encrypted;
14524
- row.phase = "pending";
14439
+ row = { ...row, encryptedCredentials: encrypted, phase: "pending" };
14525
14440
  await guard.assertOwned();
14526
- await this.repository.save(row);
14441
+ const stored = await this.tables.credentialRotations.update(
14442
+ { controllerId, revision: row.revision, phase: "provisioning" },
14443
+ { encryptedCredentials: encrypted, phase: "pending" }
14444
+ );
14445
+ if (!stored) throw new import_common31.ConflictException("Credential recovery storage is unavailable.");
14527
14446
  }
14528
14447
  if (!row?.encryptedCredentials) throw new import_common31.ConflictException("Credential recovery storage is unavailable.");
14529
14448
  const credential = JSON.parse(this.context.secrets.decrypt(row.encryptedCredentials));
@@ -14531,9 +14450,12 @@ var WagoCredentialRotationService = class {
14531
14450
  throw new import_common31.ConflictException("Credential recovery storage is unavailable.");
14532
14451
  await this.handoff(controller.hardwareId, row, credential, guard);
14533
14452
  await guard.assertOwned();
14534
- row.phase = "completed";
14535
- row.encryptedCredentials = null;
14536
- await this.repository.save(row);
14453
+ const completed2 = await this.tables.credentialRotations.update(
14454
+ { controllerId, revision: row.revision, phase: "pending", token: row.token },
14455
+ { phase: "completed", encryptedCredentials: null }
14456
+ );
14457
+ if (!completed2) throw new import_common31.ConflictException("Credential rotation changed during the handoff.");
14458
+ row = { ...row, phase: "completed", encryptedCredentials: null };
14537
14459
  await guard.assertOwned();
14538
14460
  await lifecycle.finish("succeeded");
14539
14461
  return { state: "completed", revision: row.revision };
@@ -14547,21 +14469,21 @@ var WagoCredentialRotationService = class {
14547
14469
  }
14548
14470
  /** Call inside guarded removal, before its existing broker revocation; deletion then cascades this row. */
14549
14471
  async assertRemovalBroker(controllerId, mqttServerId) {
14550
- const row = await this.repository.findOneBy({ controllerId });
14472
+ const row = await this.tables.credentialRotations.get(controllerId);
14551
14473
  if (row && row.mqttServerId !== mqttServerId)
14552
14474
  throw new import_common31.ConflictException("Revoke the original rotation broker identity before removing this controller.");
14553
14475
  }
14554
14476
  async status(controllerId) {
14555
- const row = await this.repository.findOne({ where: { controllerId }, select: { phase: true, revision: true } });
14477
+ const row = await this.tables.credentialRotations.get(controllerId);
14556
14478
  return row ? { state: row.phase, revision: row.revision } : { state: "none" };
14557
14479
  }
14558
- get repository() {
14559
- return this.context.getRepository(WagoCredentialRotationEntity);
14480
+ get tables() {
14481
+ return openWagoStorage(this.context);
14560
14482
  }
14561
14483
  };
14562
14484
  WagoCredentialRotationService = __decorateClass([
14563
14485
  (0, import_common31.Injectable)(),
14564
- __decorateParam(0, (0, import_common31.Inject)(import_plugins_backend_sdk15.PLUGIN_CONTEXT))
14486
+ __decorateParam(0, (0, import_common31.Inject)(import_plugins_backend_sdk12.PLUGIN_CONTEXT))
14565
14487
  ], WagoCredentialRotationService);
14566
14488
 
14567
14489
  // backend/controllers/controller.ts
@@ -14844,26 +14766,26 @@ __decorateClass([
14844
14766
  __decorateParam(1, (0, import_common32.Req)())
14845
14767
  ], WagoControllerApi.prototype, "removeController", 1);
14846
14768
  __decorateClass([
14847
- (0, import_plugins_backend_sdk16.Auth)("resources.update"),
14769
+ (0, import_plugins_backend_sdk13.Auth)("resources.update"),
14848
14770
  (0, import_common32.Post)("controllers/:id/commands"),
14849
14771
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe)),
14850
14772
  __decorateParam(1, (0, import_common32.Body)()),
14851
14773
  __decorateParam(2, (0, import_common32.Req)())
14852
14774
  ], WagoControllerApi.prototype, "manualCommand", 1);
14853
14775
  __decorateClass([
14854
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14776
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14855
14777
  (0, import_common32.Post)("controllers/:id/credentials/rotate"),
14856
14778
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe)),
14857
14779
  __decorateParam(1, (0, import_common32.Body)()),
14858
14780
  __decorateParam(2, (0, import_common32.Req)())
14859
14781
  ], WagoControllerApi.prototype, "rotateCredentials", 1);
14860
14782
  __decorateClass([
14861
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14783
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14862
14784
  (0, import_common32.Get)("controllers/:id/credentials/rotation"),
14863
14785
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe))
14864
14786
  ], WagoControllerApi.prototype, "credentialRotationStatus", 1);
14865
14787
  __decorateClass([
14866
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14788
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14867
14789
  (0, import_common32.Post)("controllers/:id/credentials/manual/complete"),
14868
14790
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe)),
14869
14791
  __decorateParam(1, (0, import_common32.Body)()),
@@ -14876,17 +14798,17 @@ __decorateClass([
14876
14798
  __decorateParam(2, (0, import_common32.Req)())
14877
14799
  ], WagoControllerApi.prototype, "claim", 1);
14878
14800
  __decorateClass([
14879
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14801
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14880
14802
  (0, import_common32.Delete)("commissioning/sessions/:id"),
14881
14803
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe))
14882
14804
  ], WagoControllerApi.prototype, "removeCommissioningSession", 1);
14883
14805
  __decorateClass([
14884
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14806
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14885
14807
  (0, import_common32.Post)("commissioning/sessions/:id/revoke"),
14886
14808
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe))
14887
14809
  ], WagoControllerApi.prototype, "revokeCommissioningSession", 1);
14888
14810
  __decorateClass([
14889
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14811
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14890
14812
  (0, import_common32.Post)("commissioning/sessions/:id/management/:action"),
14891
14813
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe)),
14892
14814
  __decorateParam(1, (0, import_common32.Param)("action")),
@@ -14894,7 +14816,7 @@ __decorateClass([
14894
14816
  __decorateParam(3, (0, import_common32.Req)())
14895
14817
  ], WagoControllerApi.prototype, "manageSecurity", 1);
14896
14818
  __decorateClass([
14897
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14819
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14898
14820
  (0, import_common32.Post)("commissioning/sessions/:id/platform/:action"),
14899
14821
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe)),
14900
14822
  __decorateParam(1, (0, import_common32.Param)("action")),
@@ -14902,65 +14824,65 @@ __decorateClass([
14902
14824
  __decorateParam(3, (0, import_common32.Req)())
14903
14825
  ], WagoControllerApi.prototype, "platformAction", 1);
14904
14826
  __decorateClass([
14905
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14827
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14906
14828
  (0, import_common32.Get)("commissioning/sessions/:id/management"),
14907
14829
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe))
14908
14830
  ], WagoControllerApi.prototype, "managementStatus", 1);
14909
14831
  __decorateClass([
14910
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14832
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14911
14833
  (0, import_common32.Get)("commissioning/sessions/:id/verification"),
14912
14834
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe))
14913
14835
  ], WagoControllerApi.prototype, "commissioningVerification", 1);
14914
14836
  __decorateClass([
14915
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14837
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14916
14838
  (0, import_common32.Post)("commissioning/sessions/:id/recover"),
14917
14839
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe)),
14918
14840
  __decorateParam(1, (0, import_common32.Body)()),
14919
14841
  __decorateParam(2, (0, import_common32.Req)())
14920
14842
  ], WagoControllerApi.prototype, "recoverCommissioningSession", 1);
14921
14843
  __decorateClass([
14922
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14844
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14923
14845
  (0, import_common32.Post)("commissioning/sessions/:id/deliver"),
14924
14846
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe)),
14925
14847
  __decorateParam(1, (0, import_common32.Body)()),
14926
14848
  __decorateParam(2, (0, import_common32.Req)())
14927
14849
  ], WagoControllerApi.prototype, "deliverCommissioningSession", 1);
14928
14850
  __decorateClass([
14929
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14851
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14930
14852
  (0, import_common32.Post)("commissioning/sessions/:id/confirm-host-key"),
14931
14853
  __decorateParam(0, (0, import_common32.Param)("id", import_common32.ParseIntPipe)),
14932
14854
  __decorateParam(1, (0, import_common32.Body)())
14933
14855
  ], WagoControllerApi.prototype, "confirmCommissioningHostKey", 1);
14934
14856
  __decorateClass([
14935
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14857
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14936
14858
  (0, import_common32.Post)("commissioning/sessions"),
14937
14859
  __decorateParam(0, (0, import_common32.Body)()),
14938
14860
  __decorateParam(1, (0, import_common32.Req)())
14939
14861
  ], WagoControllerApi.prototype, "createCommissioningSession", 1);
14940
14862
  __decorateClass([
14941
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14863
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14942
14864
  (0, import_common32.Get)("commissioning/sessions"),
14943
14865
  __decorateParam(0, (0, import_common32.Query)("limit")),
14944
14866
  __decorateParam(1, (0, import_common32.Query)("offset"))
14945
14867
  ], WagoControllerApi.prototype, "commissioningSessions", 1);
14946
14868
  __decorateClass([
14947
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14869
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14948
14870
  (0, import_common32.Get)("commissioning/support")
14949
14871
  ], WagoControllerApi.prototype, "commissioningSupport", 1);
14950
14872
  __decorateClass([
14951
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14873
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14952
14874
  (0, import_common32.Post)("settings"),
14953
14875
  __decorateParam(0, (0, import_common32.Body)())
14954
14876
  ], WagoControllerApi.prototype, "setSettings", 1);
14955
14877
  __decorateClass([
14956
- (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
14878
+ (0, import_plugins_backend_sdk13.Auth)("system.settings.manage"),
14957
14879
  (0, import_common32.Get)("settings")
14958
14880
  ], WagoControllerApi.prototype, "settings", 1);
14959
14881
  __decorateClass([
14960
14882
  (0, import_common32.Get)("controllers")
14961
14883
  ], WagoControllerApi.prototype, "list", 1);
14962
14884
  WagoControllerApi = __decorateClass([
14963
- (0, import_plugins_backend_sdk16.Auth)("resources.update"),
14885
+ (0, import_plugins_backend_sdk13.Auth)("resources.update"),
14964
14886
  (0, import_common32.Controller)("wago"),
14965
14887
  __decorateParam(0, (0, import_common32.Inject)(WagoService)),
14966
14888
  __decorateParam(1, (0, import_common32.Inject)(WagoCommissioningService)),
@@ -14970,7 +14892,7 @@ WagoControllerApi = __decorateClass([
14970
14892
 
14971
14893
  // backend/runtime/artifacts/controller.ts
14972
14894
  var import_common33 = require("@nestjs/common");
14973
- var import_plugins_backend_sdk17 = require("@attraccess/plugins-backend-sdk");
14895
+ var import_plugins_backend_sdk14 = require("@attraccess/plugins-backend-sdk");
14974
14896
  var WagoArtifactsController = class {
14975
14897
  constructor(artifacts) {
14976
14898
  __publicField(this, "artifacts", artifacts);
@@ -14997,14 +14919,37 @@ __decorateClass([
14997
14919
  (0, import_common33.Get)("current")
14998
14920
  ], WagoArtifactsController.prototype, "current", 1);
14999
14921
  WagoArtifactsController = __decorateClass([
15000
- (0, import_plugins_backend_sdk17.Auth)("system.settings.manage"),
14922
+ (0, import_plugins_backend_sdk14.Auth)("system.settings.manage"),
15001
14923
  (0, import_common33.Controller)("wago/runtime-artifacts"),
15002
14924
  __decorateParam(0, (0, import_common33.Inject)(WagoRuntimeArtifactsService))
15003
14925
  ], WagoArtifactsController);
15004
14926
 
15005
14927
  // backend/diagnostics/service.ts
15006
- var import_plugins_backend_sdk18 = require("@attraccess/plugins-backend-sdk");
14928
+ var import_plugins_backend_sdk15 = require("@attraccess/plugins-backend-sdk");
15007
14929
  var import_common34 = require("@nestjs/common");
14930
+
14931
+ // backend/configuration/latest-applied.ts
14932
+ var BATCH = 50;
14933
+ async function loadLatestAppliedRevisions(revisions, controllerIds) {
14934
+ const latest = [];
14935
+ for (let start = 0; start < controllerIds.length; start += BATCH) {
14936
+ const found = await Promise.all(
14937
+ controllerIds.slice(start, start + BATCH).map(async (controllerId) => ({
14938
+ controllerId,
14939
+ revision: (await revisions.aggregate("revision", { controllerId, state: "applied" })).max
14940
+ }))
14941
+ );
14942
+ for (const entry of found) if (entry.revision !== null) latest.push({ ...entry, revision: entry.revision });
14943
+ }
14944
+ const rows = [];
14945
+ for (let start = 0; start < latest.length; start += BATCH) {
14946
+ const keys = latest.slice(start, start + BATCH).map(({ controllerId, revision: revision2 }) => ({ controllerId, revision: revision2 }));
14947
+ rows.push(...await revisions.find({ where: { and: [{ state: "applied" }, { or: keys }] } }));
14948
+ }
14949
+ return rows;
14950
+ }
14951
+
14952
+ // backend/diagnostics/service.ts
15008
14953
  function configurationRejections(latest, runtime) {
15009
14954
  return latest?.rejectionErrors ? safeValidationSummaries(JSON.parse(latest.rejectionErrors)) : latest && runtime.rejection?.revision === latest.revision && runtime.rejection.contentHash === latest.contentHash ? runtime.rejection.errors : [];
15010
14955
  }
@@ -15035,6 +14980,10 @@ function own(values, key) {
15035
14980
  function referenceOwner(node) {
15036
14981
  return node.flowId != null ? `flow ${node.flowId}` : `resource ${node.resourceId}`;
15037
14982
  }
14983
+ var withFlow = (node) => ({
14984
+ ...node,
14985
+ flow: node.flowName ? { name: node.flowName } : null
14986
+ });
15038
14987
  function diagnosticReferences(nodes, channelIds, revision2, capabilities) {
15039
14988
  return nodes.map((node) => {
15040
14989
  const channelId2 = typeof node.data.channelId === "string" ? node.data.channelId : "";
@@ -15082,13 +15031,24 @@ var WagoDiagnosticsService = class {
15082
15031
  __publicField(this, "wago", wago);
15083
15032
  }
15084
15033
  async get(controllerId) {
15085
- const controller = await this.context.getRepository(WagoController).findOneBy({ id: controllerId });
15034
+ const tables = openWagoStorage(this.context);
15035
+ const controller = await tables.controllers.get(controllerId);
15086
15036
  if (!controller) throw new import_common34.NotFoundException("WAGO controller not found");
15087
15037
  const [draft, latest, applied, nodes] = await Promise.all([
15088
- this.context.getRepository(WagoConfigurationDraft).findOneBy({ controllerId }),
15089
- this.context.getRepository(WagoConfigurationRevision).findOne({ where: { controllerId }, order: { revision: "DESC" } }),
15090
- this.context.getRepository(WagoConfigurationRevision).findOne({ where: { controllerId, state: "applied" }, order: { revision: "DESC" } }),
15091
- this.context.dataSource.getRepository(import_plugins_backend_sdk18.ResourceFlowNode).createQueryBuilder("node").leftJoin("node.flow", "flow").addSelect(["flow.id", "flow.name"]).where("node.type LIKE :type", { type: "plugin.wago.%" }).andWhere("node.data ->> 'controllerId' = :controllerId", { controllerId }).take(1001).getMany()
15038
+ tables.configurationDrafts.findOne({ where: { controllerId } }),
15039
+ tables.configurationRevisions.findOne({
15040
+ where: { controllerId },
15041
+ orderBy: [{ field: "revision", direction: "desc" }]
15042
+ }),
15043
+ tables.configurationRevisions.findOne({
15044
+ where: { controllerId, state: "applied" },
15045
+ orderBy: [{ field: "revision", direction: "desc" }]
15046
+ }),
15047
+ this.context.hostData.flows.findNodes({
15048
+ typePrefix: "plugin.wago.",
15049
+ dataEquals: { controllerId },
15050
+ limit: 1001
15051
+ })
15092
15052
  ]);
15093
15053
  const runtime = this.wago.diagnostics.read(controllerId);
15094
15054
  const runtimeUpdate = this.wago.isRuntimeUpdateRequired?.(controllerId) ?? false;
@@ -15108,7 +15068,7 @@ var WagoDiagnosticsService = class {
15108
15068
  availability: "disabled"
15109
15069
  }));
15110
15070
  const references = diagnosticReferences(
15111
- nodes.slice(0, 1e3),
15071
+ nodes.slice(0, 1e3).map(withFlow),
15112
15072
  appliedSnapshot?.logicalChannels.map((channel) => channel.id) ?? [],
15113
15073
  applied?.revision ?? null,
15114
15074
  Object.fromEntries(appliedSnapshot?.logicalChannels.map((channel) => [channel.id, channel.capabilities]) ?? [])
@@ -15172,7 +15132,12 @@ var WagoDiagnosticsService = class {
15172
15132
  };
15173
15133
  }
15174
15134
  async getResource(resourceId) {
15175
- const nodes = await this.context.dataSource.getRepository(import_plugins_backend_sdk18.ResourceFlowNode).createQueryBuilder("node").where("node.resourceId = :resourceId", { resourceId }).andWhere("node.type LIKE :type", { type: "plugin.wago.%" }).orderBy("node.id", "ASC").take(1001).getMany();
15135
+ const nodes = (await this.context.hostData.flows.findNodes({
15136
+ typePrefix: "plugin.wago.",
15137
+ resourceId,
15138
+ orderById: true,
15139
+ limit: 1001
15140
+ })).map(withFlow);
15176
15141
  const controllerIds = /* @__PURE__ */ new Set();
15177
15142
  let invalidControllerReferences = 0;
15178
15143
  for (const node of nodes.slice(0, 1e3)) {
@@ -15193,15 +15158,19 @@ var WagoDiagnosticsService = class {
15193
15158
  )
15194
15159
  ];
15195
15160
  const controllerIdsForQuery = selectedControllerIds;
15196
- const [controllers, appliedRevisions, conflictNodes] = await Promise.all([
15197
- this.context.getRepository(WagoController).createQueryBuilder("controller").select(["controller.id", "controller.name", "controller.hardwareId"]).where("controller.id IN (:...controllerIds)", { controllerIds: selectedControllerIds }).getMany(),
15198
- this.context.getRepository(WagoConfigurationRevision).createQueryBuilder("revision").select(["revision.controllerId", "revision.revision", "revision.snapshot"]).where("revision.controllerId IN (:...controllerIds)", { controllerIds: selectedControllerIds }).andWhere("revision.state = :state", { state: "applied" }).andWhere(
15199
- "revision.revision = (SELECT MAX(applied.revision) FROM plugin_wago_configuration_revisions applied WHERE applied.controller_id = revision.controller_id AND applied.state = :state)"
15200
- ).orderBy("revision.controllerId", "ASC").addOrderBy("revision.revision", "DESC").getMany(),
15201
- localChannelIds.length ? this.context.dataSource.getRepository(import_plugins_backend_sdk18.ResourceFlowNode).createQueryBuilder("node").leftJoin("node.flow", "flow").addSelect(["flow.id", "flow.name"]).where("node.data ->> 'controllerId' IN (:...controllerIds)", { controllerIds: controllerIdsForQuery }).andWhere("node.data ->> 'channelId' IN (:...channelIds)", { channelIds: localChannelIds }).andWhere("node.type = :type", { type: "plugin.wago.command" }).take(1001).getMany() : Promise.resolve([])
15161
+ const tables = openWagoStorage(this.context);
15162
+ const [controllers, appliedRows, conflictNodes] = await Promise.all([
15163
+ tables.controllers.find({ where: { id: { in: selectedControllerIds } } }),
15164
+ // Only the newest applied revision of each controller; older snapshots are never loaded.
15165
+ loadLatestAppliedRevisions(tables.configurationRevisions, selectedControllerIds),
15166
+ localChannelIds.length ? this.context.hostData.flows.findNodes({
15167
+ type: "plugin.wago.command",
15168
+ dataIn: { controllerId: controllerIdsForQuery, channelId: localChannelIds },
15169
+ limit: 1001
15170
+ }) : Promise.resolve([])
15202
15171
  ]);
15203
15172
  const controllersById = new Map(controllers.map((controller) => [controller.id, controller]));
15204
- const appliedByControllerId = new Map(appliedRevisions.map((revision2) => [revision2.controllerId, revision2]));
15173
+ const appliedByControllerId = new Map(appliedRows.map((revision2) => [revision2.controllerId, revision2]));
15205
15174
  const referencesTruncated = conflictNodes.length > 1e3;
15206
15175
  const conflictNodesByControllerId = /* @__PURE__ */ new Map();
15207
15176
  for (const node of conflictNodes.slice(0, 1e3)) {
@@ -15209,19 +15178,16 @@ var WagoDiagnosticsService = class {
15209
15178
  const controllerId = node.data.controllerId;
15210
15179
  if (typeof controllerId !== "number") continue;
15211
15180
  const matchingNodes = conflictNodesByControllerId.get(controllerId) ?? [];
15212
- matchingNodes.push(node);
15181
+ matchingNodes.push(withFlow(node));
15213
15182
  conflictNodesByControllerId.set(controllerId, matchingNodes);
15214
15183
  }
15215
- const conflictResourceIds = [
15216
- ...new Set(
15217
- [...conflictNodesByControllerId.values()].flat().map((n) => n.resourceId).filter((id) => id != null)
15218
- )
15219
- ];
15220
- const conflictResources = conflictResourceIds.length ? await this.context.dataSource.getRepository(import_plugins_backend_sdk18.Resource).createQueryBuilder("resource").select(["resource.id", "resource.name"]).where("resource.id IN (:...ids)", { ids: conflictResourceIds }).getMany() : [];
15221
- const resourceNames = new Map(conflictResources.map((resource) => [resource.id, resource.name]));
15184
+ const resourceNames = /* @__PURE__ */ new Map();
15185
+ for (const node of conflictNodes) {
15186
+ if (node.resourceId != null && node.resourceName != null) resourceNames.set(node.resourceId, node.resourceName);
15187
+ }
15222
15188
  const flowNames = /* @__PURE__ */ new Map();
15223
15189
  for (const node of conflictNodes) {
15224
- if (node.flowId != null && node.flow?.name) flowNames.set(node.flowId, node.flow.name);
15190
+ if (node.flowId != null && node.flowName) flowNames.set(node.flowId, node.flowName);
15225
15191
  }
15226
15192
  const controllersResult = selectedControllerIds.map((controllerId) => {
15227
15193
  const controller = controllersById.get(controllerId);
@@ -15303,7 +15269,7 @@ __decorateClass([
15303
15269
  __decorateParam(0, (0, import_common34.Param)("id", import_common34.ParseIntPipe))
15304
15270
  ], WagoDiagnosticsController.prototype, "getResource", 1);
15305
15271
  WagoDiagnosticsController = __decorateClass([
15306
- (0, import_plugins_backend_sdk18.Auth)("resources.update"),
15272
+ (0, import_plugins_backend_sdk15.Auth)("resources.update"),
15307
15273
  (0, import_common34.Controller)("wago"),
15308
15274
  __decorateParam(0, (0, import_common34.Inject)(WagoDiagnosticsService))
15309
15275
  ], WagoDiagnosticsController);
@@ -15431,15 +15397,15 @@ var WagoFlowServiceState = class {
15431
15397
  __publicField(this, "messageQueue", Promise.resolve());
15432
15398
  __publicField(this, "refreshTimer", null);
15433
15399
  }
15434
- // Plugin registration precedes the host datasource; resolve repositories only when used.
15400
+ // Plugin registration precedes the host storage; open the tables only when used.
15435
15401
  get controllers() {
15436
- return this.context.getRepository(WagoController);
15402
+ return openWagoStorage(this.context).controllers;
15437
15403
  }
15438
15404
  get revisions() {
15439
- return this.context.getRepository(WagoConfigurationRevision);
15405
+ return openWagoStorage(this.context).configurationRevisions;
15440
15406
  }
15441
15407
  get settings() {
15442
- return this.context.getRepository(WagoSettings);
15408
+ return openWagoStorage(this.context).settings;
15443
15409
  }
15444
15410
  };
15445
15411
  WagoFlowServiceState = __decorateClass([
@@ -15523,20 +15489,21 @@ var WagoFlowQueries = class extends WagoFlowServiceState {
15523
15489
  }
15524
15490
  async resolveConfigSchema(config, kind, validationContext = /* @__PURE__ */ new Map(), previewOnly = false) {
15525
15491
  const controllerCacheKey = previewOnly ? `wago-flow-controllers:preview:${config.controllerId}` : "wago-flow-controllers";
15492
+ const controllerId = Number.isSafeInteger(config.controllerId) ? config.controllerId : null;
15526
15493
  const controllers = await this.cached(
15527
15494
  validationContext,
15528
15495
  controllerCacheKey,
15529
- () => previewOnly && typeof config.controllerId !== "number" ? Promise.resolve([]) : this.controllers.find({
15530
- where: { trustState: "claimed", ...previewOnly ? { id: config.controllerId } : {} },
15531
- order: { name: "ASC" }
15496
+ () => previewOnly && controllerId === null ? Promise.resolve([]) : this.controllers.find({
15497
+ where: { trustState: "claimed", ...previewOnly ? { id: controllerId } : {} },
15498
+ orderBy: [{ field: "name", direction: "asc" }]
15532
15499
  })
15533
15500
  );
15534
15501
  const selected = typeof config.controllerId === "number" ? controllers.find((controller) => controller.id === config.controllerId) : void 0;
15535
15502
  const revision2 = selected ? await this.cached(validationContext, `wago-applied-revision:${selected.id}`, async () => {
15536
15503
  const [latest] = await this.revisions.find({
15537
15504
  where: { controllerId: selected.id, state: "applied" },
15538
- order: { revision: "DESC" },
15539
- take: 1
15505
+ orderBy: [{ field: "revision", direction: "desc" }],
15506
+ limit: 1
15540
15507
  });
15541
15508
  return latest ?? null;
15542
15509
  }) : null;
@@ -15615,7 +15582,7 @@ var WagoFlowQueries = class extends WagoFlowServiceState {
15615
15582
  };
15616
15583
  }
15617
15584
  async refresh() {
15618
- const settings = await this.settings.findOneBy({ id: 1 });
15585
+ const settings = await this.settings.get(1);
15619
15586
  if (!settings) return;
15620
15587
  const controllers = await this.controllers.find({ where: { trustState: "claimed" } });
15621
15588
  const controllerIds = new Set(controllers.map((controller) => controller.id));
@@ -15798,20 +15765,15 @@ var WagoFlowService = class extends WagoFlowQueries {
15798
15765
  }
15799
15766
  }
15800
15767
  async loadLatestAppliedRevisions(controllerIds) {
15801
- if (!controllerIds.length) return [];
15802
- return this.revisions.createQueryBuilder("revision").innerJoin(
15803
- (query) => query.subQuery().select("latest.controllerId", "controllerId").addSelect("MAX(latest.revision)", "revision").from(WagoConfigurationRevision, "latest").where("latest.controllerId IN (:...controllerIds)", { controllerIds }).andWhere("latest.state = :state", { state: "applied" }).groupBy("latest.controllerId"),
15804
- "latest",
15805
- "latest.controllerId = revision.controllerId AND latest.revision = revision.revision"
15806
- ).where("revision.state = :state", { state: "applied" }).getMany();
15768
+ return loadLatestAppliedRevisions(this.revisions, controllerIds);
15807
15769
  }
15808
15770
  async channels(controllerId) {
15809
15771
  const cached = this.channelCache.get(controllerId);
15810
15772
  if (cached) return cached;
15811
15773
  const [revision2] = await this.revisions.find({
15812
15774
  where: { controllerId, state: "applied" },
15813
- order: { revision: "DESC" },
15814
- take: 1
15775
+ orderBy: [{ field: "revision", direction: "desc" }],
15776
+ limit: 1
15815
15777
  });
15816
15778
  if (!revision2) {
15817
15779
  this.channelCache.set(controllerId, []);
@@ -16092,11 +16054,11 @@ var WAGO_AUDIT_DOMAIN = {
16092
16054
  };
16093
16055
 
16094
16056
  // backend/runtime/update/controller.ts
16095
- var import_plugins_backend_sdk19 = require("@attraccess/plugins-backend-sdk");
16096
- var import_common39 = require("@nestjs/common");
16057
+ var import_plugins_backend_sdk16 = require("@attraccess/plugins-backend-sdk");
16058
+ var import_common40 = require("@nestjs/common");
16097
16059
 
16098
16060
  // backend/network/service.ts
16099
- var import_common38 = require("@nestjs/common");
16061
+ var import_common39 = require("@nestjs/common");
16100
16062
  var import_node_crypto25 = require("node:crypto");
16101
16063
 
16102
16064
  // backend/network/model.ts
@@ -16131,8 +16093,52 @@ function assertSameManagedIdentity(row, access) {
16131
16093
  throw new import_common37.ConflictException("Pending change belongs to another managed identity.");
16132
16094
  }
16133
16095
 
16134
- // backend/network/service.ts
16096
+ // backend/network/status.ts
16097
+ var import_common38 = require("@nestjs/common");
16098
+ async function networkStatus(storage, controllerId) {
16099
+ const controller = await storage.controllers.get(controllerId);
16100
+ if (!controller) throw new import_common38.NotFoundException("WAGO controller not found");
16101
+ const [access, row, pendingCredentialRetirements] = await Promise.all([
16102
+ storage.managedAccess.findOne({
16103
+ where: { controllerId },
16104
+ orderBy: [{ field: "sessionId", direction: "desc" }]
16105
+ }),
16106
+ storage.networkChanges.get(controllerId),
16107
+ storage.mqttCredentialRetirements.count({ controllerId })
16108
+ ]);
16109
+ const lease = row && await storage.deviceOperations.get(row.fingerprint);
16110
+ return {
16111
+ available: access?.state === "managed",
16112
+ targetHost: access?.host ?? null,
16113
+ mqttServerId: controller.mqttServerId,
16114
+ pendingCredentialRetirements,
16115
+ operation: row ? {
16116
+ targetHost: row.targetHost,
16117
+ mqttServerId: row.mqttServerId,
16118
+ phase: row.phase,
16119
+ failure: row.failure,
16120
+ running: row.phase !== "completed" && !!lease?.owner && Number(lease.leaseUntil) > Date.now()
16121
+ } : null
16122
+ };
16123
+ }
16124
+
16125
+ // backend/network/credential-destination.ts
16135
16126
  var import_promises11 = require("node:dns/promises");
16127
+ async function sharesCredentialDestination(previous, current) {
16128
+ const sameHost = previous.host.toLowerCase().replace(/\.$/, "") === current.host.toLowerCase().replace(/\.$/, "");
16129
+ if (sameHost) return true;
16130
+ const destinations = await Promise.all([(0, import_promises11.lookup)(previous.host, { all: true }), (0, import_promises11.lookup)(current.host, { all: true })]);
16131
+ const address = (value) => value.toLowerCase().replace(/^::ffff:/, "");
16132
+ if (!destinations[0].length || !destinations[1].length) throw new Error();
16133
+ const previousAddresses = new Set(destinations[0].map((item) => address(item.address)));
16134
+ const currentAddresses = new Set(destinations[1].map((item) => address(item.address)));
16135
+ const overlaps = [...previousAddresses].some((item) => currentAddresses.has(item));
16136
+ const sameAddresses = previousAddresses.size === currentAddresses.size && [...previousAddresses].every((item) => currentAddresses.has(item));
16137
+ if (overlaps && !sameAddresses) throw new Error();
16138
+ return sameAddresses;
16139
+ }
16140
+
16141
+ // backend/network/service.ts
16136
16142
  var WagoNetworkChangeService = class {
16137
16143
  constructor(context, managed, wago) {
16138
16144
  __publicField(this, "context", context);
@@ -16140,31 +16146,36 @@ var WagoNetworkChangeService = class {
16140
16146
  __publicField(this, "wago", wago);
16141
16147
  __publicField(this, "active", /* @__PURE__ */ new Set());
16142
16148
  __publicField(this, "destroyed", false);
16149
+ __publicField(this, "storageCache");
16143
16150
  }
16144
16151
  async apply(controllerId, body, principal, retry = false) {
16145
- if (this.destroyed) throw new import_common38.ConflictException("Controller operation has stopped. Retry the request.");
16152
+ if (this.destroyed) throw new import_common39.ConflictException("Controller operation has stopped. Retry the request.");
16146
16153
  const input = retry ? null : networkChangeInput(body);
16147
- const access = await this.context.getRepository(WagoManagedAccess).findOne({ where: { controllerId, state: "managed" }, order: { sessionId: "DESC" } });
16148
- if (!access) throw new import_common38.ConflictException("Automatic SSH management is required for this operation.");
16149
- const operations = new WagoDeviceOperations(this.context.getRepository(WagoDeviceOperation));
16154
+ const access = await this.storage.managedAccess.findOne({
16155
+ where: { controllerId, state: "managed" },
16156
+ orderBy: [{ field: "sessionId", direction: "desc" }]
16157
+ });
16158
+ if (!access) throw new import_common39.ConflictException("Automatic SSH management is required for this operation.");
16159
+ const operations = new WagoDeviceOperations(this.storage.deviceOperations);
16150
16160
  const owner = (0, import_node_crypto25.randomBytes)(16).toString("hex"), now = Date.now();
16151
16161
  if (!await operations.acquire(access.fingerprint, owner, now, now + OPERATION_MS2 + 6e4))
16152
- throw new import_common38.ConflictException("Another controller operation is active. Retry after it finishes.");
16162
+ throw new import_common39.ConflictException("Another controller operation is active. Retry after it finishes.");
16153
16163
  const abort = new AbortController();
16154
16164
  this.active.add(abort);
16155
16165
  const timer = setTimeout(() => abort.abort(), OPERATION_MS2).unref();
16156
- const assertOwned = async () => {
16166
+ const assertOwned = async (scope) => {
16157
16167
  abort.signal.throwIfAborted();
16158
- await operations.assertOwned(access.fingerprint, owner);
16168
+ if (scope) await this.assertLeaseIn(scope, access.fingerprint, owner);
16169
+ else await operations.assertOwned(access.fingerprint, owner);
16159
16170
  };
16160
16171
  let row = null;
16161
16172
  let audited = false;
16162
16173
  const lifecycle = new WagoAudit(this.context).begin(principal, controllerId, "network_change");
16163
16174
  try {
16164
- const controller = await this.context.getRepository(WagoController).findOneBy({ id: controllerId, trustState: "claimed" });
16175
+ const controller = await this.storage.controllers.findOne({ where: { id: controllerId, trustState: "claimed" } });
16165
16176
  if (!controller?.mqttServerId || !controller.credentialEpoch)
16166
- throw new import_common38.ConflictException("Managed enrolled controller required.");
16167
- row = await this.repository.createQueryBuilder("change").addSelect("change.encryptedPayload").where("change.controllerId = :controllerId", { controllerId }).getOne();
16177
+ throw new import_common39.ConflictException("Managed enrolled controller required.");
16178
+ row = await this.storage.networkChanges.get(controllerId);
16168
16179
  if (retry && (!row || row.phase === "completed")) return this.status(controllerId);
16169
16180
  if (!retry) assertNoUnfinishedChange(row);
16170
16181
  await this.assertNoPendingRecovery(controllerId);
@@ -16192,7 +16203,7 @@ var WagoNetworkChangeService = class {
16192
16203
  } catch (error) {
16193
16204
  if (row && row.phase !== "completed") await this.recordFailure(row, error, assertOwned);
16194
16205
  if (audited) await lifecycle.finish("failed");
16195
- throw new import_common38.ConflictException("MQTT/address change is incomplete. Check its status and retry the saved operation.");
16206
+ throw new import_common39.ConflictException("MQTT/address change is incomplete. Check its status and retry the saved operation.");
16196
16207
  } finally {
16197
16208
  clearTimeout(timer);
16198
16209
  abort.abort();
@@ -16202,17 +16213,19 @@ var WagoNetworkChangeService = class {
16202
16213
  }
16203
16214
  /** Network changes must not race credential rotation or runtime update recovery. */
16204
16215
  async assertNoPendingRecovery(controllerId) {
16205
- const rotation = await this.context.getRepository(WagoCredentialRotationEntity).findOneBy({ controllerId });
16206
- const update = await this.context.getRepository(WagoRuntimeUpdateEntity).findOneBy({ controllerId });
16216
+ const [rotation, update] = await Promise.all([
16217
+ this.storage.credentialRotations.get(controllerId),
16218
+ this.storage.runtimeUpdates.get(controllerId)
16219
+ ]);
16207
16220
  if (rotation && rotation.phase !== "completed" || update?.metadata && JSON.parse(update.metadata).token)
16208
- throw new import_common38.ConflictException(
16221
+ throw new import_common39.ConflictException(
16209
16222
  "Finish credential rotation or runtime update recovery before changing MQTT/address settings."
16210
16223
  );
16211
16224
  }
16212
16225
  /** Durably record a new change intent before contacting the controller. */
16213
16226
  async savePendingChange(controllerId, access, input, assertOwned) {
16214
- if (!input) throw new import_common38.BadRequestException("Invalid MQTT/address change");
16215
- const row = this.repository.create({
16227
+ if (!input) throw new import_common39.BadRequestException("Invalid MQTT/address change");
16228
+ const row = {
16216
16229
  controllerId,
16217
16230
  sessionId: access.sessionId,
16218
16231
  fingerprint: access.fingerprint,
@@ -16221,10 +16234,21 @@ var WagoNetworkChangeService = class {
16221
16234
  failure: null,
16222
16235
  encryptedPayload: null,
16223
16236
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
16224
- });
16237
+ };
16225
16238
  await assertOwned();
16226
- await this.repository.save(row);
16227
- return row;
16239
+ return this.storage.networkChanges.upsert(row, {
16240
+ conflictOn: ["controllerId"],
16241
+ update: [
16242
+ "sessionId",
16243
+ "fingerprint",
16244
+ "targetHost",
16245
+ "mqttServerId",
16246
+ "phase",
16247
+ "failure",
16248
+ "encryptedPayload",
16249
+ "updatedAt"
16250
+ ]
16251
+ });
16228
16252
  }
16229
16253
  /** Apply an address-only change; the broker binding stays unchanged. */
16230
16254
  async applyAddressChange(row, host, assertOwned) {
@@ -16236,7 +16260,7 @@ var WagoNetworkChangeService = class {
16236
16260
  /** Keep the durable intent for an explicit retry, recording only a safe failure code. */
16237
16261
  async recordFailure(row, error, assertOwned) {
16238
16262
  row.failure = error instanceof RuntimeUpdateError || error instanceof NetworkChangeError ? error.failure : "interrupted";
16239
- await assertOwned().then(() => this.repository.save(row)).catch(() => void 0);
16263
+ await assertOwned().then(() => this.persist(row)).catch(() => void 0);
16240
16264
  }
16241
16265
  async applyBrokerChange(controllerId, row, controller, host, abort, assertOwned, retry) {
16242
16266
  let superseded;
@@ -16365,36 +16389,55 @@ var WagoNetworkChangeService = class {
16365
16389
  }
16366
16390
  }
16367
16391
  async saveBindings(row, encryptedCredentials, payload, assertOwned) {
16368
- await this.repository.manager.transaction(async (manager) => {
16369
- await assertOwned();
16370
- await manager.getRepository(WagoManagedAccess).update(row.sessionId, { host: row.targetHost, encryptedCredentials });
16371
- await manager.getRepository(WagoCommissioningSession).update(row.sessionId, {
16372
- targetHost: row.targetHost,
16373
- ...payload ? { mqttServerId: payload.mqttServerId } : {}
16374
- });
16392
+ await this.context.persistence.transaction(async (scope) => {
16393
+ await assertOwned(scope);
16394
+ const { managedAccess, commissioningSessions, mqttCredentialRetirements, controllers, credentialRotations } = this.storage;
16395
+ await managedAccess.update(
16396
+ { sessionId: row.sessionId },
16397
+ { host: row.targetHost, encryptedCredentials },
16398
+ { scope }
16399
+ );
16400
+ await commissioningSessions.update(
16401
+ { id: row.sessionId },
16402
+ { targetHost: row.targetHost, ...payload ? { mqttServerId: payload.mqttServerId } : {} },
16403
+ { scope }
16404
+ );
16375
16405
  if (payload) {
16376
16406
  if (payload.previousServerId !== payload.mqttServerId)
16377
- await manager.getRepository(WagoMqttCredentialRetirement).save({ controllerId: row.controllerId, mqttServerId: payload.previousServerId });
16378
- await manager.getRepository(WagoMqttCredentialRetirement).delete({ controllerId: row.controllerId, mqttServerId: payload.mqttServerId });
16379
- await manager.getRepository(WagoController).update(row.controllerId, {
16380
- mqttServerId: payload.mqttServerId,
16381
- credentialMqttServerId: payload.mqttServerId,
16382
- credentialEpoch: payload.credentialEpoch,
16383
- lastHeartbeatAt: null,
16384
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
16385
- });
16386
- await manager.getRepository(WagoCredentialRotationEntity).save({
16387
- controllerId: row.controllerId,
16388
- revision: 1,
16389
- token: payload.token,
16390
- phase: "completed",
16391
- credentialEpoch: payload.credentialEpoch,
16392
- mqttServerId: payload.mqttServerId,
16393
- prefix: payload.prefix,
16394
- encryptedCredentials: null
16395
- });
16407
+ await mqttCredentialRetirements.upsert(
16408
+ { controllerId: row.controllerId, mqttServerId: payload.previousServerId },
16409
+ { conflictOn: ["controllerId", "mqttServerId"], update: [], scope }
16410
+ );
16411
+ await mqttCredentialRetirements.delete(
16412
+ { controllerId: row.controllerId, mqttServerId: payload.mqttServerId },
16413
+ { scope }
16414
+ );
16415
+ await controllers.update(
16416
+ { id: row.controllerId },
16417
+ {
16418
+ mqttServerId: payload.mqttServerId,
16419
+ credentialMqttServerId: payload.mqttServerId,
16420
+ credentialEpoch: payload.credentialEpoch,
16421
+ lastHeartbeatAt: null,
16422
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
16423
+ },
16424
+ { scope }
16425
+ );
16426
+ await credentialRotations.upsert(
16427
+ {
16428
+ controllerId: row.controllerId,
16429
+ revision: 1,
16430
+ token: payload.token,
16431
+ phase: "completed",
16432
+ credentialEpoch: payload.credentialEpoch,
16433
+ mqttServerId: payload.mqttServerId,
16434
+ prefix: payload.prefix,
16435
+ encryptedCredentials: null
16436
+ },
16437
+ { conflictOn: ["controllerId"], scope }
16438
+ );
16396
16439
  }
16397
- await assertOwned();
16440
+ await assertOwned(scope);
16398
16441
  });
16399
16442
  }
16400
16443
  payload(row, controller) {
@@ -16429,63 +16472,48 @@ var WagoNetworkChangeService = class {
16429
16472
  row.phase = phase;
16430
16473
  row.failure = null;
16431
16474
  row.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
16432
- await this.repository.save(row);
16475
+ await this.persist(row);
16476
+ }
16477
+ /** Writes the mutable columns of the held intent. A vanished row (controller removed) is a lost operation. */
16478
+ async persist(row) {
16479
+ const affected = await this.storage.networkChanges.update(
16480
+ { controllerId: row.controllerId },
16481
+ { phase: row.phase, failure: row.failure, encryptedPayload: row.encryptedPayload, updatedAt: row.updatedAt }
16482
+ );
16483
+ if (affected !== 1) throw new import_common39.ConflictException("The network change no longer exists.");
16484
+ }
16485
+ /** Lease check that joins the given transaction. */
16486
+ async assertLeaseIn(scope, fingerprint2, owner) {
16487
+ const row = await this.storage.deviceOperations.findOne({ where: { fingerprint: fingerprint2, owner } }, { scope });
16488
+ if (!row || Number(row.leaseUntil) <= Date.now()) throw new Error("Controller operation ownership lost");
16433
16489
  }
16434
16490
  async status(controllerId) {
16435
- const controller = await this.context.getRepository(WagoController).findOneBy({ id: controllerId });
16436
- if (!controller) throw new import_common38.NotFoundException("WAGO controller not found");
16437
- const access = await this.context.getRepository(WagoManagedAccess).findOne({ where: { controllerId }, order: { sessionId: "DESC" } });
16438
- const row = await this.repository.findOneBy({ controllerId });
16439
- const lease = row && await this.context.getRepository(WagoDeviceOperation).findOneBy({ fingerprint: row.fingerprint });
16440
- return {
16441
- available: access?.state === "managed",
16442
- targetHost: access?.host ?? null,
16443
- mqttServerId: controller.mqttServerId,
16444
- pendingCredentialRetirements: await this.context.getRepository(WagoMqttCredentialRetirement).countBy({ controllerId }),
16445
- operation: row ? {
16446
- targetHost: row.targetHost,
16447
- mqttServerId: row.mqttServerId,
16448
- phase: row.phase,
16449
- failure: row.failure,
16450
- running: row.phase !== "completed" && !!lease?.owner && Number(lease.leaseUntil) > Date.now()
16451
- } : null
16452
- };
16491
+ return networkStatus(this.storage, controllerId);
16453
16492
  }
16454
16493
  async retirePreviousCredentials(controllerId, principal) {
16455
- const access = await this.context.getRepository(WagoManagedAccess).findOne({ where: { controllerId }, order: { sessionId: "DESC" } });
16456
- if (!access) throw new import_common38.ConflictException("Controller management identity is unavailable.");
16457
- const operations = new WagoDeviceOperations(this.context.getRepository(WagoDeviceOperation)), owner = (0, import_node_crypto25.randomBytes)(16).toString("hex");
16494
+ const access = await this.storage.managedAccess.findOne({
16495
+ where: { controllerId },
16496
+ orderBy: [{ field: "sessionId", direction: "desc" }]
16497
+ });
16498
+ if (!access) throw new import_common39.ConflictException("Controller management identity is unavailable.");
16499
+ const operations = new WagoDeviceOperations(this.storage.deviceOperations), owner = (0, import_node_crypto25.randomBytes)(16).toString("hex");
16458
16500
  if (!await operations.acquire(access.fingerprint, owner, Date.now(), Date.now() + 12e4))
16459
- throw new import_common38.ConflictException("Controller is busy");
16501
+ throw new import_common39.ConflictException("Controller is busy");
16460
16502
  const lifecycle = new WagoAudit(this.context).begin(principal, controllerId, "network_credential_retirement");
16461
16503
  let audited = false;
16462
16504
  try {
16463
16505
  await this.managed.assertNetworkSettled(controllerId);
16464
16506
  await lifecycle.attempt();
16465
16507
  audited = true;
16466
- const controller = await this.context.getRepository(WagoController).findOneByOrFail({ id: controllerId });
16508
+ const controller = await this.storage.controllers.get(controllerId);
16509
+ if (!controller) throw new Error();
16467
16510
  const current = controller.mqttServerId && await this.context.getMqttServerConfig(controller.mqttServerId);
16468
16511
  if (!current) throw new Error();
16469
- const repository = this.context.getRepository(WagoMqttCredentialRetirement);
16470
- for (const row of await repository.findBy({ controllerId })) {
16512
+ const repository = this.storage.mqttCredentialRetirements;
16513
+ for (const row of await repository.find({ where: { controllerId } })) {
16471
16514
  const previous = await this.context.getMqttServerConfig(row.mqttServerId);
16472
16515
  if (!previous) throw new Error();
16473
- const sameHost = previous.host.toLowerCase().replace(/\.$/, "") === current.host.toLowerCase().replace(/\.$/, "");
16474
- let sharedDestination = sameHost;
16475
- if (!sameHost) {
16476
- const destinations = await Promise.all([
16477
- (0, import_promises11.lookup)(previous.host, { all: true }),
16478
- (0, import_promises11.lookup)(current.host, { all: true })
16479
- ]);
16480
- const address = (value) => value.toLowerCase().replace(/^::ffff:/, "");
16481
- if (!destinations[0].length || !destinations[1].length) throw new Error();
16482
- const previousAddresses = new Set(destinations[0].map((item) => address(item.address)));
16483
- const currentAddresses = new Set(destinations[1].map((item) => address(item.address)));
16484
- const overlaps = [...previousAddresses].some((item) => currentAddresses.has(item));
16485
- const sameAddresses = previousAddresses.size === currentAddresses.size && [...previousAddresses].every((item) => currentAddresses.has(item));
16486
- if (overlaps && !sameAddresses) throw new Error();
16487
- sharedDestination = sameAddresses;
16488
- }
16516
+ const sharedDestination = await sharesCredentialDestination(previous, current);
16489
16517
  if (sharedDestination) {
16490
16518
  if (previous.port !== current.port || previous.useTls !== current.useTls) throw new Error();
16491
16519
  await operations.assertOwned(access.fingerprint, owner);
@@ -16504,7 +16532,7 @@ var WagoNetworkChangeService = class {
16504
16532
  return this.status(controllerId);
16505
16533
  } catch {
16506
16534
  if (audited) await lifecycle.finish("failed").catch(() => void 0);
16507
- throw new import_common38.ConflictException(
16535
+ throw new import_common39.ConflictException(
16508
16536
  "Previous broker credentials could not be retired. Check the previous broker connection and retry."
16509
16537
  );
16510
16538
  } finally {
@@ -16515,15 +16543,15 @@ var WagoNetworkChangeService = class {
16515
16543
  this.destroyed = true;
16516
16544
  this.active.forEach((controller) => controller.abort());
16517
16545
  }
16518
- get repository() {
16519
- return this.context.getRepository(WagoNetworkChange);
16546
+ get storage() {
16547
+ return this.storageCache ??= openWagoStorage(this.context);
16520
16548
  }
16521
16549
  };
16522
16550
  WagoNetworkChangeService = __decorateClass([
16523
- (0, import_common38.Injectable)(),
16524
- __decorateParam(0, (0, import_common38.Inject)(/* @__PURE__ */ Symbol.for("attraccess.plugin.context"))),
16525
- __decorateParam(1, (0, import_common38.Inject)(WagoManagedRuntimeService)),
16526
- __decorateParam(2, (0, import_common38.Inject)(WagoService))
16551
+ (0, import_common39.Injectable)(),
16552
+ __decorateParam(0, (0, import_common39.Inject)(/* @__PURE__ */ Symbol.for("attraccess.plugin.context"))),
16553
+ __decorateParam(1, (0, import_common39.Inject)(WagoManagedRuntimeService)),
16554
+ __decorateParam(2, (0, import_common39.Inject)(WagoService))
16527
16555
  ], WagoNetworkChangeService);
16528
16556
 
16529
16557
  // backend/runtime/update/controller.ts
@@ -16555,7 +16583,7 @@ var WagoUpdatesController = class {
16555
16583
  }
16556
16584
  recovery(id, body, request) {
16557
16585
  if (body?.confirm !== true || Object.keys(body).length !== 1)
16558
- throw new import_common39.BadRequestException("Confirm administrator recovery disclosure");
16586
+ throw new import_common40.BadRequestException("Confirm administrator recovery disclosure");
16559
16587
  return this.managed.recoverPassword(id, wagoAuditPrincipal(request));
16560
16588
  }
16561
16589
  retry(id) {
@@ -16563,71 +16591,71 @@ var WagoUpdatesController = class {
16563
16591
  }
16564
16592
  restore(id, body, request) {
16565
16593
  if (body?.confirm !== true || Object.keys(body).length !== 1)
16566
- throw new import_common39.BadRequestException("Confirm bootstrap SSH restoration");
16594
+ throw new import_common40.BadRequestException("Confirm bootstrap SSH restoration");
16567
16595
  return this.managed.restoreAccess(id, wagoAuditPrincipal(request));
16568
16596
  }
16569
16597
  };
16570
16598
  __decorateClass([
16571
- (0, import_common39.Get)("controllers/:id/network-change"),
16572
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe))
16599
+ (0, import_common40.Get)("controllers/:id/network-change"),
16600
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe))
16573
16601
  ], WagoUpdatesController.prototype, "networkStatus", 1);
16574
16602
  __decorateClass([
16575
- (0, import_common39.Post)("controllers/:id/network-change"),
16576
- (0, import_common39.Header)("Cache-Control", "no-store"),
16577
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe)),
16578
- __decorateParam(1, (0, import_common39.Body)()),
16579
- __decorateParam(2, (0, import_common39.Req)())
16603
+ (0, import_common40.Post)("controllers/:id/network-change"),
16604
+ (0, import_common40.Header)("Cache-Control", "no-store"),
16605
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe)),
16606
+ __decorateParam(1, (0, import_common40.Body)()),
16607
+ __decorateParam(2, (0, import_common40.Req)())
16580
16608
  ], WagoUpdatesController.prototype, "changeNetwork", 1);
16581
16609
  __decorateClass([
16582
- (0, import_common39.Post)("controllers/:id/network-change/retry"),
16583
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe)),
16584
- __decorateParam(1, (0, import_common39.Req)())
16610
+ (0, import_common40.Post)("controllers/:id/network-change/retry"),
16611
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe)),
16612
+ __decorateParam(1, (0, import_common40.Req)())
16585
16613
  ], WagoUpdatesController.prototype, "retryNetwork", 1);
16586
16614
  __decorateClass([
16587
- (0, import_common39.Post)("controllers/:id/network-change/retire-credentials"),
16588
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe)),
16589
- __decorateParam(1, (0, import_common39.Req)())
16615
+ (0, import_common40.Post)("controllers/:id/network-change/retire-credentials"),
16616
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe)),
16617
+ __decorateParam(1, (0, import_common40.Req)())
16590
16618
  ], WagoUpdatesController.prototype, "retirePreviousCredentials", 1);
16591
16619
  __decorateClass([
16592
- (0, import_common39.Get)("controllers/:id/runtime-update"),
16593
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe))
16620
+ (0, import_common40.Get)("controllers/:id/runtime-update"),
16621
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe))
16594
16622
  ], WagoUpdatesController.prototype, "status", 1);
16595
16623
  __decorateClass([
16596
- (0, import_common39.Get)("commissioning/sessions/:id/managed-access"),
16597
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe))
16624
+ (0, import_common40.Get)("commissioning/sessions/:id/managed-access"),
16625
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe))
16598
16626
  ], WagoUpdatesController.prototype, "sessionStatus", 1);
16599
16627
  __decorateClass([
16600
- (0, import_common39.Post)("controllers/:id/runtime-update/retry"),
16601
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe))
16628
+ (0, import_common40.Post)("controllers/:id/runtime-update/retry"),
16629
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe))
16602
16630
  ], WagoUpdatesController.prototype, "retryRuntime", 1);
16603
16631
  __decorateClass([
16604
- (0, import_common39.Post)("commissioning/sessions/:id/root-recovery"),
16605
- (0, import_common39.Header)("Cache-Control", "no-store"),
16606
- (0, import_common39.Header)("Pragma", "no-cache"),
16607
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe)),
16608
- __decorateParam(1, (0, import_common39.Body)()),
16609
- __decorateParam(2, (0, import_common39.Req)())
16632
+ (0, import_common40.Post)("commissioning/sessions/:id/root-recovery"),
16633
+ (0, import_common40.Header)("Cache-Control", "no-store"),
16634
+ (0, import_common40.Header)("Pragma", "no-cache"),
16635
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe)),
16636
+ __decorateParam(1, (0, import_common40.Body)()),
16637
+ __decorateParam(2, (0, import_common40.Req)())
16610
16638
  ], WagoUpdatesController.prototype, "recovery", 1);
16611
16639
  __decorateClass([
16612
- (0, import_common39.Post)("commissioning/sessions/:id/managed-access/retry"),
16613
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe))
16640
+ (0, import_common40.Post)("commissioning/sessions/:id/managed-access/retry"),
16641
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe))
16614
16642
  ], WagoUpdatesController.prototype, "retry", 1);
16615
16643
  __decorateClass([
16616
- (0, import_common39.Post)("commissioning/sessions/:id/managed-access/restore"),
16617
- __decorateParam(0, (0, import_common39.Param)("id", import_common39.ParseIntPipe)),
16618
- __decorateParam(1, (0, import_common39.Body)()),
16619
- __decorateParam(2, (0, import_common39.Req)())
16644
+ (0, import_common40.Post)("commissioning/sessions/:id/managed-access/restore"),
16645
+ __decorateParam(0, (0, import_common40.Param)("id", import_common40.ParseIntPipe)),
16646
+ __decorateParam(1, (0, import_common40.Body)()),
16647
+ __decorateParam(2, (0, import_common40.Req)())
16620
16648
  ], WagoUpdatesController.prototype, "restore", 1);
16621
16649
  WagoUpdatesController = __decorateClass([
16622
- (0, import_common39.Controller)("wago"),
16623
- (0, import_plugins_backend_sdk19.Auth)("system.settings.manage"),
16624
- __decorateParam(0, (0, import_common39.Inject)(WagoManagedRuntimeService)),
16625
- __decorateParam(1, (0, import_common39.Inject)(WagoNetworkChangeService))
16650
+ (0, import_common40.Controller)("wago"),
16651
+ (0, import_plugins_backend_sdk16.Auth)("system.settings.manage"),
16652
+ __decorateParam(0, (0, import_common40.Inject)(WagoManagedRuntimeService)),
16653
+ __decorateParam(1, (0, import_common40.Inject)(WagoNetworkChangeService))
16626
16654
  ], WagoUpdatesController);
16627
16655
 
16628
16656
  // backend/wago-live-updates.service.ts
16629
- var import_common40 = require("@nestjs/common");
16630
- var import_plugins_backend_sdk20 = require("@attraccess/plugins-backend-sdk");
16657
+ var import_common41 = require("@nestjs/common");
16658
+ var import_plugins_backend_sdk17 = require("@attraccess/plugins-backend-sdk");
16631
16659
  var WagoLiveUpdatesService = class {
16632
16660
  constructor(context, wago, commissioning, diagnostics, managed, network) {
16633
16661
  __publicField(this, "context", context);
@@ -16636,7 +16664,7 @@ var WagoLiveUpdatesService = class {
16636
16664
  __publicField(this, "diagnostics", diagnostics);
16637
16665
  __publicField(this, "managed", managed);
16638
16666
  __publicField(this, "network", network);
16639
- __publicField(this, "sample", (0, import_plugins_backend_sdk20.createSharedLiveSampler)());
16667
+ __publicField(this, "sample", (0, import_plugins_backend_sdk17.createSharedLiveSampler)());
16640
16668
  }
16641
16669
  onModuleInit() {
16642
16670
  const live = this.context.liveUpdates;
@@ -16646,14 +16674,15 @@ var WagoLiveUpdatesService = class {
16646
16674
  topic,
16647
16675
  identifier: kind === "none" ? "none" : "required",
16648
16676
  authorize: async ({ identifier: identifier3 }, user) => {
16649
- if (!user.effectivePermissions?.has(permission)) throw new import_common40.ForbiddenException();
16677
+ if (!user.effectivePermissions?.has(permission)) throw new import_common41.ForbiddenException();
16650
16678
  if (kind === "none") return;
16651
16679
  const pattern = kind === "revisions" ? /^[1-9]\d*:(0|[1-9]\d*)$/ : /^[1-9]\d*$/;
16652
- if (!pattern.test(identifier3 ?? "")) throw new import_common40.NotFoundException();
16680
+ if (!pattern.test(identifier3 ?? "")) throw new import_common41.NotFoundException();
16653
16681
  const [id, offset = 0] = identifier3.split(":").map(Number);
16654
- if (!Number.isSafeInteger(id) || !Number.isSafeInteger(offset)) throw new import_common40.NotFoundException();
16655
- const exists = kind === "session" ? await this.context.getRepository(WagoCommissioningSession).existsBy({ id }) : await this.context.getRepository(WagoController).existsBy({ id });
16656
- if (!exists) throw new import_common40.NotFoundException();
16682
+ if (!Number.isSafeInteger(id) || !Number.isSafeInteger(offset)) throw new import_common41.NotFoundException();
16683
+ const storage = openWagoStorage(this.context);
16684
+ const exists = kind === "session" ? await storage.commissioningSessions.count({ id }) : await storage.controllers.count({ id });
16685
+ if (!exists) throw new import_common41.NotFoundException();
16657
16686
  },
16658
16687
  source: ({ identifier: identifier3 }) => this.sample(`${topic}:${identifier3 ?? ""}`, interval, () => {
16659
16688
  const [id = 0, offset = 0] = (identifier3 ?? "").split(":").map(Number);
@@ -16691,13 +16720,13 @@ var WagoLiveUpdatesService = class {
16691
16720
  }
16692
16721
  };
16693
16722
  WagoLiveUpdatesService = __decorateClass([
16694
- (0, import_common40.Injectable)(),
16695
- __decorateParam(0, (0, import_common40.Inject)(/* @__PURE__ */ Symbol.for("attraccess.plugin.context"))),
16696
- __decorateParam(1, (0, import_common40.Inject)(WagoService)),
16697
- __decorateParam(2, (0, import_common40.Inject)(WagoCommissioningService)),
16698
- __decorateParam(3, (0, import_common40.Inject)(WagoDiagnosticsService)),
16699
- __decorateParam(4, (0, import_common40.Inject)(WagoManagedRuntimeService)),
16700
- __decorateParam(5, (0, import_common40.Inject)(WagoNetworkChangeService))
16723
+ (0, import_common41.Injectable)(),
16724
+ __decorateParam(0, (0, import_common41.Inject)(/* @__PURE__ */ Symbol.for("attraccess.plugin.context"))),
16725
+ __decorateParam(1, (0, import_common41.Inject)(WagoService)),
16726
+ __decorateParam(2, (0, import_common41.Inject)(WagoCommissioningService)),
16727
+ __decorateParam(3, (0, import_common41.Inject)(WagoDiagnosticsService)),
16728
+ __decorateParam(4, (0, import_common41.Inject)(WagoManagedRuntimeService)),
16729
+ __decorateParam(5, (0, import_common41.Inject)(WagoNetworkChangeService))
16701
16730
  ], WagoLiveUpdatesService);
16702
16731
 
16703
16732
  // backend/plugin.ts
@@ -16711,21 +16740,7 @@ function services(context) {
16711
16740
  return result;
16712
16741
  }
16713
16742
  var plugin = {
16714
- entities: [
16715
- WagoController,
16716
- WagoSettings,
16717
- WagoEnrollment,
16718
- WagoConfigurationDraft,
16719
- WagoConfigurationRevision,
16720
- WagoCredentialRotationEntity,
16721
- WagoCommissioningSession,
16722
- WagoManagementEntity,
16723
- WagoManagedAccess,
16724
- WagoRuntimeUpdateEntity,
16725
- WagoDeviceOperation,
16726
- WagoNetworkChange,
16727
- WagoMqttCredentialRetirement
16728
- ],
16743
+ storage: wagoStorage,
16729
16744
  flowNodes: (context) => [
16730
16745
  createWagoCommandNode(() => services(context).command),
16731
16746
  ...createWagoStateNodes(() => services(context).state)