diff --git a/TEST_FAST.md b/TEST_FAST.md index fbea72db9c..11f8969fca 100644 --- a/TEST_FAST.md +++ b/TEST_FAST.md @@ -42,10 +42,12 @@ Use `-Dpkg.skip=true` to skip all packaging at once (equivalent to all four flag |----------------------------|-------------------------------------------|--------------------------------------------------------------| | `-Dpkg.skip=true` | All of the below (bootjar + deb + rpm + zip) | Yes | | `-Dpkg.skip.bootjar=true` | `spring-boot:repackage` (`*-boot.jar`) | Yes — tests use the regular `.jar`, not the fat boot jar | -| `-Dpkg.skip.deb=true` | Gradle `buildDeb` + Maven `attach-artifact` | Yes — MSA docker modules copy the DEB from `target/` directly | +| `-Dpkg.skip.deb=true` | Gradle `buildDeb` | Yes — MSA docker modules copy the DEB from `target/` directly | | `-Dpkg.skip.rpm=true` | Gradle `buildRpm` | Yes — no test depends on the RPM | | `-Dpkg.skip.zip=true` | `maven-assembly-plugin` Windows ZIP | Yes — no test depends on the ZIP | +`-Dskip.yarn=true` and `-Dskip.ui.build=true` imply `-Dpkg.skip=true`: packages built without the UI are incomplete. + ## Testcontainers compatibility with the Docker API workaround In case your tests failed to run testcontainers due to unsupported Docker API version diff --git a/application/pom.xml b/application/pom.xml index 6cd1435b2c..6dc44433f9 100644 --- a/application/pom.xml +++ b/application/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard application diff --git a/application/src/main/data/upgrade/basic/schema_update.sql b/application/src/main/data/upgrade/basic/schema_update.sql index 20a3528e9a..c7ac2598a0 100644 --- a/application/src/main/data/upgrade/basic/schema_update.sql +++ b/application/src/main/data/upgrade/basic/schema_update.sql @@ -3,6 +3,8 @@ -- SPDX-License-Identifier: Apache-2.0 -- +-- Runs before schema-entities.sql and the LTS schema migrations: reference only tables a released version already has. + -- UPDATE TENANT PROFILE CONFIGURATION START UPDATE tenant_profile diff --git a/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql b/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql new file mode 100644 index 0000000000..740462d6c9 --- /dev/null +++ b/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql @@ -0,0 +1,29 @@ +-- +-- SPDX-FileCopyrightText: Copyright The Thingsboard Authors +-- SPDX-License-Identifier: Apache-2.0 +-- + +-- TB_CLUSTER START + +-- The patch path never runs schema-entities.sql, so tb_cluster is created here too. +-- Keep this block identical to the one in schema-entities.sql. + +CREATE TABLE IF NOT EXISTS tb_cluster ( + cluster_id uuid NOT NULL, + license_claim_token varchar, + license_secret varchar, + CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id) +); + +-- Backstop against two concurrent install jobs both minting an id: a unique index on a constant +-- expression allows at most one row in the table, no matter how many rows race to insert. +CREATE UNIQUE INDEX IF NOT EXISTS tb_cluster_single_row ON tb_cluster ((true)); + +-- TB_CLUSTER END + +-- TB_CLUSTER LICENSE SECRET START + +-- The CREATE above is a no-op on a database that already carries tb_cluster. +ALTER TABLE tb_cluster ADD COLUMN IF NOT EXISTS license_secret varchar; + +-- TB_CLUSTER LICENSE SECRET END diff --git a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java index 533ef331bd..9b85e65762 100644 --- a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java +++ b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java @@ -196,8 +196,8 @@ public class TenantActor extends RuleChainManagerActor { private void forwardToCfActor(TenantAwareMsg msg, boolean priority) { if (cfActor == null) { - if (msg instanceof CalculatedFieldStateRestoreMsg) { - log.warn("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg); + if (msg instanceof CalculatedFieldStateRestoreMsg restoreMsg) { + log.warn("[{}] CF Actor is not initialized. Skipping CF state restore: [{}]", tenantId, restoreMsg.getId()); } else { log.debug("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg); } diff --git a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java index 0eeb602c1d..9e638d271b 100644 --- a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java +++ b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java @@ -75,8 +75,11 @@ public class ThingsboardSecurityConfiguration { public static final String WS_ENTRY_POINT = "/api/ws/**"; public static final String MAIL_OAUTH2_PROCESSING_ENTRY_POINT = "/api/admin/mail/oauth2/code"; public static final String DEVICE_CONNECTIVITY_CERTIFICATE_DOWNLOAD_ENTRY_POINT = "/api/device-connectivity/*/certificate/download"; + public static final String COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT = "/api/communityGrant/offline/run"; + public static final String COMMUNITY_GRANT_OFFLINE_RUN_PAYLOAD_LIMIT = COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT + "=35651584"; - @Value("${server.http.max_payload_size:/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}") + // First match wins, so the community grant entry must stay ahead of /api/**. + @Value("${server.http.max_payload_size:/api/communityGrant/offline/run=35651584;/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}") private String maxPayloadSizeConfig; @Autowired @@ -133,9 +136,13 @@ public class ThingsboardSecurityConfiguration { @Autowired private HttpSecurityHeadersCustomizer httpSecurityHeadersCustomizer; + // An override replaces the whole list, so the offline upload's entry is re-added unless it names that path. @Bean protected PayloadSizeFilter payloadSizeFilter() { - return new PayloadSizeFilter(maxPayloadSizeConfig); + String config = maxPayloadSizeConfig.contains(COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT + "=") + ? maxPayloadSizeConfig + : COMMUNITY_GRANT_OFFLINE_RUN_PAYLOAD_LIMIT + ";" + maxPayloadSizeConfig; + return new PayloadSizeFilter(config); } @Bean diff --git a/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java new file mode 100644 index 0000000000..8df6f400ac --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.controller; + +import io.swagger.v3.oas.annotations.Hidden; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.community_grant.CommunityGrantOfflineBundle; +import org.thingsboard.server.service.community_grant.CommunityGrantPlatform; +import org.thingsboard.server.service.community_grant.CommunityGrantService; +import org.thingsboard.server.service.security.model.SecurityUser; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; + +@Hidden +@RestController +@TbCoreComponent +@RequestMapping("/api/communityGrant") +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantController extends BaseController { + + private static final String REPORT_FILE_NAME = "tb-instance-check-report.txt"; + + @Value("${community-grant.max-checker-size-bytes:33554432}") + private long maxCheckerSizeBytes; + + private final CommunityGrantService communityGrantService; + private final TbClusterStore tbClusterStore; + + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @GetMapping("/state") + @ResponseBody + public CommunityGrantStateInfo getState() { + return communityGrantService.getStateInfo(); + } + + /** Every failure is audited as a refusal, hence the catch on {@code Exception}. */ + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping("/start") + @ResponseBody + public CommunityGrantStateInfo start() throws ThingsboardException { + SecurityUser user = getCurrentUser(); + CommunityGrantStateInfo stateInfo; + try { + stateInfo = communityGrantService.start(); + } catch (Exception e) { + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, e); + throw e; + } + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, null); + return stateInfo; + } + + /** + * Answers {@code 202} once the run has started on this node; a refusal is audited here, and the run + * audits its own ending. + */ + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping(value = "/offline/run", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity runOfflineChecker(@RequestPart("bundle") MultipartFile bundle) + throws ThingsboardException { + SecurityUser user = getCurrentUser(); + CommunityGrantStateInfo stateInfo; + try { + stateInfo = runOfflineChecker(bundle, user); + } catch (Exception e) { + auditOfflineRun(user, e); + throw e; + } + return ResponseEntity.status(HttpStatus.ACCEPTED).body(stateInfo); + } + + private void auditOfflineRun(SecurityUser user, Exception failure) { + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, failure); + } + + private CommunityGrantStateInfo runOfflineChecker(MultipartFile bundle, SecurityUser user) + throws ThingsboardException { + long maxBundleSize = maxCheckerSizeBytes + CommunityGrantOfflineBundle.MAX_OVERHEAD_BYTES; + if (bundle.getSize() > maxBundleSize) { + throw new ThingsboardException("The uploaded enrollment bundle is larger than the configured limit of " + + maxBundleSize + " bytes", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + byte[] bundleData; + try { + bundleData = bundle.getBytes(); + } catch (IOException e) { + throw new ThingsboardException("Failed to read the uploaded file", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + CommunityGrantOfflineBundle parsed; + try { + parsed = CommunityGrantOfflineBundle.parse(bundleData); + } catch (IllegalArgumentException e) { + throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + refuseBundleForAnotherInstallation(parsed); + refuseBundleForAnotherPlatform(parsed); + warnIfChallengeExpired(parsed, user); + return communityGrantService.runOfflineChecker(parsed.checker(), parsed.signature(), + parsed.checkerFileName(), parsed.checkerInput(), failure -> auditOfflineRun(user, failure)); + } + + /** Skipped when this deployment has no cluster id at all. */ + private void refuseBundleForAnotherInstallation(CommunityGrantOfflineBundle parsed) throws ThingsboardException { + Optional clusterId = tbClusterStore.getClusterId(); + if (clusterId.isPresent() && !clusterId.get().equals(parsed.clusterId())) { + throw new ThingsboardException("This enrollment bundle was issued for a different installation. " + + "Download a bundle for this installation from the License Portal and upload that one.", + ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + } + + private void refuseBundleForAnotherPlatform(CommunityGrantOfflineBundle parsed) throws ThingsboardException { + CommunityGrantPlatform platform; + try { + platform = CommunityGrantPlatform.current(); + } catch (RuntimeException e) { + log.debug("Refusing an enrollment bundle: this server's platform has no instance checker build", e); + throw new ThingsboardException("This server's operating system and CPU architecture have no " + + "instance checker build, so an enrollment bundle cannot be run here.", + ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + if (!platform.os().equals(parsed.os()) || !platform.arch().equals(parsed.arch())) { + throw new ThingsboardException("This enrollment bundle is for " + parsed.os() + "/" + parsed.arch() + + ", and this server is " + platform.os() + "/" + platform.arch() + + ". Download the bundle for this server's platform.", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + } + + /** Warns, never blocks: the portal is the authoritative clock, and an air-gapped host may have drifted. */ + private void warnIfChallengeExpired(CommunityGrantOfflineBundle parsed, SecurityUser user) { + if (parsed.isChallengeExpired(System.currentTimeMillis())) { + log.warn("Running an instance checker from an enrollment bundle whose challenge expired at {} " + + "(requested by user {}). The portal will refuse the report it produces; a fresh " + + "bundle is the remedy.", + Instant.ofEpochMilli(parsed.challengeExpiresAt()), user.getId()); + } + } + + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping("/requestAccess") + public void requestAccess() throws ThingsboardException { + SecurityUser user = getCurrentUser(); + try { + communityGrantService.requestAccess(); + } catch (Exception e) { + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, e); + throw e; + } + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, null); + } + + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping("/offline/handoff") + @ResponseBody + public CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException { + SecurityUser user = getCurrentUser(); + CommunityGrantStateInfo stateInfo; + try { + stateInfo = communityGrantService.confirmOfflineHandoff(); + } catch (Exception e) { + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, e); + throw e; + } + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, null); + return stateInfo; + } + + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @GetMapping("/offline/report") + public ResponseEntity downloadOfflineReport() throws ThingsboardException { + byte[] report = communityGrantService.getOfflineReport().getBytes(StandardCharsets.UTF_8); + return ResponseEntity.ok() + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + REPORT_FILE_NAME + "\"") + .contentType(MediaType.TEXT_PLAIN) + .contentLength(report.length) + .body(new ByteArrayResource(report)); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java index ffa76d658a..b582612803 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java +++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java @@ -12,6 +12,7 @@ import jakarta.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -35,6 +36,7 @@ import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; import org.thingsboard.server.common.msg.rpc.RemoveRpcActorMsg; +import org.thingsboard.server.service.rpc.TbRpcService; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.exception.ToErrorResponseEntity; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -62,6 +64,9 @@ import static org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CU @Slf4j public class RpcV2Controller extends AbstractRpcController { + @Autowired + private TbRpcService tbRpcService; + private static final String RPC_REQUEST_DESCRIPTION = "Sends the one-way remote-procedure call (RPC) request to device. " + "The RPC call is A JSON that contains the method name ('method'), parameters ('params') and multiple optional fields. " + "See example below. We will review the properties of the RPC call one-by-one below. " + @@ -220,13 +225,13 @@ public class RpcV2Controller extends AbstractRpcController { Rpc rpc = checkRpcId(rpcId, Operation.DELETE); if (rpc != null) { - if (rpc.getStatus().isPushDeleteNotificationToCore()) { + if (rpc.getStatus().isIntermediate()) { RemoveRpcActorMsg removeMsg = new RemoveRpcActorMsg(getTenantId(), rpc.getDeviceId(), rpc.getUuidId()); log.trace("[{}] Forwarding msg {} to queue actor!", rpc.getDeviceId(), rpc); tbClusterService.pushMsgToCore(removeMsg, null); } - rpcService.deleteRpc(getTenantId(), rpcId); + tbRpcService.deleteRpc(getTenantId(), rpc); rpc.setStatus(RpcStatus.DELETED); TbMsg msg = TbMsg.newMsg() diff --git a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java index a7e3ed4ba9..2e8dda4d32 100644 --- a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java +++ b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java @@ -19,6 +19,7 @@ import org.springframework.beans.factory.BeanCreationNotAllowedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; +import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Service; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.PongMessage; @@ -34,6 +35,7 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.limit.LimitedApi; +import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.config.WebSocketConfiguration; import org.thingsboard.server.dao.tenant.TbTenantProfileCache; @@ -55,6 +57,7 @@ import org.thingsboard.server.service.ws.telemetry.cmd.TelemetryCmdsWrapper; import java.io.IOException; import java.security.InvalidParameterException; +import java.util.EnumSet; import java.util.Optional; import java.util.Queue; import java.util.Set; @@ -76,6 +79,8 @@ import static org.thingsboard.server.service.ws.DefaultWebSocketService.NUMBER_O @RequiredArgsConstructor public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocketMsgEndpoint { + private static final Set USER_AUTHORITIES = EnumSet.of(Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER); + private final ConcurrentMap internalSessionMap = new ConcurrentHashMap<>(); private final ConcurrentMap externalSessionMap = new ConcurrentHashMap<>(); @@ -181,7 +186,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke log.trace("{} Authenticating session", sessionRef); SecurityUser securityCtx; try { - securityCtx = authenticationProvider.authenticate(authCmd.getToken()); + securityCtx = authenticate(authCmd.getToken()); } catch (Exception e) { close(sessionRef, CloseStatus.BAD_DATA.withReason(e.getMessage())); return; @@ -317,7 +322,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke SecurityUser securityCtx = null; String token = StringUtils.substringAfter(session.getUri().getQuery(), "token="); if (StringUtils.isNotEmpty(token)) { - securityCtx = authenticationProvider.authenticate(token); + securityCtx = authenticate(token); } return WebSocketSessionRef.builder() .sessionId(UUID.randomUUID().toString()) @@ -328,6 +333,14 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke .build(); } + private SecurityUser authenticate(String token) { + SecurityUser securityUser = authenticationProvider.authenticate(token); + if (!USER_AUTHORITIES.contains(securityUser.getAuthority())) { + throw new BadCredentialsException("Token is invalid"); + } + return securityUser; + } + private SessionMetaData getSessionMd(String internalSessionId) { SessionMetaData sessionMd = internalSessionMap.get(internalSessionId); if (sessionMd == null) { diff --git a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java index 0f2c37a8dc..508edc321b 100644 --- a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java +++ b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java @@ -112,6 +112,7 @@ public class ThingsboardInstallService { systemDataLoaderService.loadSystemWidgets(); installScripts.loadSystemLwm2mResources(); installScripts.loadSystemImagesAndResources(); + entityDatabaseSchemaService.generateClusterIdIfNotExist(); databaseSchemaVersionService.updateSchemaVersion(); } log.info("Upgrade finished successfully!"); @@ -158,6 +159,8 @@ public class ThingsboardInstallService { installScripts.loadSystemLwm2mResources(); installScripts.loadSystemImagesAndResources(); + entityDatabaseSchemaService.generateClusterIdIfNotExist(); + if (loadDemo) { log.info("Loading demo data..."); systemDataLoaderService.loadDemoData(); diff --git a/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java b/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java index e4850b9128..72f34918c8 100644 --- a/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java +++ b/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java @@ -70,6 +70,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -489,10 +490,17 @@ public abstract class AbstractCalculatedFieldProcessingService { callback.onFailure(new IllegalArgumentException("Only TimeSeriesImmediateOutputStrategy is supported.")); } else { TimeseriesSaveRequest.Strategy strategy = new TimeseriesSaveRequest.Strategy(tsOutputStrategy.isSaveTimeSeries(), tsOutputStrategy.isSaveLatest(), tsOutputStrategy.isSendWsUpdate(), tsOutputStrategy.isProcessCfs()); - saveTimeSeriesInternal(tenantId, entityId, jsonResult, tsOutputStrategy.getTtl(), cfIds, ts, strategy, callback); + saveTimeSeriesInternal(tenantId, entityId, jsonResult, resolveTtl(tenantId, tsOutputStrategy.getTtl()), cfIds, ts, strategy, callback); } } + private long resolveTtl(TenantId tenantId, long ttl) { + if (ttl == 0L) { + return TimeUnit.DAYS.toSeconds(apiLimitService.getLimit(tenantId, DefaultTenantProfileConfiguration::getDefaultStorageTtlDays)); + } + return ttl; + } + private void saveTimeSeriesInternal(TenantId tenantId, EntityId entityId, JsonElement jsonResult, Long ttl, List cfIds, long ts, TimeseriesSaveRequest.Strategy strategy, TbCallback callback) { Map> tsKvMap = JsonConverter.convertToTelemetry(jsonResult, ts); if (tsKvMap.isEmpty()) { diff --git a/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java b/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java index 097a0da2f0..f984b23d87 100644 --- a/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java +++ b/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java @@ -4,6 +4,8 @@ package org.thingsboard.server.service.cf.ctx.state.alarm; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.KvUtil; @@ -38,6 +40,8 @@ public class AlarmRuleState { private final AlarmSeverity severity; private AlarmRule alarmRule; + @ToString.Exclude + @EqualsAndHashCode.Exclude private AlarmCalculatedFieldState state; private AlarmCondition condition; diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java new file mode 100644 index 0000000000..66fa1e6197 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import lombok.Getter; + +/** + * Why {@link CommunityGrantOfflineBundle#parse} refused a {@code TBICBDL1} file. The message is shown to the + * uploader and stored in an audit row, so it must never carry secrets or the uploaded bytes. + */ +@Getter +public class CommunityGrantBundleFormatException extends IllegalArgumentException { + + /** In the order the checks are made. */ + public enum Reason { + TOO_SHORT, + BAD_MAGIC, + UNSUPPORTED_VERSION, + MANIFEST_LEN_RANGE, + CHECKER_LEN_RANGE, + LENGTH_MISMATCH, + MANIFEST_NOT_UTF8, + MANIFEST_NOT_JSON, + MANIFEST_FIELD + } + + private final Reason reason; + + public CommunityGrantBundleFormatException(Reason reason, String message) { + super(message); + this.reason = reason; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java new file mode 100644 index 0000000000..775ed7b090 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import org.thingsboard.common.util.JacksonUtil; + +import java.util.Optional; + +/** + * The portal-decided input for the instance checker, passed through to its {@code TB_IC_INPUT} unread. + */ +public record CommunityGrantCheckerInput(String json) { + + /** Empty unless {@code input} is a non-empty JSON object. */ + public static Optional from(JsonNode input) { + if (input == null || !input.isObject() || input.isEmpty()) { + return Optional.empty(); + } + return Optional.of(new CommunityGrantCheckerInput(JacksonUtil.toString(input))); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java new file mode 100644 index 0000000000..b26e39fbcf --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.springframework.web.client.RestClientException; + +/** + * Thrown by {@link CommunityGrantPortalClient#downloadChecker} when the checker exceeds the configured size + * cap, whether advertised by Content-Length or discovered mid-stream. + */ +public class CommunityGrantCheckerTooLargeException extends RestClientException { + + public CommunityGrantCheckerTooLargeException(String message) { + super(message); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java new file mode 100644 index 0000000000..f40cd9d2de --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommunityGrantClusterStatus(boolean alreadyRegistered) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java new file mode 100644 index 0000000000..a0be2548f7 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.exception.DataValidationException; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.UnaryOperator; + +/** + * Every write goes through {@link #update}, which re-reads under a per-node lock. {@code admin_settings} has no + * unique index on {@code (tenant_id, key)}, so two creates that both commit leave duplicate rows, and every + * later read throws until one is deleted by hand. + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantFlowStateStore { + + public static final String SETTINGS_KEY = "communityGrant"; + + private final AdminSettingsService adminSettingsService; + + private final ReentrantLock updateLock = new ReentrantLock(); + + public CommunityGrantFlowState get() { + try { + return readOrThrow(); + } catch (IllegalStateException e) { + // Read-only fallback; a store failure still propagates. + log.warn("Failed to parse the stored community grant flow state, falling back to the initial state", e); + return CommunityGrantFlowState.initial(); + } + } + + /** + * The updater runs a second time against the winner's document when a create race is lost, so it must be + * deterministic: read the clock before the call, not inside it. + */ + public CommunityGrantFlowState update(UnaryOperator updater) { + updateLock.lock(); + try { + AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY); + JsonNode stored = settings != null ? settings.getJsonValue() : null; + CommunityGrantFlowState updated = updater.apply(parseOrThrow(settings)); + JsonNode serialized = JacksonUtil.valueToTree(updated); + // Every poll runs an updater; an unchanged document is not written back. + if (serialized.equals(stored)) { + return updated; + } + if (settings == null) { + settings = new AdminSettings(); + settings.setTenantId(TenantId.SYS_TENANT_ID); + settings.setKey(SETTINGS_KEY); + } + settings.setJsonValue(serialized); + try { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings); + return updated; + } catch (DataValidationException e) { + if (settings.getId() != null) { + throw e; + } + // Lost a create race to another node: re-apply the change to the winner's row. + AdminSettings winner = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY); + if (winner == null) { + throw e; + } + CommunityGrantFlowState reapplied; + try { + reapplied = updater.apply(parseOrThrow(winner)); + } catch (RuntimeException retryFailure) { + retryFailure.addSuppressed(e); + throw retryFailure; + } + winner.setJsonValue(JacksonUtil.valueToTree(reapplied)); + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, winner); + return reapplied; + } + } finally { + updateLock.unlock(); + } + } + + private CommunityGrantFlowState readOrThrow() { + return parseOrThrow(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY)); + } + + private CommunityGrantFlowState parseOrThrow(AdminSettings settings) { + if (settings == null || settings.getJsonValue() == null || settings.getJsonValue().isNull()) { + return CommunityGrantFlowState.initial(); + } + CommunityGrantFlowState flowState; + try { + flowState = JacksonUtil.treeToValue(settings.getJsonValue(), CommunityGrantFlowState.class); + } catch (Exception e) { + // The cause is dropped: it carries the whole stored document, claim token included. + throw new IllegalStateException("Stored community grant flow state at admin_settings[" + SETTINGS_KEY + + "] could not be parsed: " + e.getClass().getSimpleName()); + } + if (flowState == null || flowState.getState() == null) { + return CommunityGrantFlowState.initial(); + } + if (flowState.getMode() == null) { + flowState.setMode(CommunityGrantMode.ONLINE); + } + return flowState; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java new file mode 100644 index 0000000000..608adff2dc --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; + +/** + * Rewrites this deployment's JDBC url as the libpq connection string the instance checker's driver + * understands. + */ +final class CommunityGrantLibpqDsn { + + private static final String JDBC_PREFIX = "jdbc:"; + private static final String JDBC_POSTGRESQL_PREFIX = "jdbc:postgresql:"; + private static final String POSTGRES_SCHEME = "postgres://"; + + private CommunityGrantLibpqDsn() { + } + + /** + * The JDBC query string is dropped: its parameters are the JDBC driver's, not libpq's. + * + * @throws IllegalStateException if the url is not a PostgreSQL JDBC url naming a single host and a + * database, or the username is blank + */ + static String from(String jdbcUrl, String username, String password) { + if (jdbcUrl == null || !jdbcUrl.startsWith(JDBC_POSTGRESQL_PREFIX)) { + throw new IllegalStateException("The datasource url is not a PostgreSQL JDBC url"); + } + URI jdbc; + try { + jdbc = new URI(jdbcUrl.substring(JDBC_PREFIX.length())); + } catch (URISyntaxException e) { + // The cause is dropped: its message quotes the url, which may carry the database password. + throw new IllegalStateException("The datasource url is not a valid PostgreSQL JDBC url"); + } + if (jdbc.getHost() == null) { + throw new IllegalStateException("The datasource url does not name a single host"); + } + String path = jdbc.getPath(); + if (path == null || path.length() <= 1) { + throw new IllegalStateException("The datasource url does not name a database"); + } + if (username == null || username.isBlank()) { + throw new IllegalStateException("The datasource has no configured username"); + } + String userInfo = percentEncodeUserInfoComponent(username) + ":" + + percentEncodeUserInfoComponent(password == null ? "" : password); + try { + // Spliced in rather than passed to the URI constructor, which would escape every '%' above again. + String withoutUserInfo = new URI("postgres", null, jdbc.getHost(), jdbc.getPort(), path, null, null) + .toASCIIString(); + return POSTGRES_SCHEME + userInfo + "@" + withoutUserInfo.substring(POSTGRES_SCHEME.length()); + } catch (URISyntaxException e) { + // The cause is dropped for the same reason as above. + throw new IllegalStateException("Failed to build the instance check connection string"); + } + } + + /** Escapes everything outside the RFC 3986 unreserved set, ':' and '%' included. */ + private static String percentEncodeUserInfoComponent(String value) { + StringBuilder encoded = new StringBuilder(); + for (byte b : value.getBytes(StandardCharsets.UTF_8)) { + int c = b & 0xFF; + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') + || c == '-' || c == '.' || c == '_' || c == '~') { + encoded.append((char) c); + } else { + encoded.append('%').append(String.format("%02X", c)); + } + } + return encoded.toString(); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java new file mode 100644 index 0000000000..57c68a9fc4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestClientException; + +/** + * Thrown by {@link CommunityGrantPortalClient#claimLicense} when the portal will not hand the license key + * over. Terminal, unlike a transport failure: retrying the claim cannot change the answer. + */ +public class CommunityGrantLicenseClaimRefusedException extends RestClientException { + + public CommunityGrantLicenseClaimRefusedException(HttpStatusCodeException cause) { + super(cause.getMessage(), cause); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java new file mode 100644 index 0000000000..080bc59393 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +public record CommunityGrantLicenseClaimRequest(String claimToken) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java new file mode 100644 index 0000000000..77a6ff114b --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** {@code secret} is set only once {@code activated} is true. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommunityGrantLicenseClaimResponse(boolean activated, String secret) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java new file mode 100644 index 0000000000..09d261e7ae --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java @@ -0,0 +1,314 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import org.thingsboard.server.service.community_grant.CommunityGrantBundleFormatException.Reason; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * The {@code TBICBDL1} offline enrollment bundle. + *
+ * offset  width  field         value / constraint
+ * 0       8      MAGIC         "TBICBDL1"
+ * 8       1      VERSION       0x01
+ * 9       4      MANIFEST_LEN  uint32 big-endian, 1..8192
+ * 13      4      CHECKER_LEN   uint32 big-endian, >= 1
+ * 17      74     RELSIG        a complete TBICSIG1 file, verbatim
+ * 91      M      MANIFEST      UTF-8 JSON
+ * 91+M    C      CHECKER       the executable image
+ * 
+ * {@code RELSIG} is not inspected here; {@link CommunityGrantReleaseSignatureVerifier} does that. + */ +public record CommunityGrantOfflineBundle(String os, String arch, UUID clusterId, String checkerFileName, + long issuedAt, long challengeExpiresAt, + CommunityGrantCheckerInput checkerInput, byte[] signature, byte[] checker) { + + public static final int HEADER_LEN = 91; + public static final int MIN_MANIFEST_LEN = 1; + public static final int MAX_MANIFEST_LEN = 8192; + + public static final int MAX_OVERHEAD_BYTES = HEADER_LEN + MAX_MANIFEST_LEN; + + private static final byte[] MAGIC = {'T', 'B', 'I', 'C', 'B', 'D', 'L', '1'}; + private static final byte VERSION_V1 = 0x01; + private static final int RELSIG_OFFSET = 17; + private static final int RELSIG_LEN = 74; + private static final long MIN_CHECKER_LEN = 1; + + private static final int MANIFEST_LEN_OFFSET = 9; + private static final int CHECKER_LEN_OFFSET = 13; + + private static final int MAX_CHECKER_FILE_NAME_LEN = 255; + private static final int MAX_QUOTED_KEY_LEN = 64; + + private static final List KNOWN_OS = List.of("linux", "darwin", "windows"); + private static final List KNOWN_ARCH = List.of("amd64", "arm64"); + + /** {@link UUID#fromString} alone is far too lenient. */ + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + + /** Duplicate keys and trailing content are rejected: parsers disagree on which duplicate wins. */ + private static final ObjectMapper MANIFEST_MAPPER = JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + /** + * @throws CommunityGrantBundleFormatException with a message safe to show the uploader and to store in + * an audit row. + */ + public static CommunityGrantOfflineBundle parse(byte[] data) { + int total = data == null ? 0 : data.length; + if (total < HEADER_LEN) { + throw new CommunityGrantBundleFormatException(Reason.TOO_SHORT, "The uploaded file is " + total + + " bytes, shorter than the " + HEADER_LEN + "-byte enrollment bundle header, so it is not" + + " a ThingsBoard enrollment bundle."); + } + if (!Arrays.equals(data, 0, MAGIC.length, MAGIC, 0, MAGIC.length)) { + throw new CommunityGrantBundleFormatException(Reason.BAD_MAGIC, "The uploaded file is not a" + + " ThingsBoard enrollment bundle: it does not carry the marker every bundle begins with."); + } + if (data[MAGIC.length] != VERSION_V1) { + throw new CommunityGrantBundleFormatException(Reason.UNSUPPORTED_VERSION, "The enrollment bundle" + + " declares format version " + (data[MAGIC.length] & 0xFF) + ", and this deployment" + + " supports version " + VERSION_V1 + " only."); + } + // Unsigned: read into a long so 0xFFFFFFFF cannot wrap the length arithmetic. + long manifestLen = readUnsignedInt(data, MANIFEST_LEN_OFFSET); + long checkerLen = readUnsignedInt(data, CHECKER_LEN_OFFSET); + if (manifestLen < MIN_MANIFEST_LEN || manifestLen > MAX_MANIFEST_LEN) { + throw new CommunityGrantBundleFormatException(Reason.MANIFEST_LEN_RANGE, "The enrollment bundle" + + " declares a manifest of " + manifestLen + " bytes, outside the permitted range of " + + MIN_MANIFEST_LEN + " to " + MAX_MANIFEST_LEN + " bytes, so the file is damaged."); + } + if (checkerLen < MIN_CHECKER_LEN) { + throw new CommunityGrantBundleFormatException(Reason.CHECKER_LEN_RANGE, "The enrollment bundle" + + " declares a checker of " + checkerLen + " bytes, so the file is damaged."); + } + long expectedTotal = HEADER_LEN + manifestLen + checkerLen; + if (expectedTotal != total) { + throw new CommunityGrantBundleFormatException(Reason.LENGTH_MISMATCH, "The enrollment bundle is" + + " damaged or truncated: its declared " + manifestLen + "-byte manifest and " + + checkerLen + "-byte checker need a file of " + expectedTotal + " bytes, but the" + + " uploaded file is " + total + " bytes. Download the bundle again."); + } + JsonNode manifest = readManifest(data, (int) manifestLen); + return new CommunityGrantOfflineBundle( + readEnum(manifest, "os", KNOWN_OS), + readEnum(manifest, "arch", KNOWN_ARCH), + readClusterId(manifest), + readCheckerFileName(manifest), + readIssuedAt(manifest), + readTimestamp(manifest, "challengeExpiresAt"), + readCheckerInput(manifest), + Arrays.copyOfRange(data, RELSIG_OFFSET, RELSIG_OFFSET + RELSIG_LEN), + Arrays.copyOfRange(data, HEADER_LEN + (int) manifestLen, total)); + } + + /** Strictly later: the portal still accepts the deadline instant itself. */ + public boolean isChallengeExpired(long now) { + return now > challengeExpiresAt; + } + + private static long readUnsignedInt(byte[] data, int offset) { + return ((long) (data[offset] & 0xFF) << 24) + | ((long) (data[offset + 1] & 0xFF) << 16) + | ((long) (data[offset + 2] & 0xFF) << 8) + | (data[offset + 3] & 0xFF); + } + + /** A strict decoder: a substituting one would report binary garbage as bad JSON rather than bad text. */ + private static JsonNode readManifest(byte[] data, int manifestLen) { + CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT); + CharBuffer text; + try { + text = decoder.decode(ByteBuffer.wrap(data, HEADER_LEN, manifestLen)); + } catch (CharacterCodingException e) { + throw new CommunityGrantBundleFormatException(Reason.MANIFEST_NOT_UTF8, "The enrollment bundle's" + + " manifest is not readable text, so the file is damaged. Download the bundle again."); + } + String manifestJson = text.toString(); + JsonNode manifest; + try { + manifest = MANIFEST_MAPPER.readTree(manifestJson); + } catch (JsonParseException e) { + throw notAJsonObject(); + } catch (IOException e) { + // Not a syntax error, so the duplicate-key refusal; Jackson's message does not name the key reliably. + String duplicate = findDuplicateKey(manifestJson); + if (duplicate == null) { + throw notAJsonObject(); + } + throw fieldError(quoteKey(duplicate), "appears more than once"); + } + if (manifest == null || !manifest.isObject()) { + throw notAJsonObject(); + } + int declaredVersion = readInt(manifest, "bundleVersion"); + if (declaredVersion != VERSION_V1) { + throw fieldError("bundleVersion", "must be " + VERSION_V1); + } + return manifest; + } + + /** Scans the root value only, so trailing junk is not blamed for a duplicate key. */ + private static String findDuplicateKey(String manifestJson) { + Deque> seenPerObject = new ArrayDeque<>(); + try (JsonParser parser = MANIFEST_MAPPER.createParser(manifestJson)) { + for (JsonToken token = parser.nextToken(); token != null; token = parser.nextToken()) { + if (token == JsonToken.START_OBJECT) { + seenPerObject.push(new HashSet<>()); + } else if (token == JsonToken.END_OBJECT) { + seenPerObject.pop(); + if (seenPerObject.isEmpty()) { + break; + } + } else if (token == JsonToken.FIELD_NAME && !seenPerObject.peek().add(parser.currentName())) { + return parser.currentName(); + } + } + } catch (IOException e) { + return null; + } + return null; + } + + private static CommunityGrantBundleFormatException notAJsonObject() { + return new CommunityGrantBundleFormatException(Reason.MANIFEST_NOT_JSON, "The enrollment bundle's" + + " manifest is not a JSON object, so the file is damaged. Download the bundle again."); + } + + /** Never quotes the offending value: the message is shown to the uploader and audited. */ + private static CommunityGrantBundleFormatException fieldError(String key, String problem) { + return new CommunityGrantBundleFormatException(Reason.MANIFEST_FIELD, "The enrollment bundle's" + + " manifest is not usable: \"" + key + "\" " + problem + ". Download the bundle again."); + } + + /** The one uploaded string a refusal quotes, so it is bounded and stripped of control characters. */ + private static String quoteKey(String key) { + String quoted = key; + if (quoted.length() > MAX_QUOTED_KEY_LEN) { + // Never cut between the halves of a surrogate pair. + int end = Character.isHighSurrogate(quoted.charAt(MAX_QUOTED_KEY_LEN - 1)) + ? MAX_QUOTED_KEY_LEN - 1 : MAX_QUOTED_KEY_LEN; + quoted = quoted.substring(0, end) + "..."; + } + return quoted.replaceAll("\\p{Cntrl}", "?"); + } + + private static JsonNode required(JsonNode manifest, String key) { + JsonNode value = manifest.get(key); + if (value == null || value.isNull()) { + throw fieldError(key, "is missing"); + } + return value; + } + + private static String readString(JsonNode manifest, String key) { + JsonNode value = required(manifest, key); + if (!value.isTextual()) { + throw fieldError(key, "must be a string"); + } + return value.textValue(); + } + + private static int readInt(JsonNode manifest, String key) { + JsonNode value = required(manifest, key); + if (!value.isIntegralNumber() || !value.canConvertToInt()) { + throw fieldError(key, "must be a whole number"); + } + return value.intValue(); + } + + private static long readTimestamp(JsonNode manifest, String key) { + JsonNode value = required(manifest, key); + if (!value.isIntegralNumber() || !value.canConvertToLong()) { + throw fieldError(key, "must be a whole number of milliseconds"); + } + long millis = value.longValue(); + if (millis <= 0) { + throw fieldError(key, "must be a positive number of milliseconds"); + } + return millis; + } + + private static String readEnum(JsonNode manifest, String key, List permitted) { + String value = readString(manifest, key); + if (!permitted.contains(value)) { + throw fieldError(key, "must be one of " + String.join(", ", permitted)); + } + return value; + } + + private static UUID readClusterId(JsonNode manifest) { + String value = readString(manifest, "clusterId"); + if (!CANONICAL_UUID.matcher(value).matches()) { + throw fieldError("clusterId", "must be a canonical lowercase UUID"); + } + return UUID.fromString(value); + } + + private static String readCheckerFileName(JsonNode manifest) { + String value = readString(manifest, "checkerFileName"); + if (value.isEmpty() || value.length() > MAX_CHECKER_FILE_NAME_LEN) { + throw fieldError("checkerFileName", "must be between 1 and " + MAX_CHECKER_FILE_NAME_LEN + + " characters"); + } + // Logged verbatim, so control characters could forge log lines. + if (value.indexOf('/') >= 0 || value.indexOf('\\') >= 0 || value.contains("..") + || containsControlCharacter(value)) { + throw fieldError("checkerFileName", + "must not contain a path separator, \"..\" or a control character"); + } + return value; + } + + private static boolean containsControlCharacter(String value) { + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c < 0x20 || c == 0x7F) { + return true; + } + } + return false; + } + + private static long readIssuedAt(JsonNode manifest) { + long issuedAt = readTimestamp(manifest, "issuedAt"); + if (issuedAt > readTimestamp(manifest, "challengeExpiresAt")) { + throw fieldError("issuedAt", "must not be later than the challenge's expiry"); + } + return issuedAt; + } + + private static CommunityGrantCheckerInput readCheckerInput(JsonNode manifest) { + return CommunityGrantCheckerInput.from(manifest.get("checkerInput")) + .orElseThrow(() -> fieldError("checkerInput", "must be a non-empty object")); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java new file mode 100644 index 0000000000..3909e60c21 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongSupplier; + +/** + * The last offline report: a durable row plus a node-local copy that outranks it until a newer write lands, so + * a node whose durable write failed still serves what it produced. Ordering relies on wall clocks across + * nodes. {@link #clear()} writes a tombstone so "cleared" differs from "never stored". + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantOfflineReportStore { + + public static final String SETTINGS_KEY = "communityGrantReport"; + private static final String REPORT_FIELD = "report"; + private static final String UPDATED_AT_FIELD = "updatedAt"; + + private final AdminSettingsService adminSettingsService; + + private final AtomicReference nodeLocalReport = new AtomicReference<>(); + + @Setter(AccessLevel.PACKAGE) + private LongSupplier clock = System::currentTimeMillis; + + /** + * The last report, or empty when there is none. A failed read propagates unless this node has a copy of + * its own to answer with: a read that did not reach the database is no evidence of absence. + */ + public Optional get() { + LocalReport localReport = nodeLocalReport.get(); + Optional local = Optional.ofNullable(localReport) + .map(LocalReport::report) + .filter(StringUtils::isNotEmpty); + StoredReport stored; + try { + stored = readStored(); + } catch (RuntimeException e) { + if (localReport == null) { + throw e; + } + log.warn("Failed to read the stored community grant offline report; " + + "serving what this node last did itself", e); + return local; + } + if (stored == null) { + return local; + } + if (localReport != null && !localReport.durable() + && stored.updatedAt() <= localReport.writtenAt()) { + return local; + } + if (stored.report() == null) { + nodeLocalReport.compareAndSet(localReport, null); + return Optional.empty(); + } + if (localReport != null && !localReport.durable()) { + // Dropped so a later write carrying an earlier instant cannot revive it. + nodeLocalReport.compareAndSet(localReport, null); + } + return Optional.of(stored.report()); + } + + public void put(String report) { + long writtenAt = clock.getAsLong(); + LocalReport pending = new LocalReport(report, false, writtenAt); + nodeLocalReport.set(pending); + if (writeStored(report, writtenAt)) { + nodeLocalReport.compareAndSet(pending, new LocalReport(report, true, writtenAt)); + } + } + + /** + * Retires the report along with the enrollment it belonged to. Until the durable write lands, the local + * copy answers empty on this node. + */ + public void clear() { + long writtenAt = clock.getAsLong(); + LocalReport pending = new LocalReport(null, false, writtenAt); + nodeLocalReport.set(pending); + if (writeStored(null, writtenAt)) { + nodeLocalReport.compareAndSet(pending, null); + } + } + + /** {@code null} for no usable row; a {@link StoredReport} with a {@code null} report for the tombstone. */ + private StoredReport readStored() { + AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY); + if (settings == null || settings.getJsonValue() == null) { + return null; + } + JsonNode value = settings.getJsonValue(); + JsonNode report = value.get(REPORT_FIELD); + if (report == null) { + return null; + } + long updatedAt = value.path(UPDATED_AT_FIELD).asLong(); + if (report.isNull()) { + return new StoredReport(null, updatedAt); + } + return report.isTextual() && !report.asText().isEmpty() + ? new StoredReport(report.asText(), updatedAt) + : null; + } + + /** A null report writes the tombstone. Returns whether the write reached the database. */ + private boolean writeStored(String report, long updatedAt) { + try { + AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY); + if (settings == null) { + settings = new AdminSettings(); + settings.setTenantId(TenantId.SYS_TENANT_ID); + settings.setKey(SETTINGS_KEY); + } + ObjectNode value = JacksonUtil.newObjectNode(); + if (report == null) { + value.putNull(REPORT_FIELD); + } else { + value.put(REPORT_FIELD, report); + } + value.put(UPDATED_AT_FIELD, updatedAt); + settings.setJsonValue(value); + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings); + return true; + } catch (RuntimeException e) { + log.warn("Failed to store the community grant offline report", e); + return false; + } + } + + /** A {@code null} report stands for a {@link #clear()}. */ + private record LocalReport(String report, boolean durable, long writtenAt) {} + + private record StoredReport(String report, long updatedAt) {} + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java new file mode 100644 index 0000000000..7858638b8c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.thingsboard.server.common.data.StringUtils; + +import java.util.List; +import java.util.Locale; + +/** + * The host platform in the vocabulary the portal's {@code /checker} endpoint expects. + */ +public record CommunityGrantPlatform(String os, String arch) { + + private static final List KNOWN_OS = List.of("darwin", "windows", "linux"); + private static final List KNOWN_ARCH = List.of("amd64", "arm64"); + + public static CommunityGrantPlatform current() { + return of(System.getProperty("os.name", ""), System.getProperty("os.arch", "")); + } + + static CommunityGrantPlatform of(String rawOsName, String rawOsArch) { + String osName = rawOsName.toLowerCase(Locale.ROOT); + String osArch = rawOsArch.toLowerCase(Locale.ROOT); + String os; + if (osName.contains("mac") || osName.contains("darwin")) { + os = "darwin"; + } else if (osName.contains("win")) { + os = "windows"; + } else { + os = "linux"; + } + String arch; + if (osArch.contains("aarch64") || osArch.contains("arm64")) { + arch = "arm64"; + } else if (osArch.contains("amd64") || osArch.contains("x86_64") || osArch.contains("x64")) { + arch = "amd64"; + } else { + throw new IllegalStateException("Unsupported architecture for the instance checker: " + osArch); + } + return new CommunityGrantPlatform(os, arch); + } + + public String checkerFileName() { + return "windows".equals(os) ? "tb-instance-check.exe" : "tb-instance-check"; + } + + /** A legibility check, not a security one: true only for a name that spells out another os or arch. */ + public boolean namesAnotherPlatform(String fileName) { + if (StringUtils.isEmpty(fileName)) { + return false; + } + String normalized = fileName.toLowerCase(Locale.ROOT); + return namesAnother(normalized, KNOWN_OS, os) || namesAnother(normalized, KNOWN_ARCH, arch); + } + + private static boolean namesAnother(String fileName, List known, String mine) { + return known.stream().anyMatch(token -> !token.equals(mine) && fileName.contains(token)); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java new file mode 100644 index 0000000000..a19f4e3163 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java @@ -0,0 +1,547 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.annotation.PreDestroy; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.thingsboard.common.util.ThingsBoardExecutors; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.TbApplicationEventListener; +import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; +import org.thingsboard.server.queue.util.AfterStartUp; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.UnaryOperator; + +/** + * Polls the portal about this deployment's claim and projects the answer onto the local state. Only the node + * owning the system tenant's TB_CORE partition runs the loop; it supervises for flows other nodes began. + * On the offline rail it never calls out, and only enforces the sign-up deadline. + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantPoller extends TbApplicationEventListener { + + static final long MIN_POLL_INTERVAL_MS = 2000; + static final int MAX_RETRY_AFTER_SEC = 3600; + static final long MAX_FAILURE_BACKOFF_MS = TimeUnit.MINUTES.toMillis(10); + static final int CONSECUTIVE_FAILURE_WARN_THRESHOLD = 5; + + static final int MAX_POLL_FAILURES = 200; + + /** Several of these failures are permanent, and every retry re-downloads the whole checker. */ + static final int MAX_VERIFICATION_FAILURES = 5; + + @Value("${community-grant.enabled:true}") + private boolean enabled; + + @Value("${community-grant.fast-poll-interval-ms:3000}") + private long fastPollIntervalMs; + + @Value("${community-grant.fast-poll-window-ms:120000}") + private long fastPollWindowMs; + + @Value("${community-grant.slow-poll-interval-ms:30000}") + private long slowPollIntervalMs; + + /** Matched to the portal's claim-token lifetime (24h). */ + @Value("${community-grant.sign-up-deadline-ms:86400000}") + private long signUpDeadlineMs; + + @Value("${community-grant.supervise-interval-ms:30000}") + private long superviseIntervalMs; + + private final PartitionService partitionService; + private final TbClusterStore tbClusterStore; + private final CommunityGrantFlowStateStore flowStateStore; + private final CommunityGrantPortalClient portalClient; + private final CommunityGrantReportRunner reportRunner; + + private final ScheduledExecutorService scheduler = + ThingsBoardExecutors.newSingleThreadScheduledExecutor("tb-community-grant-poller"); + private final AtomicBoolean armed = new AtomicBoolean(false); + private final ReentrantLock pollLock = new ReentrantLock(); + private final AtomicInteger consecutiveFailures = new AtomicInteger(0); + private final AtomicInteger verificationFailures = new AtomicInteger(0); + + /** Stops a poll still running across a disarm and re-arm from rescheduling beside the new chain. */ + private final AtomicLong generation = new AtomicLong(); + + private volatile ScheduledFuture pendingPoll; + private volatile ScheduledFuture supervisor; + private volatile long pollingSince; + private volatile long lastPollTs; + + /** The claim token the current budgets and fast window belong to. */ + private volatile String pollingToken; + + @AfterStartUp(order = AfterStartUp.REGULAR_SERVICE) + public void init() { + if (enabled && isSystemTenantPartitionMine()) { + startSupervising(); + armIfPollable(); + } + } + + @Override + protected void onTbApplicationEvent(PartitionChangeEvent event) { + if (!enabled) { + return; + } + if (isSystemTenantPartitionMine()) { + startSupervising(); + armIfPollable(); + } else { + stopSupervising(); + disarm(); + } + } + + @Override + protected boolean filterTbApplicationEvent(PartitionChangeEvent event) { + return ServiceType.TB_CORE == event.getServiceType(); + } + + /** A no-op off the partition owner, whose supervisor picks the flow up instead. Arms offline flows too. */ + public void arm() { + if (!enabled) { + return; + } + if (!isSystemTenantPartitionMine()) { + log.debug("Not arming the community grant poller: this node does not own the system tenant's " + + "TB_CORE partition"); + return; + } + if (armed.compareAndSet(false, true)) { + pollingSince = System.currentTimeMillis(); + verificationFailures.set(0); + consecutiveFailures.set(0); + cancelPendingPoll(); + schedule(fastPollIntervalMs, generation.incrementAndGet()); + } + } + + public void disarm() { + armed.set(false); + cancelPendingPoll(); + } + + boolean isArmed() { + return armed.get(); + } + + @PreDestroy + public void stop() { + stopSupervising(); + disarm(); + scheduler.shutdownNow(); + } + + private synchronized void startSupervising() { + if (supervisor != null) { + return; + } + try { + supervisor = scheduler.scheduleWithFixedDelay(this::supervise, + superviseIntervalMs, superviseIntervalMs, TimeUnit.MILLISECONDS); + } catch (Exception e) { + log.warn("Failed to schedule the community grant supervisor", e); + } + } + + private synchronized void stopSupervising() { + ScheduledFuture pending = supervisor; + if (pending != null) { + pending.cancel(false); + supervisor = null; + } + } + + void supervise() { + try { + if (!armed.get()) { + armIfPollable(); + } + } catch (Throwable e) { + // A fixed-delay task that throws is never run again. + log.debug("The community grant supervisor tick failed", e); + } + } + + private boolean isSystemTenantPartitionMine() { + try { + return partitionService.resolve(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID).isMyPartition(); + } catch (Exception e) { + log.debug("Failed to resolve the system tenant partition", e); + return false; + } + } + + /** Offline, nothing ever answers past the sign-up form, so there is no work left once it is done. */ + private static boolean hasWorkLeft(CommunityGrantFlowState state) { + return state.getMode() != CommunityGrantMode.OFFLINE + || state.getState() == CommunityGrantState.AWAITING_SIGNUP; + } + + private void armIfPollable() { + boolean pollable; + try { + CommunityGrantFlowState stored = flowStateStore.get(); + pollable = stored.getState().isPollable() && hasWorkLeft(stored); + } catch (Exception e) { + log.warn("Failed to read the stored community grant state, not arming the community grant poller", e); + return; + } + if (pollable) { + arm(); + } + } + + private void schedule(long delayMs, long gen) { + if (!armed.get() || gen != generation.get()) { + return; + } + try { + pendingPoll = scheduler.schedule(() -> pollAndReschedule(gen), delayMs, TimeUnit.MILLISECONDS); + } catch (Exception e) { + // Cleared so arm() can start a new chain. + armed.set(false); + log.warn("Failed to schedule the next community grant poll", e); + } + } + + private void cancelPendingPoll() { + ScheduledFuture pending = pendingPoll; + if (pending != null) { + pending.cancel(false); + pendingPoll = null; + } + } + + void pollAndReschedule() { + pollAndReschedule(generation.get()); + } + + private void pollAndReschedule(long gen) { + if (gen != generation.get()) { + return; + } + long nextDelay; + try { + nextDelay = nextDelay(poll()); + } catch (Throwable e) { + // Throwable, so an Error cannot cancel the scheduled task. + int failures = consecutiveFailures.incrementAndGet(); + if (failures >= CONSECUTIVE_FAILURE_WARN_THRESHOLD) { + log.warn("Failed to poll the license portal ({} consecutive failures)", failures, e); + } else { + log.debug("Failed to poll the license portal", e); + } + onPollFailure(failures); + nextDelay = failureDelay(failures); + } + schedule(nextDelay, gen); + } + + /** An unreachable portal never answers, so its endings are enforced locally. */ + private void onPollFailure(int failures) { + try { + String token = tbClusterStore.getLicenseClaimToken().orElse(null); + if (StringUtils.isEmpty(token)) { + return; + } + long now = System.currentTimeMillis(); + if (parkIfSignUpAbandoned(token, flowStateStore.get(), now)) { + return; + } + if (failures >= MAX_POLL_FAILURES) { + log.warn("Parking the community grant flow after {} consecutive poll failures", failures); + park(token, now, CommunityGrantParkReason.PORTAL_UNREACHABLE); + } + } catch (Exception e) { + log.debug("Failed to park the community grant flow after a poll failure", e); + } + } + + /** + * @return the portal's own pacing instruction, or {@code null} when this tick did not reach it. + */ + Integer poll() { + if (!armed.get()) { + return null; + } + String token = tbClusterStore.getLicenseClaimToken().orElse(null); + if (StringUtils.isEmpty(token)) { + disarm(); + return null; + } + if (!token.equals(pollingToken)) { + // A new token is a new enrollment. Re-based here: on another node, the owner never sees start(). + if (pollingToken != null) { + pollingSince = System.currentTimeMillis(); + verificationFailures.set(0); + consecutiveFailures.set(0); + } + pollingToken = token; + } + CommunityGrantFlowState current = flowStateStore.get(); + if (current.getMode() == CommunityGrantMode.OFFLINE) { + if (!hasWorkLeft(current)) { + disarm(); + return null; + } + parkIfSignUpAbandoned(token, current, System.currentTimeMillis()); + return null; + } + UUID clusterId = tbClusterStore.getClusterId().orElse(null); + if (clusterId == null) { + disarm(); + return null; + } + if (System.currentTimeMillis() - lastPollTs < MIN_POLL_INTERVAL_MS || !pollLock.tryLock()) { + return null; + } + try { + lastPollTs = System.currentTimeMillis(); + CommunityGrantPortalStatus status = portalClient.getStatus(token, clusterId); + // Reset only once the portal has actually answered. + consecutiveFailures.set(0); + if (status == null) { + return null; + } + apply(token, status); + return status.retryAfterSec(); + } finally { + pollLock.unlock(); + } + } + + /** The portal's {@code retryAfterSec}, when positive, wins over the local cadence. */ + long nextDelay(Integer retryAfterSec) { + if (retryAfterSec != null && retryAfterSec > 0) { + return TimeUnit.SECONDS.toMillis(Math.min(retryAfterSec, MAX_RETRY_AFTER_SEC)); + } + return System.currentTimeMillis() - pollingSince < fastPollWindowMs ? fastPollIntervalMs : slowPollIntervalMs; + } + + long failureDelay(int failures) { + return Math.min(nextDelay(null) << Math.min(failures - 1, 10), MAX_FAILURE_BACKOFF_MS); + } + + void apply(String token, CommunityGrantPortalStatus status) { + long now = System.currentTimeMillis(); + String statusValue = status.status(); + if (statusValue == null) { + // An empty or partial 200 body. + log.debug("Ignoring a portal status response with no status value"); + return; + } + if (applyIfTerminal(token, statusValue, now)) { + return; + } + switch (statusValue) { + case "AWAITING_SIGNUP" -> onAwaitingSignup(token, now); + case "VERIFICATION_REQUIRED" -> onVerificationRequired(token, status, now); + case "UNDER_REVIEW" -> onUnderReview(token, now); + case "EXPIRED" -> park(token, now, CommunityGrantParkReason.LINK_EXPIRED); + default -> log.debug("Ignoring an unrecognized portal status"); + } + } + + /** @return whether the status was a terminal one, even when the flow could not be ended on this poll. */ + private boolean applyIfTerminal(String token, String status, long now) { + CommunityGrantState terminalState = terminalStateFor(status); + if (terminalState == null) { + return false; + } + if (terminalState == CommunityGrantState.REGISTERED) { + onDone(token, now); + } else { + retire(token, terminalState, now, null); + } + return true; + } + + /** The key is stored before the token is cleared, so a failure above it leaves the next poll to retry. */ + private void onDone(String token, long now) { + String licenseSecret; + try { + licenseSecret = portalClient.claimLicense(token); + } catch (CommunityGrantLicenseClaimRefusedException e) { + log.warn("The license portal did not hand over the license key for this registration ({}). " + + "The registration stands and the key can be entered by hand later", e.getMessage()); + retire(token, CommunityGrantState.REGISTERED, now, null); + return; + } + if (StringUtils.isEmpty(licenseSecret)) { + return; + } + tbClusterStore.saveLicenseSecret(licenseSecret); + retire(token, CommunityGrantState.REGISTERED, now, null); + } + + /** @return the state the flow ends in, or {@code null} if the status is not a terminal one. */ + private static CommunityGrantState terminalStateFor(String status) { + return switch (status) { + case "DONE" -> CommunityGrantState.REGISTERED; + case "WRONG_INSTALLATION" -> CommunityGrantState.WRONG_INSTALLATION; + default -> null; + }; + } + + /** The portal cannot tell an unfinished sign-up from an abandoned one, so the deadline is enforced here. */ + private void onAwaitingSignup(String token, long now) { + if (parkIfSignUpAbandoned(token, flowStateStore.get(), now)) { + return; + } + applyIfCurrent(token, state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + state.setLastPolledAt(now); + return state; + }); + } + + /** @return whether the flow was parked. */ + private boolean parkIfSignUpAbandoned(String token, CommunityGrantFlowState current, long now) { + Long startedAt = current.getStartedAt(); + if (current.getState() != CommunityGrantState.AWAITING_SIGNUP + || startedAt == null || now - startedAt <= signUpDeadlineMs) { + return false; + } + park(token, now, CommunityGrantParkReason.SIGNUP_ABANDONED); + return true; + } + + private void onVerificationRequired(String token, CommunityGrantPortalStatus status, long now) { + CommunityGrantFlowState updated = applyIfCurrent(token, state -> { + // The portal asks for verification until a by-hand report lands; that state must not be overwritten. + if (state.getState() != CommunityGrantState.VALIDATING + && state.getState() != CommunityGrantState.REPORT_HANDED_OVER) { + state.setState(CommunityGrantState.COLLECTING); + } + state.setLastPolledAt(now); + return state; + }); + if (updated == null) { + return; + } + if (updated.getMode() == CommunityGrantMode.OFFLINE) { + return; + } + if (updated.getState() == CommunityGrantState.VALIDATING) { + // A by-hand report is already in flight. + return; + } + Optional checkerInput = CommunityGrantCheckerInput.from(status.checkerInput()); + if (checkerInput.isEmpty()) { + log.warn("The portal asked for verification without the input needed to produce it"); + return; + } + String uploadedStatus; + try { + uploadedStatus = reportRunner.runAndUpload(token, checkerInput.get()); + } catch (Exception e) { + int failures = verificationFailures.incrementAndGet(); + if (failures < MAX_VERIFICATION_FAILURES) { + log.warn("Failed to produce and upload the instance check", e); + } else if (updated.getState() == CommunityGrantState.REPORT_HANDED_OVER) { + // Parking would retire the token the handed-over report is bound to. + log.warn("The instance check keeps failing ({} attempts), but the report has been handed over " + + "by hand, so the flow is left waiting on the portal", failures, e); + } else { + log.warn("Parking the community grant flow after {} failed instance checks", failures, e); + park(token, now, CommunityGrantParkReason.CHECK_FAILED); + } + return; + } + verificationFailures.set(0); + if (uploadedStatus == null) { + return; + } + if (applyIfTerminal(token, uploadedStatus, now)) { + return; + } + if ("UNDER_REVIEW".equals(uploadedStatus)) { + onUnderReview(token, now); + } else { + log.debug("Ignoring an unrecognized portal status after the upload"); + } + } + + /** A wait, not an ending: the token is kept for the poll that brings the reviewer's decision. */ + private void onUnderReview(String token, long now) { + applyIfCurrent(token, state -> { + state.setState(CommunityGrantState.UNDER_REVIEW); + state.setLastPolledAt(now); + return state; + }); + } + + /** @return the state as written, or {@code null} if the claim token had been replaced. */ + private CommunityGrantFlowState applyIfCurrent(String token, UnaryOperator updater) { + AtomicBoolean applied = new AtomicBoolean(); + CommunityGrantFlowState updated = flowStateStore.update(state -> { + // Checked under the store's lock, so a start() on this node cannot replace the token mid-write. + applied.set(token.equals(tbClusterStore.getLicenseClaimToken().orElse(null))); + return applied.get() ? updater.apply(state) : state; + }); + if (!applied.get()) { + log.debug("Ignoring a portal answer for a claim token that has since been replaced"); + return null; + } + return updated; + } + + private void park(String token, long now, CommunityGrantParkReason reason) { + retire(token, CommunityGrantState.RESUME, now, reason); + } + + /** The state is written before the token is cleared, so a failed write leaves the next poll to retry. */ + private void retire(String token, CommunityGrantState newState, long now, CommunityGrantParkReason reason) { + AtomicBoolean applied = new AtomicBoolean(); + flowStateStore.update(state -> { + // Checked under the store's lock, so a start() on this node cannot replace the token mid-write. + applied.set(token.equals(tbClusterStore.getLicenseClaimToken().orElse(null))); + if (!applied.get()) { + return state; + } + // The portal still serves a finished grant's page on this link. + String registrationLink = newState == CommunityGrantState.REGISTERED ? state.getSignUpUrl() : null; + state.setState(newState); + state.setParkReason(reason); + state.clearClaim(); + state.setSignUpUrl(registrationLink); + state.setLastPolledAt(now); + return state; + }); + if (!applied.get()) { + log.debug("Ignoring a portal answer for a claim token that has since been replaced"); + return; + } + tbClusterStore.clearLicenseClaimToken(token); + disarm(); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java new file mode 100644 index 0000000000..ea5410220f --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java @@ -0,0 +1,294 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpRequest; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.client.DefaultResponseErrorHandler; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.Duration; +import java.util.UUID; + +/** + * The only outbound path to the license portal. Calls that carry grant state are authenticated by the claim + * token, never by the cluster id, which is not a secret. + */ +@Component +@TbCoreComponent +@Slf4j +public class CommunityGrantPortalClient { + + private static final String BASE_PATH = "/api/noauth/communityGrant"; + private static final String CLUSTER_STATUS_PATH = BASE_PATH + "/clusterStatus?clusterId={clusterId}"; + private static final String LICENSE_CLAIM_PATH = "/api/noauth/freeLicense/claim"; + + /** A header rather than a query parameter, which would be written to access and proxy logs. */ + private static final String CLAIM_TOKEN_HEADER = "X-TB-Claim-Token"; + + private static final UUID REACHABILITY_PROBE_CLUSTER_ID = new UUID(0L, 0L); + + private static final int REACHABILITY_PROBE_MAX_BODY_BYTES = 4096; + + private static final int ERROR_BODY_MAX_BYTES = 4096; + + @Value("${community-grant.enabled:true}") + private boolean enabled; + + @Value("${community-grant.base-url:https://license.thingsboard.io}") + private String baseUrl; + + @Value("${community-grant.connect-timeout-sec:5}") + private int connectTimeoutSec; + + @Value("${community-grant.read-timeout-sec:10}") + private int readTimeoutSec; + + @Value("${community-grant.max-checker-size-bytes:33554432}") + private long maxCheckerSizeBytes; + + private RestTemplate restTemplate; + + @PostConstruct + public void initRestClient() { + // Validation failure stops the node, so a disabled feature does not validate its URL. + if (enabled) { + baseUrl = normalizeBaseUrl(baseUrl); + } + restTemplate = new RestTemplateBuilder() + .connectTimeout(Duration.ofSeconds(connectTimeoutSec)) + .readTimeout(Duration.ofSeconds(readTimeoutSec)) + .errorHandler(new BoundedBodyErrorHandler()) + .build(); + } + + /** Spring's default handler buffers an error body in full. */ + private static class BoundedBodyErrorHandler extends DefaultResponseErrorHandler { + + @Override + protected byte[] getResponseBody(ClientHttpResponse response) { + try (InputStream in = response.getBody()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int read; + while (out.size() < ERROR_BODY_MAX_BYTES && (read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return out.toByteArray(); + } catch (IOException e) { + return new byte[0]; + } + } + } + + /** A trailing slash would 404 every route, and the reachability probe counts a 404 as reachable. */ + private static String normalizeBaseUrl(String configured) { + String normalized = configured == null ? "" : configured.trim().replaceAll("/+$", ""); + URI uri; + try { + uri = new URI(normalized); + } catch (URISyntaxException e) { + throw new IllegalStateException("community-grant.base-url is not a valid URL: " + configured, e); + } + if (uri.getHost() == null || !("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))) { + throw new IllegalStateException("community-grant.base-url must be an absolute http(s) URL: " + configured); + } + return normalized; + } + + public String getPortalUrl() { + return baseUrl; + } + + /** + * The platform rides along on every link, not only an offline one: the portal needs it to build a checker + * bundle if the enrollment later moves to the by-hand route. + * + * @throws IllegalArgumentException if {@code community-grant.base-url} cannot be parsed + */ + public String buildSignUpUrl(UUID clusterId, String token, CommunityGrantMode mode) { + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) + .path("/communityGrant") + .queryParam("clusterId", clusterId) + .queryParam("claimToken", token); + if (mode == CommunityGrantMode.OFFLINE) { + builder.queryParam("offline", true); + } + appendPlatform(builder); + return builder.build().toUriString(); + } + + /** Omitted on an architecture with no checker build rather than failing the enrollment. */ + private static void appendPlatform(UriComponentsBuilder builder) { + CommunityGrantPlatform platform; + try { + platform = CommunityGrantPlatform.current(); + } catch (RuntimeException e) { + log.debug("Leaving the platform out of the community grant sign-up link", e); + return; + } + builder.queryParam("os", platform.os()).queryParam("arch", platform.arch()); + } + + /** Only a transport failure counts as unreachable; any HTTP status means reachable. */ + public boolean isPortalReachable() { + String url = baseUrl + CLUSTER_STATUS_PATH; + try { + restTemplate.execute(url, HttpMethod.GET, null, response -> { + try (InputStream in = response.getBody()) { + byte[] buffer = new byte[1024]; + int total = 0; + int read; + while (total < REACHABILITY_PROBE_MAX_BODY_BYTES && (read = in.read(buffer)) != -1) { + total += read; + } + } + return null; + }, REACHABILITY_PROBE_CLUSTER_ID); + return true; + } catch (HttpStatusCodeException e) { + return true; + } catch (RestClientException e) { + log.info("The license portal is not reachable from this server: {}", e.getMessage()); + return false; + } + } + + public boolean isAlreadyRegistered(UUID clusterId) { + String url = baseUrl + CLUSTER_STATUS_PATH; + CommunityGrantClusterStatus response = restTemplate.getForObject(url, CommunityGrantClusterStatus.class, clusterId); + return response != null && response.alreadyRegistered(); + } + + /** The portal always answers a bare 200, so a registration is never confirmed to the caller. */ + public void requestAccess(UUID clusterId) { + String url = baseUrl + BASE_PATH + "/requestAccess?clusterId={clusterId}"; + restTemplate.postForObject(url, null, Void.class, clusterId); + } + + /** + * The cluster id goes with every poll: the token resolves to an account whose grant may belong to a + * different installation. + * + * @return the portal's parsed answer, or {@code null} if the portal answered with an empty body + */ + public CommunityGrantPortalStatus getStatus(String token, UUID clusterId) { + String url = baseUrl + BASE_PATH + "/status?clusterId={clusterId}"; + HttpHeaders headers = new HttpHeaders(); + headers.set(CLAIM_TOKEN_HEADER, token); + return restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), + CommunityGrantPortalStatus.class, clusterId).getBody(); + } + + /** + * @return the portal's status after it accepted the report, or {@code null} if the portal answered with + * an empty body. + */ + public String uploadReport(String token, String report) { + String url = baseUrl + BASE_PATH + "/report"; + CommunityGrantReportResponse response = restTemplate.postForObject(url, + new CommunityGrantReportRequest(token, report), CommunityGrantReportResponse.class); + return response == null ? null : response.status(); + } + + /** + * This route reads the claim token from the body, not from the header the grant routes use. + * + * @return the granted license key, or {@code null} while the portal has none to hand over yet + * @throws CommunityGrantLicenseClaimRefusedException if the portal refuses the claim + */ + public String claimLicense(String token) { + String url = baseUrl + LICENSE_CLAIM_PATH; + CommunityGrantLicenseClaimResponse response; + try { + response = restTemplate.postForObject(url, new CommunityGrantLicenseClaimRequest(token), + CommunityGrantLicenseClaimResponse.class); + } catch (HttpStatusCodeException e) { + // A rate-limited claim is the one client error that is worth trying again. + if (e.getStatusCode().is4xxClientError() + && e.getStatusCode().value() != HttpStatus.TOO_MANY_REQUESTS.value()) { + throw new CommunityGrantLicenseClaimRefusedException(e); + } + throw e; + } + return response != null && response.activated() ? response.secret() : null; + } + + /** + * @throws CommunityGrantCheckerTooLargeException if the checker exceeds {@code maxCheckerSizeBytes} + * @throws ResourceAccessException if reading the stream fails + */ + public byte[] downloadChecker(String token, String os, String arch) { + return download(BASE_PATH + "/checker?os={os}&arch={arch}", "instance checker", token, os, arch); + } + + /** + * @throws HttpStatusCodeException if the portal has no signature staged for this platform + */ + public byte[] downloadCheckerSignature(String token, String os, String arch) { + return download(BASE_PATH + "/checkerSignature?os={os}&arch={arch}", + "instance checker's release signature", token, os, arch); + } + + private byte[] download(String path, String what, String token, String os, String arch) { + String url = baseUrl + path; + final long limit = maxCheckerSizeBytes; + return restTemplate.execute(url, HttpMethod.GET, request -> setClaimToken(request, token), response -> { + long contentLength = response.getHeaders().getContentLength(); + if (contentLength > limit) { + throw new CommunityGrantCheckerTooLargeException("The " + what + " size " + contentLength + + " bytes exceeds the configured limit of " + limit + " bytes"); + } + int initialCapacity = contentLength > 0 && contentLength <= Integer.MAX_VALUE + ? (int) contentLength : 8192; + ByteArrayOutputStream out = new ByteArrayOutputStream(initialCapacity); + boolean complete = false; + try (InputStream in = response.getBody()) { + byte[] buffer = new byte[8192]; + long total = 0; + int read; + while ((read = in.read(buffer)) != -1) { + total += read; + if (total > limit) { + throw new CommunityGrantCheckerTooLargeException("The " + what + + " stream exceeded the configured limit of " + limit + " bytes"); + } + out.write(buffer, 0, read); + } + complete = true; + } catch (IOException e) { + if (!complete) { + throw new ResourceAccessException("Failed to read the " + what + " (GET " + url + ")", e); + } + // Only close() failed after a complete read; the download is kept. + log.debug("Failed to close the {} response stream after a complete read", what, e); + } + return out.toByteArray(); + }, os, arch); + } + + private static void setClaimToken(ClientHttpRequest request, String token) { + request.getHeaders().set(CLAIM_TOKEN_HEADER, token); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java new file mode 100644 index 0000000000..755ee5a322 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.JsonNode; + +/** + * The portal's answer to a poll. {@code status} is a raw string so an unknown value leaves the flow where it + * is rather than failing deserialization. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommunityGrantPortalStatus(String status, + JsonNode checkerInput, + Integer retryAfterSec) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java new file mode 100644 index 0000000000..309efb6565 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java @@ -0,0 +1,212 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Verifies the instance checker's detached release signature against the configured release-signing keys. + * Fails closed: with no trusted key, every checker is refused. + */ +@Component +@TbCoreComponent +@Slf4j +public class CommunityGrantReleaseSignatureVerifier { + + static final String PUBLIC_KEYS_PROPERTY = "community-grant.checker-release-public-keys"; + + /** The whole signature file: {@code MAGIC(8) ‖ VERSION(1) ‖ KEYID(1) ‖ SIG(64)}, and nothing after it. */ + static final int SIGNATURE_FILE_LENGTH = 74; + + private static final byte[] MAGIC = {'T', 'B', 'I', 'C', 'S', 'I', 'G', '1'}; + private static final int VERSION_OFFSET = 8; + private static final byte SUPPORTED_VERSION = 0x01; + private static final int KEY_ID_OFFSET = 9; + private static final int SIGNATURE_OFFSET = 10; + + private static final int ED25519_PUBLIC_KEY_LENGTH = 32; + + /** RFC 8410 SubjectPublicKeyInfo prefix for a raw 32-byte Ed25519 key; KeyFactory takes no raw spec. */ + private static final byte[] ED25519_SPKI_PREFIX = { + 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00 + }; + + @Value("${" + PUBLIC_KEYS_PROPERTY + ":}") + private String checkerReleasePublicKeys; + + /** Empty when nothing is configured and when the configured value could not be parsed. */ + private Map trustStore = Map.of(); + + private String trustStoreError; + + @PostConstruct + void init() { + try { + trustStore = parsePublicKeys(checkerReleasePublicKeys); + trustStoreError = null; + } catch (IllegalArgumentException e) { + trustStore = Map.of(); + trustStoreError = e.getMessage(); + log.error("{} could not be parsed, so no release-signing key is trusted and every " + + "instance checker will be refused: {}", PUBLIC_KEYS_PROPERTY, e.getMessage()); + } + } + + public boolean hasTrustedKeys() { + return !trustStore.isEmpty(); + } + + /** + * Throws {@link IllegalArgumentException} unless {@code signatureData} is a valid release signature over + * exactly {@code checkerData} under a trusted key. Messages are safe to show the uploader and to audit. + */ + public void verify(byte[] checkerData, byte[] signatureData) { + if (checkerData == null || checkerData.length == 0) { + throw new IllegalArgumentException("The uploaded instance checker is empty, so there is nothing " + + "to verify. It was not run."); + } + if (signatureData == null || signatureData.length == 0) { + throw new IllegalArgumentException("The enrollment bundle carries no release signature for the " + + "instance checker, so it could not be verified and was not run. Download the enrollment " + + "bundle for this platform again from the License Portal."); + } + if (signatureData.length != SIGNATURE_FILE_LENGTH) { + throw new IllegalArgumentException("The release signature is " + signatureData.length + + " bytes; a ThingsBoard release signature is exactly " + SIGNATURE_FILE_LENGTH + + " bytes. The uploaded instance checker was not run. Download the enrollment bundle again " + + "from the License Portal and upload it unmodified."); + } + if (!Arrays.equals(signatureData, 0, MAGIC.length, MAGIC, 0, MAGIC.length)) { + throw new IllegalArgumentException("The release signature is not a ThingsBoard release " + + "signature. The uploaded instance checker was not run. Download the enrollment bundle again " + + "from the License Portal and upload it unmodified."); + } + byte version = signatureData[VERSION_OFFSET]; + if (version != SUPPORTED_VERSION) { + throw new IllegalArgumentException("The release signature declares signature format " + + "version " + (version & 0xFF) + "; this deployment only understands version " + + SUPPORTED_VERSION + ". The uploaded instance checker was not run. Upgrade ThingsBoard, or " + + "use a checker release this version can verify."); + } + int keyId = signatureData[KEY_ID_OFFSET] & 0xFF; + if (keyId == 0) { + throw new IllegalArgumentException("The release signature names key id 0, which is " + + "reserved and never valid. The uploaded instance checker was not run."); + } + if (trustStore.isEmpty()) { + if (trustStoreError != null) { + throw new IllegalArgumentException("The configured " + PUBLIC_KEYS_PROPERTY + " could not be " + + "parsed (" + trustStoreError + "), so no uploaded instance checker can be verified. " + + "It was not run. Fix the configured value."); + } + throw new IllegalArgumentException("This deployment is not configured to verify an uploaded " + + "instance checker, so it refuses to run one. Set " + PUBLIC_KEYS_PROPERTY + " to the " + + "release-signing public key ThingsBoard publishes, as a comma-separated list of " + + "keyId:base64PublicKey entries."); + } + PublicKey publicKey = trustStore.get(keyId); + if (publicKey == null) { + throw new IllegalArgumentException("The uploaded instance checker is signed under release-signing " + + "key id " + keyId + ", which this deployment does not trust. It was not run. Add that " + + "key id and its public key to " + PUBLIC_KEYS_PROPERTY + " if ThingsBoard published " + + "this release under it."); + } + byte[] signature = Arrays.copyOfRange(signatureData, SIGNATURE_OFFSET, SIGNATURE_FILE_LENGTH); + boolean verified; + try { + Signature ed25519 = Signature.getInstance("Ed25519"); + ed25519.initVerify(publicKey); + ed25519.update(checkerData); + verified = ed25519.verify(signature); + } catch (GeneralSecurityException e) { + // The JDK throws, rather than returning false, for some invalid encodings. + log.debug("An uploaded instance checker's release signature could not be evaluated", e); + verified = false; + } + if (!verified) { + throw new IllegalArgumentException("The uploaded instance checker does not match its release " + + "signature, so it was not run. Download the enrollment bundle again from the License Portal " + + "and upload it unmodified."); + } + } + + /** + * Parses {@code keyId:base64PublicKey[,keyId:base64PublicKey...]}. Every malformed entry throws rather + * than being skipped. + */ + static Map parsePublicKeys(String configured) { + Map keys = new LinkedHashMap<>(); + if (configured == null || configured.isBlank()) { + return Map.copyOf(keys); + } + for (String entry : configured.split(",", -1)) { + String trimmed = entry.trim(); + if (trimmed.isEmpty()) { + throw new IllegalArgumentException("it has an empty entry; every entry must be " + + "keyId:base64PublicKey"); + } + int separator = trimmed.indexOf(':'); + if (separator < 0) { + throw new IllegalArgumentException("an entry is not in the keyId:base64PublicKey form"); + } + int keyId; + try { + keyId = Integer.parseInt(trimmed.substring(0, separator).trim()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("an entry's key id is not a number"); + } + if (keyId < 1 || keyId > 255) { + throw new IllegalArgumentException("an entry's key id is " + keyId + "; it must be 1-255 " + + "(0 is reserved and never valid)"); + } + byte[] raw; + try { + raw = Base64.getDecoder().decode(trimmed.substring(separator + 1).trim()); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("the public key for key id " + keyId + + " is not valid standard base64"); + } + if (raw.length != ED25519_PUBLIC_KEY_LENGTH) { + throw new IllegalArgumentException("the public key for key id " + keyId + " decodes to " + + raw.length + " bytes; a raw Ed25519 public key is " + ED25519_PUBLIC_KEY_LENGTH + + " bytes (it must not be X.509 SubjectPublicKeyInfo-wrapped)"); + } + if (keys.containsKey(keyId)) { + throw new IllegalArgumentException("key id " + keyId + " is configured more than once"); + } + keys.put(keyId, ed25519PublicKey(keyId, raw)); + } + return Map.copyOf(keys); + } + + /** Probes initVerify here: KeyFactory accepts some off-curve values and only initVerify rejects them. */ + private static PublicKey ed25519PublicKey(int keyId, byte[] raw) { + byte[] encoded = new byte[ED25519_SPKI_PREFIX.length + raw.length]; + System.arraycopy(ED25519_SPKI_PREFIX, 0, encoded, 0, ED25519_SPKI_PREFIX.length); + System.arraycopy(raw, 0, encoded, ED25519_SPKI_PREFIX.length, raw.length); + try { + PublicKey publicKey = KeyFactory.getInstance("Ed25519") + .generatePublic(new X509EncodedKeySpec(encoded)); + Signature.getInstance("Ed25519").initVerify(publicKey); + return publicKey; + } catch (GeneralSecurityException e) { + throw new IllegalArgumentException("the public key for key id " + keyId + + " is not a usable Ed25519 public key"); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java new file mode 100644 index 0000000000..1c825a6d59 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +public record CommunityGrantReportRequest(String token, String report) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java new file mode 100644 index 0000000000..221528aa31 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommunityGrantReportResponse(String status) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java new file mode 100644 index 0000000000..a5a3c23ec8 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java @@ -0,0 +1,383 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FileUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.info.BuildProperties; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Fetches or accepts the instance checker, verifies its release signature and runs it against this instance's + * own database. + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantReportRunner { + + static final String REPORT_HEADER = "-----BEGIN TB INSTANCE CHECK-----"; + static final String REPORT_FOOTER = "-----END TB INSTANCE CHECK-----"; + + private static final int TERMINATION_GRACE_SEC = 5; + + private static final int MAX_STDERR_CAPTURE_BYTES = 8192; + + @Value("${spring.datasource.url}") + private String dbUrl; + + @Value("${spring.datasource.username}") + private String dbUserName; + + @Value("${spring.datasource.password}") + private String dbPassword; + + @Getter + @Value("${community-grant.checker-timeout-sec:600}") + private int checkerTimeoutSec; + + @Value("${community-grant.max-report-size-bytes:1048576}") + private int maxReportSizeBytes; + + @Value("${community-grant.max-checker-size-bytes:33554432}") + private long maxCheckerSizeBytes; + + @Autowired(required = false) + private BuildProperties buildProperties; + + private final CommunityGrantPortalClient portalClient; + private final CommunityGrantReleaseSignatureVerifier releaseSignatureVerifier; + + /** + * @return the portal's status after it accepted the report, or {@code null} if the portal answered with + * an empty body. + */ + public String runAndUpload(String token, CommunityGrantCheckerInput checkerInput) { + Path checker; + try { + checker = fetchChecker(token); + } catch (IOException e) { + throw new UncheckedIOException("Failed to obtain the instance checker", e); + } + return portalClient.uploadReport(token, runCheckerAndCleanUp(checker, checkerInput)); + } + + /** + * The checks {@link #runUploadedChecker} runs before anything is executed, callable on their own so a + * refusal can answer the upload request while the run itself happens later. + * + * @throws IllegalArgumentException on every refusal + */ + public void verifyUploadedChecker(byte[] checkerData, byte[] signatureData, String fileName) { + if (checkerData == null || checkerData.length == 0) { + throw new IllegalArgumentException("The uploaded file is empty"); + } + if (checkerData.length > maxCheckerSizeBytes) { + throw new IllegalArgumentException("The uploaded file is larger than the configured limit of " + + maxCheckerSizeBytes + " bytes"); + } + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + if (platform.namesAnotherPlatform(fileName)) { + throw new IllegalArgumentException("The uploaded file does not match this server's platform (" + + platform.os() + "/" + platform.arch() + ")"); + } + verifyOfflineCheckerSignature(checkerData, signatureData); + } + + /** Repeats {@link #verifyUploadedChecker} so nothing unverified reaches disk however this is called. */ + public String runUploadedChecker(byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput) { + verifyUploadedChecker(checkerData, signatureData, fileName); + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + log.info("Running an uploaded instance checker (uploaded file name {}, SHA-256 {})", + fileName, HexFormat.of().formatHex(sha256(checkerData))); + Path checker; + try { + checker = writeChecker(checkerData, platform.checkerFileName()); + } catch (IOException e) { + throw new UncheckedIOException("Failed to store the uploaded file", e); + } + return runCheckerAndCleanUp(checker, checkerInput); + } + + private String runCheckerAndCleanUp(Path checker, CommunityGrantCheckerInput checkerInput) { + try { + return runChecker(checker, checkerInput); + } finally { + deleteQuietly(checker); + } + } + + private void verifyOfflineCheckerSignature(byte[] checkerData, byte[] signatureData) { + try { + releaseSignatureVerifier.verify(checkerData, signatureData); + } catch (IllegalArgumentException e) { + log.warn("Refused to run an uploaded instance checker (uploaded file SHA-256 {}): {}", + HexFormat.of().formatHex(sha256(checkerData)), e.getMessage()); + throw e; + } + } + + private static byte[] sha256(byte[] data) { + try { + return MessageDigest.getInstance("SHA-256").digest(data); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is not available", e); + } + } + + Path fetchChecker(String token) throws IOException { + if (!releaseSignatureVerifier.hasTrustedKeys()) { + throw new IllegalStateException("No trusted release-signing key is configured in " + + CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY + + ", so the instance checker could not be verified and was not run"); + } + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + byte[] checkerData = portalClient.downloadChecker(token, platform.os(), platform.arch()); + verifyDownloadedCheckerSignature(token, platform, checkerData); + return writeChecker(checkerData, platform.checkerFileName()); + } + + private void verifyDownloadedCheckerSignature(String token, CommunityGrantPlatform platform, byte[] checkerData) { + byte[] signatureData; + try { + signatureData = portalClient.downloadCheckerSignature(token, platform.os(), platform.arch()); + } catch (HttpStatusCodeException e) { + throw new IllegalStateException("The portal served no release signature for the instance checker (" + + e.getStatusCode() + "), so it could not be verified and was not run", e); + } + try { + releaseSignatureVerifier.verify(checkerData, signatureData); + } catch (IllegalArgumentException e) { + // The verifier's messages name an uploaded checker. + throw new IllegalStateException("The instance checker downloaded from the portal does not match " + + "the release signature published for it, so it was not run", e); + } + } + + Path writeChecker(byte[] checkerData, String fileName) throws IOException { + boolean posix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + Path dir = posix + ? Files.createTempDirectory("tb-instance-check", + PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))) + : Files.createTempDirectory("tb-instance-check"); + try { + Path checker = dir.resolve(fileName); + Files.write(checker, checkerData); + if (posix) { + Files.setPosixFilePermissions(checker, PosixFilePermissions.fromString("r-x------")); + } else if (!checker.toFile().setExecutable(true, true)) { + throw new IOException("Failed to make the instance checker executable"); + } + return checker; + } catch (IOException | RuntimeException e) { + deleteRecursivelyQuietly(dir); + throw e; + } + } + + /** + * Secrets travel in the environment, never on the command line, where {@code ps} shows them to every + * local user. + */ + String runChecker(Path checker, CommunityGrantCheckerInput checkerInput) { + ProcessBuilder processBuilder = new ProcessBuilder(buildCommand(checker)); + processBuilder.directory(checker.getParent().toFile()); + prepareCheckerEnvironment(processBuilder.environment(), + CommunityGrantLibpqDsn.from(dbUrl, dbUserName, dbPassword), checkerInput); + + Process process; + try { + process = processBuilder.start(); + } catch (IOException e) { + throw new UncheckedIOException("Failed to start the instance check", e); + } + ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + AtomicBoolean overflow = new AtomicBoolean(false); + Thread stdoutDrain = drainCappedAsync(process.getInputStream(), stdout, overflow, process); + Thread stderrDrain = drainBoundedAsync(process.getErrorStream(), stderr); + try { + process.getOutputStream().close(); + } catch (IOException e) { + log.debug("Failed to close the instance check input stream", e); + } + boolean exited; + try { + exited = process.waitFor(checkerTimeoutSec, TimeUnit.SECONDS); + if (!exited) { + killTree(process); + awaitTermination(process); + } + stdoutDrain.join(TimeUnit.SECONDS.toMillis(TERMINATION_GRACE_SEC)); + stderrDrain.join(TimeUnit.SECONDS.toMillis(TERMINATION_GRACE_SEC)); + // Ahead of the timeout: the overflow branch kills the process too. + if (overflow.get()) { + String ending = "produced more output than the configured limit of " + maxReportSizeBytes + " bytes"; + logCheckerDiagnostics(stderr, ending); + throw new IllegalStateException("The instance check " + ending); + } + if (!exited) { + String ending = "did not finish within " + checkerTimeoutSec + " seconds"; + logCheckerDiagnostics(stderr, ending); + throw new IllegalStateException("The instance check " + ending); + } + if (stdoutDrain.isAlive()) { + // Reading a buffer the drain is still filling could upload a truncated report. stderr is not + // checked: a grandchild holding that pipe open would keep its drain alive indefinitely. + String ending = "output could not be read back in time"; + logCheckerDiagnostics(stderr, ending); + throw new IllegalStateException("The instance check " + ending); + } + } catch (InterruptedException e) { + killTree(process); + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while running the instance check", e); + } + int exitCode = process.exitValue(); + if (exitCode != 0) { + String ending = "failed with exit code " + exitCode; + logCheckerDiagnostics(stderr, ending); + throw new IllegalStateException("The instance check " + ending); + } + return readReport(stdout); + } + + /** Logged, never put in the exception: it is untrusted child output and the message is shown to the user. */ + private void logCheckerDiagnostics(ByteArrayOutputStream stderr, String ending) { + String diagnostics = stderr.toString(StandardCharsets.UTF_8).trim(); + if (!diagnostics.isEmpty()) { + log.warn("The instance check {}. It wrote to standard error: {}", ending, diagnostics); + } + } + + private List buildCommand(Path checker) { + List command = new ArrayList<>(List.of(checker.toAbsolutePath().toString())); + if (buildProperties != null) { + command.add("--tb-version"); + command.add(buildProperties.getVersion()); + } + return command; + } + + private static String readReport(ByteArrayOutputStream stdout) { + String report = stdout.toString(StandardCharsets.UTF_8).trim(); + if (!report.startsWith(REPORT_HEADER) || !report.endsWith(REPORT_FOOTER)) { + throw new IllegalStateException("The instance check produced unexpected output"); + } + return report; + } + + /** Descendants are collected first: once the parent dies they are reparented and no longer found. */ + private static void killTree(Process process) { + List descendants = process.descendants().toList(); + process.destroyForcibly(); + descendants.forEach(ProcessHandle::destroyForcibly); + } + + /** + * Drops the inherited {@code PG*} variables, which could change how the DSN's connection is made. + * Case-insensitive because {@link ProcessBuilder#environment()} is on Windows. + */ + static void prepareCheckerEnvironment(Map environment, String dsn, + CommunityGrantCheckerInput checkerInput) { + environment.keySet().removeIf(name -> name.toUpperCase(Locale.ROOT).startsWith("PG")); + environment.put("TB_IC_DSN", dsn); + environment.put("TB_IC_INPUT", checkerInput.json()); + } + + /** On Windows, deleting the binary of a still-exiting process fails. */ + private void awaitTermination(Process process) { + try { + if (!process.waitFor(TERMINATION_GRACE_SEC, TimeUnit.SECONDS)) { + log.debug("The instance check process did not terminate within {} seconds of being killed", + TERMINATION_GRACE_SEC); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private Thread drainCappedAsync(InputStream in, ByteArrayOutputStream sink, AtomicBoolean overflow, + Process process) { + return startDaemon("tb-instance-check-stdout", () -> { + try (InputStream stream = in) { + byte[] buffer = new byte[8192]; + int read; + while ((read = stream.read(buffer)) != -1) { + if (sink.size() + read > maxReportSizeBytes) { + overflow.set(true); + killTree(process); + awaitTermination(process); + return; + } + sink.write(buffer, 0, read); + } + } catch (IOException e) { + log.debug("Failed to read the instance check output", e); + } + }); + } + + /** Keeps reading past the cap so a chatty checker cannot deadlock on the pipe. */ + private Thread drainBoundedAsync(InputStream in, ByteArrayOutputStream sink) { + return startDaemon("tb-instance-check-stderr", () -> { + try (InputStream stream = in) { + byte[] buffer = new byte[8192]; + int read; + while ((read = stream.read(buffer)) != -1) { + int room = MAX_STDERR_CAPTURE_BYTES - sink.size(); + if (room > 0) { + sink.write(buffer, 0, Math.min(read, room)); + } + } + } catch (IOException e) { + log.debug("Failed to read the instance check diagnostics", e); + } + }); + } + + private static Thread startDaemon(String name, Runnable body) { + Thread thread = new Thread(body, name); + thread.setDaemon(true); + thread.start(); + return thread; + } + + private void deleteQuietly(Path checker) { + deleteRecursivelyQuietly(checker.getParent()); + } + + private void deleteRecursivelyQuietly(Path dir) { + if (!FileUtils.deleteQuietly(dir.toFile())) { + log.debug("Failed to clean up the instance check directory {}", dir); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java new file mode 100644 index 0000000000..5bb7a84d87 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.exception.ThingsboardException; + +import java.util.function.Consumer; + +public interface CommunityGrantService { + + CommunityGrantStateInfo getStateInfo(); + + /** Starts or restarts the flow; a restart supersedes the previous claim token. */ + CommunityGrantStateInfo start() throws ThingsboardException; + + /** + * Starts an uploaded instance checker in the background on this node. The signature must verify before + * this returns; a refusal throws here, and the run's own outcome reaches {@link #getStateInfo()}. + * + * @param completionListener told how the run ended, on the run's own thread: {@code null} on success + */ + CommunityGrantStateInfo runOfflineChecker(byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput, + Consumer completionListener) throws ThingsboardException; + + String getOfflineReport() throws ThingsboardException; + + /** Records that the operator handed the report to the portal by hand; the flow keeps waiting. */ + CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException; + + /** Asks the portal to notify this cluster's registered owner. Throttled by a cooldown. */ + void requestAccess() throws ThingsboardException; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java b/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java new file mode 100644 index 0000000000..df4f44ac23 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java @@ -0,0 +1,527 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.annotation.PreDestroy; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.thingsboard.common.util.ThingsBoardThreadFactory; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRunStatus; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.security.SecureRandom; +import java.util.Base64; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; + +@Service +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class DefaultCommunityGrantService implements CommunityGrantService { + + static final int CLAIM_TOKEN_BYTES = 32; + + static final long REQUEST_ACCESS_COOLDOWN_MS = TimeUnit.MINUTES.toMillis(5); + + static final String NOT_AVAILABLE_MESSAGE = "This action is not available on this deployment."; + static final String NO_CLUSTER_ID_MESSAGE = + "This deployment is not fully installed yet. Restart the platform and try again."; + private static final String START_FAILED_MESSAGE = + "Failed to start. Please check that the database is reachable and try again."; + private static final String ALREADY_FINISHED_MESSAGE = "This deployment has already completed this process."; + static final String UNDER_REVIEW_MESSAGE = + "This deployment's registration is with a reviewer. There is nothing to send again while it is."; + static final String REPORT_HANDED_OVER_MESSAGE = + "This deployment's check result has already been handed over. Starting again would abandon it."; + static final String NOTHING_TO_HAND_OVER_MESSAGE = + "This deployment is not waiting for a check result to be handed over."; + static final String HANDOFF_FAILED_MESSAGE = + "Failed to record the hand-over. Please check that the database is reachable and try again."; + private static final String PORTAL_MISCONFIGURED_MESSAGE = + "This deployment's connection to the license portal is misconfigured. Contact your administrator."; + static final String NO_OFFLINE_REPORT_MESSAGE = "No result is available. Run the check first."; + static final String OFFLINE_RUN_IN_PROGRESS_MESSAGE = + "A check is already running on this deployment. Wait for it to finish and try again."; + static final String OFFLINE_STATE_NOT_PERSISTED_MESSAGE = + "The check completed, but this deployment could not record it. The result is still available for download."; + static final String OFFLINE_RUN_START_FAILED_MESSAGE = + "Failed to start the check. Please check that the database is reachable and try again."; + static final String OFFLINE_RUN_NOT_SCHEDULED_MESSAGE = + "Failed to start the check: this server is shutting down. Please try again."; + static final String OFFLINE_RUN_INTERRUPTED_MESSAGE = + "The check was interrupted before it finished. Please run it again."; + static final String OFFLINE_RESULT_NOT_RECORDED_MESSAGE = + "The check completed, but this deployment could not record its result. Please check that the database " + + "is reachable and run the check again."; + static final String OFFLINE_RUN_SUPERSEDED_MESSAGE = + "The check finished after a newer check or enrollment replaced it, so its result was discarded."; + private static final String RUN_FAILED_PREFIX = "Failed to run the check. "; + + /** Past the checker's own timeout: room for writing the binary and recording the result. */ + static final long OFFLINE_RUN_GRACE_MS = TimeUnit.MINUTES.toMillis(2); + static final String NOT_ALREADY_REGISTERED_MESSAGE = + "This action is only available once this deployment is confirmed as already registered under another account."; + static final String REQUEST_ACCESS_RATE_LIMITED_MESSAGE = + "Please wait a few minutes before requesting access again."; + static final String REQUEST_ACCESS_STORE_FAILED_MESSAGE = + "Failed to process the request. Please check that the database is reachable and try again."; + static final String REQUEST_ACCESS_FAILED_MESSAGE = + "Failed to reach the license portal. Please try again later."; + + @Value("${community-grant.enabled:true}") + private boolean enabled; + + private final TbClusterStore tbClusterStore; + private final CommunityGrantFlowStateStore flowStateStore; + private final CommunityGrantPortalClient portalClient; + private final CommunityGrantPoller poller; + private final CommunityGrantReportRunner reportRunner; + private final CommunityGrantOfflineReportStore offlineReportStore; + + private final SecureRandom secureRandom = new SecureRandom(); + private final ReentrantLock startLock = new ReentrantLock(); + + /** A permit, not a lock: the request thread takes it and the executor thread gives it back. */ + private final Semaphore offlineRunPermit = new Semaphore(1); + + private ExecutorService offlineRunExecutor = + Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName("tb-community-grant-offline-run")); + + /** A failure to read the report drops it from the answer rather than failing the whole read. */ + @Override + public CommunityGrantStateInfo getStateInfo() { + CommunityGrantFlowState flowState = flowStateStore.get(); + String portalUrl = portalClient.getPortalUrl(); + CommunityGrantOfflineRun run = flowState.getOfflineRun(); + boolean runInProgress = isOfflineRunInProgress(run, System.currentTimeMillis(), offlineRunStaleAfterMs()); + String runError = offlineRunError(run, runInProgress); + String report = null; + if (CommunityGrantStateInfo.carriesOfflineReport(flowState)) { + try { + report = offlineReportStore.get().orElse(null); + } catch (Exception e) { + log.warn("Failed to read the stored community grant offline report", e); + } + } + return CommunityGrantStateInfo.of(flowState, portalUrl, report, runInProgress, runError); + } + + @Override + public CommunityGrantStateInfo start() throws ThingsboardException { + if (!enabled) { + throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND); + } + startLock.lock(); + try { + CommunityGrantFlowState currentState = flowStateStore.get(); + CommunityGrantState current = currentState.getState(); + if (current.isTerminal()) { + throw new ThingsboardException(ALREADY_FINISHED_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + if (current == CommunityGrantState.UNDER_REVIEW) { + // Re-minting would replace the token the reviewer's decision is delivered against. + throw new ThingsboardException(UNDER_REVIEW_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + if (current == CommunityGrantState.REPORT_HANDED_OVER) { + // Re-minting would abandon the submission and clear the report a failed paste comes back for. + throw new ThingsboardException(REPORT_HANDED_OVER_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + UUID clusterId = tbClusterStore.getClusterId() + .orElseThrow(() -> new ThingsboardException(NO_CLUSTER_ID_MESSAGE, ThingsboardErrorCode.GENERAL)); + + // Probed even when OFFLINE: the only way back to ONLINE. + CommunityGrantMode mode; + try { + mode = portalClient.isPortalReachable() ? CommunityGrantMode.ONLINE : CommunityGrantMode.OFFLINE; + } catch (IllegalArgumentException e) { + // Only a malformed base URL; unreachability is a plain false. + log.warn("Failed to reach the license portal: the configured base URL is not valid", e); + throw new ThingsboardException(PORTAL_MISCONFIGURED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + + // Only from NOT_STARTED: on a flow this deployment began, its own pending registration answers + // true, and the terminal ALREADY_REGISTERED would dead-end the operator's own enrollment. + if (mode == CommunityGrantMode.ONLINE && current == CommunityGrantState.NOT_STARTED + && isAlreadyRegistered(clusterId)) { + return enrollAsAlreadyRegistered(); + } + + String token = mintToken(); + // Built before the token is stored, so a bad base URL leaves nothing to retire. + String signUpUrl; + try { + signUpUrl = portalClient.buildSignUpUrl(clusterId, token, mode); + } catch (Exception e) { + log.warn("Failed to build the sign-up URL: the configured base URL is not valid", e); + throw new ThingsboardException(PORTAL_MISCONFIGURED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + try { + tbClusterStore.saveLicenseClaimToken(token); + } catch (Exception e) { + log.warn("Failed to store the community grant claim token", e); + throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + + CommunityGrantFlowState updated; + try { + long now = System.currentTimeMillis(); + updated = flowStateStore.update(state -> { + state.setMode(mode); + state.setState(CommunityGrantState.AWAITING_SIGNUP); + state.setSignUpUrl(signUpUrl); + state.setStartedAt(now); + state.setLastPolledAt(null); + state.setParkReason(null); + state.setLastOfflineCheckAt(null); + state.setOfflineRun(null); + return state; + }); + } catch (Exception e) { + tbClusterStore.clearLicenseClaimToken(token); + log.warn("Failed to persist the community grant flow state after minting a token", e); + throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + // After the write, so a failed start keeps the previous report. + offlineReportStore.clear(); + // After the write: the loop reads the persisted mode. + poller.arm(); + return CommunityGrantStateInfo.of(updated, portalClient.getPortalUrl()); + } finally { + startLock.unlock(); + } + } + + /** + * Refusals answer the upload request; the run itself goes to {@link #offlineRunExecutor} on this node. + * One run at a time: per node by {@link #offlineRunPermit}, cluster-wide by the run record on the flow + * state. Two nodes starting in the same instant can both pass; the run written last keeps its result. + */ + @Override + public CommunityGrantStateInfo runOfflineChecker(byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput, + Consumer completionListener) + throws ThingsboardException { + if (!enabled) { + throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND); + } + if (!offlineRunPermit.tryAcquire()) { + throw new ThingsboardException(OFFLINE_RUN_IN_PROGRESS_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS); + } + boolean handedToExecutor = false; + try { + try { + reportRunner.verifyUploadedChecker(checkerData, signatureData, fileName); + } catch (IllegalArgumentException e) { + throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } catch (Exception e) { + log.warn("Failed to verify the uploaded instance check", e); + throw new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL); + } + UUID runId = UUID.randomUUID(); + long startedAt = System.currentTimeMillis(); + CommunityGrantStateInfo answer = CommunityGrantStateInfo.of(recordOfflineRunStarted(runId, startedAt), + portalClient.getPortalUrl(), null, true, null); + try { + offlineRunExecutor.execute(() -> + completeOfflineRun(runId, checkerData, signatureData, fileName, checkerInput, + completionListener)); + } catch (RejectedExecutionException e) { + log.warn("Failed to schedule the uploaded instance check", e); + recordOfflineRunFailed(runId, OFFLINE_RUN_NOT_SCHEDULED_MESSAGE); + throw new ThingsboardException(OFFLINE_RUN_NOT_SCHEDULED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + handedToExecutor = true; + return answer; + } finally { + if (!handedToExecutor) { + offlineRunPermit.release(); + } + } + } + + private CommunityGrantFlowState recordOfflineRunStarted(UUID runId, long startedAt) throws ThingsboardException { + long staleAfterMs = offlineRunStaleAfterMs(); + try { + return flowStateStore.update(state -> { + if (isOfflineRunInProgress(state.getOfflineRun(), startedAt, staleAfterMs)) { + throw new UpdateRefusal(OFFLINE_RUN_IN_PROGRESS_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS); + } + state.setOfflineRun(CommunityGrantOfflineRun.running(runId, startedAt)); + return state; + }); + } catch (UpdateRefusal e) { + throw new ThingsboardException(e.getMessage(), e.errorCode); + } catch (Exception e) { + // No cause: the audit log stores the full stack trace. + log.warn("Failed to record the start of a community grant offline check", e); + throw new ThingsboardException(OFFLINE_RUN_START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + } + + private void completeOfflineRun(UUID runId, byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput, Consumer completionListener) { + try { + ThingsboardException failure = null; + try { + runAndRecordOfflineCheck(runId, checkerData, signatureData, fileName, checkerInput); + } catch (ThingsboardException e) { + failure = e; + } catch (Exception e) { + log.warn("Failed to complete the uploaded instance check", e); + failure = new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL); + } + if (failure != null) { + recordOfflineRunFailed(runId, failure.getMessage()); + } + try { + completionListener.accept(failure); + } catch (Exception e) { + log.warn("Failed to report the end of a community grant offline check", e); + } + } finally { + offlineRunPermit.release(); + } + } + + private void runAndRecordOfflineCheck(UUID runId, byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput) throws ThingsboardException { + String report; + try { + report = reportRunner.runUploadedChecker(checkerData, signatureData, fileName, checkerInput); + } catch (IllegalArgumentException e) { + throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } catch (Exception e) { + log.warn("Failed to run the uploaded instance check", e); + throw new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL); + } + CommunityGrantOfflineRun current; + try { + current = flowStateStore.get().getOfflineRun(); + } catch (Exception e) { + log.warn("Failed to read the community grant flow state after an offline check", e); + throw new ThingsboardException(OFFLINE_RESULT_NOT_RECORDED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + if (current == null || !current.isOwnedBy(runId)) { + throw supersededOfflineRun(); + } + // Before and apart from the state write: OFFLINE_STATE_NOT_PERSISTED_MESSAGE promises the download. + offlineReportStore.put(report); + long lastOfflineCheckAt = System.currentTimeMillis(); + AtomicBoolean owned = new AtomicBoolean(); + try { + flowStateStore.update(state -> { + owned.set(state.getOfflineRun() != null && state.getOfflineRun().isOwnedBy(runId)); + if (!owned.get()) { + return state; + } + if (state.getMode() != CommunityGrantMode.ONLINE) { + state.setMode(CommunityGrantMode.OFFLINE); + } + if (!state.getState().isAwaitingOrPastDecision()) { + state.setState(CommunityGrantState.VALIDATING); + state.setParkReason(null); + } + state.setLastOfflineCheckAt(lastOfflineCheckAt); + state.setOfflineRun(null); + return state; + }); + } catch (Exception e) { + log.warn("Failed to persist the community grant flow state after a successful offline check", e); + throw new ThingsboardException(OFFLINE_STATE_NOT_PERSISTED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + if (!owned.get()) { + // The report stays: deleting it could delete a newer run's. + throw supersededOfflineRun(); + } + } + + private static ThingsboardException supersededOfflineRun() { + return new ThingsboardException(OFFLINE_RUN_SUPERSEDED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + + /** Best effort: a run left {@code RUNNING} is reported as interrupted once it goes stale. */ + private void recordOfflineRunFailed(UUID runId, String error) { + try { + flowStateStore.update(state -> { + CommunityGrantOfflineRun run = state.getOfflineRun(); + if (run != null && run.isOwnedBy(runId)) { + run.setStatus(CommunityGrantOfflineRunStatus.FAILED); + run.setError(error); + } + return state; + }); + } catch (Exception e) { + log.warn("Failed to record a failed community grant offline check", e); + } + } + + private long offlineRunStaleAfterMs() { + return TimeUnit.SECONDS.toMillis(reportRunner.getCheckerTimeoutSec()) + OFFLINE_RUN_GRACE_MS; + } + + private static boolean isOfflineRunInProgress(CommunityGrantOfflineRun run, long now, long staleAfterMs) { + return run != null && run.getStatus() == CommunityGrantOfflineRunStatus.RUNNING + && run.getStartedAt() != null && now - run.getStartedAt() <= staleAfterMs; + } + + private static String offlineRunError(CommunityGrantOfflineRun run, boolean inProgress) { + if (run == null || inProgress) { + return null; + } + return run.getStatus() == CommunityGrantOfflineRunStatus.FAILED + ? run.getError() + : OFFLINE_RUN_INTERRUPTED_MESSAGE; + } + + @PreDestroy + public void stop() { + offlineRunExecutor.shutdownNow(); + } + + @Override + public String getOfflineReport() throws ThingsboardException { + return offlineReportStore.get() + .orElseThrow(() -> new ThingsboardException(NO_OFFLINE_REPORT_MESSAGE, + ThingsboardErrorCode.ITEM_NOT_FOUND)); + } + + /** Under {@link #startLock}, so a concurrent start() is not relabelled as handed over. */ + @Override + public CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException { + if (!enabled) { + throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND); + } + startLock.lock(); + try { + CommunityGrantState current = flowStateStore.get().getState(); + if (current == CommunityGrantState.REPORT_HANDED_OVER) { + return getStateInfo(); + } + if (current != CommunityGrantState.VALIDATING) { + throw new ThingsboardException(NOTHING_TO_HAND_OVER_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + try { + flowStateStore.update(state -> { + // Re-tested: a poll may have retired the flow since the read above. + if (state.getState() == CommunityGrantState.VALIDATING) { + state.setState(CommunityGrantState.REPORT_HANDED_OVER); + } + return state; + }); + } catch (Exception e) { + log.warn("Failed to persist the community grant offline hand-off", e); + throw new ThingsboardException(HANDOFF_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + return getStateInfo(); + } finally { + startLock.unlock(); + } + } + + @Override + public void requestAccess() throws ThingsboardException { + if (!enabled) { + throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND); + } + UUID clusterId; + long now = System.currentTimeMillis(); + try { + clusterId = tbClusterStore.getClusterId().orElse(null); + // The cooldown lives on the shared flow state; only the lock is per node. + flowStateStore.update(state -> { + // Not WRONG_INSTALLATION: there is no registration on this cluster id to notify. + if (state.getState() != CommunityGrantState.ALREADY_REGISTERED) { + throw new UpdateRefusal(NOT_ALREADY_REGISTERED_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + Long lastRequestAccessAt = state.getLastRequestAccessAt(); + if (lastRequestAccessAt != null && now - lastRequestAccessAt < REQUEST_ACCESS_COOLDOWN_MS) { + throw new UpdateRefusal(REQUEST_ACCESS_RATE_LIMITED_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS); + } + if (clusterId == null) { + throw new UpdateRefusal(NO_CLUSTER_ID_MESSAGE, ThingsboardErrorCode.GENERAL); + } + // Recorded whatever the portal call below does. + state.setLastRequestAccessAt(now); + return state; + }); + } catch (UpdateRefusal e) { + throw new ThingsboardException(e.getMessage(), e.errorCode); + } catch (Exception e) { + log.warn("Failed to read or persist the community grant request-access state", e); + throw new ThingsboardException(REQUEST_ACCESS_STORE_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + try { + portalClient.requestAccess(clusterId); + } catch (Exception e) { + log.warn("Failed to ask the license portal to notify the registered owner", e); + throw new ThingsboardException(REQUEST_ACCESS_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + } + + /** Unchecked so it can leave an updater; translated back to {@link ThingsboardException} by the caller. */ + private static final class UpdateRefusal extends RuntimeException { + private final ThingsboardErrorCode errorCode; + + private UpdateRefusal(String message, ThingsboardErrorCode errorCode) { + super(message); + this.errorCode = errorCode; + } + } + + /** The token is retired before the terminal state is written, since nothing retires it afterwards. */ + private CommunityGrantStateInfo enrollAsAlreadyRegistered() throws ThingsboardException { + poller.disarm(); + tbClusterStore.forceClearLicenseClaimToken(); + try { + CommunityGrantFlowState updated = flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.ONLINE); + state.setState(CommunityGrantState.ALREADY_REGISTERED); + state.clearClaim(); + state.setLastPolledAt(null); + state.setParkReason(null); + state.setOfflineRun(null); + return state; + }); + offlineReportStore.clear(); + return CommunityGrantStateInfo.of(updated, portalClient.getPortalUrl()); + } catch (Exception e) { + log.warn("Failed to persist the community grant flow state for an already-registered deployment", e); + throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + } + + /** Best effort: a failure here reads as not registered, and the poll reaches the same answer later. */ + private boolean isAlreadyRegistered(UUID clusterId) { + try { + return portalClient.isAlreadyRegistered(clusterId); + } catch (Exception e) { + log.debug("Failed to read the cluster status from the portal", e); + return false; + } + } + + private String mintToken() { + byte[] tokenBytes = new byte[CLAIM_TOKEN_BYTES]; + secureRandom.nextBytes(tokenBytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java index 1564ad8e7b..87f9f4ec1d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java @@ -47,6 +47,7 @@ import org.thingsboard.server.dao.widget.WidgetsBundleService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.rpc.EdgeEventStorageSettings; import org.thingsboard.server.service.edge.rpc.EdgeRpcService; +import org.thingsboard.server.service.rpc.TbRpcService; import org.thingsboard.server.service.edge.rpc.processor.EdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.ai.AiModelProcessor; import org.thingsboard.server.service.edge.rpc.processor.apikey.ApiKeyProcessor; @@ -130,6 +131,9 @@ public class EdgeContextComponent { @Autowired private DeviceService deviceService; + @Autowired + private TbRpcService tbRpcService; + @Autowired private DomainService domainService; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java index 129ff896f2..b2b8f37c0a 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java @@ -326,20 +326,23 @@ public class EdgeMsgConstructorUtils { responseBuilder.setResponse(body.get("response").asText()); } builder.setResponseMsg(responseBuilder.build()); - } else { + } else if (body.has("method")) { RpcRequestMsg.Builder requestBuilder = RpcRequestMsg.newBuilder(); requestBuilder.setMethod(body.get("method").asText()); requestBuilder.setParams(body.get("params").asText()); builder.setRequestMsg(requestBuilder.build()); } + // else: status-only message (rpcStatus set in constructDeviceRpcMsg) carries neither request nor response body return builder.build(); } private static DeviceRpcCallMsg.Builder constructDeviceRpcMsg(UUID deviceId, JsonNode body) { DeviceRpcCallMsg.Builder builder = DeviceRpcCallMsg.newBuilder() .setDeviceIdMSB(deviceId.getMostSignificantBits()) - .setDeviceIdLSB(deviceId.getLeastSignificantBits()) - .setRequestId(body.get("requestId").asInt()); + .setDeviceIdLSB(deviceId.getLeastSignificantBits()); + if (body.get("requestId") != null) { + builder.setRequestId(body.get("requestId").asInt()); + } if (body.get("oneway") != null) { builder.setOneway(body.get("oneway").asBoolean()); } @@ -366,6 +369,9 @@ public class EdgeMsgConstructorUtils { if (body.get("sessionId") != null) { builder.setSessionId(body.get("sessionId").asText()); } + if (body.get("rpcStatus") != null) { + builder.setRpcStatus(body.get("rpcStatus").asText()); + } return builder; } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index b14fa32a38..ba80a4cf2b 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -74,9 +74,11 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; +import java.util.function.Predicate; import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME; @@ -306,13 +308,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Override public void deleteEdge(TenantId tenantId, EdgeId edgeId) { - EdgeGrpcSession session = sessions.get(edgeId); - if (session != null && session.isConnected()) { + EdgeGrpcSession toRemove = detachSession(edgeId); + if (toRemove != null) { log.info("[{}] Closing and removing session for edge [{}]", tenantId, edgeId); - destroySession(session); - session.cleanUp(); - sessions.remove(edgeId); - sessionsById.remove(session.getSessionId()); + sessionsById.remove(toRemove.getSessionId()); final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); newEventLock.lock(); try { @@ -320,7 +319,8 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } - cancelScheduleEdgeEventsCheck(edgeId); + destroySession(toRemove); + toRemove.cleanUp(); } cancelPendingDisconnectNotification(edgeId); } @@ -362,16 +362,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i Edge edge = edgeGrpcSession.getEdge(); TenantId tenantId = edge.getTenantId(); log.info("[{}][{}] edge [{}] connected successfully.", tenantId, edgeGrpcSession.getSessionId(), edgeId); - if (sessions.containsKey(edgeId)) { - EdgeGrpcSession existing = sessions.get(edgeId); - if (existing != null) { - log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), existing.getSessionId(), edgeId); - destroySession(existing); - sessionsById.remove(existing.getSessionId()); - } - } - sessions.put(edgeId, edgeGrpcSession); + EdgeGrpcSession replaced = attachSession(edgeId, edgeGrpcSession); sessionsById.put(edgeGrpcSession.getSessionId(), edgeGrpcSession); + if (replaced != null) { + log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), replaced.getSessionId(), edgeId); + sessionsById.remove(replaced.getSessionId()); + } final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); newEventLock.lock(); try { @@ -392,9 +388,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i // Connect notifies immediately; only the disconnect notification is debounced (see scheduleDisconnectNotification). pushStateEventToRuleEngine(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); notifyEdgeConnectivity(edge, true); - cancelScheduleEdgeEventsCheck(edgeId); edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); + if (replaced != null) { + destroySession(replaced); + } } private void startSyncProcess(TenantId tenantId, EdgeId edgeId, UUID requestId, String requestServiceId) { @@ -456,54 +454,73 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = session.getEdge().getId(); TenantId tenantId = session.getEdge().getTenantId(); - cancelScheduleEdgeEventsCheck(edgeId); + // arm the next check only while this exact session is still the current one, atomically with + // cancelling the previous one, so that a concurrent connect/disconnect can neither lose the + // re-arm nor cancel a check that belongs to a session other than the one it is tearing down + sessions.compute(edgeId, (id, current) -> { + if (current != session) { + log.debug("[{}] Session is not current anymore and edge event check schedule must not be started [{}]", + tenantId, edgeId.getId()); + return current; + } + cancelScheduleEdgeEventsCheck(edgeId); + sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule( + () -> processEvents(session, edgeId, tenantId), + ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS)); + log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId()); + return current; + }); + } - if (sessions.containsKey(edgeId)) { - ScheduledFuture edgeEventCheckTask = edgeEventProcessingExecutorService.schedule(() -> { - try { - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { - log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, false); - session.processHighPriorityEvents(); - processEdgeEventMigrationIfNeeded(session, edgeId); - if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { - Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { - @Override - public void onSuccess(Boolean newEventsAdded) { - if (Boolean.TRUE.equals(newEventsAdded)) { - log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, true); - } - scheduleEdgeEventsCheck(session); + private void processEvents(EdgeGrpcSession session, EdgeId edgeId, TenantId tenantId) { + try { + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); + try { + if (sessions.get(edgeId) != session) { + log.debug("[{}] Session is not current anymore, edge event check must not run for edge [{}]", + tenantId, edgeId.getId()); + return; + } + if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { + log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, false); + session.processHighPriorityEvents(); + processEdgeEventMigrationIfNeeded(session, edgeId); + if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { + Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { + @Override + public void onSuccess(Boolean newEventsAdded) { + if (Boolean.TRUE.equals(newEventsAdded)) { + log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); + try { + sessionNewEvents.put(edgeId, true); + } finally { + newEventLock.unlock(); } + } + scheduleEdgeEventsCheck(session); + } - @Override - public void onFailure(Throwable t) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); - scheduleEdgeEventsCheck(session); - } - }, ctx.getGrpcCallbackExecutorService()); - } else { + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); scheduleEdgeEventsCheck(session); } - } else { - scheduleEdgeEventsCheck(session); - } - } finally { - newEventLock.unlock(); + }, ctx.getGrpcCallbackExecutorService()); + } else { + scheduleEdgeEventsCheck(session); } - } catch (Exception e) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } else { + scheduleEdgeEventsCheck(session); } - }, ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS); - sessionEdgeEventChecks.put(edgeId, edgeEventCheckTask); - log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId()); - } else { - log.debug("[{}] Session was removed and edge event check schedule must not be started [{}]", - tenantId, edgeId.getId()); + } finally { + newEventLock.unlock(); + } + } catch (Exception e) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); } } @@ -531,58 +548,26 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void onEdgeDisconnect(Edge edge, UUID sessionId) { EdgeId edgeId = edge.getId(); log.info("[{}][{}] edge disconnected!", edgeId, sessionId); - EdgeGrpcSession current = sessions.get(edgeId); - // Claim-once removal: get() and remove() are not atomic, so a session that was replaced between the - // two would otherwise be dropped from the map, torn down and marked inactive by this stale callback - // even though it is the live one. Losing the race means this callback owns nothing - fall through to - // the stale-session branch below. - if (current != null && current.getSessionId().equals(sessionId) && sessions.remove(edgeId, current)) { - EdgeGrpcSession toRemove = current; - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - sessionNewEvents.remove(edgeId); - } finally { - newEventLock.unlock(); - } - destroySession(toRemove); + EdgeGrpcSession toRemove = detachSession(edgeId, current -> current.getSessionId().equals(sessionId)); + if (toRemove != null) { + // sessionNewEvents is deliberately left as is: clearing it here could wipe the flag a + // reconnecting session has just set, and updateSessionEventsFlag only lifts FALSE, not a + // missing entry, which would leave the check loop idle forever. deleteEdge still clears it sessionsById.remove(sessionId); TenantId tenantId = toRemove.getEdge().getTenantId(); - // The edge may already have been claimed by a newer session - on this node (a replacement that - // landed while this stale callback was tearing its own session down) or on another live node. - // Either way the edge is connected, so none of the disconnect side effects apply: - // - clearing the flag makes saveEdgeEvent drop assignment events until a full sync; - // - a newer lastDisconnectTime would contradict the live session's lastConnectTime; - // - the DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE in the metadata, - // so a rule chain wiring Disconnect Event -> Save Attributes writes active=false straight - // back, re-creating the dropped-event behaviour through the rule engine; - // - the user-facing 'edge disconnected' notification would contradict a live session. - // Ownership being unknown (no cache entry) still counts as disconnected, so a genuinely offline - // edge is always marked inactive. - boolean replacedOnThisNode = sessions.containsKey(edgeId); - if (!replacedOnThisNode && !isOwnedByAnotherNode(edgeId)) { + // A newer session may already own the edge, on this node or on another live one. In that case the edge + // is connected, so skip all disconnect side effects: active=false, lastDisconnectTime, DISCONNECT_EVENT + // (its payload can write active=false back via Save Attributes) and the disconnect notification. + // Unknown ownership (no cache entry) still counts as disconnected. The local map is read last, after + // the cache round-trip, to see a same-node replacement as late as possible. + if (!isOwnedByAnotherNode(edgeId) && !sessions.containsKey(edgeId)) { save(tenantId, edgeId, ACTIVITY_STATE, false); long lastDisconnectTs = System.currentTimeMillis(); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); - pushStateEventToRuleEngine(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); - // Inside the guard, not after it. fireDelayedDisconnectNotification does re-verify liveness, - // but only on the debounced path: with EDGES_DISCONNECT_NOTIFICATION_DELAY_MS=0 - // scheduleDisconnectNotification notifies straight away and skips that re-verify, so a live - // replacement would still raise a false 'edge disconnected'. The guard above has already - // answered the same question, so use it. On the debounced path this only saves a task that - // would have re-verified and dropped the notification anyway. + pushStateEventToRuleEngine(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); scheduleDisconnectNotification(edge); } - // sessionEdgeEventChecks is keyed by edgeId, not by session, so a replacement that landed on this - // node while this stale callback was running has already scheduled its check under the same key. - // Cancelling it here would leave the live session with no check loop - the loop only reschedules - // itself from inside the task, so a cancelled task never runs again - and downlinks, the migration - // check and high-priority events would stall silently until the edge reconnects. When the edge is - // owned by another node there is nothing live to protect: the check is node-local and belongs to - // the session we just tore down. - if (!replacedOnThisNode) { - cancelScheduleEdgeEventsCheck(edgeId); - } + destroySession(toRemove); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); EdgeGrpcSession stale = sessionsById.remove(sessionId); @@ -605,6 +590,53 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } } + /** + * Registers the session as the current one for the edge and cancels the edge event check armed by + * the session it replaces, as a single atomic step. Returns the replaced session, or null if there + * was none - the caller is responsible for destroying it outside of this critical section. + *

+ * Only cheap non-blocking work may run inside the remapping function: it holds the bin lock of + * {@link #sessions} for this edge, so everything slow or lock-taking - {@link #destroySession}, + * {@code EdgeGrpcSession.cleanUp()}, {@code save(...)}, {@code pushRuleEngineMessage(...)} or + * acquiring the per-edge new events lock - has to be done by the caller once compute has returned. + */ + private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) { + AtomicReference replaced = new AtomicReference<>(); + sessions.compute(edgeId, (id, current) -> { + replaced.set(current); + cancelScheduleEdgeEventsCheck(edgeId); + return session; + }); + return replaced.get(); + } + + private EdgeGrpcSession detachSession(EdgeId edgeId) { + return detachSession(edgeId, s -> true); + } + + /** + * Detaches the edge's registered session and cancels its edge event check as a single atomic step, + * but only if that session satisfies shouldDetach. Returns the detached session, or null if the + * predicate rejected it - most importantly when another session has taken the edge over in the + * meantime, in which case nothing is touched and a reconnect racing with a teardown cannot lose + * the check it has just armed. The caller destroys the returned session outside the atomic step. + *

+ * The remapping function is subject to the same "cheap non-blocking work only" rule as + * {@link #attachSession(EdgeId, EdgeGrpcSession)}. + */ + private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) { + AtomicReference detached = new AtomicReference<>(); + sessions.compute(edgeId, (id, current) -> { + if (current == null || !shouldDetach.test(current)) { + return current; + } + detached.set(current); + cancelScheduleEdgeEventsCheck(edgeId); + return null; + }); + return detached.get(); + } + // Only evict if the cache still points to this node. If the edge already reconnected to a different // TB-Core node within the keep-alive window, that node has overwritten the entry - evicting it here // would wipe the live owner and make fireDelayedDisconnectNotification raise a false 'disconnected'. @@ -627,11 +659,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i // - entry naming a node that is no longer in the cluster: the edge sessions cache has no TTL by default // (CACHE_SPECS_EDGE_SESSIONS_TTL=0) and is only ever evicted by the owning node, so a node that died // without evicting would otherwise keep the edge marked active forever, with no reconciler to correct it. - // Note this covers a node that is gone, not one that restarted under the same service id - that claim - // still resolves as live, leaving the edge marked active until something reconnects. That errs towards - // queueing edge events rather than dropping them, which is the safe direction. - // This narrows the race rather than closing it: the attribute is plain last-writer-wins, and two nodes can - // still issue their async writes in an order this read cannot see. private boolean isOwnedByAnotherNode(EdgeId edgeId) { TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId); if (wrapper == null) { @@ -649,6 +676,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return edgeIdServiceIdCache.get(edgeId) != null; } + /** + * Stops the session's edge event consumer and shuts down its executor, collecting the session for a + * later retry if that fails. This can block for seconds - {@code KafkaEdgeGrpcSession.destroy()} + * gives the consumer executor up to 5s to terminate - so it must never be called from inside a + * {@link #sessions} remapping function. + */ private void destroySession(EdgeGrpcSession session) { try (session) { if (!session.destroy()) { @@ -863,10 +896,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - // Compare-and-remove: destroy() above is not instantaneous, so the edge may have reconnected and - // put a live session under this id in the meantime. Removing it unconditionally would leave a - // connected edge with no entry in 'sessions', silently no-opping every downlink lookup. - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); + // detach by identity: the edge may have reconnected since the zombie scan, and that newer + // session must neither be evicted nor have its edge event check cancelled by the cleanup of + // the one it replaced + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> detachSession(s.getEdge().getId(), current -> current == s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java index b0db4d7f2d..75e0c22a73 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java @@ -9,6 +9,7 @@ import com.google.common.util.concurrent.SettableFuture; import lombok.extern.slf4j.Slf4j; import org.springframework.data.util.Pair; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.JsonNode; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; @@ -24,7 +25,10 @@ import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.msg.TbMsgType; +import org.thingsboard.server.common.data.id.RpcId; +import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcError; +import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgDataType; @@ -116,7 +120,10 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr @Override public ListenableFuture processDeviceRpcCallFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { log.trace("[{}] processDeviceRpcCallFromEdge [{}]", tenantId, deviceRpcCallMsg); - if (deviceRpcCallMsg.hasResponseMsg()) { + if (deviceRpcCallMsg.hasRpcStatus()) { + // RPC v2 (persistent) status update from the edge - update the cloud Rpc entity (same id == request UUID). + return processDeviceRpcStatusFromEdge(tenantId, edge, deviceRpcCallMsg); + } else if (deviceRpcCallMsg.hasResponseMsg()) { return processDeviceRpcResponseFromEdge(tenantId, deviceRpcCallMsg); } else if (deviceRpcCallMsg.hasRequestMsg()) { return processDeviceRpcRequestFromEdge(tenantId, edge, deviceRpcCallMsg); @@ -124,6 +131,46 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr return Futures.immediateFuture(null); } + private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { + RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); + Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId); + if (existingRpc == null) { + // RPC is unknown to the cloud (edge-originated or already deleted) - nothing to sync + log.debug("[{}][{}] Ignoring RPC status [{}] from edge - RPC not found", tenantId, rpcId, deviceRpcCallMsg.getRpcStatus()); + return Futures.immediateFuture(null); + } + if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) { + // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy. + // Mark the edge-sync context so TbRpcService.deleteRpc does not echo the delete back to edges. + try { + edgeSynchronizationManager.getEdgeId().set(edge.getId()); + edgeCtx.getTbRpcService().deleteRpc(tenantId, existingRpc); + } finally { + edgeSynchronizationManager.getEdgeId().remove(); + } + return Futures.immediateFuture(null); + } + RpcStatus rpcStatus = RpcStatus.valueOf(deviceRpcCallMsg.getRpcStatus()); + if (!existingRpc.getStatus().isIntermediate() && existingRpc.getStatus() != RpcStatus.TIMEOUT && rpcStatus.isIntermediate()) { + // guard against a final RPC regressing to an intermediate status (e.g. stale DELIVERED after SUCCESSFUL). + // TIMEOUT is not final - the device actor retries the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED). + log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already final [{}]", + tenantId, rpcId, rpcStatus, existingRpc.getStatus()); + return Futures.immediateFuture(null); + } + JsonNode response = null; + if (deviceRpcCallMsg.hasResponseMsg() && !StringUtils.isEmpty(deviceRpcCallMsg.getResponseMsg().getResponse())) { + String payload = deviceRpcCallMsg.getResponseMsg().getResponse(); + try { + response = JacksonUtil.toJsonNode(payload); + } catch (IllegalArgumentException e) { + response = JacksonUtil.newObjectNode().put("error", payload); + } + } + edgeCtx.getTbRpcService().save(tenantId, rpcId, rpcStatus, response); + return Futures.immediateFuture(null); + } + private ListenableFuture processDeviceRpcResponseFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) { SettableFuture futureToSet = SettableFuture.create(); UUID requestUuid = new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB()); diff --git a/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java b/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java index 24bdadd2d5..b3a46fd60f 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java @@ -8,4 +8,6 @@ public interface EntityDatabaseSchemaService extends DatabaseSchemaService { void createOrUpdateViewsAndFunctions() throws Exception; + void generateClusterIdIfNotExist(); + } diff --git a/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java b/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java index 8ed65c390f..e90df5e1ea 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java @@ -6,6 +6,14 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + @Service @Profile("install") @Slf4j @@ -43,4 +51,36 @@ public class SqlEntityDatabaseSchemaService extends SqlAbstractDatabaseSchemaSer executeQueryFromFile(SCHEMA_FUNCTIONS_SQL); } + @Override + public void generateClusterIdIfNotExist() { + var clusterId = UUID.randomUUID(); + try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword); + PreparedStatement statement = conn.prepareStatement( + "INSERT INTO tb_cluster (cluster_id) SELECT ?::uuid WHERE NOT EXISTS (SELECT 1 FROM tb_cluster) ON CONFLICT DO NOTHING")) { + statement.setString(1, clusterId.toString()); + int insertedRows = statement.executeUpdate(); + UUID storedClusterId = insertedRows > 0 ? clusterId : readClusterId(conn); + if (storedClusterId != null) { + logClusterId(storedClusterId); + } + } catch (SQLException e) { + log.error("Failed to generate Cluster id", e); + throw new RuntimeException("Failed to generate Cluster id", e); + } + } + + private UUID readClusterId(Connection conn) throws SQLException { + try (Statement statement = conn.createStatement(); + ResultSet rs = statement.executeQuery("SELECT cluster_id FROM tb_cluster")) { + return rs.next() ? rs.getObject(1, UUID.class) : null; + } + } + + private void logClusterId(UUID clusterId) { + String line = ":: Cluster Id: " + clusterId + " ::"; + String border = "=".repeat(line.length()); + // Logged at JVM shutdown so it follows the rest of the install output. + Runtime.getRuntime().addShutdownHook(new Thread(() -> log.info("\n{}\n{}\n{}\n", border, line, border))); + } + } diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java b/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java index 9f6e22b2b3..d333814171 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java @@ -67,18 +67,29 @@ public class LtsMigrationService { .toList(); } - /** No-downtime path: per migration in (from, to] run SQL, then apply(), then record the version. */ - public void applyMigrations(String fromVersion, String toVersion) { - for (VersionedMigration vm : select(fromVersion, toVersion)) { - LtsMigration migration = vm.migration(); + /** + * No version in (from, to] is recorded until every migration and {@code afterSchemaPhase} succeed, so a + * failure re-runs them all: each {@link LtsMigration} and its SQL must be idempotent. + */ + public void applyMigrations(String fromVersion, String toVersion, Runnable afterSchemaPhase) { + List selected = select(fromVersion, toVersion); + for (VersionedMigration versionedMigration : selected) { + LtsMigration migration = versionedMigration.migration(); String version = migration.getVersion(); transactionTemplate.executeWithoutResult(status -> { runSchemaUpdate(version); migration.apply(); - schemaSettingsService.updateSchemaVersion(version); }); log.info("Applied LTS migration {}", version); } + + afterSchemaPhase.run(); + + for (VersionedMigration versionedMigration : selected) { + String version = versionedMigration.migration().getVersion(); + schemaSettingsService.updateSchemaVersion(version); + log.info("Recorded LTS migration version {}", version); + } } /** Offline major-upgrade schema phase: per migration in (from, to] run SQL only. No version record. */ diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java new file mode 100644 index 0000000000..2a28cce7af --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install.lts; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.UUID; + +/** + * Creates {@code tb_cluster} and mints the cluster id on the no-downtime patch path, which runs neither + * {@code schema-entities.sql} nor {@code generateClusterIdIfNotExist()}. Both steps are idempotent. + */ +@Slf4j +@Component +@TbCoreComponent +@RequiredArgsConstructor +public class V4_3_1_6Migration implements LtsMigration { + + private final JdbcTemplate jdbcTemplate; + + @Override + public String getVersion() { + return "4.3.1.6"; + } + + // Must run in the migration transaction: tb_cluster is created there and is not yet visible to other connections. + @Override + public void apply() { + UUID clusterId = UUID.randomUUID(); + int insertedRows = jdbcTemplate.update( + "INSERT INTO tb_cluster (cluster_id) SELECT ?::uuid WHERE NOT EXISTS (SELECT 1 FROM tb_cluster) ON CONFLICT DO NOTHING", + clusterId.toString()); + if (insertedRows > 0) { + log.info("Generated Cluster Id: {}", clusterId); + } else { + log.info("Cluster Id already exists, keeping it"); + } + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index bb57ceab5d..2fd3425ed0 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -7,9 +7,9 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.asset.AssetProfile; -import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.cf.CalculatedFieldType; @@ -25,7 +25,6 @@ import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor; -import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItemDescriptor; @@ -82,7 +81,6 @@ public class DefaultIotHubService implements IotHubService { private static final String SECTION_RULE_CHAIN_METADATA = "rule chain metadata"; private static final String ITEM_TYPE_WIDGET = "widget"; - private static final String ITEM_TYPE_DASHBOARD = "dashboard"; private static final String ITEM_TYPE_CALCULATED_FIELD = "calculated field"; private static final String ITEM_TYPE_ALARM_RULE = "alarm rule"; private static final String ITEM_TYPE_RULE_CHAIN = "rule chain"; @@ -157,7 +155,6 @@ public class DefaultIotHubService implements IotHubService { IotHubInstalledItemDescriptor descriptor = switch (itemType) { case "WIDGET" -> installWidget(user, tenantId, fileData); - case "DASHBOARD" -> installDashboard(user, tenantId, fileData); case "CALCULATED_FIELD" -> installCalculatedField(user, tenantId, fileData, data); case "ALARM_RULE" -> installAlarmRule(user, tenantId, fileData, data); case "RULE_CHAIN" -> installRuleChain(user, tenantId, fileData, data); @@ -218,22 +215,6 @@ public class DefaultIotHubService implements IotHubService { return descriptor; } - private DashboardInstalledItemDescriptor installDashboard(SecurityUser user, TenantId tenantId, byte[] fileData) throws Exception { - Dashboard dashboard; - try { - dashboard = JacksonUtil.fromString(new String(fileData), Dashboard.class, true); - } catch (Exception e) { - throw parseFailure(ACTION_INSTALL, ITEM_TYPE_DASHBOARD, e); - } - dashboard.setId(null); - dashboard.setTenantId(tenantId); - Dashboard saved = tbDashboardService.save(dashboard, user); - log.debug("[{}] Dashboard installed: {}", tenantId, saved.getTitle()); - DashboardInstalledItemDescriptor descriptor = new DashboardInstalledItemDescriptor(); - descriptor.setDashboardId(saved.getId()); - return descriptor; - } - private CalculatedFieldInstalledItemDescriptor installCalculatedField(SecurityUser user, TenantId tenantId, byte[] fileData, JsonNode data) throws Exception { CalculatedField calculatedField; try { @@ -435,7 +416,6 @@ public class DefaultIotHubService implements IotHubService { switch (itemType) { case "WIDGET" -> updateWidget(user, tenantId, (WidgetInstalledItemDescriptor) descriptor, fileData); - case "DASHBOARD" -> updateDashboard(user, tenantId, (DashboardInstalledItemDescriptor) descriptor, fileData); case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData); case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData); case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData); @@ -493,22 +473,6 @@ public class DefaultIotHubService implements IotHubService { tbWidgetTypeService.save(existing, false, user); } - private void updateDashboard(SecurityUser user, TenantId tenantId, DashboardInstalledItemDescriptor descriptor, byte[] fileData) throws Exception { - Dashboard newDashboard; - try { - newDashboard = JacksonUtil.fromString(new String(fileData), Dashboard.class, true); - } catch (Exception e) { - throw parseFailure(ACTION_UPDATE, ITEM_TYPE_DASHBOARD, e); - } - Dashboard existing = dashboardService.findDashboardById(tenantId, descriptor.getDashboardId()); - if (existing == null) { - throw new Exception("Dashboard not found for update"); - } - existing.setTitle(newDashboard.getTitle()); - existing.setConfiguration(newDashboard.getConfiguration()); - tbDashboardService.save(existing, user); - } - private void updateCalculatedField(SecurityUser user, TenantId tenantId, CalculatedFieldInstalledItemDescriptor descriptor, byte[] fileData) throws Exception { CalculatedField newCf; try { @@ -575,8 +539,6 @@ public class DefaultIotHubService implements IotHubService { IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); if (descriptor instanceof WidgetInstalledItemDescriptor wd) { return calculateWidgetChecksum(tenantId, wd); - } else if (descriptor instanceof DashboardInstalledItemDescriptor dd) { - return calculateDashboardChecksum(tenantId, dd); } else if (descriptor instanceof CalculatedFieldInstalledItemDescriptor cd) { return calculateCalculatedFieldChecksum(tenantId, cd.getCalculatedFieldId()); } else if (descriptor instanceof AlarmRuleInstalledItemDescriptor ad) { @@ -598,16 +560,6 @@ public class DefaultIotHubService implements IotHubService { return sha256(content); } - private String calculateDashboardChecksum(TenantId tenantId, DashboardInstalledItemDescriptor descriptor) { - Dashboard dashboard = dashboardService.findDashboardById(tenantId, descriptor.getDashboardId()); - if (dashboard == null) { - return null; - } - String content = (dashboard.getTitle() != null ? dashboard.getTitle() : "") + - (dashboard.getConfiguration() != null ? dashboard.getConfiguration().toString() : ""); - return sha256(content); - } - private String calculateWidgetChecksum(TenantId tenantId, WidgetInstalledItemDescriptor descriptor) { WidgetTypeDetails widgetType = widgetTypeService.findWidgetTypeDetailsById(tenantId, descriptor.getWidgetTypeId()); if (widgetType == null) { @@ -780,11 +732,6 @@ public class DefaultIotHubService implements IotHubService { if (widgetType != null) { tbWidgetTypeService.delete(widgetType, user); } - } else if (descriptor instanceof DashboardInstalledItemDescriptor dd) { - Dashboard dashboard = dashboardService.findDashboardById(tenantId, dd.getDashboardId()); - if (dashboard != null) { - tbDashboardService.delete(dashboard, user); - } } else if (descriptor instanceof CalculatedFieldInstalledItemDescriptor cd) { CalculatedField calculatedField = calculatedFieldService.findById(tenantId, cd.getCalculatedFieldId()); if (calculatedField != null) { @@ -993,12 +940,13 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - resultEntry.setErrorMessage(e.getMessage()); + String failureMessage = ExceptionUtil.getMessage(e); + resultEntry.setErrorMessage(failureMessage); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage("Failed to install '" + entry.getName() + "': " + e.getMessage()); + result.setErrorMessage(failureMessage); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java index 8c7deeea1b..ae777fbff7 100644 --- a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java +++ b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java @@ -6,6 +6,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier; import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MServerSecurityConfigDefault; import org.thingsboard.server.common.transport.config.ssl.SslCredentials; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -14,6 +15,8 @@ import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportBootstrapConf import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig; import java.util.Optional; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.LWM2M_SERVER_MAX; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.PRIMARY_LWM2M_SERVER; @Slf4j @Service @@ -28,20 +31,34 @@ public class LwM2MServiceImpl implements LwM2MService { public LwM2MServerSecurityConfigDefault getServerSecurityInfo(boolean bootstrapServer) { LwM2MSecureServerConfig bsServerConfig = bootstrapServer ? bootstrapConfig.orElse(null) : serverConfig; if (bsServerConfig!= null) { - LwM2MServerSecurityConfigDefault result = getServerSecurityConfig(bsServerConfig); - result.setBootstrapServerIs(bootstrapServer); - return result; + return getServerSecurityConfig(bsServerConfig, bootstrapServer); } else { return null; } } - private LwM2MServerSecurityConfigDefault getServerSecurityConfig(LwM2MSecureServerConfig bsServerConfig) { + private LwM2MServerSecurityConfigDefault getServerSecurityConfig(LwM2MSecureServerConfig bsServerConfig, boolean bootstrapServer) { LwM2MServerSecurityConfigDefault bsServ = new LwM2MServerSecurityConfigDefault(); - bsServ.setShortServerId(bsServerConfig.getId()); bsServ.setHost(bsServerConfig.getHost()); bsServ.setPort(bsServerConfig.getPort()); + bsServ.setBootstrapServerIs(bootstrapServer); + if (bootstrapServer) { + if (bsServerConfig.getId() != null) { + log.warn("Ignoring Short Server ID [{}] on the Bootstrap Server entry: cleared to null for backward compatibility (ThingsBoard <= 4.2).", + bsServerConfig.getId()); + } + bsServ.setShortServerId(null); + } else { + Integer configId = bsServerConfig.getId(); + if (Lwm2mServerIdentifier.isNotLwm2mServer(configId)) { + log.warn("Invalid LwM2M Server ShortServerId [{}] in configuration (transport.lwm2m.server.id). " + + "Must be in range [{} - {}]. Using [{}] instead.", + configId, PRIMARY_LWM2M_SERVER.getId(), LWM2M_SERVER_MAX.getId(), PRIMARY_LWM2M_SERVER.getId()); + configId = PRIMARY_LWM2M_SERVER.getId(); + } + bsServ.setShortServerId(configId); + } bsServ.setSecurityHost(bsServerConfig.getSecureHost()); bsServ.setSecurityPort(bsServerConfig.getSecurePort()); byte[] publicKeyBase64 = getPublicKey(bsServerConfig); diff --git a/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java b/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java index 39688d8c1e..18930326a9 100644 --- a/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java +++ b/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java @@ -7,9 +7,11 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; +import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.common.util.SetCache; import org.thingsboard.server.cache.TbTransactionalCache; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.ApiUsageState; @@ -85,6 +87,7 @@ import org.thingsboard.server.queue.common.TbProtoQueueMsg; import org.thingsboard.server.queue.common.TbRuleEngineProducerService; import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.TopicService; +import org.thingsboard.server.queue.discovery.event.ServiceListChangedEvent; import org.thingsboard.server.queue.provider.TbQueueProducerProvider; import org.thingsboard.server.service.gateway_device.GatewayNotificationsService; import org.thingsboard.server.service.ota.OtaPackageStateService; @@ -118,6 +121,12 @@ public class DefaultTbClusterService implements TbClusterService { private final AtomicInteger toTransportNfs = new AtomicInteger(0); private final AtomicInteger toEdgeMsgs = new AtomicInteger(0); private final AtomicInteger toEdgeNfs = new AtomicInteger(0); + private final AtomicInteger skippedUnknownServiceNfs = new AtomicInteger(0); + + private static final int RECENTLY_SEEN_SERVICES_MAX_SIZE = 1024; + // serviceType:serviceId -> seen. Bounded LRU of cluster members ever observed, used to grace a service id that is + // briefly missing from the live snapshot (see isUnknownService). Fed from ServiceListChangedEvent. + private final SetCache recentlySeenServices = SetCache.boundedBySize(RECENTLY_SEEN_SERVICES_MAX_SIZE); @Autowired private PartitionService partitionService; @@ -197,6 +206,10 @@ public class DefaultTbClusterService implements TbClusterService { @Override public void pushNotificationToCore(String serviceId, FromDeviceRpcResponse response, TbQueueCallback callback) { + if (isUnknownService(ServiceType.TB_CORE, serviceId)) { + skipNotificationToUnknownService(ServiceType.TB_CORE, serviceId, callback); + return; + } TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, serviceId); log.trace("PUSHING msg: {} to:{}", response, tpi); FromDeviceRPCResponseProto.Builder builder = FromDeviceRPCResponseProto.newBuilder() @@ -211,12 +224,93 @@ public class DefaultTbClusterService implements TbClusterService { @Override public void pushNotificationToCore(String targetServiceId, TransportProtos.RestApiCallResponseMsgProto responseMsgProto, TbQueueCallback callback) { + if (isUnknownService(ServiceType.TB_CORE, targetServiceId)) { + skipNotificationToUnknownService(ServiceType.TB_CORE, targetServiceId, callback); + return; + } TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, targetServiceId); ToCoreNotificationMsg msg = ToCoreNotificationMsg.newBuilder().setRestApiCallResponseMsg(responseMsgProto).build(); producerProvider.getTbCoreNotificationsMsgProducer().send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), msg), callback); toCoreNfs.incrementAndGet(); } + /** + * Per-service notification topics ({@code .}) are auto-created by the producer on + * first send. A {@code serviceId} that is not a member of the cluster - e.g. a stale node id or a value injected + * via message metadata - would therefore create an orphan topic that nobody ever consumes and that is never + * cleaned up. To prevent that, notifications whose target service id is not a current member of the cluster are + * skipped. + *

+ * This is a safety net for never-real ids, not a precise gatekeeper, so it is deliberately lenient. A service id is + * treated as known if it is either a current member ({@link PartitionService#isKnownServiceId}) or a recently seen + * one ({@link #recentlySeenServices}). The recently-seen grace covers nodes that are briefly absent from the live + * snapshot - a discovery-propagation lag, a rolling restart or a transient scale-down - so legitimate replies to + * them are not dropped; genuine non-delivery to a node that is actually gone is already handled by the caller-side + * RPC/REST timeout. The check also fails open while the cluster topology is not yet known (empty/absent membership, + * e.g. right after startup). + */ + private boolean isUnknownService(ServiceType serviceType, String serviceId) { + if (serviceId == null || serviceId.isEmpty()) { + return true; + } + if (partitionService.isKnownServiceId(serviceType, serviceId)) { + return false; // currently a live member + } + Set serviceIds = partitionService.getAllServiceIds(serviceType); + if (serviceIds == null || serviceIds.isEmpty()) { + return false; // topology not known yet - fail open + } + return !recentlySeenServices.contains(recentlySeenServiceKey(serviceType, serviceId)); + } + + private void skipNotificationToUnknownService(ServiceType serviceType, String serviceId, TbQueueCallback callback) { + log.debug("Skipping notification push to unknown {} service id [{}]", serviceType, serviceId); + skippedUnknownServiceNfs.incrementAndGet(); + if (callback != null) { + // Deliberate skip - the target is not a cluster member. Complete the callback as a no-op success, + // matching pushNotificationToTransport, so callers don't treat an intentional skip as a delivery error. + callback.onSuccess(null); + } + } + + /** + * Records every observed cluster member so that {@link #isUnknownService} can grace a service id that has dropped + * out of the live snapshot (propagation lag, rolling restart, transient scale-down) instead of dropping + * notifications to it. Bounded by {@link #RECENTLY_SEEN_SERVICES_MAX_SIZE} with LRU eviction, so an id that is gone + * for good eventually ages out and the guard tightens again. Discovery events are change-only, so this never + * removes entries - it only adds; the live-snapshot check in {@link #isUnknownService} stays authoritative for + * current members. + */ + @EventListener + public void onServiceListChanged(ServiceListChangedEvent event) { + rememberSeenService(event.getCurrentService()); + List otherServices = event.getOtherServices(); + if (otherServices != null) { + otherServices.forEach(this::rememberSeenService); + } + } + + private void rememberSeenService(TransportProtos.ServiceInfo serviceInfo) { + if (serviceInfo == null) { + return; + } + String serviceId = serviceInfo.getServiceId(); + if (serviceId == null || serviceId.isEmpty()) { + return; + } + for (String serviceType : serviceInfo.getServiceTypesList()) { + recentlySeenServices.add(recentlySeenServiceKey(serviceType, serviceId)); + } + } + + private static String recentlySeenServiceKey(ServiceType serviceType, String serviceId) { + return recentlySeenServiceKey(serviceType.name(), serviceId); + } + + private static String recentlySeenServiceKey(String serviceType, String serviceId) { + return serviceType + ":" + serviceId; + } + @Override public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) { log.trace("PUSHING msg: {} to:{}", msg, tpi); @@ -311,6 +405,10 @@ public class DefaultTbClusterService implements TbClusterService { @Override public void pushNotificationToRuleEngine(String serviceId, FromDeviceRpcResponse response, TbQueueCallback callback) { + if (isUnknownService(ServiceType.TB_RULE_ENGINE, serviceId)) { + skipNotificationToUnknownService(ServiceType.TB_RULE_ENGINE, serviceId, callback); + return; + } TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_RULE_ENGINE, serviceId); log.trace("PUSHING msg: {} to:{}", response, tpi); FromDeviceRPCResponseProto.Builder builder = FromDeviceRPCResponseProto.newBuilder() @@ -325,11 +423,8 @@ public class DefaultTbClusterService implements TbClusterService { @Override public void pushNotificationToTransport(String serviceId, ToTransportMsg response, TbQueueCallback callback) { - if (serviceId == null || serviceId.isEmpty()) { - log.trace("pushNotificationToTransport: skipping message without serviceId [{}], (ToTransportMsg) response [{}]", serviceId, response); - if (callback != null) { - callback.onSuccess(null); //callback that message already sent, no useful payload expected - } + if (isUnknownService(ServiceType.TB_TRANSPORT, serviceId)) { + skipNotificationToUnknownService(ServiceType.TB_TRANSPORT, serviceId, callback); return; } TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_TRANSPORT, serviceId); @@ -632,9 +727,11 @@ public class DefaultTbClusterService implements TbClusterService { int toTransportNfsCnt = toTransportNfs.getAndSet(0); int toEdgeMsgCnt = toEdgeMsgs.getAndSet(0); int toEdgeNfsCnt = toEdgeNfs.getAndSet(0); - if (toCoreMsgCnt > 0 || toCoreNfsCnt > 0 || toRuleEngineMsgsCnt > 0 || toRuleEngineNfsCnt > 0 || toTransportNfsCnt > 0 || toEdgeMsgCnt > 0 || toEdgeNfsCnt > 0) { + int skippedUnknownServiceNfsCnt = skippedUnknownServiceNfs.getAndSet(0); + if (toCoreMsgCnt > 0 || toCoreNfsCnt > 0 || toRuleEngineMsgsCnt > 0 || toRuleEngineNfsCnt > 0 || toTransportNfsCnt > 0 || toEdgeMsgCnt > 0 || toEdgeNfsCnt > 0 || skippedUnknownServiceNfsCnt > 0) { log.info("To TbCore: [{}] messages [{}] notifications; To TbRuleEngine: [{}] messages [{}] notifications; To Transport: [{}] notifications;" + - "To Edge: [{}] messages [{}] notifications", toCoreMsgCnt, toCoreNfsCnt, toRuleEngineMsgsCnt, toRuleEngineNfsCnt, toTransportNfsCnt, toEdgeMsgCnt, toEdgeNfsCnt); + "To Edge: [{}] messages [{}] notifications; Skipped notifications to unknown service id: [{}]", + toCoreMsgCnt, toCoreNfsCnt, toRuleEngineMsgsCnt, toRuleEngineNfsCnt, toTransportNfsCnt, toEdgeMsgCnt, toEdgeNfsCnt, skippedUnknownServiceNfsCnt); } } } diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java index 5e1ea8e44e..b0a6a490ee 100644 --- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java @@ -3,12 +3,18 @@ package org.thingsboard.server.service.rpc; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.edge.EdgeEvent; +import org.thingsboard.server.common.data.edge.EdgeEventActionType; +import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.RpcId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.msg.TbMsgType; @@ -18,9 +24,14 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; +import org.thingsboard.server.dao.edge.EdgeEventService; +import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.edge.EdgeSynchronizationManager; import org.thingsboard.server.dao.rpc.RpcService; import org.thingsboard.server.queue.util.TbCoreComponent; +import java.util.List; + @TbCoreComponent @Service @RequiredArgsConstructor @@ -28,6 +39,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent; public class TbRpcService { private final RpcService rpcService; private final TbClusterService tbClusterService; + private final EdgeService edgeService; + private final EdgeEventService edgeEventService; + private final EdgeSynchronizationManager edgeSynchronizationManager; public Rpc save(TenantId tenantId, Rpc rpc) { Rpc saved = rpcService.save(rpc); @@ -67,4 +81,32 @@ public class TbRpcService { return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink); } + /** + * The only edge-aware RPC delete: propagates the delete to related edges (Cloud -> Edge) for ANY status. + * Other delete paths (RpcService.deleteRpc, TTL clean-up) intentionally do not sync, so each side expires its own copies. + */ + public void deleteRpc(TenantId tenantId, Rpc rpc) { + rpcService.deleteRpc(tenantId, rpc.getId()); + // skipped when the delete originated from an edge (edge-sync context) so it is not echoed back + if (edgeSynchronizationManager.getEdgeId().get() == null) { + pushRpcDeleteToEdges(tenantId, rpc); + } + } + + private void pushRpcDeleteToEdges(TenantId tenantId, Rpc rpc) { + List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(tenantId, rpc.getDeviceId()); + if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) { + return; + } + ObjectNode body = JacksonUtil.newObjectNode(); + body.put("requestUUID", rpc.getId().getId().toString()); + body.put("rpcStatus", RpcStatus.DELETED.name()); + for (EdgeId edgeId : relatedEdgeIds) { + // persisted (not high-priority) so the delete is replayed when the edge reconnects + EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(tenantId, edgeId, EdgeEventType.DEVICE, + EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); + edgeEventService.saveAsync(edgeEvent); + } + } + } diff --git a/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java b/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java index 84e7d928d0..f990d96af7 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java +++ b/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java @@ -263,6 +263,7 @@ public class AccessValidator { accessControlService.checkPermission(currentUser, Resource.DEVICE_PROFILE, operation, entityId, deviceProfile); } catch (ThingsboardException e) { callback.onSuccess(ValidationResult.accessDenied(e.getMessage())); + return; } callback.onSuccess(ValidationResult.ok(deviceProfile)); } @@ -281,6 +282,7 @@ public class AccessValidator { accessControlService.checkPermission(currentUser, Resource.ASSET_PROFILE, operation, entityId, assetProfile); } catch (ThingsboardException e) { callback.onSuccess(ValidationResult.accessDenied(e.getMessage())); + return; } callback.onSuccess(ValidationResult.ok(assetProfile)); } @@ -293,6 +295,7 @@ public class AccessValidator { } else { if (!operation.equals(Operation.READ_TELEMETRY)) { callback.onSuccess(ValidationResult.accessDenied("Allowed only READ_TELEMETRY operation!")); + return; } ApiUsageState apiUsageState = apiUsageStateService.findApiUsageStateById(currentUser.getTenantId(), new ApiUsageStateId(entityId.getId())); if (apiUsageState == null) { @@ -302,6 +305,7 @@ public class AccessValidator { accessControlService.checkPermission(currentUser, Resource.API_USAGE_STATE, operation, entityId, apiUsageState); } catch (ThingsboardException e) { callback.onSuccess(ValidationResult.accessDenied(e.getMessage())); + return; } callback.onSuccess(ValidationResult.ok(apiUsageState)); } @@ -320,6 +324,7 @@ public class AccessValidator { accessControlService.checkPermission(currentUser, Resource.OTA_PACKAGE, operation, entityId, otaPackage); } catch (ThingsboardException e) { callback.onSuccess(ValidationResult.accessDenied(e.getMessage())); + return; } callback.onSuccess(ValidationResult.ok(otaPackage)); } diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java index 4691f4d114..fe02ae5efb 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java +++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java @@ -2,30 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.security.auth.oauth2; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.security.jackson2.SecurityJackson2Modules; -import java.io.IOException; -import java.util.Arrays; -import java.util.Base64; import java.util.Optional; -@Slf4j public class CookieUtils { - private static final ObjectMapper OBJECT_MAPPER; - - static { - ClassLoader loader = CookieUtils.class.getClassLoader(); - OBJECT_MAPPER = new ObjectMapper(); - OBJECT_MAPPER.registerModules(SecurityJackson2Modules.getModules(loader)); - } - public static Optional getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); @@ -61,24 +45,4 @@ public class CookieUtils { } } } - - public static String serialize(Object object) { - try { - return Base64.getUrlEncoder() - .encodeToString(OBJECT_MAPPER.writeValueAsBytes(object)); - } catch (JsonProcessingException e) { - throw new IllegalArgumentException("The given Json object value: " - + object + " cannot be transformed to a String", e); - } - } - - public static T deserialize(Cookie cookie, Class cls) { - byte[] decodedBytes = Base64.getUrlDecoder().decode(cookie.getValue()); - try { - return OBJECT_MAPPER.readValue(decodedBytes, cls); - } catch (IOException e) { - throw new IllegalArgumentException("The given string value: " - + Arrays.toString(decodedBytes) + " cannot be transformed to Json object", e); - } - } } diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java index 5bcda9476a..d867dc9645 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java +++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java @@ -2,13 +2,34 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.security.auth.oauth2; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.generators.HKDFBytesGenerator; +import org.bouncycastle.crypto.params.HKDFParameters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.stereotype.Component; import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService; +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.time.Clock; +import java.util.Arrays; +import java.util.Base64; + +@Slf4j @Component @TbCoreComponent public class HttpCookieOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository { @@ -17,10 +38,31 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza public static final String PREV_URI_COOKIE_NAME = "prev_uri"; private static final int cookieExpireSeconds = 180; + private static final byte[] KEY_DERIVATION_INFO = "thingsboard-oauth2-authorization-request-cookie".getBytes(StandardCharsets.UTF_8); + private static final int KEY_LENGTH = 32; + private static final int NONCE_LENGTH = 12; + private static final int TAG_LENGTH_BITS = 128; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() + .registerModules(SecurityJackson2Modules.getModules(HttpCookieOAuth2AuthorizationRequestRepository.class.getClassLoader())); + + private final JwtSettingsService jwtSettingsService; + private final Clock clock; + private final SecureRandom secureRandom = new SecureRandom(); + + @Autowired + public HttpCookieOAuth2AuthorizationRequestRepository(JwtSettingsService jwtSettingsService) { + this(jwtSettingsService, Clock.systemUTC()); + } + + HttpCookieOAuth2AuthorizationRequestRepository(JwtSettingsService jwtSettingsService, Clock clock) { + this.jwtSettingsService = jwtSettingsService; + this.clock = clock; + } + @Override public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) { return CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME) - .map(cookie -> CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class)) + .map(this::decrypt) .orElse(null); } @@ -34,7 +76,7 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza if (PrevUriValidator.isValid(prevUri)) { CookieUtils.addCookie(response, PREV_URI_COOKIE_NAME, prevUri, cookieExpireSeconds); } - CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds); + CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, encrypt(authorizationRequest), cookieExpireSeconds); } @Override @@ -45,4 +87,56 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) { CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); } + + private String encrypt(OAuth2AuthorizationRequest authorizationRequest) { + try { + byte[] json = OBJECT_MAPPER.writeValueAsBytes(authorizationRequest); + byte[] plaintext = ByteBuffer.allocate(Long.BYTES + json.length).putLong(clock.millis()).put(json).array(); + byte[] nonce = new byte[NONCE_LENGTH]; + secureRandom.nextBytes(nonce); + byte[] ciphertext = initCipher(Cipher.ENCRYPT_MODE, nonce).doFinal(plaintext); + byte[] envelope = ByteBuffer.allocate(NONCE_LENGTH + ciphertext.length).put(nonce).put(ciphertext).array(); + return Base64.getUrlEncoder().withoutPadding().encodeToString(envelope); + } catch (Exception e) { + throw new IllegalStateException("Failed to encrypt OAuth2 authorization request", e); + } + } + + private OAuth2AuthorizationRequest decrypt(Cookie cookie) { + try { + byte[] envelope = Base64.getUrlDecoder().decode(cookie.getValue()); + if (envelope.length < NONCE_LENGTH + TAG_LENGTH_BITS / Byte.SIZE + Long.BYTES) { + log.debug("Ignoring OAuth2 authorization request cookie: too short"); + return null; + } + byte[] nonce = Arrays.copyOf(envelope, NONCE_LENGTH); + byte[] plaintext = initCipher(Cipher.DECRYPT_MODE, nonce).doFinal(envelope, NONCE_LENGTH, envelope.length - NONCE_LENGTH); + ByteBuffer buffer = ByteBuffer.wrap(plaintext); + long issuedAt = buffer.getLong(); + if (clock.millis() - issuedAt > cookieExpireSeconds * 1000L) { + log.debug("Ignoring OAuth2 authorization request cookie: expired"); + return null; + } + return OBJECT_MAPPER.readValue(plaintext, Long.BYTES, plaintext.length - Long.BYTES, OAuth2AuthorizationRequest.class); + } catch (Exception e) { + log.debug("Ignoring invalid OAuth2 authorization request cookie: {}", e.getClass().getSimpleName()); + return null; + } + } + + private Cipher initCipher(int mode, byte[] nonce) throws GeneralSecurityException { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(mode, new SecretKeySpec(deriveKey(), "AES"), new GCMParameterSpec(TAG_LENGTH_BITS, nonce)); + return cipher; + } + + private byte[] deriveKey() { + byte[] signingKey = Base64.getDecoder().decode(jwtSettingsService.getJwtSettings().getTokenSigningKey()); + HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest()); + hkdf.init(new HKDFParameters(signingKey, null, KEY_DERIVATION_INFO)); + byte[] key = new byte[KEY_LENGTH]; + hkdf.generateBytes(key, 0, KEY_LENGTH); + return key; + } + } diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 1a279b109c..e587661fc8 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -19,7 +19,6 @@ import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.alarm.AlarmInfo; @@ -30,7 +29,6 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; @@ -102,6 +100,7 @@ import org.thingsboard.server.service.solutions.data.DashboardLinkInfo; import org.thingsboard.server.service.solutions.data.DeviceCredentialsInfo; import org.thingsboard.server.service.solutions.data.EdgeLinkInfo; import org.thingsboard.server.service.solutions.data.SolutionInstallContext; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import org.thingsboard.server.service.solutions.data.UserCredentialsInfo; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.thingsboard.server.service.solutions.data.definition.AssetDefinition; @@ -115,6 +114,7 @@ import org.thingsboard.server.service.solutions.data.definition.UserDefinition; import org.thingsboard.server.service.solutions.data.definition.DashboardDefinition; import org.thingsboard.server.service.solutions.data.definition.DeviceProfileDefinition; import org.thingsboard.server.service.solutions.data.definition.EdgeDefinition; +import org.thingsboard.server.service.solutions.data.definition.EntityDefinition; import org.thingsboard.server.service.solutions.data.definition.RelationDefinition; import org.thingsboard.server.service.solutions.data.definition.ReferenceableEntityDefinition; import org.thingsboard.server.service.solutions.data.definition.TenantDefinition; @@ -144,8 +144,10 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutorService; @@ -166,6 +168,14 @@ import java.util.zip.ZipInputStream; @Slf4j public class DefaultSolutionService implements SolutionService { + private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + private static final String RANDOM_PLACEHOLDER = "$random"; + private static final int MAX_LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + MAX_LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; + @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -237,9 +247,9 @@ public class DefaultSolutionService implements SolutionService { throw new IllegalArgumentException("Solution template is missing solution.json or its 'title' field"); } - SolutionInstallResponse validateResult = validateSolution(tenantId, tempDir); - if (validateResult != null && !validateResult.isSuccess()) { - return validateResult; + SolutionValidationResult validation = validateSolution(tenantId, tempDir); + if (!validation.isPassed()) { + return conflictResponse(validation.getConflictReport()); } return doInstallSolution(user, tenantId, solutionId, tempDir, request); } finally { @@ -280,73 +290,159 @@ public class DefaultSolutionService implements SolutionService { } } - private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - Map> alreadyExistingEntities = new HashMap<>(); - - //TODO: check other entities. + SolutionValidationResult validateSolution(TenantId tenantId, Path tempDir) { + //TODO: pre-validate what still only fails at provision time: customer users (unique by email), + // alarm rules and calculated fields. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); - if (!ruleChains.isEmpty()) { - for (ReferenceableEntityDefinition ruleChain : ruleChains) { - List savedRuleChains = ruleChainService.findTenantRuleChainsByType(tenantId, RuleChainType.CORE, new PageLink(1, 0, ruleChain.getName())).getData(); - if (savedRuleChains != null && !savedRuleChains.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.RULE_CHAIN, key -> new ArrayList<>()).add(savedRuleChains.get(0)); - } - } - } - List deviceProfiles = loadListOfEntitiesIfFileExists(tempDir, "device_profiles.json", new TypeReference<>() { }); deviceProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "device_profiles", DeviceProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!deviceProfiles.isEmpty()) { - for (DeviceProfile deviceProfile : deviceProfiles) { - DeviceProfile savedProfile = deviceProfileService.findDeviceProfileByName(tenantId, deviceProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.DEVICE_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - List assetProfiles = loadListOfEntitiesIfFileExists(tempDir, "asset_profiles.json", new TypeReference<>() { }); assetProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "asset_profiles", AssetProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!assetProfiles.isEmpty()) { - for (AssetProfile assetProfile : assetProfiles) { - AssetProfile savedProfile = assetProfileService.findAssetProfileByName(tenantId, assetProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.ASSET_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } + List customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() { + }); + List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() { + }); + List assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() { + }); + List devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() { + }); + List edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() { + }); + + // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. + Map> conflicts = new LinkedHashMap<>(); + collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); + collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, + name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, + name -> assetProfileService.findAssetProfileByName(tenantId, name)); + collectConflicts(conflicts, customers, + title -> isRandomizedCustomerTitle(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, assets, name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, devices, name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, dashboards, title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + + if (conflicts.isEmpty()) { + return SolutionValidationResult.passed(); + } + StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); + conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); + if (conflicts.values().stream().anyMatch(descriptions -> descriptions.size() > MAX_LISTED_NAMES_PER_TYPE)) { + details.append(System.lineSeparator()).append(TRUNCATION_NOTE); + } + + return SolutionValidationResult.conflictsFound(details.toString()); + } + + private static SolutionInstallResponse conflictResponse(String conflictReport) { + SolutionInstallResponse response = new SolutionInstallResponse(); + response.setSuccess(false); + response.setDetails(conflictReport); + return response; + } + + /** + * The entity type and the name both come from the definition, so a list can not end up checked against the + * wrong type by mistake. + */ + private void collectConflicts(Map> conflicts, List definitions, + Function lookup) { + Set checked = new HashSet<>(); + for (EntityDefinition definition : definitions) { + if (checked.add(definition.getName())) { + collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup); } } + } - List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() { - }); - if (!dashboards.isEmpty()) { - for (DashboardDefinition dashboard : dashboards) { - List savedDashboards = dashboardService.findDashboardsByTenantId(tenantId, new PageLink(1, 0, dashboard.getName())).getData(); - if (savedDashboards != null && !savedDashboards.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.DASHBOARD, key -> new ArrayList<>()).add(savedDashboards.get(0)); - } + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + Function nameExtractor, Function lookup) { + Set checked = new HashSet<>(); + for (T definition : definitions) { + String name = nameExtractor.apply(definition); + if (checked.add(name)) { + collectConflict(conflicts, entityType, name, lookup); } } - if (!alreadyExistingEntities.isEmpty()) { - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - StringBuilder detailsBuilder = new StringBuilder(); - detailsBuilder.append("## Validation failed").append(System.lineSeparator()).append(System.lineSeparator()); - alreadyExistingEntities.forEach((type, list) -> detailsBuilder.append("The following **").append(getTypeLabel(type)).append("** entities already exist: ") - .append(list.stream().map(HasName::getName).map(name -> "'" + name + "'").collect(Collectors.joining(","))).append(";") - .append(System.lineSeparator()).append(System.lineSeparator())); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(detailsBuilder.toString()); - return solutionInstallResponse; - } else { - return null; + } + + private void collectConflict(Map> conflicts, EntityType entityType, String name, + Function lookup) { + if (StringUtils.isEmpty(name)) { + return; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName())); + } + } + + /** + * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will + * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. + */ + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + List definitions) { + Set checked = new HashSet<>(); + for (ReferenceableEntityDefinition definition : definitions) { + if (StringUtils.isEmpty(definition.getFile())) { + continue; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate + continue; + } + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + if (ruleChain == null || !ruleChain.hasNonNull("name")) { + continue; + } + RuleChainType type = ruleChain.hasNonNull("type") + ? RuleChainType.valueOf(ruleChain.get("type").asText()) : RuleChainType.CORE; + String name = ruleChain.get("name").asText(); + if (!checked.add(type + name)) { + continue; + } + collectConflict(conflicts, EntityType.RULE_CHAIN, name, + ignored -> ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, type, name) + .stream().findFirst().orElse(null)); } } + /** + * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} + * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of + * every other entity are used as written, placeholder included, and must be looked up as is. + */ + private static boolean isRandomizedCustomerTitle(String title) { + return title.contains(RANDOM_PLACEHOLDER); + } + + private static String quoted(String value) { + return "'" + value + "'"; + } + + /** + * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, + * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} + * names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of + * that type is not complete. + */ + private static void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + details.append("- **").append(entityType.getNormalName()).append("**: ") + .append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) { + details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE) + .append(" more (").append(conflictDescriptions.size()).append(" in total)"); + } + details.append(System.lineSeparator()); + } + private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { SolutionInstallContext ctx = new SolutionInstallContext(tenantId, solutionId, tempDir, user, new TenantSolutionTemplateInstructions()); @@ -1442,10 +1538,6 @@ public class DefaultSolutionService implements SolutionService { return String.valueOf(now.toInstant().toEpochMilli()); } - private String getTypeLabel(EntityType type) { - return type.name().toLowerCase().replace('_', ' '); - } - private T loadEntityIfFileExists(Path tempDir, String fileName, Class clazz) { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { @@ -1459,7 +1551,7 @@ public class DefaultSolutionService implements SolutionService { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { try { - return JacksonUtil.readValue(filePath.toFile(), typeReference); + return Objects.requireNonNullElseGet(JacksonUtil.readValue(filePath.toFile(), typeReference), ArrayList::new); } catch (Exception e) { throw new IllegalArgumentException("Invalid json file " + fileName + " data structure", e); } diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java new file mode 100644 index 0000000000..4b6b07c54b --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.solutions.data; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** + * The outcome of validating a solution template before anything is created: either the install can go ahead, or the + * entities of the tenant the template clashes with, reported as the markdown the install dialog renders. + */ +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class SolutionValidationResult { + + private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, ""); + + private final boolean passed; + private final String conflictReport; + + public static SolutionValidationResult passed() { + return PASSED; + } + + public static SolutionValidationResult conflictsFound(String conflictReport) { + return new SolutionValidationResult(false, conflictReport); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java b/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java index d97d2c5ddf..c1391f111b 100644 --- a/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java +++ b/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java @@ -93,19 +93,7 @@ public class SystemPatchApplier { try { String dbVersion = schemaSettingsService.getDbSchemaVersion(); String packageVersion = schemaSettingsService.getPackageSchemaVersion(); - ltsMigrationService.applyMigrations(dbVersion, packageVersion); - - updateSqlViews(); - log.info("Updated sql database views"); - - WidgetTypeStats widgetStats = updateWidgetTypes(); - log.info("System widget types: {} created, {} updated", widgetStats.created(), widgetStats.updated()); - - int updatedBundles = updateWidgetBundles(); - log.info("System widget bundles: {} updated", updatedBundles); - - int createdImages = createMissingSystemImages(); - log.info("Created {} new system images", createdImages); + ltsMigrationService.applyMigrations(dbVersion, packageVersion, this::syncSystemData); schemaSettingsService.updateSchemaVersion(); log.info("System data patch update completed successfully"); @@ -115,6 +103,21 @@ public class SystemPatchApplier { } } + // Views are rebuilt with SELECT * over tables the migrations may have altered, so this must run after them. + private void syncSystemData() { + updateSqlViews(); + log.info("Updated sql database views"); + + WidgetTypeStats widgetStats = updateWidgetTypes(); + log.info("System widget types: {} created, {} updated", widgetStats.created(), widgetStats.updated()); + + int updatedBundles = updateWidgetBundles(); + log.info("System widget bundles: {} updated", updatedBundles); + + int createdImages = createMissingSystemImages(); + log.info("Created {} new system images", createdImages); + } + private boolean isVersionChanged() { String packageVersion = schemaSettingsService.getPackageSchemaVersion(); String dbVersion = schemaSettingsService.getDbSchemaVersion(); diff --git a/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java b/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java index 54c5d271e1..da1a748c37 100644 --- a/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java +++ b/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java @@ -19,7 +19,9 @@ import org.thingsboard.server.common.data.kv.ReadTsKvQuery; import org.thingsboard.server.common.data.kv.TsKvEntry; import org.thingsboard.server.dao.timeseries.TimeseriesService; import org.thingsboard.server.service.security.AccessValidator; +import org.thingsboard.server.service.security.ValidationCallback; import org.thingsboard.server.service.security.ValidationResult; +import org.thingsboard.server.service.security.ValidationResultCode; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.permission.Operation; @@ -42,6 +44,10 @@ public class DefaultTbTelemetryService implements TbTelemetryService { accessValidator.validate(currentUser, Operation.READ_TELEMETRY, entityId, new FutureCallback<>() { @Override public void onSuccess(ValidationResult validationResult) { + if (validationResult.getResultCode() != ValidationResultCode.OK) { + onFailure(ValidationCallback.getException(validationResult)); + return; + } try { AggregationParams params; if (Aggregation.NONE.equals(agg)) { diff --git a/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java b/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java index 71f4e73929..15e470085b 100644 --- a/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java +++ b/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java @@ -882,72 +882,36 @@ public class DefaultWebSocketService implements WebSocketService { }, executor); } - private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List keys, final FutureCallback> callback) { - return new FutureCallback() { - @Override - public void onSuccess(@Nullable ValidationResult result) { - List>> futures = new ArrayList<>(); - for (AttributeScope scope : AttributeScope.values()) { - futures.add(attributesService.find(tenantId, entityId, scope, keys)); - } - - ListenableFuture> future = mergeAllAttributesFutures(futures); - Futures.addCallback(future, callback, MoreExecutors.directExecutor()); + private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List keys, final FutureCallback> callback) { + return on(r -> { + List>> futures = new ArrayList<>(); + for (AttributeScope scope : AttributeScope.values()) { + futures.add(attributesService.find(tenantId, entityId, scope, keys)); } - @Override - public void onFailure(Throwable t) { - callback.onFailure(t); - } - }; + ListenableFuture> future = mergeAllAttributesFutures(futures); + Futures.addCallback(future, callback, MoreExecutors.directExecutor()); + }, callback::onFailure); } - private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List keys, final FutureCallback> callback) { - return new FutureCallback() { - @Override - public void onSuccess(@Nullable ValidationResult result) { - Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor()); - } - - @Override - public void onFailure(Throwable t) { - callback.onFailure(t); - } - }; + private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List keys, final FutureCallback> callback) { + return on(r -> Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor()), callback::onFailure); } - private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback> callback) { - return new FutureCallback() { - @Override - public void onSuccess(@Nullable ValidationResult result) { - List>> futures = new ArrayList<>(); - for (AttributeScope scope : AttributeScope.values()) { - futures.add(attributesService.findAll(tenantId, entityId, scope)); - } - - ListenableFuture> future = mergeAllAttributesFutures(futures); - Futures.addCallback(future, callback, MoreExecutors.directExecutor()); + private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback> callback) { + return on(r -> { + List>> futures = new ArrayList<>(); + for (AttributeScope scope : AttributeScope.values()) { + futures.add(attributesService.findAll(tenantId, entityId, scope)); } - @Override - public void onFailure(Throwable t) { - callback.onFailure(t); - } - }; + ListenableFuture> future = mergeAllAttributesFutures(futures); + Futures.addCallback(future, callback, MoreExecutors.directExecutor()); + }, callback::onFailure); } - private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback> callback) { - return new FutureCallback() { - @Override - public void onSuccess(@Nullable ValidationResult result) { - Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor()); - } - - @Override - public void onFailure(Throwable t) { - callback.onFailure(t); - } - }; + private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback> callback) { + return on(r -> Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor()), callback::onFailure); } private FutureCallback on(Consumer success, Consumer failure) { diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 5bf7eda87b..d0fa7565f9 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -43,7 +43,8 @@ server: # HTTP settings http: # Semi-colon-separated list of urlPattern=maxPayloadSize pairs that define max http request size for specified url pattern. After first match all other will be skipped - max_payload_size: "${HTTP_MAX_PAYLOAD_SIZE_LIMIT_CONFIGURATION:/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}" + # The /api/communityGrant/offline/run entry must precede /api/** to allow instance checker uploads; it is prepended automatically if missing + max_payload_size: "${HTTP_MAX_PAYLOAD_SIZE_LIMIT_CONFIGURATION:/api/communityGrant/offline/run=35651584;/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}" # HTTP/2 support (takes effect only if server SSL is enabled) http2: # Enable/disable HTTP/2 support @@ -1291,7 +1292,7 @@ transport: #

  • A value that are > 4: MultiNodeConnectionIdGenerator is used
  • connection_id_length: "${LWM2M_DTLS_CONNECTION_ID_LENGTH:8}" server: - # LwM2M Server ID + # LwM2M Server Short Server ID. Valid range [1 - 65534]; 0 and 65535 are reserved. Default: 123. id: "${LWM2M_SERVER_ID:123}" # LwM2M server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" @@ -1333,8 +1334,8 @@ transport: bootstrap: # Enable/disable Bootstrap Server enabled: "${LWM2M_ENABLED_BS:true}" - # Default value in LwM2M client after start in mode Bootstrap for the object : name "LWM2M Security" field: "Short Server ID" (deviceProfile: Bootstrap.BOOTSTRAP SERVER.Short ID) - id: "${LWM2M_SERVER_ID_BS:0}" + # Deprecated: Short Server ID is not applicable for Bootstrap Server per OMA spec (Object 0 Resource 10) and is forced to null. + id: "${LWM2M_SERVER_ID_BS:}" # LwM2M bootstrap server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BS_BIND_ADDRESS:0.0.0.0}" # LwM2M bootstrap server bind port @@ -2237,3 +2238,18 @@ iot-hub: max-uncompressed-entry-bytes: "${IOT_HUB_MAX_UNCOMPRESSED_ENTRY_BYTES:52428800}" # maximum uncompressed size in bytes for any single entry inside a solution template archive. max-archive-entry-count: "${IOT_HUB_MAX_ARCHIVE_ENTRY_COUNT:10000}" # maximum number of entries allowed inside a solution template archive. max-install-timeout-ms: "${IOT_HUB_MAX_INSTALL_TIMEOUT_MS:60000}" # upper clamp in milliseconds for the post-install wait declared in a solution template's solution.json. Prevents a malicious or misconfigured template from pinning an HTTP worker thread. + +community-grant: + enabled: "${COMMUNITY_GRANT_ENABLED:true}" # enables the community grant enrollment flow; when disabled, no flow can be started and no outbound calls are made. + base-url: "${COMMUNITY_GRANT_BASE_URL:https://license.thingsboard.io}" # base URL of the license portal. + connect-timeout-sec: "${COMMUNITY_GRANT_CONNECT_TIMEOUT_SEC:5}" # timeout in seconds to connect to the license portal. + read-timeout-sec: "${COMMUNITY_GRANT_READ_TIMEOUT_SEC:10}" # timeout in seconds to read from the license portal. + fast-poll-interval-ms: "${COMMUNITY_GRANT_FAST_POLL_INTERVAL_MS:3000}" # interval in milliseconds between portal polls during the initial polling window; a node never polls more often than every 2000 ms. + fast-poll-window-ms: "${COMMUNITY_GRANT_FAST_POLL_WINDOW_MS:120000}" # duration in milliseconds of the initial polling window, after which the slow interval is used. + slow-poll-interval-ms: "${COMMUNITY_GRANT_SLOW_POLL_INTERVAL_MS:30000}" # interval in milliseconds between portal polls after the initial polling window. + supervise-interval-ms: "${COMMUNITY_GRANT_SUPERVISE_INTERVAL_MS:30000}" # interval in milliseconds at which the node owning the system tenant partition picks up enrollment flows started on other nodes. + sign-up-deadline-ms: "${COMMUNITY_GRANT_SIGN_UP_DEADLINE_MS:86400000}" # how long in milliseconds to poll for an uncompleted sign-up before the flow is stopped and can be restarted. + max-checker-size-bytes: "${COMMUNITY_GRANT_MAX_CHECKER_SIZE_BYTES:33554432}" # maximum size in bytes of the instance checker, downloaded or uploaded; keep below the /api/communityGrant/offline/run limit in server.http.max_payload_size. + checker-timeout-sec: "${COMMUNITY_GRANT_CHECKER_TIMEOUT_SEC:600}" # maximum time in seconds the instance checker may run before it is terminated; an offline run still unfinished 2 minutes later is reported as interrupted. + max-report-size-bytes: "${COMMUNITY_GRANT_MAX_REPORT_SIZE_BYTES:1048576}" # maximum size in bytes of the output accepted from the instance checker. + checker-release-public-keys: "${COMMUNITY_GRANT_CHECKER_RELEASE_PUBLIC_KEYS:1:Xwg49dWb+Ofzx4FzIvxqYMS9EV9hqzlTGmphtTYZtw4=}" # comma-separated keyId:base64Key list (keyId 1-255, raw 32-byte Ed25519 key) trusted to sign the instance checker; if empty or unparseable, no instance checker is run. diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java index aaa878193f..6b7b0201f4 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java @@ -92,7 +92,7 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest { } protected TbTestWebSocketClient buildAndConnectWebSocketClient(String path) throws URISyntaxException, InterruptedException { - TbTestWebSocketClient wsClient = new TbTestWebSocketClient(new URI(WS_URL + wsPort + path)); + TbTestWebSocketClient wsClient = buildWebSocketClient(path); assertThat(wsClient.connectBlocking(TIMEOUT, TimeUnit.SECONDS)).isTrue(); if (!path.contains("token=")) { wsClient.authenticate(token); @@ -100,4 +100,8 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest { return wsClient; } + protected TbTestWebSocketClient buildWebSocketClient(String path) throws URISyntaxException { + return new TbTestWebSocketClient(new URI(WS_URL + wsPort + path)); + } + } diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java index 84cebb2673..4eee0265dc 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java @@ -364,8 +364,13 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest { } private void testSendNotificationMsgToEdgeServiceTimeEntityEqAny(TenantId tenantId, ActionType actionType, int cntTime) { + // Count only entities that can be synced to edge. Background services may save non-edge entities for the + // tenant at any moment (e.g. QUEUE_STATS created by the periodic rule engine stats report), and their + // ADDED notifications have no edge event type, so they are dropped by TbClusterService anyway. + ArgumentMatcher matcherEdgeEntityId = argument -> argument != null + && EdgeUtils.getEdgeEventTypeByEntityType(argument.getEntityType()) != null; Mockito.verify(tbClusterService, times(cntTime)).sendNotificationMsgToEdge(Mockito.eq(tenantId), - Mockito.any(), Mockito.any(EntityId.class), Mockito.any(), Mockito.isNull(), + Mockito.any(), Mockito.argThat(matcherEdgeEntityId), Mockito.any(), Mockito.isNull(), Mockito.eq(EdgeUtils.getEdgeEventActionTypeByActionType(actionType)), Mockito.any()); } diff --git a/application/src/test/java/org/thingsboard/server/controller/CommunityGrantControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/CommunityGrantControllerTest.java new file mode 100644 index 0000000000..8d34f8a7ba --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/CommunityGrantControllerTest.java @@ -0,0 +1,678 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.controller; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.hamcrest.Matchers; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.AopTestUtils; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionStatus; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.audit.AuditLog; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.page.SortOrder; +import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.dao.audit.AuditLogService; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures; +import org.thingsboard.server.service.community_grant.CommunityGrantCheckerInput; +import org.thingsboard.server.service.community_grant.CommunityGrantFlowStateStore; +import org.thingsboard.server.service.community_grant.CommunityGrantOfflineReportStore; +import org.thingsboard.server.service.community_grant.CommunityGrantPlatform; +import org.thingsboard.server.service.community_grant.CommunityGrantPoller; +import org.thingsboard.server.service.community_grant.CommunityGrantPortalClient; +import org.thingsboard.server.service.community_grant.CommunityGrantPortalStatus; +import org.thingsboard.server.service.community_grant.CommunityGrantReportRunner; +import org.thingsboard.server.service.community_grant.CommunityGrantService; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@DaoSqlTest +public class CommunityGrantControllerTest extends AbstractControllerTest { + + private static final List ALLOWED_FIELDS = + List.of("mode", "state", "signUpUrl", "lastPolledAt", "parkReason", "portalUrl", "offlineReport", + "offlineRunInProgress", "offlineRunError"); + private static final String REPORT = "-----BEGIN TB INSTANCE CHECK-----\nbody"; + private static final String BUNDLE_FILE_NAME = "tb-instance-check-bundle_" + + CommunityGrantPlatform.current().os() + "_" + CommunityGrantPlatform.current().arch() + ".tbicb"; + private static final long EXPIRED_ISSUED_AT = 1609459200000L; + private static final long EXPIRED_EXPIRES_AT = 1609545600000L; + // Mirror package-private constants of DefaultCommunityGrantService. + private static final String NOT_ALREADY_REGISTERED_MESSAGE = + "This action is only available once this deployment is confirmed as already registered under another account."; + private static final String NOTHING_TO_HAND_OVER_MESSAGE = + "This deployment is not waiting for a check result to be handed over."; + + @Autowired + private AuditLogService auditLogService; + @Autowired + private CommunityGrantFlowStateStore flowStateStore; + @Autowired + private CommunityGrantPoller poller; + @Autowired + private CommunityGrantService communityGrantService; + @Autowired + private CommunityGrantOfflineReportStore offlineReportStore; + @MockitoSpyBean + private CommunityGrantPortalClient portalClient; + @MockitoSpyBean + private CommunityGrantReportRunner reportRunner; + + @Test + public void testStateIsNotStartedBeforeAnyAction() throws Exception { + loginSysAdmin(); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.NOT_STARTED.name()); + assertThat(state.get("mode").asText()).isEqualTo("ONLINE"); + assertThat(state.get("signUpUrl").isNull()).isTrue(); + assertThat(state.get("lastPolledAt").isNull()).isTrue(); + } + + @Test + public void testStateExposesNothingBeyondTheContract() throws Exception { + loginSysAdmin(); + + ResultActions result = doGet("/api/communityGrant/state").andExpect(status().isOk()); + String body = result.andReturn().getResponse().getContentAsString(); + JsonNode state = JacksonUtil.toJsonNode(body); + + state.fieldNames().forEachRemaining(field -> assertThat(field).isIn(ALLOWED_FIELDS)); + assertThat(state.get("portalUrl").asText()).isNotBlank(); + } + + @Test + public void testStateRequiresAuthentication() throws Exception { + loginSysAdmin(); + TimeUnit.SECONDS.sleep(1); //We need to make sure that event for invalidating token was successfully processed + logout(); + doGet("/api/communityGrant/state").andExpect(status().isUnauthorized()); + } + + @Test + public void testStateIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doGet("/api/communityGrant/state").andExpect(status().isForbidden()); + } + + @Test + public void testStartIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doPost("/api/communityGrant/start").andExpect(status().isForbidden()); + } + + @Test + public void testOfflineReportIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doGet("/api/communityGrant/offline/report").andExpect(status().isForbidden()); + } + + @Test + public void testOfflineReportIsDownloadedAsAPlainTextAttachment() throws Exception { + loginSysAdmin(); + offlineReportStore.put(REPORT); + try { + doGet("/api/communityGrant/offline/report") + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"tb-instance-check-report.txt\"")) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)) + .andExpect(content().string(REPORT)); + } finally { + // The stored report outlives the test, and other tests expect none. + offlineReportStore.clear(); + } + } + + @Test + public void testOfflineReportIsServedFromTheDatabaseRow() throws Exception { + loginSysAdmin(); + offlineReportStore.put(REPORT); + try { + String served = doGet("/api/communityGrant/offline/report").andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + assertThat(served).isEqualTo(REPORT); + Mockito.verifyNoInteractions(reportRunner); + // This node also holds a local copy, so the row itself is checked. + assertThat(jdbcTemplate.queryForObject( + "SELECT json_value::json ->> 'report' FROM admin_settings WHERE key = 'communityGrantReport'", + String.class)).isEqualTo(REPORT); + } finally { + offlineReportStore.clear(); + } + } + + @Test + public void testStateCarriesTheReportOnTheStepThatShowsIt() throws Exception { + loginSysAdmin(); + offlineReportStore.put(REPORT); + try { + flowStateStore.update(state -> { + state.setState(CommunityGrantState.VALIDATING); + state.setLastOfflineCheckAt(System.currentTimeMillis()); + return state; + }); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + + assertThat(state.get("offlineReport").asText()).isEqualTo(REPORT); + } finally { + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testStateCarriesNoReportBeforeAnyCheckHasRun() throws Exception { + loginSysAdmin(); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + + assertThat(state.get("offlineReport").isNull()).isTrue(); + } + + @Test + public void testOfflineReportIsNotFoundBeforeAnyCheckHasRun() throws Exception { + loginSysAdmin(); + + doGet("/api/communityGrant/offline/report").andExpect(status().isNotFound()); + } + + @Test + public void testOfflineHandoffIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doPost("/api/communityGrant/offline/handoff").andExpect(status().isForbidden()); + } + + @Test + public void testOfflineHandoffClaimsTheReportAndIsAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + offlineReportStore.put(REPORT); + try { + flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.OFFLINE); + state.setState(CommunityGrantState.VALIDATING); + state.setLastOfflineCheckAt(System.currentTimeMillis()); + return state; + }); + + JsonNode state = JacksonUtil.toJsonNode(doPost("/api/communityGrant/offline/handoff") + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString()); + + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER.name()); + assertThat(state.get("offlineReport").asText()).isEqualTo(REPORT); + assertThat(flowStateStore.get().getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_ENROLLMENT, ActionStatus.SUCCESS); + } finally { + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testOfflineHandoffRefusalIsAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + + doPost("/api/communityGrant/offline/handoff").andExpect(status().isBadRequest()); + + assertThat(assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_ENROLLMENT, ActionStatus.FAILURE) + .getActionFailureDetails()).contains(NOTHING_TO_HAND_OVER_MESSAGE); + } + + @Test + public void testRequestAccessIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doPost("/api/communityGrant/requestAccess").andExpect(status().isForbidden()); + } + + // A well-formed bundle, so the 403 comes from @PreAuthorize. + @Test + public void testOfflineRunIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isForbidden()); + } + + @Test + public void testRequestAccessRefusalIsAuditedWhenNotAlreadyRegistered() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + + doPost("/api/communityGrant/requestAccess").andExpect(status().isBadRequest()); + + String failureDetails = assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, + ActionStatus.FAILURE).getActionFailureDetails(); + // The column carries a whole stack trace, so the refusal message is asserted rather than absent substrings. + assertThat(failureDetails).contains(NOT_ALREADY_REGISTERED_MESSAGE); + } + + // Neither tb_cluster nor the admin_settings row is reset between tests, and DaoSqlTest does not seed tb_cluster. + @Test + public void testRequestAccessSuccessIsAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + boolean seededClusterId = Boolean.TRUE.equals( + jdbcTemplate.queryForObject("SELECT NOT EXISTS (SELECT 1 FROM tb_cluster)", Boolean.class)); + try { + if (seededClusterId) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", UUID.randomUUID().toString()); + } + flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.ONLINE); + state.setState(CommunityGrantState.ALREADY_REGISTERED); + return state; + }); + Mockito.doNothing().when(portalClient).requestAccess(any()); + + doPost("/api/communityGrant/requestAccess").andExpect(status().isOk()); + + assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, ActionStatus.SUCCESS); + Mockito.verify(portalClient).requestAccess(any()); + } finally { + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + if (seededClusterId) { + jdbcTemplate.update("DELETE FROM tb_cluster"); + } + } + } + + @Test + public void testStartIsDrivenToATerminalStateByTheRealPoller() throws Exception { + loginSysAdmin(); + boolean seededClusterId = Boolean.TRUE.equals( + jdbcTemplate.queryForObject("SELECT NOT EXISTS (SELECT 1 FROM tb_cluster)", Boolean.class)); + try { + if (seededClusterId) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", UUID.randomUUID().toString()); + } + Mockito.doReturn(true).when(portalClient).isPortalReachable(); + Mockito.doReturn(false).when(portalClient).isAlreadyRegistered(any()); + Mockito.doReturn(new CommunityGrantPortalStatus("AWAITING_SIGNUP", null, null), + new CommunityGrantPortalStatus("DONE", null, null)) + .when(portalClient).getStatus(any(), any()); + + doPost("/api/communityGrant/start").andExpect(status().isOk()); + + await("the poller reaching a terminal state").atMost(30, TimeUnit.SECONDS) + .until(() -> flowStateStore.get().getState() == CommunityGrantState.REGISTERED); + assertThat(jdbcTemplate.queryForObject("SELECT license_claim_token FROM tb_cluster", String.class)).isNull(); + } finally { + poller.disarm(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + if (seededClusterId) { + jdbcTemplate.update("DELETE FROM tb_cluster"); + } + } + } + + @Test + public void testStartReturnsASignUpUrlToASysAdmin() throws Exception { + loginSysAdmin(); + boolean seededClusterId = Boolean.TRUE.equals( + jdbcTemplate.queryForObject("SELECT NOT EXISTS (SELECT 1 FROM tb_cluster)", Boolean.class)); + try { + if (seededClusterId) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", UUID.randomUUID().toString()); + } + Mockito.doReturn(true).when(portalClient).isPortalReachable(); + Mockito.doReturn(false).when(portalClient).isAlreadyRegistered(any()); + Mockito.doReturn(new CommunityGrantPortalStatus("AWAITING_SIGNUP", null, null)) + .when(portalClient).getStatus(any(), any()); + + JsonNode state = JacksonUtil.toJsonNode(doPost("/api/communityGrant/start") + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString()); + + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP.name()); + assertThat(state.get("mode").asText()).isEqualTo(CommunityGrantMode.ONLINE.name()); + assertThat(state.get("signUpUrl").asText()).startsWith("http"); + } finally { + poller.disarm(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + if (seededClusterId) { + jdbcTemplate.update("DELETE FROM tb_cluster"); + } + } + } + + // Zero bytes in place of the release signature: the parser passes them on and the verifier refuses them. + @Test + public void testOfflineRunRefusalIsAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(new byte[74]))).andExpect(status().isBadRequest()); + } finally { + setClusterId(previousClusterId); + } + + String failureDetails = assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + ActionStatus.FAILURE).getActionFailureDetails(); + assertThat(failureDetails).contains("not a ThingsBoard release signature"); + assertThat(failureDetails.toLowerCase()).doesNotContain("secret"); + assertThat(failureDetails).doesNotContain("postgres://"); + assertThat(failureDetails.toLowerCase()).doesNotContain("password"); + } + + @Test + public void testOfflineRunWithAFileThatIsNotABundleIsRefusedAndAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + + mockMvc.perform(offlineRunRequest("not a bundle at all".getBytes(StandardCharsets.UTF_8))) + .andExpect(status().isBadRequest()); + + assertThat(assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + ActionStatus.FAILURE).getActionFailureDetails()).contains("not a ThingsBoard enrollment bundle"); + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + } + + @Test + public void testOfflineRunOnAnArchitectureWithNoCheckerBuildIsRefusedAndAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + // Built before os.arch is swapped, so the manifest names the real host. + byte[] bundle = bundleForThisHost(CommunityGrantBundleFixtures.relsig()); + String previousArch = System.getProperty("os.arch"); + try { + System.setProperty("os.arch", "s390x"); + + mockMvc.perform(offlineRunRequest(bundle)) + .andExpect(status().isBadRequest()) + .andExpect(content().string(Matchers.containsString("no instance checker build"))); + } finally { + System.setProperty("os.arch", previousArch); + } + + assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, ActionStatus.FAILURE); + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + } + + @Test + public void testOfflineRunWithABundleForAnotherInstallationIsRefused() throws Exception { + loginSysAdmin(); + String previousClusterId = currentClusterId(); + try { + setClusterId(UUID.randomUUID().toString()); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isBadRequest()) + .andExpect(content().string(Matchers.containsString("different installation"))); + + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + } finally { + setClusterId(previousClusterId); + } + } + + @Test + public void testOfflineRunWithAWrongPlatformBundleNamesBothPlatforms() throws Exception { + loginSysAdmin(); + CommunityGrantPlatform host = CommunityGrantPlatform.current(); + String otherOs = "linux".equals(host.os()) ? "darwin" : "linux"; + ObjectNode manifest = CommunityGrantBundleFixtures.validManifest(); + manifest.put("os", otherOs); + manifest.put("arch", host.arch()); + + mockMvc.perform(offlineRunRequest(CommunityGrantBundleFixtures.bundle(manifest))) + .andExpect(status().isBadRequest()) + .andExpect(content().string(Matchers.containsString(otherOs))) + .andExpect(content().string(Matchers.containsString(host.os()))); + + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + } + + @Test + public void testTheRunnerIsGivenTheCheckersOwnNameAndTheManifestsInput() throws Exception { + loginSysAdmin(); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + givenTheRunnerAcceptsAndReturns(REPORT); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isAccepted()); + awaitOfflineRunFinished(); + + ArgumentCaptor verifiedName = ArgumentCaptor.forClass(String.class); + Mockito.verify(reportRunner).verifyUploadedChecker(any(), any(), verifiedName.capture()); + assertThat(verifiedName.getValue()).isEqualTo(CHECKER_FILE_NAME_FOR_THIS_HOST); + ArgumentCaptor fileName = ArgumentCaptor.forClass(String.class); + ArgumentCaptor checkerInput = + ArgumentCaptor.forClass(CommunityGrantCheckerInput.class); + Mockito.verify(reportRunner) + .runUploadedChecker(any(), any(), fileName.capture(), checkerInput.capture()); + assertThat(fileName.getValue()).isEqualTo(CHECKER_FILE_NAME_FOR_THIS_HOST); + assertThat(checkerInput.getValue().json()) + .isEqualTo(JacksonUtil.toString(CommunityGrantBundleFixtures.validCheckerInput())); + } finally { + setClusterId(previousClusterId); + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testOfflineRunAnswers202AndTheReportArrivesThroughTheState() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + givenAnOfflineEnrollment(); + givenTheRunnerAcceptsAndReturns(REPORT); + + byte[] bundle = bundleForThisHost(CommunityGrantBundleFixtures.relsig()); + String body = mockMvc.perform(offlineRunRequest(bundle)) + .andExpect(status().isAccepted()) + .andReturn().getResponse().getContentAsString(); + assertThat(JacksonUtil.toJsonNode(body).get("offlineRunInProgress").asBoolean()).isTrue(); + awaitOfflineRunFinished(); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + assertThat(state.get("offlineRunInProgress").asBoolean()).isFalse(); + assertThat(state.get("offlineRunError").isNull()).isTrue(); + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.VALIDATING.name()); + assertThat(state.get("offlineReport").asText()).isEqualTo(REPORT); + assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, ActionStatus.SUCCESS); + } finally { + setClusterId(previousClusterId); + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testAFailedOfflineRunIsReportedThroughTheState() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + givenAnOfflineEnrollment(); + Mockito.doNothing().when(reportRunner).verifyUploadedChecker(any(), any(), any()); + Mockito.doThrow(new IllegalStateException("The instance check failed with exit code 3")) + .when(reportRunner).runUploadedChecker(any(), any(), any(), any()); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isAccepted()); + awaitOfflineRunFinished(); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + assertThat(state.get("offlineRunInProgress").asBoolean()).isFalse(); + assertThat(state.get("offlineRunError").asText()) + .isEqualTo("Failed to run the check. The instance check failed with exit code 3"); + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP.name()); + assertThat(assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + ActionStatus.FAILURE).getActionFailureDetails()).contains("exit code 3"); + } finally { + setClusterId(previousClusterId); + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testOfflineRunIsRefusedWhileAnotherRunIsInProgress() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + Mockito.doNothing().when(reportRunner).verifyUploadedChecker(any(), any(), any()); + flowStateStore.update(state -> { + state.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), System.currentTimeMillis())); + return state; + }); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isTooManyRequests()); + + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + assertThat(state.get("offlineRunInProgress").asBoolean()).isTrue(); + assertThat(assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + ActionStatus.FAILURE).getActionFailureDetails()).contains("already running"); + } finally { + setClusterId(previousClusterId); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + /** The stand-in checker is not signed by a trusted key, so both runner steps are stubbed. */ + private void givenTheRunnerAcceptsAndReturns(String report) { + Mockito.doNothing().when(reportRunner).verifyUploadedChecker(any(), any(), any()); + Mockito.doReturn(report).when(reportRunner).runUploadedChecker(any(), any(), any(), any()); + } + + private void givenAnOfflineEnrollment() { + flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.OFFLINE); + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + }); + } + + /** The permit is released last, after the run's state write and audit call. */ + private void awaitOfflineRunFinished() { + Object service = AopTestUtils.getUltimateTargetObject(communityGrantService); + Semaphore permit = (Semaphore) ReflectionTestUtils.getField(service, "offlineRunPermit"); + await("the background offline run").atMost(10, TimeUnit.SECONDS) + .until(() -> permit.availablePermits() == 1); + } + + @Test + public void testAnExpiredChallengeWarnsAndStillReachesTheRunner() throws Exception { + loginSysAdmin(); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + givenTheRunnerAcceptsAndReturns(REPORT); + ObjectNode manifest = CommunityGrantBundleFixtures.validManifest(); + manifest.put("os", CommunityGrantPlatform.current().os()); + manifest.put("arch", CommunityGrantPlatform.current().arch()); + manifest.put("issuedAt", EXPIRED_ISSUED_AT); + manifest.put("challengeExpiresAt", EXPIRED_EXPIRES_AT); + + mockMvc.perform(offlineRunRequest(CommunityGrantBundleFixtures.bundle(manifest))) + .andExpect(status().isAccepted()); + awaitOfflineRunFinished(); + + Mockito.verify(reportRunner).runUploadedChecker(any(), any(), any(), any()); + } finally { + setClusterId(previousClusterId); + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + private String currentClusterId() { + return jdbcTemplate.query("SELECT cluster_id FROM tb_cluster LIMIT 1", + rs -> rs.next() ? rs.getString(1) : null); + } + + private void setClusterId(String clusterId) { + jdbcTemplate.update("DELETE FROM tb_cluster"); + if (clusterId != null) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", clusterId); + } + } + + private static final String CHECKER_FILE_NAME_FOR_THIS_HOST = "tb-instance-check_" + + CommunityGrantPlatform.current().os() + "_" + CommunityGrantPlatform.current().arch(); + + private static byte[] bundleForThisHost(byte[] relsig) { + ObjectNode manifest = CommunityGrantBundleFixtures.validManifest(); + manifest.put("os", CommunityGrantPlatform.current().os()); + manifest.put("arch", CommunityGrantPlatform.current().arch()); + manifest.put("checkerFileName", CHECKER_FILE_NAME_FOR_THIS_HOST); + return CommunityGrantBundleFixtures.bundle(relsig, + JacksonUtil.toString(manifest).getBytes(StandardCharsets.UTF_8), + CommunityGrantBundleFixtures.standInChecker()); + } + + private MockMultipartHttpServletRequestBuilder offlineRunRequest(byte[] bundle) { + MockMultipartHttpServletRequestBuilder postRequest = + MockMvcRequestBuilders.multipart("/api/communityGrant/offline/run"); + postRequest.file(new MockMultipartFile("bundle", BUNDLE_FILE_NAME, "application/octet-stream", bundle)); + setJwtToken(postRequest); + return postRequest; + } + + /** Audit logs are written asynchronously. */ + private AuditLog assertSingleAuditLog(User user, ActionType actionType, ActionStatus expectedStatus) { + await("async audit log saving").atMost(5, TimeUnit.SECONDS) + .until(() -> !findAuditLogs(user, actionType).isEmpty()); + List auditLogs = findAuditLogs(user, actionType); + + assertThat(auditLogs).hasSize(1); + assertThat(auditLogs.get(0).getActionStatus()).isEqualTo(expectedStatus); + return auditLogs.get(0); + } + + private List findAuditLogs(User user, ActionType actionType) { + return auditLogService.findAuditLogsByTenantIdAndUserId( + user.getTenantId(), user.getId(), List.of(actionType), + new TimePageLink(new PageLink(10, 0, null, new SortOrder("createdTime", SortOrder.Direction.DESC)), + 0L, System.currentTimeMillis())).getData(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java index fa4d65b1a4..3d226d903a 100644 --- a/application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java @@ -34,6 +34,7 @@ import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.device.profile.JsonTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MServerSecurityConfigDefault; import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -1167,6 +1168,29 @@ public class DeviceProfileControllerTest extends AbstractControllerTest { assertThat(deviceProfile.getVersion()).isEqualTo(3); } + @Test + public void testGetLwm2mBootstrapSecurityInfo_BootstrapServer_Returns_ShortServerId_Null() throws Exception { + LwM2MServerSecurityConfigDefault result = doGet( + "/api/lwm2m/deviceProfile/bootstrap/true", + LwM2MServerSecurityConfigDefault.class + ); + Assert.assertNotNull(result); + Assert.assertTrue(result.isBootstrapServerIs()); + Assert.assertNull(result.getShortServerId()); + } + + @Test + public void testGetLwm2mBootstrapSecurityInfo_BootstrapServer_Returns_ShortServerId_1() throws Exception { + LwM2MServerSecurityConfigDefault result = doGet( + "/api/lwm2m/deviceProfile/bootstrap/false", + LwM2MServerSecurityConfigDefault.class + ); + Assert.assertNotNull(result); + Assert.assertFalse(result.isBootstrapServerIs()); + Assert.assertNotNull(result.getShortServerId()); + Assert.assertEquals(Integer.valueOf(123), result.getShortServerId()); + } + private DeviceProfile saveDeviceProfile(String name) { DeviceProfile deviceProfile = createDeviceProfile(name); return saveDeviceProfile(deviceProfile); diff --git a/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplConfigTest.java b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplConfigTest.java new file mode 100644 index 0000000000..30afb0e667 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplConfigTest.java @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.controller; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MServerSecurityConfigDefault; +import org.thingsboard.server.service.lwm2m.LwM2MServiceImpl; +import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportBootstrapConfig; +import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.LWM2M_SERVER_MAX; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.PRIMARY_LWM2M_SERVER; + +@ExtendWith(MockitoExtension.class) +public class LwM2MServiceImplConfigTest { + + @Mock + private LwM2MTransportServerConfig serverConfig; + + @Mock + private LwM2MTransportBootstrapConfig bootstrapConfig; + + private LwM2MServiceImpl lwM2MService; + + @BeforeEach + void setUp() { + lwM2MService = new LwM2MServiceImpl(serverConfig, Optional.of(bootstrapConfig)); + } + + @Test + void testGetServerSecurityInfo_BsServerWithNonEmptyId_ClearsToNullAndLogsWarn() { + given(bootstrapConfig.getId()).willReturn(111); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(true); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isTrue(); + assertThat(result.getShortServerId()).isNull(); + } + + @Test + void testGetServerSecurityInfo_DmServerWithValidId_Success() { + Integer validShortServerId = 123; + given(serverConfig.getId()).willReturn(validShortServerId); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(validShortServerId); + } + + @Test + void testGetServerSecurityInfo_DmServerWithMinValidId_ReturnedUnchanged() { + Integer validShortServerId = PRIMARY_LWM2M_SERVER.getId(); + given(serverConfig.getId()).willReturn(validShortServerId); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(validShortServerId); + } + + @Test + void testGetServerSecurityInfo_DmServerWithMaxValidId_ReturnedUnchanged() { + Integer validShortServerId = LWM2M_SERVER_MAX.getId(); + given(serverConfig.getId()).willReturn(validShortServerId); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(validShortServerId); + } + + @Test + void testGetServerSecurityInfo_Server_Less_PRIMARY_LWM2M_SERVER_DefaultsToOneAndLogsWarn() { + Integer inValidShortServerId = PRIMARY_LWM2M_SERVER.getId() - 1; + given(serverConfig.getId()).willReturn(inValidShortServerId); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); + } + + @Test + void testGetServerSecurityInfo_Server_NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX_DefaultsToOneAndLogsWarn() { + Integer inValidShortServerId = NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(); + given(serverConfig.getId()).willReturn(inValidShortServerId); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); + } + + @Test + void testGetServerSecurityInfo_ServerWithNullId_DefaultsToOneAndLogsWarn() { + Integer inValidShortServerId = null; + given(serverConfig.getId()).willReturn(inValidShortServerId); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); + } +} diff --git a/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java b/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java index 4a9f2673a9..1b5817ac21 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java +++ b/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java @@ -42,6 +42,8 @@ public class TbTestWebSocketClient extends WebSocketClient { @Getter private volatile String lastMsg; + @Getter + private volatile Integer closeCode; private volatile CountDownLatch reply; private volatile CountDownLatch update; @@ -74,6 +76,7 @@ public class TbTestWebSocketClient extends WebSocketClient { @Override public void onClose(int i, String s, boolean b) { + closeCode = i; log.info("CLOSED."); } diff --git a/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java index 3ae44db1b0..0db18a5795 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java @@ -10,8 +10,10 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.SaveDeviceWithCredentialsRequest; +import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.kv.BasicTsKvEntry; import org.thingsboard.server.common.data.kv.LongDataEntry; import org.thingsboard.server.common.data.query.AliasEntityId; @@ -22,9 +24,11 @@ import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.List; +import java.util.UUID; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.thingsboard.server.common.data.query.EntityKeyType.TIME_SERIES; @@ -291,6 +295,38 @@ public class TelemetryControllerTest extends AbstractControllerTest { Assert.assertTrue(tsDataAfterDeletion.get("key3").get(0).get("value").isNull()); } + @Test + public void testCustomerUserCannotReadTimeseriesOfNotAssignedDevice() throws Exception { + loginTenantAdmin(); + Device device = createDevice(); + tsService.save(tenantId, device.getId(), new BasicTsKvEntry(1000L, new LongDataEntry("t", 1L))).get(); + + loginCustomerUser(); + String url = "/api/plugins/telemetry/DEVICE/{entityId}/values/timeseries?keys=t&startTs=0&endTs={endTs}"; + doGetAsync(url, device.getUuidId(), System.currentTimeMillis()).andExpect(status().isForbidden()); + doGetAsync(url + "&agg=SUM&interval=86400000", device.getUuidId(), System.currentTimeMillis()).andExpect(status().isForbidden()); + doGetAsync(url, UUID.randomUUID(), System.currentTimeMillis()).andExpect(status().isNotFound()); + + loginTenantAdmin(); + assignDeviceToCustomer(device.getId(), customerId); + + loginCustomerUser(); + ObjectNode result = doGetAsync(url, ObjectNode.class, device.getUuidId(), System.currentTimeMillis()); + Assert.assertEquals(1L, result.get("t").get(0).get("value").asLong()); + } + + @Test + public void testCustomerUserCannotSaveDeviceProfileAttributes() throws Exception { + loginTenantAdmin(); + DeviceProfileId deviceProfileId = createDevice().getDeviceProfileId(); + + loginCustomerUser(); + doPostAsync("/api/plugins/telemetry/DEVICE_PROFILE/" + deviceProfileId + "/SERVER_SCOPE", "{\"attr\": \"value\"}", String.class, status().isForbidden()); + + await().during(1, TimeUnit.SECONDS).atMost(2, TimeUnit.SECONDS) + .until(() -> attributesService.find(tenantId, deviceProfileId, AttributeScope.SERVER_SCOPE, "attr").get().isEmpty()); + } + private Device createDevice() throws Exception { String testToken = "TEST_TOKEN"; diff --git a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java index 4bcf47e355..fd88b2ca65 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java @@ -4,6 +4,7 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; +import org.java_websocket.framing.CloseFrame; import org.jboss.aerogear.security.otp.Totp; import org.junit.After; import org.junit.Before; @@ -14,6 +15,8 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.web.util.UriComponentsBuilder; import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionStatus; @@ -26,6 +29,8 @@ import org.thingsboard.server.common.data.notification.targets.platform.TenantAd import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.SortOrder; import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.common.data.query.EntityData; +import org.thingsboard.server.common.data.query.EntityTypeFilter; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.model.JwtPair; import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; @@ -43,6 +48,7 @@ import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; import org.thingsboard.server.service.security.auth.rest.LoginRequest; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.EntityDataUpdate; import java.time.Duration; import java.util.Arrays; @@ -145,6 +151,48 @@ public class TwoFactorAuthTest extends AbstractControllerTest { assertThat(currentUser.getId()).isEqualTo(user.getId()); } + @Test + public void testWsAuthCmd_preVerificationTokenRejected() throws Exception { + configureTotpTwoFa(); + logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN); + + wsClient = buildAndConnectWebSocketClient(); + + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed); + } + + @Test + public void testWsQueryToken_preVerificationTokenRejected() throws Exception { + configureTotpTwoFa(); + logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN); + + // The server accepts the handshake and closes the session right away from afterConnectionEstablished(). + // connectBlocking() returns false when that close frame is processed before it checks the open state, + // so its result is not asserted here; the server-side close code proves the token was rejected. + wsClient = buildWebSocketClient("/api/ws?token=" + token); + wsClient.connectBlocking(TIMEOUT, TimeUnit.SECONDS); + + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed); + assertThat(wsClient.getCloseCode()).isEqualTo(CloseFrame.UNEXPECTED_CONDITION); + } + + @Test + public void testWs_accessTokenAcceptedAfterTwoFa() throws Exception { + TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa(); + logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN); + JsonNode tokenPair = readResponse(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + getCorrectTotp(totpTwoFaAccountConfig)) + .andExpect(status().isOk()), JsonNode.class); + validateAndSetJwtToken(tokenPair, username); + Device device = createDevice("2FA device", "2FA device token"); + + EntityTypeFilter deviceFilter = new EntityTypeFilter(); + deviceFilter.setEntityType(EntityType.DEVICE); + EntityDataUpdate update = getWsClient().sendEntityDataQuery(deviceFilter); + + assertThat(update.getData().getData()).singleElement() + .extracting(EntityData::getEntityId).isEqualTo(device.getId()); + } + @Test public void testTwoFaPreVerificationTokenLifetime() throws Exception { configureTotpTwoFa(twoFaSettings -> { diff --git a/application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java b/application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java index 53c4760c35..dfdb3c0527 100644 --- a/application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java @@ -966,6 +966,18 @@ public class WebsocketApiTest extends AbstractControllerTest { assertThat(update.get("data").get("attr").get(0).get(1).asText()).isEqualTo(expectedAttrValue); } + @Test + public void testAttributesSubscription_customerUserNotAssignedDevice() throws Exception { + sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, List.of( + new BaseAttributeKvEntry(System.currentTimeMillis(), new StringDataEntry("attr", "secret")) + )); + + loginCustomerUser(); + JsonNode update = getWsClient().subscribeForAttributes(device.getId(), TbAttributeSubscriptionScope.SERVER_SCOPE.name(), List.of("attr")); + assertThat(update.get("errorCode").asInt()).isNotEqualTo(SubscriptionErrorCode.NO_ERROR.getCode()); + assertThat(update.path("data").isEmpty()).isTrue(); + } + @Test public void testEntityCountCmd_filterTypeSingularCompatibilityTest() throws Exception { ObjectNode oldFormatDeviceTypeFilterSingular = JacksonUtil.newObjectNode(); diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java index 48178c92c5..fe80391fb2 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java @@ -38,12 +38,16 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.RpcId; import org.thingsboard.server.common.data.ota.OtaPackageType; +import org.thingsboard.server.common.data.rpc.Rpc; +import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.common.msg.session.FeatureType; import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.rpc.RpcService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.AttributesRequestMsg; import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg; @@ -93,6 +97,9 @@ public class DeviceEdgeTest extends AbstractEdgeTest { @Autowired protected EdgeService edgeService; + @Autowired + protected RpcService rpcService; + @Test public void testDevices() throws Exception { // create device and assign to edge; update device @@ -654,6 +661,118 @@ public class DeviceEdgeTest extends AbstractEdgeTest { Assert.assertEquals(2, latestDeviceRpcCallMsg.getRetries()); } + @Test + public void testRpcV2StatusUpdateFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.QUEUED); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELIVERED, null); + Assert.assertEquals(RpcStatus.DELIVERED, getPersistentRpc(rpc.getId()).getStatus()); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "{\"result\":\"ok\"}"); + Rpc successful = getPersistentRpc(rpc.getId()); + Assert.assertEquals(RpcStatus.SUCCESSFUL, successful.getStatus()); + Assert.assertEquals("ok", successful.getResponse().get("result").asText()); + + // stale intermediate status must not regress a final RPC + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELIVERED, null); + Assert.assertEquals(RpcStatus.SUCCESSFUL, getPersistentRpc(rpc.getId()).getStatus()); + } + + @Test + public void testRpcV2StatusRetryAfterTimeoutFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.SENT); + + // TIMEOUT with retries left is followed by a re-delivery + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.TIMEOUT, null); + Assert.assertEquals(RpcStatus.TIMEOUT, getPersistentRpc(rpc.getId()).getStatus()); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SENT, null); + Assert.assertEquals(RpcStatus.SENT, getPersistentRpc(rpc.getId()).getStatus()); + } + + @Test + public void testRpcV2NonJsonResponseFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.DELIVERED); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "not a json"); + Rpc successful = getPersistentRpc(rpc.getId()); + Assert.assertEquals(RpcStatus.SUCCESSFUL, successful.getStatus()); + Assert.assertEquals("not a json", successful.getResponse().get("error").asText()); + } + + @Test + public void testRpcV2StatusForUnknownRpcFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + RpcId unknownRpcId = new RpcId(Uuids.timeBased()); + + sendRpcStatusUplink(device, unknownRpcId, RpcStatus.DELIVERED, null); + doGet("/api/rpc/persistent/" + unknownRpcId.getId()).andExpect(status().isNotFound()); + } + + @Test + public void testRpcV2DeleteFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.DELIVERED); + + edgeImitator.expectMessageAmount(1); + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELETED, null); + doGet("/api/rpc/persistent/" + rpc.getUuidId()).andExpect(status().isNotFound()); + // delete originated from the edge must not be echoed back + Assert.assertFalse(edgeImitator.waitForMessages(1)); + } + + @Test + public void testRpcV2DeleteFromCloud() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.SUCCESSFUL); + + edgeImitator.expectMessageAmount(1); + doDelete("/api/rpc/persistent/" + rpc.getUuidId()).andExpect(status().isOk()); + Assert.assertTrue(edgeImitator.waitForMessages()); + + AbstractMessage latestMessage = edgeImitator.getLatestMessage(); + Assert.assertTrue(latestMessage instanceof DeviceRpcCallMsg); + DeviceRpcCallMsg deviceRpcCallMsg = (DeviceRpcCallMsg) latestMessage; + Assert.assertEquals(RpcStatus.DELETED.name(), deviceRpcCallMsg.getRpcStatus()); + Assert.assertEquals(rpc.getUuidId(), new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); + Assert.assertFalse(deviceRpcCallMsg.hasRequestMsg()); + Assert.assertFalse(deviceRpcCallMsg.hasResponseMsg()); + } + + private Rpc savePersistentRpc(Device device, RpcStatus status) { + Rpc rpc = new Rpc(new RpcId(Uuids.timeBased())); + rpc.setTenantId(tenantId); + rpc.setDeviceId(device.getId()); + rpc.setExpirationTime(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1)); + rpc.setRequest(JacksonUtil.newObjectNode().put("method", "test_method")); + rpc.setStatus(status); + return rpcService.save(rpc); + } + + private Rpc getPersistentRpc(RpcId rpcId) throws Exception { + return doGet("/api/rpc/persistent/" + rpcId.getId(), Rpc.class); + } + + private void sendRpcStatusUplink(Device device, RpcId rpcId, RpcStatus rpcStatus, String response) throws Exception { + DeviceRpcCallMsg.Builder builder = DeviceRpcCallMsg.newBuilder() + .setDeviceIdMSB(device.getUuidId().getMostSignificantBits()) + .setDeviceIdLSB(device.getUuidId().getLeastSignificantBits()) + .setRequestUuidMSB(rpcId.getId().getMostSignificantBits()) + .setRequestUuidLSB(rpcId.getId().getLeastSignificantBits()) + .setRpcStatus(rpcStatus.name()); + if (response != null) { + builder.setResponseMsg(RpcResponseMsg.newBuilder().setResponse(response).build()); + } + UplinkMsg uplinkMsg = UplinkMsg.newBuilder().addDeviceRpcCallMsg(builder.build()).build(); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsg); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + private void sendAttributesRequestAndVerify(Device device, String scope, String attributesDataStr, String expectedKey, String expectedValue) throws Exception { JsonNode attributesData = JacksonUtil.toJsonNode(attributesDataStr); diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java index d558cd6648..51765db04e 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java @@ -232,13 +232,13 @@ public class DeviceProfileEdgeTest extends AbstractEdgeTest { Assert.assertFalse(transportConfiguration.getBootstrap().isEmpty()); LwM2MBootstrapServerCredential lwM2MBootstrapServerCredential = transportConfiguration.getBootstrap().get(0); Assert.assertTrue(lwM2MBootstrapServerCredential instanceof NoSecLwM2MBootstrapServerCredential); - NoSecLwM2MBootstrapServerCredential noSecLwM2MBootstrapServerCredential = (NoSecLwM2MBootstrapServerCredential) lwM2MBootstrapServerCredential; + NoSecLwM2MBootstrapServerCredential noSecLwM2MBootstrapSectionDmServerCredential = (NoSecLwM2MBootstrapServerCredential) lwM2MBootstrapServerCredential; - Assert.assertEquals("PUBLIC_KEY", noSecLwM2MBootstrapServerCredential.getServerPublicKey()); - Assert.assertEquals(Integer.valueOf(123), noSecLwM2MBootstrapServerCredential.getShortServerId()); - Assert.assertFalse(noSecLwM2MBootstrapServerCredential.isBootstrapServerIs()); - Assert.assertEquals("localhost", noSecLwM2MBootstrapServerCredential.getHost()); - Assert.assertEquals(Integer.valueOf(5685), noSecLwM2MBootstrapServerCredential.getPort()); + Assert.assertEquals("PUBLIC_KEY", noSecLwM2MBootstrapSectionDmServerCredential.getServerPublicKey()); + Assert.assertEquals(Integer.valueOf(123), noSecLwM2MBootstrapSectionDmServerCredential.getShortServerId()); + Assert.assertFalse(noSecLwM2MBootstrapSectionDmServerCredential.isBootstrapServerIs()); + Assert.assertEquals("localhost", noSecLwM2MBootstrapSectionDmServerCredential.getHost()); + Assert.assertEquals(Integer.valueOf(5685), noSecLwM2MBootstrapSectionDmServerCredential.getPort()); TelemetryMappingConfiguration observeAttr = transportConfiguration.getObserveAttr(); Assert.assertEquals("batteryLevel", observeAttr.getKeyName().get("/3_1.2/0/9")); @@ -400,15 +400,15 @@ public class DeviceProfileEdgeTest extends AbstractEdgeTest { JacksonUtil.fromString(AbstractLwM2MIntegrationTest.TELEMETRY_WITHOUT_OBSERVE, TelemetryMappingConfiguration.class); transportConfiguration.setObserveAttr(observeAttrConfiguration); - List bootstrap = new ArrayList<>(); - AbstractLwM2MBootstrapServerCredential bootstrapServerCredential = new NoSecLwM2MBootstrapServerCredential(); - bootstrapServerCredential.setServerPublicKey("PUBLIC_KEY"); - bootstrapServerCredential.setShortServerId(123); - bootstrapServerCredential.setBootstrapServerIs(false); - bootstrapServerCredential.setHost("localhost"); - bootstrapServerCredential.setPort(5685); - bootstrap.add(bootstrapServerCredential); - transportConfiguration.setBootstrap(bootstrap); + List bootstrapSections = new ArrayList<>(); + AbstractLwM2MBootstrapServerCredential bootstrapSectionServerCredential = new NoSecLwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential.setServerPublicKey("PUBLIC_KEY"); + bootstrapSectionServerCredential.setShortServerId(123); + bootstrapSectionServerCredential.setBootstrapServerIs(false); + bootstrapSectionServerCredential.setHost("localhost"); + bootstrapSectionServerCredential.setPort(5685); + bootstrapSections.add(bootstrapSectionServerCredential); + transportConfiguration.setBootstrap(bootstrapSections); return transportConfiguration; } diff --git a/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java new file mode 100644 index 0000000000..71f2d6938d --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.install; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.context.ApplicationContext; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.service.component.ComponentDiscoveryService; +import org.thingsboard.server.service.install.DatabaseEntitiesUpgradeService; +import org.thingsboard.server.service.install.DatabaseSchemaSettingsService; +import org.thingsboard.server.service.install.EntityDatabaseSchemaService; +import org.thingsboard.server.service.install.InstallScripts; +import org.thingsboard.server.service.install.SystemDataLoaderService; +import org.thingsboard.server.service.install.TsDatabaseSchemaService; +import org.thingsboard.server.service.install.update.CacheCleanupService; +import org.thingsboard.server.service.install.update.DataUpdateService; + +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class ThingsboardInstallServiceTest { + + @Mock + private EntityDatabaseSchemaService entityDatabaseSchemaService; + @Mock + private TsDatabaseSchemaService tsDatabaseSchemaService; + @Mock + private DatabaseEntitiesUpgradeService databaseEntitiesUpgradeService; + @Mock + private ComponentDiscoveryService componentDiscoveryService; + @Mock + private ApplicationContext context; + @Mock + private SystemDataLoaderService systemDataLoaderService; + @Mock + private DataUpdateService dataUpdateService; + @Mock + private CacheCleanupService cacheCleanupService; + @Mock + private InstallScripts installScripts; + @Mock + private DatabaseSchemaSettingsService databaseSchemaVersionService; + + private ThingsboardInstallService installService; + + @BeforeEach + void setUp() { + installService = new ThingsboardInstallService(); + ReflectionTestUtils.setField(installService, "entityDatabaseSchemaService", entityDatabaseSchemaService); + ReflectionTestUtils.setField(installService, "tsDatabaseSchemaService", tsDatabaseSchemaService); + ReflectionTestUtils.setField(installService, "databaseEntitiesUpgradeService", databaseEntitiesUpgradeService); + ReflectionTestUtils.setField(installService, "componentDiscoveryService", componentDiscoveryService); + ReflectionTestUtils.setField(installService, "context", context); + ReflectionTestUtils.setField(installService, "systemDataLoaderService", systemDataLoaderService); + ReflectionTestUtils.setField(installService, "dataUpdateService", dataUpdateService); + ReflectionTestUtils.setField(installService, "cacheCleanupService", cacheCleanupService); + ReflectionTestUtils.setField(installService, "installScripts", installScripts); + ReflectionTestUtils.setField(installService, "databaseSchemaVersionService", databaseSchemaVersionService); + ReflectionTestUtils.setField(installService, "loadDemo", false); + ReflectionTestUtils.setField(installService, "persistToTelemetry", false); + } + + @Test + void testUpgradeMintsTheClusterIdBeforeStampingTheSchemaVersion() { + ReflectionTestUtils.setField(installService, "isUpgrade", true); + ReflectionTestUtils.setField(installService, "upgradeFromVersion", "4.3.1.3"); + + installService.performInstall(); + + InOrder inOrder = inOrder(entityDatabaseSchemaService, databaseSchemaVersionService); + inOrder.verify(entityDatabaseSchemaService).generateClusterIdIfNotExist(); + inOrder.verify(databaseSchemaVersionService).updateSchemaVersion(); + } + + @Test + void testFreshInstallMintsTheClusterId() { + ReflectionTestUtils.setField(installService, "isUpgrade", false); + + installService.performInstall(); + + verify(entityDatabaseSchemaService).generateClusterIdIfNotExist(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java index 82b0dbcd07..a03658175e 100644 --- a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java @@ -83,6 +83,7 @@ public class HashPartitionServiceTest { .setServiceId("tb-core-0") .addAllServiceTypes(Collections.singletonList(ServiceType.TB_CORE.name())) .build(); + when(serviceInfoProvider.getServiceInfo()).thenReturn(currentServer); List otherServers = new ArrayList<>(); for (int i = 1; i < SERVER_COUNT; i++) { otherServers.add(ServiceInfo.newBuilder() @@ -94,6 +95,14 @@ public class HashPartitionServiceTest { partitionService.recalculatePartitions(currentServer, otherServers); } + @Test + public void testIsKnownServiceId() { + assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "tb-core-0")).isTrue(); // current server + assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "tb-rule-1")).isTrue(); // other server + assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "unknown-id")).isFalse(); + assertThat(partitionService.isKnownServiceId(ServiceType.TB_RULE_ENGINE, "tb-core-0")).isFalse(); // wrong type + } + @Test public void testDispersionOnMillionDevices() { List devices = new ArrayList<>(); diff --git a/application/src/test/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldProcessingServiceTest.java b/application/src/test/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldProcessingServiceTest.java new file mode 100644 index 0000000000..925eaed40a --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldProcessingServiceTest.java @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.cf; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.TimeseriesSaveRequest; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.cf.configuration.OutputType; +import org.thingsboard.server.common.data.cf.configuration.TimeSeriesImmediateOutputStrategy; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.TbCallback; +import org.thingsboard.server.dao.attributes.AttributesService; +import org.thingsboard.server.dao.relation.RelationService; +import org.thingsboard.server.dao.timeseries.TimeseriesService; +import org.thingsboard.server.dao.usagerecord.ApiLimitService; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.Collections; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class DefaultCalculatedFieldProcessingServiceTest { + + private final TenantId tenantId = TenantId.fromUUID(UUID.fromString("e7f46b23-0c7d-42f5-9b06-fc35ab17af8a")); + private final DeviceId deviceId = new DeviceId(UUID.fromString("ccd71696-0586-422d-940e-755a41ec3b0d")); + + @Mock + private AttributesService attributesService; + @Mock + private TimeseriesService timeseriesService; + @Mock + private ApiLimitService apiLimitService; + @Mock + private RelationService relationService; + @Mock + private OwnerService ownerService; + @Mock + private TbClusterService clusterService; + @Mock + private TelemetrySubscriptionService tsSubService; + @Mock + private PartitionService partitionService; + + private DefaultCalculatedFieldProcessingService service; + + @BeforeEach + public void setUp() { + service = new DefaultCalculatedFieldProcessingService(attributesService, timeseriesService, apiLimitService, + relationService, ownerService, clusterService, tsSubService, partitionService); + } + + @Test + public void givenTimeSeriesOutputWithoutTtl_whenProcessResult_thenTenantProfileDefaultStorageTtlIsUsed() { + when(apiLimitService.getLimit(eq(tenantId), any())).thenReturn(30L); + + service.processResult(tenantId, deviceId, "cf", buildTimeSeriesResult(0L), Collections.emptyList(), TbCallback.EMPTY); + + assertThat(captureSaveRequest().getTtl()).isEqualTo(TimeUnit.DAYS.toSeconds(30)); + } + + @Test + public void givenTimeSeriesOutputWithCustomTtl_whenProcessResult_thenCustomTtlIsUsed() { + service.processResult(tenantId, deviceId, "cf", buildTimeSeriesResult(3600L), Collections.emptyList(), TbCallback.EMPTY); + + assertThat(captureSaveRequest().getTtl()).isEqualTo(3600L); + verify(apiLimitService, never()).getLimit(any(), any()); + } + + private TelemetryCalculatedFieldResult buildTimeSeriesResult(long ttl) { + return TelemetryCalculatedFieldResult.builder() + .type(OutputType.TIME_SERIES) + .outputStrategy(new TimeSeriesImmediateOutputStrategy(ttl, true, true, true, true)) + .result(JacksonUtil.newObjectNode().put("result", 42)) + .build(); + } + + private TimeseriesSaveRequest captureSaveRequest() { + ArgumentCaptor captor = ArgumentCaptor.forClass(TimeseriesSaveRequest.class); + verify(tsSubService).saveTimeseries(captor.capture()); + return captor.getValue(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFixtures.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFixtures.java new file mode 100644 index 0000000000..28b68841ec --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFixtures.java @@ -0,0 +1,126 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.common.util.JacksonUtil; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.HexFormat; + +/** + * Golden {@code TBICBDL1} vectors; {@code vectors.json} records each file's size and SHA-256. + */ +public final class CommunityGrantBundleFixtures { + + public static final String CLUSTER_ID = "3f2a1c44-9f3b-11ee-8c90-0242ac120002"; + public static final String CHALLENGE = "Y2hhbGxlbmdlLTAwMS1ieXRlcw=="; + public static final String PORTAL_PUBLIC_KEY = "KTA3PkVMU1phaG92fYSLkpmgp661vMPK0djf5u30+wI="; + public static final int KEY_ID = 1; + public static final long REFERENCE_MILLIS = 1787788800000L; + public static final long ISSUED_AT = 4102444800000L; + public static final long CHALLENGE_EXPIRES_AT = 4102531200000L; + public static final String CHECKER_FILE_NAME = "tb-instance-check_linux_amd64"; + + /** Verifies the golden bundle's {@code RELSIG} under {@link #KEY_ID}. */ + public static final String RELEASE_PUBLIC_KEY = "Nqbrd0SVV4w9yZWl0cgu9I7G/URhdL3PN8mWRwnWDzE="; + public static final String TRUSTS_RELEASE_KEY = KEY_ID + ":" + RELEASE_PUBLIC_KEY; + + private static final String RELSIG_HEX = "544249435349473101013ab2afc43727f37b9388510b6c0e0b7d920a738ee" + + "df45aae5169aa7d97abe3f73796b907168188e0685566bbf792ae0977b6c38072e684ee149d6bcf161fc004"; + + private static final String VECTOR_RESOURCE_DIR = "/community-grant/"; + + private CommunityGrantBundleFixtures() { + } + + public static byte[] vector(String fileName) { + return resource(VECTOR_RESOURCE_DIR + fileName); + } + + public static JsonNode vectorsManifest() { + return JacksonUtil.fromBytes(resource(VECTOR_RESOURCE_DIR + "vectors.json")); + } + + public static byte[] relsig() { + return HexFormat.of().parseHex(RELSIG_HEX); + } + + public static byte[] standInChecker() { + byte[] checker = new byte[64]; + for (int i = 0; i < checker.length; i++) { + checker[i] = (byte) (i * 7 + 3); + } + return checker; + } + + public static ObjectNode validManifest() { + ObjectNode manifest = JacksonUtil.newObjectNode(); + manifest.put("bundleVersion", 1); + manifest.put("os", "linux"); + manifest.put("arch", "amd64"); + manifest.put("clusterId", CLUSTER_ID); + manifest.set("checkerInput", validCheckerInput()); + manifest.put("challengeExpiresAt", CHALLENGE_EXPIRES_AT); + manifest.put("issuedAt", ISSUED_AT); + manifest.put("checkerFileName", CHECKER_FILE_NAME); + return manifest; + } + + public static ObjectNode validCheckerInput() { + ObjectNode checkerInput = JacksonUtil.newObjectNode(); + checkerInput.put("clusterId", CLUSTER_ID); + checkerInput.put("keyId", KEY_ID); + checkerInput.put("publicKey", PORTAL_PUBLIC_KEY); + checkerInput.put("challenge", CHALLENGE); + checkerInput.put("referenceMillis", REFERENCE_MILLIS); + return checkerInput; + } + + public static byte[] bundle(JsonNode manifest) { + return bundle(JacksonUtil.toString(manifest)); + } + + public static byte[] bundle(String manifestJson) { + return bundle(manifestJson.getBytes(StandardCharsets.UTF_8)); + } + + public static byte[] bundle(byte[] manifest) { + return bundle(relsig(), manifest, standInChecker()); + } + + public static byte[] bundle(byte[] relsig, byte[] manifest, byte[] checker) { + return frame((byte) 1, manifest.length, checker.length, relsig, manifest, checker); + } + + /** Declared lengths are written as given, so the header can disagree with the body. */ + public static byte[] frame(byte version, long declaredManifestLen, long declaredCheckerLen, + byte[] relsig, byte[] manifest, byte[] checker) { + return ByteBuffer.allocate(CommunityGrantOfflineBundle.HEADER_LEN + manifest.length + checker.length) + .put("TBICBDL1".getBytes(StandardCharsets.US_ASCII)) + .put(version) + .putInt((int) declaredManifestLen) + .putInt((int) declaredCheckerLen) + .put(relsig) + .put(manifest) + .put(checker) + .array(); + } + + private static byte[] resource(String path) { + try (InputStream in = CommunityGrantBundleFixtures.class.getResourceAsStream(path)) { + if (in == null) { + throw new IllegalStateException(path + " is not on the test classpath"); + } + return in.readAllBytes(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStoreTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStoreTest.java new file mode 100644 index 0000000000..1c9efca6be --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStoreTest.java @@ -0,0 +1,305 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.id.AdminSettingsId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.exception.DataValidationException; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CommunityGrantFlowStateStoreTest { + + @Mock + private AdminSettingsService adminSettingsService; + + @InjectMocks + private CommunityGrantFlowStateStore store; + + @Test + void testGetReturnsTheInitialStateWhenNothingIsStored() { + givenStored(null); + + CommunityGrantFlowState state = store.get(); + + assertThat(state.getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + assertThat(state.getMode()).isEqualTo(CommunityGrantMode.ONLINE); + assertThat(state.getSignUpUrl()).isNull(); + assertThat(state.getLastPolledAt()).isNull(); + } + + @Test + void testGetReadsTheStoredState() { + CommunityGrantFlowState stored = CommunityGrantFlowState.initial(); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setSignUpUrl("https://portal.example/signup?clusterId=x&claimToken=y&offline=true"); + stored.setLastPolledAt(42L); + givenStored(settingsOf(stored)); + + CommunityGrantFlowState state = store.get(); + + assertThat(state.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(state.getMode()).isEqualTo(CommunityGrantMode.OFFLINE); + assertThat(state.getSignUpUrl()) + .isEqualTo("https://portal.example/signup?clusterId=x&claimToken=y&offline=true"); + assertThat(state.getLastPolledAt()).isEqualTo(42L); + } + + @Test + void testUpdateRoundTripsTheFieldsTheFlowCarriesBetweenPolls() { + givenStored(null); + + store.update(state -> { + state.setState(CommunityGrantState.COLLECTING); + state.setStartedAt(1234L); + state.setLastOfflineCheckAt(5678L); + state.setParkReason(CommunityGrantParkReason.CHECK_FAILED); + return state; + }); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AdminSettings.class); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), captor.capture()); + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, CommunityGrantFlowStateStore.SETTINGS_KEY)) + .thenReturn(captor.getValue()); + + CommunityGrantFlowState reread = store.get(); + + assertThat(reread.getStartedAt()).isEqualTo(1234L); + assertThat(reread.getLastOfflineCheckAt()).isEqualTo(5678L); + assertThat(reread.getParkReason()).isEqualTo(CommunityGrantParkReason.CHECK_FAILED); + } + + @Test + void testUpdateCreatesTheSettingsRowOnFirstWrite() { + givenStored(null); + + CommunityGrantFlowState updated = store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + state.setSignUpUrl("https://portal.example/signup"); + return state; + }); + + assertThat(updated.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + ArgumentCaptor captor = ArgumentCaptor.forClass(AdminSettings.class); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), captor.capture()); + AdminSettings saved = captor.getValue(); + assertThat(saved.getKey()).isEqualTo(CommunityGrantFlowStateStore.SETTINGS_KEY); + assertThat(saved.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID); + JsonNode json = saved.getJsonValue(); + assertThat(json.get("state").asText()).isEqualTo("AWAITING_SIGNUP"); + assertThat(json.get("signUpUrl").asText()).isEqualTo("https://portal.example/signup"); + } + + @Test + void testUpdatePreservesFieldsTheUpdaterDoesNotTouch() { + CommunityGrantFlowState stored = CommunityGrantFlowState.initial(); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setSignUpUrl("https://portal.example/signup"); + givenStored(settingsOf(stored)); + + store.update(state -> { + state.setLastPolledAt(100L); + return state; + }); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AdminSettings.class); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), captor.capture()); + JsonNode json = captor.getValue().getJsonValue(); + assertThat(json.get("signUpUrl").asText()).isEqualTo("https://portal.example/signup"); + assertThat(json.get("lastPolledAt").asLong()).isEqualTo(100L); + } + + @Test + void testGetFallsBackToTheInitialStateOnUnreadableJson() { + givenStored(settingsOf("{\"state\":\"NOT_A_STATE\"}")); + + assertThat(store.get().getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + } + + @Test + void testUpdateThrowsOnUnreadableJsonAndLeavesTheStoredDocumentUntouched() { + givenStored(settingsOf("{\"state\":\"NOT_A_STATE\"}")); + + assertThatThrownBy(() -> store.update(state -> state)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("could not be parsed"); + + verify(adminSettingsService, never()).saveAdminSettings(any(), any()); + } + + @Test + void testUpdateRetriesAsAnUpdateWhenAConcurrentFirstWriteWinsTheCreateRace() { + CommunityGrantFlowState winnerState = CommunityGrantFlowState.initial(); + winnerState.setState(CommunityGrantState.COLLECTING); + winnerState.setSignUpUrl("https://portal.example/signup?winner=true"); + AdminSettings winnerRow = new AdminSettings(); + winnerRow.setId(new AdminSettingsId(UUID.randomUUID())); + winnerRow.setTenantId(TenantId.SYS_TENANT_ID); + winnerRow.setKey(CommunityGrantFlowStateStore.SETTINGS_KEY); + winnerRow.setJsonValue(JacksonUtil.valueToTree(winnerState)); + // No row on the first read; the re-read after the lost create finds the other node's row. + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, CommunityGrantFlowStateStore.SETTINGS_KEY)) + .thenReturn(null, winnerRow); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), argThat(s -> s.getId() == null))) + .thenThrow(new DataValidationException("Admin settings with such name already exists!")); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), argThat(s -> s != null && s.getId() != null))) + .thenAnswer(invocation -> invocation.getArgument(1)); + + CommunityGrantFlowState result = store.update(state -> { + state.setLastPolledAt(999L); + return state; + }); + + assertThat(result.getState()).isEqualTo(CommunityGrantState.COLLECTING); + assertThat(result.getSignUpUrl()).isEqualTo("https://portal.example/signup?winner=true"); + assertThat(result.getLastPolledAt()).isEqualTo(999L); + verify(adminSettingsService, times(2)).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testAnUnreadableWinnerDocumentThrowsAndKeepsTheCreateRaceAttached() { + AdminSettings winnerRow = new AdminSettings(); + winnerRow.setId(new AdminSettingsId(UUID.randomUUID())); + winnerRow.setTenantId(TenantId.SYS_TENANT_ID); + winnerRow.setKey(CommunityGrantFlowStateStore.SETTINGS_KEY); + winnerRow.setJsonValue(JacksonUtil.toJsonNode("{\"state\":\"NOT_A_STATE\"}")); + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, CommunityGrantFlowStateStore.SETTINGS_KEY)) + .thenReturn(null, winnerRow); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), argThat(s -> s.getId() == null))) + .thenThrow(new DataValidationException("Admin settings with such name already exists!")); + + assertThatThrownBy(() -> store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("could not be parsed") + .satisfies(e -> assertThat(e.getSuppressed()) + .as("the create race that led to the re-read") + .anySatisfy(suppressed -> assertThat(suppressed) + .isInstanceOf(DataValidationException.class))); + + verify(adminSettingsService, times(1)).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testUpdateDoesNotRetryWhenTheRejectedWriteWasAnUpdateRatherThanACreate() { + AdminSettings stored = settingsOf(CommunityGrantFlowState.initial()); + stored.setId(new AdminSettingsId(UUID.randomUUID())); + givenStored(stored); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class))) + .thenThrow(new DataValidationException("Admin settings with such name already exists!")); + + assertThatThrownBy(() -> store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + })).isInstanceOf(DataValidationException.class); + + verify(adminSettingsService, times(1)).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testUpdateDoesNotRetryWhenTheRejectedCreateFindsNoWinnerRow() { + givenStored(null); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class))) + .thenThrow(new DataValidationException("Admin settings with such name already exists!")); + + assertThatThrownBy(() -> store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + })).isInstanceOf(DataValidationException.class); + + verify(adminSettingsService, times(1)).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testUpdateSucceedsWhenTheStoredDocumentParsesButCarriesNoState() { + givenStored(settingsOf("{}")); + + CommunityGrantFlowState updated = store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + }); + + assertThat(updated.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testUpdateSucceedsWhenTheStoredJsonValueIsAJsonNull() { + givenStored(settingsOf("null")); + + CommunityGrantFlowState updated = store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + }); + + assertThat(updated.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testGetDefaultsTheModeWhenTheStoredDocumentHasNone() { + givenStored(settingsOf("{\"state\":\"COLLECTING\"}")); + + CommunityGrantFlowState state = store.get(); + + assertThat(state.getState()).isEqualTo(CommunityGrantState.COLLECTING); + assertThat(state.getMode()).isEqualTo(CommunityGrantMode.ONLINE); + } + + @Test + void testGetIgnoresUnknownJsonFieldsInsteadOfFailing() { + givenStored(settingsOf("{\"state\":\"AWAITING_SIGNUP\",\"futureField\":1}")); + + assertThat(store.get().getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + } + + private AdminSettings settingsOf(CommunityGrantFlowState state) { + return settingsOf(JacksonUtil.valueToTree(state)); + } + + private AdminSettings settingsOf(String json) { + return settingsOf(JacksonUtil.toJsonNode(json)); + } + + private AdminSettings settingsOf(JsonNode jsonValue) { + AdminSettings settings = new AdminSettings(); + settings.setTenantId(TenantId.SYS_TENANT_ID); + settings.setKey(CommunityGrantFlowStateStore.SETTINGS_KEY); + settings.setJsonValue(jsonValue); + return settings; + } + + private void givenStored(AdminSettings settings) { + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, CommunityGrantFlowStateStore.SETTINGS_KEY)) + .thenReturn(settings); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsnTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsnTest.java new file mode 100644 index 0000000000..92523c7b43 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsnTest.java @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CommunityGrantLibpqDsnTest { + + private static final String URL = "jdbc:postgresql://localhost:5432/thingsboard"; + + @Test + void testTheJdbcUrlIsRewrittenAsALibpqConnectionString() { + assertThat(CommunityGrantLibpqDsn.from(URL, "postgres", "secret")) + .isEqualTo("postgres://postgres:secret@localhost:5432/thingsboard"); + assertThat(CommunityGrantLibpqDsn.from(URL, "postgres", "p@ss/word?x")) + .isEqualTo("postgres://postgres:p%40ss%2Fword%3Fx@localhost:5432/thingsboard"); + // JDBC driver parameters are not libpq's, so they are dropped. + assertThat(CommunityGrantLibpqDsn.from( + "jdbc:postgresql://db.internal:5432/tb?ApplicationName=ThingsBoard&ssl=false", "postgres", "secret")) + .isEqualTo("postgres://postgres:secret@db.internal:5432/tb"); + } + + // URI leaves ':' in userinfo unescaped, but libpq splits user and password at the first colon. + @Test + void testAUsernameContainingAColonIsEncodedSeparately() { + assertThat(CommunityGrantLibpqDsn.from(URL, "a:b", "c")) + .isEqualTo("postgres://a%3Ab:c@localhost:5432/thingsboard"); + } + + // The url may carry credentials, so the refusal quotes neither it nor a cause that holds it. + @Test + void testAMalformedDatasourceUrlIsRejectedWithoutQuotingTheUrl() { + assertThatThrownBy(() -> CommunityGrantLibpqDsn.from( + "jdbc:postgresql://host:5432/tb?user=admin&password=hunter2^{}", "postgres", "secret")) + .isInstanceOf(IllegalStateException.class) + .satisfies(e -> { + assertThat(e.getMessage()).doesNotContain("hunter2"); + assertThat(e.getMessage()).doesNotContain("host:5432"); + assertThat(e).hasNoCause(); + }); + } + + @Test + void testANonPostgresqlJdbcUrlIsRejected() { + assertThatThrownBy(() -> CommunityGrantLibpqDsn.from("jdbc:mysql://localhost:3306/thingsboard", + "postgres", "secret")).isInstanceOf(IllegalStateException.class); + } + + @Test + void testAUrlWithNoDatabaseNameIsRejected() { + assertThatThrownBy(() -> CommunityGrantLibpqDsn.from("jdbc:postgresql://localhost:5432", + "postgres", "secret")).isInstanceOf(IllegalStateException.class); + } + + @Test + void testABlankUsernameIsRejected() { + assertThatThrownBy(() -> CommunityGrantLibpqDsn.from(URL, "", "secret")) + .isInstanceOf(IllegalStateException.class); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundleTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundleTest.java new file mode 100644 index 0000000000..2a565e4a2f --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundleTest.java @@ -0,0 +1,421 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.IntNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.service.community_grant.CommunityGrantBundleFormatException.Reason; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.CHALLENGE; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.CHALLENGE_EXPIRES_AT; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.CHECKER_FILE_NAME; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.CLUSTER_ID; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.ISSUED_AT; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.KEY_ID; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.PORTAL_PUBLIC_KEY; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.REFERENCE_MILLIS; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.bundle; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.frame; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.relsig; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.standInChecker; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.validCheckerInput; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.validManifest; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.vector; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.vectorsManifest; + +/** + * Vectors 05-07 are malformed in two ways at once, so they pin the order of the checks as well as the reasons. + */ +class CommunityGrantOfflineBundleTest { + + private static final String CHECKER_SHA256 = + "39e3d7b6b5d075d37d053ad89b24b41bef4f3c29760c84447cab3f3be1882241"; + + @ParameterizedTest(name = "{0}") + @MethodSource("goldenVectors") + void testEveryGoldenVectorHasItsRecordedSizeDigestAndOutcome(String fileName, int sizeBytes, String sha256, + String outcome, String reason) { + byte[] data = vector(fileName); + + assertThat(data).hasSize(sizeBytes); + assertThat(HexFormat.of().formatHex(sha256(data))).isEqualTo(sha256); + if ("REJECT".equals(outcome)) { + assertThat(reasonOf(data)).isEqualTo(Reason.valueOf(reason.substring("E_".length()))); + } else { + assertThatCode(() -> CommunityGrantOfflineBundle.parse(data)).doesNotThrowAnyException(); + } + } + + @Test + void testAFileShorterThanTheHeaderIsRefusedBeforeAnythingIsRead() { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector("02-too-short.tbicb"))) + .isInstanceOf(CommunityGrantBundleFormatException.class) + .hasMessageContaining("The uploaded file is 90 bytes") + .hasMessageContaining("shorter than the 91-byte enrollment bundle header"); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 90}) + void testNoInputAndAnEmptyInputAreRefusedOnTheLengthFloor(int size) { + assertThat(reasonOf(new byte[size])).isEqualTo(Reason.TOO_SHORT); + assertThat(reasonOf(null)).isEqualTo(Reason.TOO_SHORT); + } + + @Test + void testTheVersionRefusalNamesBothTheDeclaredAndTheSupportedVersion() { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector("04-unknown-version.tbicb"))) + .hasMessageContaining("declares format version 2") + .hasMessageContaining("supports version 1 only"); + } + + @ParameterizedTest + @CsvSource({"05-manifest-len-zero.tbicb, 0", "06-manifest-len-too-large.tbicb, 8193"}) + void testTheManifestLengthRefusalNamesTheDeclaredValueAndThePermittedRange(String fileName, String declared) { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector(fileName))) + .hasMessageContaining("declares a manifest of " + declared + " bytes") + .hasMessageContaining("permitted range of 1 to 8192 bytes"); + } + + @Test + void testTheCheckerLengthRefusalNamesTheDeclaredValue() { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector("07-checker-len-zero.tbicb"))) + .hasMessageContaining("declares a checker of 0 bytes"); + } + + // Exact, not at-least: otherwise anything could be appended to a genuine bundle. + @ParameterizedTest + @CsvSource({"08-truncated-mid-manifest.tbicb, 301", "09-truncated-mid-checker.tbicb, 543", + "10-trailing-byte.tbicb, 576"}) + void testTheExactnessRefusalNamesBothTheExpectedAndTheActualTotal(String fileName, String actualTotal) { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector(fileName))) + .hasMessageContaining("need a file of 575 bytes") + .hasMessageContaining("uploaded file is " + actualTotal + " bytes"); + } + + // Decoding with new String(bytes, UTF_8) would substitute replacement characters and report bad JSON instead. + @Test + void testAManifestThatIsNotUtf8IsRefusedAsNotUtf8RatherThanAsNotJson() { + assertThat(reasonOf(vector("11-manifest-not-utf8.tbicb"))).isEqualTo(Reason.MANIFEST_NOT_UTF8); + } + + @ParameterizedTest + @ValueSource(strings = {"[1,2,3]", "\"x\"", "7", "null", "true"}) + void testAManifestThatIsNotAJsonObjectIsRefused(String manifestJson) { + assertThat(reasonOf(bundle(manifestJson))).isEqualTo(Reason.MANIFEST_NOT_JSON); + } + + @Test + void testAMissingManifestFieldIsRefusedByName() { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector("13-manifest-missing-field.tbicb"))) + .hasMessageContaining("clusterId"); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("manifestsBrokenOneRuleAtATime") + void testEveryManifestRuleIsEnforcedAndNamesItsOwnKey(String description, JsonNode manifest, String key) { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(bundle(manifest))) + .isInstanceOf(CommunityGrantBundleFormatException.class) + .hasMessageContaining(key); + assertThat(reasonOf(bundle(manifest))).isEqualTo(Reason.MANIFEST_FIELD); + } + + // Parsers disagree about which duplicate wins, so the two ends could read different values. + @Test + void testADuplicateManifestKeyIsRefusedByName() { + String manifestJson = JacksonUtil.toString(validManifest()) + .replace("\"checkerInput\":", "\"clusterId\":\"" + CLUSTER_ID + "\",\"checkerInput\":"); + + assertThat(reasonOf(bundle(manifestJson))).isEqualTo(Reason.MANIFEST_FIELD); + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(bundle(manifestJson))) + .hasMessageContaining("clusterId"); + } + + @Test + void testTheReaderDoesNotDependOnTheWritersManifestEncoding() { + ObjectNode reordered = JacksonUtil.newObjectNode(); + List keys = new ArrayList<>(); + validManifest().fieldNames().forEachRemaining(keys::add); + for (int i = keys.size() - 1; i >= 0; i--) { + reordered.set(keys.get(i), validManifest().get(keys.get(i))); + } + String reformatted = reordered.toPrettyString() + "\n"; + + assertThat(CommunityGrantOfflineBundle.parse(bundle(reformatted))) + .usingRecursiveComparison() + .isEqualTo(CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb"))); + } + + @Test + void testAnUnknownManifestKeyIsIgnored() { + ObjectNode manifest = validManifest(); + manifest.put("supportRef", "abc"); + manifest.putObject("futureDetail").put("nested", 1); + manifest.putArray("futureList").add(1).add(2); + + assertThat(CommunityGrantOfflineBundle.parse(bundle(manifest))) + .usingRecursiveComparison() + .isEqualTo(CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb"))); + } + + @Test + void testBothDeclaredLengthsAreReadAsUnsigned() { + byte[] manifest = JacksonUtil.toString(validManifest()).getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse( + frame((byte) 1, manifest.length, 0xFFFFFFFFL, relsig(), manifest, standInChecker()))) + .hasMessageContaining("4294967295") + .hasMessageNotContaining("-1"); + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse( + frame((byte) 1, 0xFFFFFFFFL, standInChecker().length, relsig(), manifest, standInChecker()))) + .hasMessageContaining("4294967295") + .hasMessageNotContaining("-1"); + } + + @Test + void testADeclaredLengthNeverSizesAnAllocation() { + byte[] manifest = {'{'}; + + assertThat(reasonOf(frame((byte) 1, 1, Integer.MAX_VALUE, relsig(), manifest, new byte[0]))) + .isEqualTo(Reason.LENGTH_MISMATCH); + } + + @Test + void testACorruptSignatureParsesAndIsHandedOnUnchanged() { + byte[] data = vector("15-relsig-not-tbicsig1.tbicb"); + + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(data); + + assertThat(parsed.signature()).hasSize(74).isEqualTo(Arrays.copyOfRange(data, 17, 91)); + assertThat(parsed.signature()).isNotEqualTo(relsig()); + } + + @Test + void testAnExpiredChallengeParsesAndReportsItselfOnlyAsAdvisory() { + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(vector("14-expired-challenge.tbicb")); + + assertThat(parsed.challengeExpiresAt()).isEqualTo(1609545600000L); + assertThat(parsed.isChallengeExpired(System.currentTimeMillis())).isTrue(); + assertThat(parsed.checkerInput()).isEqualTo(goldenCheckerInput()); + } + + @Test + void testTheExpiryBoundaryInstantIsStillLive() { + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb")); + + assertThat(parsed.isChallengeExpired(CHALLENGE_EXPIRES_AT - 1)).isFalse(); + assertThat(parsed.isChallengeExpired(CHALLENGE_EXPIRES_AT)).isFalse(); + assertThat(parsed.isChallengeExpired(CHALLENGE_EXPIRES_AT + 1)).isTrue(); + } + + @Test + void testTheGoldenBundleRoundTripsEveryValueItCarries() { + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb")); + + assertThat(parsed.os()).isEqualTo("linux"); + assertThat(parsed.arch()).isEqualTo("amd64"); + assertThat(parsed.clusterId()).isEqualTo(UUID.fromString(CLUSTER_ID)); + assertThat(parsed.checkerFileName()).isEqualTo(CHECKER_FILE_NAME); + assertThat(parsed.issuedAt()).isEqualTo(ISSUED_AT); + assertThat(parsed.challengeExpiresAt()).isEqualTo(CHALLENGE_EXPIRES_AT); + assertThat(parsed.checkerInput()).isEqualTo(goldenCheckerInput()); + assertThat(parsed.signature()).isEqualTo(relsig()); + assertThat(parsed.checker()).isEqualTo(standInChecker()); + assertThat(HexFormat.of().formatHex(sha256(parsed.checker()))).isEqualTo(CHECKER_SHA256); + } + + @Test + void testTheSynthesizedManifestIsTheOneTheVectorsRecord() { + JsonNode material = vectorsManifest().get("fixtureMaterial"); + + assertThat(JacksonUtil.toString(validManifest())).isEqualTo(material.get("validManifestJson").asText()); + assertThat(material.get("referenceMillis").asLong()).isEqualTo(REFERENCE_MILLIS); + } + + @Test + void testTheCheckerInputIsHandedOnUnreadAndCompact() { + ObjectNode checkerInput = validCheckerInput(); + checkerInput.put("keyId", 0); + checkerInput.put("publicKey", "not base64!!"); + checkerInput.remove("challenge"); + checkerInput.put("futureInput", true); + String manifestJson = JacksonUtil.toString(validManifest().set("checkerInput", checkerInput)) + .replace("\"futureInput\":", "\n \"futureInput\" : "); + + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(bundle(manifestJson)); + + assertThat(parsed.checkerInput().json()).isEqualTo("{\"clusterId\":\"" + CLUSTER_ID + "\",\"keyId\":0," + + "\"publicKey\":\"not base64!!\",\"referenceMillis\":" + REFERENCE_MILLIS + ",\"futureInput\":true}"); + } + + @Test + void testADuplicateKeyInsideTheCheckerInputIsRefusedByName() { + String manifestJson = JacksonUtil.toString(validManifest()) + .replace("\"referenceMillis\":", "\"keyId\":2,\"referenceMillis\":"); + + assertThat(reasonOf(bundle(manifestJson))).isEqualTo(Reason.MANIFEST_FIELD); + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(bundle(manifestJson))) + .hasMessageContaining("keyId"); + } + + // The checker size cap is applied by CommunityGrantReportRunner to the extracted checker, not by the parser. + @Test + void testABundleLargerThanTheCheckerCapStillParses() { + byte[] oversized = new byte[33554433]; + Arrays.fill(oversized, (byte) 7); + byte[] manifest = JacksonUtil.toString(validManifest()).getBytes(StandardCharsets.UTF_8); + + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse( + frame((byte) 1, manifest.length, oversized.length, relsig(), manifest, oversized)); + + assertThat(parsed.checker()).hasSize(oversized.length); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("goldenVectors") + void testNoRefusalMessageIsUnsafeToPublish(String fileName, int sizeBytes, String sha256, String outcome) { + if (!"REJECT".equals(outcome)) { + return; + } + String message = messageOf(vector(fileName)); + + assertThat(message.toLowerCase()).doesNotContain("password", "secret", "token", "postgres://", "jdbc:"); + assertThat(message).doesNotContain(PORTAL_PUBLIC_KEY, CHALLENGE, CLUSTER_ID); + } + + @Test + void testTheExtractedMembersVerifyAgainstEachOtherThroughTheRealVerifier() { + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb")); + + assertThatCode(() -> verifierTrusting(CommunityGrantBundleFixtures.TRUSTS_RELEASE_KEY) + .verify(parsed.checker(), parsed.signature())).doesNotThrowAnyException(); + assertThatThrownBy(() -> verifierTrusting(CommunityGrantSigningFixtures.TRUSTS_A) + .verify(parsed.checker(), parsed.signature())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CommunityGrantReleaseSignatureVerifier verifierTrusting(String configured) { + CommunityGrantReleaseSignatureVerifier verifier = new CommunityGrantReleaseSignatureVerifier(); + ReflectionTestUtils.setField(verifier, "checkerReleasePublicKeys", configured); + verifier.init(); + return verifier; + } + + private static Stream goldenVectors() { + List vectors = new ArrayList<>(); + for (JsonNode fixture : vectorsManifest().get("fixtures")) { + vectors.add(Arguments.of(fixture.get("file").asText(), fixture.get("sizeBytes").asInt(), + fixture.get("sha256").asText(), fixture.get("expectedOutcome").asText(), + fixture.get("expectedReason").asText(null))); + } + return vectors.stream(); + } + + private static Stream manifestsBrokenOneRuleAtATime() { + List cases = new ArrayList<>(); + List keys = List.of("bundleVersion", "os", "arch", "clusterId", "checkerInput", + "challengeExpiresAt", "issuedAt", "checkerFileName"); + for (String key : keys) { + cases.add(Arguments.of(key + " missing", withoutKey(key), key)); + cases.add(Arguments.of(key + " of the wrong JSON type", withValue(key, + validManifest().get(key).isTextual() ? IntNode.valueOf(1) : TextNode.valueOf("x")), key)); + } + cases.add(Arguments.of("bundleVersion disagreeing with the version byte", withInt("bundleVersion", 2), "bundleVersion")); + cases.add(Arguments.of("an unknown os", withText("os", "solaris"), "os")); + cases.add(Arguments.of("an unknown arch", withText("arch", "riscv64"), "arch")); + cases.add(Arguments.of("a clusterId that is not a UUID", withText("clusterId", "not-a-uuid"), "clusterId")); + cases.add(Arguments.of("an uppercase clusterId", withText("clusterId", CLUSTER_ID.toUpperCase(Locale.ROOT)), "clusterId")); + cases.add(Arguments.of("an empty checkerInput", withValue("checkerInput", JacksonUtil.newObjectNode()), "checkerInput")); + cases.add(Arguments.of("a checkerInput that is an array", withValue("checkerInput", JacksonUtil.newArrayNode().add(1)), "checkerInput")); + cases.add(Arguments.of("a null checkerInput", withValue("checkerInput", NullNode.getInstance()), "checkerInput")); + cases.add(Arguments.of("challengeExpiresAt of zero", withLong("challengeExpiresAt", 0), "challengeExpiresAt")); + cases.add(Arguments.of("a negative challengeExpiresAt", withLong("challengeExpiresAt", -1), "challengeExpiresAt")); + cases.add(Arguments.of("issuedAt of zero", withLong("issuedAt", 0), "issuedAt")); + cases.add(Arguments.of("issuedAt after the expiry", withLong("issuedAt", CHALLENGE_EXPIRES_AT + 1), "issuedAt")); + cases.add(Arguments.of("an empty checkerFileName", withText("checkerFileName", ""), "checkerFileName")); + cases.add(Arguments.of("a checkerFileName over 255 characters", withText("checkerFileName", "x".repeat(256)), "checkerFileName")); + cases.add(Arguments.of("a checkerFileName carrying a path", withText("checkerFileName", "bin/tb-instance-check"), "checkerFileName")); + cases.add(Arguments.of("a checkerFileName carrying a windows path", withText("checkerFileName", "bin\\tb-instance-check"), "checkerFileName")); + cases.add(Arguments.of("a checkerFileName carrying a traversal", withText("checkerFileName", "../tb-instance-check"), "checkerFileName")); + return cases.stream(); + } + + private static JsonNode withoutKey(String key) { + ObjectNode manifest = validManifest(); + manifest.remove(key); + return manifest; + } + + private static JsonNode withValue(String key, JsonNode value) { + return validManifest().set(key, value); + } + + private static JsonNode withText(String key, String value) { + return validManifest().put(key, value); + } + + private static JsonNode withInt(String key, int value) { + return validManifest().put(key, value); + } + + private static JsonNode withLong(String key, long value) { + return validManifest().put(key, value); + } + + private static CommunityGrantCheckerInput goldenCheckerInput() { + return new CommunityGrantCheckerInput("{\"clusterId\":\"" + CLUSTER_ID + "\",\"keyId\":" + KEY_ID + + ",\"publicKey\":\"" + PORTAL_PUBLIC_KEY + "\",\"challenge\":\"" + CHALLENGE + + "\",\"referenceMillis\":" + REFERENCE_MILLIS + "}"); + } + + private static Reason reasonOf(byte[] data) { + try { + CommunityGrantOfflineBundle.parse(data); + } catch (CommunityGrantBundleFormatException e) { + return e.getReason(); + } + throw new AssertionError("Expected the bundle to be refused, but it parsed"); + } + + private static String messageOf(byte[] data) { + try { + CommunityGrantOfflineBundle.parse(data); + } catch (CommunityGrantBundleFormatException e) { + return e.getMessage(); + } + throw new AssertionError("Expected the bundle to be refused, but it parsed"); + } + + private static byte[] sha256(byte[] data) { + try { + return MessageDigest.getInstance("SHA-256").digest(data); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStoreTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStoreTest.java new file mode 100644 index 0000000000..2c93740015 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStoreTest.java @@ -0,0 +1,216 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; + +import java.util.concurrent.atomic.AtomicLong; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CommunityGrantOfflineReportStoreTest { + + private static final String REPORT = "-----BEGIN TB INSTANCE CHECK-----\nbody"; + + @Mock + private AdminSettingsService adminSettingsService; + + private CommunityGrantOfflineReportStore store; + + private AdminSettings stored; + + /** A counter, so two writes microseconds apart still get distinct instants. */ + private final AtomicLong clock = new AtomicLong(); + + @BeforeEach + void setUp() { + // Hands out a copy, so a save that threw cannot change what the next read sees. + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY)) + .thenAnswer(invocation -> stored == null ? null : new AdminSettings(stored)); + saveSucceeds(); + store = node(); + } + + /** A restart or a second cluster node over the same settings. */ + private CommunityGrantOfflineReportStore node() { + CommunityGrantOfflineReportStore node = new CommunityGrantOfflineReportStore(adminSettingsService); + node.setClock(clock::incrementAndGet); + return node; + } + + private void saveSucceeds() { + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any())) + .thenAnswer(invocation -> { + AdminSettings saved = invocation.getArgument(1); + return stored = new AdminSettings(saved); + }); + } + + private void saveFails() { + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any())) + .thenThrow(new IllegalStateException("connection refused")); + } + + @Test + void testNoReportIsStoredBeforeAnyRun() { + assertThat(store.get()).isEmpty(); + } + + @Test + void testAReportSurvivesTheNodeThatProducedIt() { + store.put(REPORT); + + assertThat(node().get()).contains(REPORT); + } + + @Test + void testANewRunReplacesThePreviousReport() { + store.put(REPORT); + store.put(REPORT + " (second run)"); + + assertThat(node().get()).contains(REPORT + " (second run)"); + } + + @Test + void testANewerReportFromAnotherNodeSupersedesThisNodesOwn() { + store.put(REPORT); + + node().put(REPORT + " (another node)"); + + assertThat(store.get()).contains(REPORT + " (another node)"); + } + + @Test + void testClearRemovesTheStoredReport() { + store.put(REPORT); + store.clear(); + + assertThat(store.get()).isEmpty(); + assertThat(node().get()).isEmpty(); + } + + @Test + void testAClearOnAnotherNodeRetiresTheCopyThisNodeProduced() { + store.put(REPORT); + + node().clear(); + + assertThat(store.get()).isEmpty(); + } + + @Test + void testAReportIsStillServedWhenTheDurableWriteFails() { + // An existing row, so the failed write is not hidden behind the empty-read fallback. + store.put(REPORT + " (earlier run)"); + saveFails(); + + store.put(REPORT); + + assertThat(store.get()).contains(REPORT); + } + + @Test + void testAReportIsStillServedWhenTheDurableWriteFailsAfterAClear() { + store.clear(); + saveFails(); + + store.put(REPORT); + + assertThat(store.get()).contains(REPORT); + } + + @Test + void testAFailedReadFallsBackToThisNodesOwnCopy() { + store.put(REPORT); + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY)) + .thenThrow(new IllegalStateException("connection refused")); + + assertThat(store.get()).contains(REPORT); + } + + @Test + void testAReportIsStillServedWhileTheDatabaseIsUnreachableAltogether() { + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY)) + .thenThrow(new IllegalStateException("connection refused")); + saveFails(); + + store.put(REPORT); + + assertThat(store.get()).contains(REPORT); + } + + @Test + void testAClearOnAnotherNodeAfterAFailedWriteRetiresTheCopy() { + saveFails(); + store.put(REPORT); + + saveSucceeds(); + node().clear(); + + assertThat(store.get()).isEmpty(); + } + + @Test + void testANewerReportFromAnotherNodeAfterAFailedWriteSupersedesTheCopy() { + saveFails(); + store.put(REPORT); + + saveSucceeds(); + node().put(REPORT + " (another node)"); + + assertThat(store.get()).contains(REPORT + " (another node)"); + } + + @Test + void testASupersededCopyIsNotRevivedByAnOutOfOrderWrite() { + saveFails(); + store.put(REPORT); + saveSucceeds(); + node().put(REPORT + " (another node)"); + assertThat(store.get()).contains(REPORT + " (another node)"); + + CommunityGrantOfflineReportStore nodeWithABehindClock = node(); + nodeWithABehindClock.setClock(() -> 0L); + nodeWithABehindClock.clear(); + + assertThat(store.get()).isEmpty(); + } + + @Test + void testAFailedClearDoesNotResurrectTheStoredReport() { + store.put(REPORT); + saveFails(); + + store.clear(); + + assertThat(store.get()).isEmpty(); + } + + @Test + void testAFailedReadWithNothingLocalPropagates() { + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY)) + .thenThrow(new IllegalStateException("connection refused")); + + assertThatThrownBy(() -> store.get()).isInstanceOf(IllegalStateException.class); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatformTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatformTest.java new file mode 100644 index 0000000000..ebde39b635 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatformTest.java @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CommunityGrantPlatformTest { + + @ParameterizedTest + @CsvSource({ + "Mac OS X, aarch64, darwin, arm64", + "Mac OS X, x86_64, darwin, amd64", + "Windows 10, amd64, windows, amd64", + "Windows Server 2022, aarch64, windows, arm64", + "Linux, amd64, linux, amd64", + "Linux, x86_64, linux, amd64", + "Linux, aarch64, linux, arm64", + "SunOS, x64, linux, amd64" + }) + void testPlatformIsMappedToThePortalsVocabulary(String osName, String osArch, String os, String arch) { + assertThat(CommunityGrantPlatform.of(osName, osArch)).isEqualTo(new CommunityGrantPlatform(os, arch)); + } + + @ParameterizedTest + @CsvSource({"Linux, ppc64le", "Linux, s390x", "Linux, i386"}) + void testAnUnsupportedArchitectureIsRefused(String osName, String osArch) { + assertThatThrownBy(() -> CommunityGrantPlatform.of(osName, osArch)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Unsupported architecture"); + } + + @Test + void testOnlyWindowsGetsAnExeSuffix() { + assertThat(new CommunityGrantPlatform("windows", "amd64").checkerFileName()).isEqualTo("tb-instance-check.exe"); + assertThat(new CommunityGrantPlatform("linux", "amd64").checkerFileName()).isEqualTo("tb-instance-check"); + assertThat(new CommunityGrantPlatform("darwin", "arm64").checkerFileName()).isEqualTo("tb-instance-check"); + } + + @Test + void testOnlyAFileNameNamingAnotherPlatformIsRefused() { + CommunityGrantPlatform platform = new CommunityGrantPlatform("linux", "amd64"); + + assertThat(platform.namesAnotherPlatform("tb-instance-check_windows_amd64")).isTrue(); + assertThat(platform.namesAnotherPlatform("tb-instance-check_linux_arm64")).isTrue(); + assertThat(platform.namesAnotherPlatform("TB-Instance-Check_Darwin_ARM64")).isTrue(); + assertThat(platform.namesAnotherPlatform("tb-instance-check")).isFalse(); + assertThat(platform.namesAnotherPlatform("tb-instance-check_linux_amd64")).isFalse(); + assertThat(platform.namesAnotherPlatform("tb-instance-check (1)")).isFalse(); + assertThat(platform.namesAnotherPlatform("tb-instance-check_solaris_sparc")).isFalse(); + assertThat(platform.namesAnotherPlatform(null)).isFalse(); + assertThat(platform.namesAnotherPlatform("")).isFalse(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java new file mode 100644 index 0000000000..791e5c6379 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java @@ -0,0 +1,1008 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; + +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CommunityGrantPollerTest { + + private static final String TOKEN = "token-one"; + private static final String LICENSE_SECRET = "granted-license-key"; + private static final String SIGN_UP_URL = + "https://portal.example/communityGrant?clusterId=c1&claimToken=t1"; + private static final UUID CLUSTER_ID = UUID.fromString("2f0a5b1e-1111-4a2b-9c3d-4e5f60718293"); + private static final String CHECKER_INPUT_JSON = "{\"clusterId\":\"" + CLUSTER_ID + "\",\"keyId\":7," + + "\"publicKey\":\"cHVi\",\"challenge\":\"Y2hh\",\"referenceMillis\":1787788800000}"; + private static final CommunityGrantCheckerInput CHECKER_INPUT = new CommunityGrantCheckerInput(CHECKER_INPUT_JSON); + + @Mock + private PartitionService partitionService; + @Mock + private TbClusterStore tbClusterStore; + @Mock + private CommunityGrantFlowStateStore flowStateStore; + @Mock + private CommunityGrantPortalClient portalClient; + @Mock + private CommunityGrantReportRunner reportRunner; + + /** Keeps real background ticks away from the mocks, and lets the reschedule be asserted. */ + @Mock + private ScheduledExecutorService scheduler; + @Mock + private ScheduledFuture scheduledPoll; + @Mock + private ScheduledFuture supervisorFuture; + + @InjectMocks + private CommunityGrantPoller poller; + + private CommunityGrantFlowState stored; + + @BeforeEach + void setUp() { + // Without enabled, init() returns before arming. + ReflectionTestUtils.setField(poller, "enabled", true); + ReflectionTestUtils.setField(poller, "fastPollIntervalMs", 3000L); + ReflectionTestUtils.setField(poller, "fastPollWindowMs", 120000L); + ReflectionTestUtils.setField(poller, "slowPollIntervalMs", 30000L); + ReflectionTestUtils.setField(poller, "signUpDeadlineMs", 86400000L); + ReflectionTestUtils.setField(poller, "superviseIntervalMs", 30000L); + ReflectionTestUtils.setField(poller, "scheduler", scheduler); + stored = CommunityGrantFlowState.initial(); + stored.setMode(CommunityGrantMode.ONLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setStartedAt(System.currentTimeMillis()); + lenient().when(flowStateStore.get()).thenAnswer(invocation -> stored); + lenient().when(flowStateStore.update(any())).thenAnswer(invocation -> { + UnaryOperator updater = invocation.getArgument(0); + stored = updater.apply(stored); + return stored; + }); + lenient().when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of(TOKEN)); + lenient().when(portalClient.claimLicense(TOKEN)).thenReturn(LICENSE_SECRET); + lenient().when(tbClusterStore.getClusterId()).thenReturn(Optional.of(CLUSTER_ID)); + lenient().doReturn(scheduledPoll).when(scheduler).schedule(any(Runnable.class), anyLong(), any()); + // Non-null, so the supervisor's already-running guard can trip. + lenient().doReturn(supervisorFuture).when(scheduler) + .scheduleWithFixedDelay(any(), anyLong(), anyLong(), any()); + ownsSystemTenantPartition(true); + poller.arm(); + } + + @AfterEach + void tearDown() { + poller.stop(); + } + + @Test + void testAwaitingSignupIsProjected() { + poller.apply(TOKEN, status("AWAITING_SIGNUP", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testAwaitingSignupPastTheDeadlineParksTheFlow() { + stored.setStartedAt(System.currentTimeMillis() - 86400000L - 1000L); + + poller.apply(TOKEN, status("AWAITING_SIGNUP", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getSignUpUrl()).isNull(); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.SIGNUP_ABANDONED); + assertThat(poller.isArmed()).isFalse(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testVerificationRequiredRunsTheReportWithThePortalsInput() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("UNDER_REVIEW"); + + poller.apply(TOKEN, verificationRequired()); + + verify(reportRunner).runAndUpload(TOKEN, CHECKER_INPUT); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + } + + @Test + void testVerificationRequiredUploadThatIsAcceptedOutrightIsTerminal() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("DONE"); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testVerificationRequiredUploadUnderReviewKeepsTheTokenAndKeepsWatching() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("UNDER_REVIEW"); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testVerificationRequiredUploadWrongInstallationIsTerminal() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("WRONG_INSTALLATION"); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.WRONG_INSTALLATION); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testVerificationRequiredUploadWithAnUnknownStatusLeavesTheFlowCollecting() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("SOMETHING_NEW"); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testVerificationRequiredUploadReturningNullLeavesTheFlowCollecting() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn(null); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + // Refused before the runner, so a status that was never runnable does not spend the verification budget. + @ParameterizedTest + @ValueSource(strings = {"", "null", "{}", "[]", "\"text\"", "7"}) + void testVerificationRequiredWithoutAUsableInputNeverRunsTheChecker(String checkerInput) { + AtomicInteger verificationFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "verificationFailures"); + + poller.apply(TOKEN, new CommunityGrantPortalStatus("VERIFICATION_REQUIRED", + checkerInput.isEmpty() ? null : JacksonUtil.toJsonNode(checkerInput), null)); + + verifyNoInteractions(reportRunner); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + assertThat(verificationFailures).hasValue(0); + } + + @Test + void testVerificationRequiredInOfflineModeNeverRunsTheChecker() { + stored.setMode(CommunityGrantMode.OFFLINE); + + poller.apply(TOKEN, verificationRequired()); + + verifyNoInteractions(reportRunner); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + } + + @Test + void testAFailedReportRunLeavesTheFlowCollecting() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenThrow(new IllegalStateException("boom")); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testRepeatedReportFailuresParkTheFlow() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenThrow(new IllegalStateException("boom")); + + for (int i = 0; i < CommunityGrantPoller.MAX_VERIFICATION_FAILURES; i++) { + poller.apply(TOKEN, verificationRequired()); + } + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.CHECK_FAILED); + assertThat(poller.isArmed()).isFalse(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + // Only the state write is skipped; lastPolledAt still advances so the flow does not look stalled. + @Test + void testVerificationRequiredLeavesAHandedOverFlowClaimedButKeepsItsPollFresh() { + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + stored.setLastPolledAt(1L); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(stored.getLastPolledAt()).isGreaterThan(1L); + verify(reportRunner).runAndUpload(TOKEN, CHECKER_INPUT); + } + + @Test + void testRepeatedReportFailuresDoNotParkAHandedOverFlow() { + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenThrow(new IllegalStateException("boom")); + + for (int i = 0; i < CommunityGrantPoller.MAX_VERIFICATION_FAILURES; i++) { + poller.apply(TOKEN, verificationRequired()); + } + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(stored.getParkReason()).isNull(); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testVerificationRequiredLeavesAValidatingFlowClaimedButKeepsItsPollFresh() { + stored.setState(CommunityGrantState.VALIDATING); + stored.setLastPolledAt(1L); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(stored.getLastPolledAt()).isGreaterThan(1L); + } + + @Test + void testVerificationRequiredNeverRunsTheCheckerForAValidatingFlow() { + stored.setState(CommunityGrantState.VALIDATING); + + for (int i = 0; i < CommunityGrantPoller.MAX_VERIFICATION_FAILURES; i++) { + poller.apply(TOKEN, verificationRequired()); + } + + verifyNoInteractions(reportRunner); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(stored.getParkReason()).isNull(); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testAValidatingAnswerIsTreatedAsUnrecognizedAndChangesNothing() { + poller.apply(TOKEN, status("VALIDATING", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testDoneIsTerminalAndRetiresTheToken() { + poller.apply(TOKEN, status("DONE", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testDoneStoresTheGrantedLicenseKeyBeforeClearingTheToken() { + poller.apply(TOKEN, status("DONE", null)); + + InOrder inOrder = inOrder(tbClusterStore); + inOrder.verify(tbClusterStore).saveLicenseSecret(LICENSE_SECRET); + inOrder.verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + } + + @Test + void testDoneWithNoKeyToHandOverYetLeavesTheFlowForTheNextPoll() { + when(portalClient.claimLicense(TOKEN)).thenReturn(null); + + poller.apply(TOKEN, status("DONE", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).saveLicenseSecret(anyString()); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testDoneWithARefusedClaimRegistersWithoutAKey() { + when(portalClient.claimLicense(TOKEN)).thenThrow(new CommunityGrantLicenseClaimRefusedException( + new HttpClientErrorException(HttpStatus.BAD_REQUEST))); + + poller.apply(TOKEN, status("DONE", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + assertThat(poller.isArmed()).isFalse(); + verify(tbClusterStore, never()).saveLicenseSecret(anyString()); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testDoneWithAnUnreachablePortalIsLeftToTheFailureBackoff() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenReturn(status("DONE", null)); + when(portalClient.claimLicense(TOKEN)).thenThrow(new ResourceAccessException("connection refused")); + clearInvocations(scheduler); + + poller.pollAndReschedule(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + verify(scheduler).schedule(any(Runnable.class), eq(3000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testDoneKeepsTheRegistrationLinkWhileRetiringEverythingElseAboutTheClaim() { + stored.setSignUpUrl(SIGN_UP_URL); + + poller.apply(TOKEN, status("DONE", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + assertThat(stored.getSignUpUrl()).isEqualTo(SIGN_UP_URL); + assertThat(stored.getStartedAt()).isNull(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testAWrongInstallationAnswerDropsTheRegistrationLink() { + stored.setSignUpUrl(SIGN_UP_URL); + + poller.apply(TOKEN, status("WRONG_INSTALLATION", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.WRONG_INSTALLATION); + assertThat(stored.getSignUpUrl()).isNull(); + } + + @Test + void testAParkDropsTheRegistrationLink() { + stored.setSignUpUrl(SIGN_UP_URL); + + poller.apply(TOKEN, status("EXPIRED", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getSignUpUrl()).isNull(); + } + + @Test + void testUnderReviewKeepsTheTokenAndKeepsWatching() { + poller.apply(TOKEN, status("UNDER_REVIEW", 30)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + assertThat(stored.getLastPolledAt()).isNotNull(); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testUnderReviewFollowedByDoneEndsRegistered() { + poller.apply(TOKEN, status("UNDER_REVIEW", 30)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + + poller.apply(TOKEN, status("DONE", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + assertThat(poller.isArmed()).isFalse(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testUnderReviewIsPacedByThePortalsRetryAfter() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenReturn(status("UNDER_REVIEW", 300)); + + assertThat(poller.nextDelay(poller.poll())).isEqualTo(TimeUnit.SECONDS.toMillis(300)); + } + + @Test + void testAnUnderReviewAnswerForAClearedTokenIsNotWritten() { + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.empty()); + + poller.apply(TOKEN, status("UNDER_REVIEW", 30)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + } + + @Test + void testAwaitingSignupAndVerificationRequiredAreAlsoSkippedForAReplacedToken() { + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of("a-newer-token")); + stored.setState(CommunityGrantState.NOT_STARTED); + + poller.apply(TOKEN, status("AWAITING_SIGNUP", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + + poller.apply(TOKEN, verificationRequired()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + assertThat(stored.getLastPolledAt()).isNull(); + verifyNoInteractions(reportRunner); + } + + @Test + void testWrongInstallationIsTerminalAndRetiresTheToken() { + poller.apply(TOKEN, status("WRONG_INSTALLATION", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.WRONG_INSTALLATION); + assertThat(stored.getParkReason()).isNull(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testExpiredParksTheFlowForARestart() { + poller.apply(TOKEN, status("EXPIRED", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getSignUpUrl()).isNull(); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.LINK_EXPIRED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testAnAnswerForASupersededTokenLeavesTheStateAndTheLoopAlone() { + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of("token-two")); + + poller.apply(TOKEN, status("DONE", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testAnUnknownStatusLeavesTheStateAlone() { + poller.apply(TOKEN, status("SOMETHING_NEW", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testApplyWithANullStatusValueLeavesStateAloneAndDoesNotThrow() { + poller.apply(TOKEN, status(null, null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testTerminalStateAlsoClearsStartedAt() { + poller.apply(TOKEN, status("DONE", null)); + assertThat(stored.getStartedAt()).isNull(); + } + + @Test + void testTerminalStateStopsAllFurtherOutboundCalls() { + poller.apply(TOKEN, status("DONE", null)); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + } + + @Test + void testPollWithoutATokenDisarms() { + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.empty()); + + poller.poll(); + + verify(portalClient, never()).getStatus(anyString(), any()); + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testPollWithoutAClusterIdDisarms() { + when(tbClusterStore.getClusterId()).thenReturn(Optional.empty()); + + poller.poll(); + + verify(portalClient, never()).getStatus(anyString(), any()); + assertThat(poller.isArmed()).isFalse(); + } + + // The loop stays armed because its tick enforces the sign-up deadline. + @Test + void testPollSkipsThePortalButKeepsTheLoopWhenTheModeHasSinceBecomeOffline() { + assertThat(poller.isArmed()).isTrue(); + stored.setMode(CommunityGrantMode.OFFLINE); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testAnOfflineEnrollmentIsParkedAtTheSignUpDeadlineWithoutEverCallingThePortal() { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setStartedAt(System.currentTimeMillis() - 86400000L - 1000L); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.SIGNUP_ABANDONED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testAnOfflineTickInsideTheDeadlineTouchesNothing() { + stored.setMode(CommunityGrantMode.OFFLINE); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + verify(flowStateStore, never()).update(any()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + } + + @Test + void testAnOfflineFlowPastTheSignUpFormStopsTheLoop() { + assertThat(poller.isArmed()).isTrue(); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.VALIDATING); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + verify(flowStateStore, never()).update(any()); + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testPollRecordsTheTimestampAndThrottlesTheNextCall() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)) + .thenReturn(status("AWAITING_SIGNUP", null)); + + poller.poll(); + assertThat(stored.getLastPolledAt()).isNotNull(); + + poller.poll(); + verify(portalClient).getStatus(TOKEN, CLUSTER_ID); + } + + @Test + void testPollWithANullPortalResponseLeavesStateUnchanged() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenReturn(null); + + assertThat(poller.poll()).isNull(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + } + + // The armed flag is untouched on this path, so the reschedule is what is asserted. + @Test + void testPortalThrowingDuringAPollDoesNotKillTheScheduledLoop() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenThrow(new RuntimeException("portal unreachable")); + clearInvocations(scheduler); + + poller.pollAndReschedule(); + + assertThat(poller.isArmed()).isTrue(); + verify(scheduler).schedule(any(Runnable.class), eq(3000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testFlowStateStoreThrowingDuringAPollDoesNotKillTheScheduledLoop() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)) + .thenReturn(status("AWAITING_SIGNUP", null)); + doThrow(new IllegalStateException("unparseable stored document")).when(flowStateStore).update(any()); + clearInvocations(scheduler); + + poller.pollAndReschedule(); + + assertThat(poller.isArmed()).isTrue(); + verify(scheduler).schedule(any(Runnable.class), eq(3000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testTheFailureCountIsClearedOnlyByAPollThatReachedThePortal() { + AtomicInteger consecutiveFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "consecutiveFailures"); + consecutiveFailures.set(4); + + // No claim token, so poll() returns before the portal. + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.empty()); + poller.pollAndReschedule(); + + assertThat(consecutiveFailures).hasValue(4); + verify(portalClient, never()).getStatus(anyString(), any()); + + // arm() clears the count too, so it is planted again after. + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of(TOKEN)); + when(portalClient.getStatus(TOKEN, CLUSTER_ID)) + .thenReturn(status("AWAITING_SIGNUP", null)); + poller.arm(); + consecutiveFailures.set(4); + ReflectionTestUtils.setField(poller, "lastPollTs", 0L); + poller.pollAndReschedule(); + + assertThat(consecutiveFailures).hasValue(0); + } + + // Re-based in poll(), not arm(): the partition owner is not necessarily the node that served start(). + @Test + void testANewClaimTokenReBasesTheFailureBudgets() { + AtomicInteger consecutiveFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "consecutiveFailures"); + AtomicInteger verificationFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "verificationFailures"); + // Binds the poller to TOKEN and closes the throttle, so the next poll never reaches the portal. + poller.poll(); + consecutiveFailures.set(CommunityGrantPoller.MAX_POLL_FAILURES - 1); + verificationFailures.set(CommunityGrantPoller.MAX_VERIFICATION_FAILURES - 1); + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of("token-two")); + + poller.poll(); + + assertThat(consecutiveFailures).hasValue(0); + assertThat(verificationFailures).hasValue(0); + } + + @Test + void testTheFirstClaimTokenANodeMeetsLeavesTheBudgetsAlone() { + AtomicInteger consecutiveFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "consecutiveFailures"); + AtomicInteger verificationFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "verificationFailures"); + consecutiveFailures.set(CommunityGrantPoller.MAX_POLL_FAILURES - 1); + verificationFailures.set(CommunityGrantPoller.MAX_VERIFICATION_FAILURES - 1); + // Closes the throttle, so the poll stops after the re-base. + ReflectionTestUtils.setField(poller, "lastPollTs", System.currentTimeMillis()); + + poller.poll(); + + assertThat(consecutiveFailures).hasValue(CommunityGrantPoller.MAX_POLL_FAILURES - 1); + assertThat(verificationFailures).hasValue(CommunityGrantPoller.MAX_VERIFICATION_FAILURES - 1); + } + + @Test + void testCadenceSwitchesFromFastToSlow() { + assertThat(poller.nextDelay(null)).isEqualTo(3000L); + ReflectionTestUtils.setField(poller, "pollingSince", System.currentTimeMillis() - 130000L); + assertThat(poller.nextDelay(null)).isEqualTo(30000L); + } + + @Test + void testRetryAfterSecOverridesBothIntervals() { + assertThat(poller.nextDelay(45)).isEqualTo(45000L); + ReflectionTestUtils.setField(poller, "pollingSince", System.currentTimeMillis() - 130000L); + assertThat(poller.nextDelay(1)).isEqualTo(1000L); + assertThat(poller.nextDelay(0)).isEqualTo(30000L); + } + + @Test + void testNegativeRetryAfterSecFallsBackToTheLocalCadence() { + assertThat(poller.nextDelay(-5)).isEqualTo(3000L); + } + + @Test + void testRetryAfterSecIsClampedToAnUpperBound() { + assertThat(poller.nextDelay(Integer.MAX_VALUE)).isEqualTo(CommunityGrantPoller.MAX_RETRY_AFTER_SEC * 1000L); + } + + @Test + void testAnUnreachablePortalStillEndsAnAbandonedSignUpAtTheDeadline() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenThrow(new RuntimeException("portal unreachable")); + stored.setStartedAt(System.currentTimeMillis() - 86400000L - 1000L); + + poller.pollAndReschedule(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.SIGNUP_ABANDONED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testAnUnreachablePortalParksTheFlowOnceTheFailureBudgetIsSpent() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenThrow(new RuntimeException("portal unreachable")); + stored.setState(CommunityGrantState.UNDER_REVIEW); + AtomicInteger consecutiveFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "consecutiveFailures"); + consecutiveFailures.set(CommunityGrantPoller.MAX_POLL_FAILURES - 1); + ReflectionTestUtils.setField(poller, "lastPollTs", 0L); + + poller.pollAndReschedule(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.PORTAL_UNREACHABLE); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testAFailureBelowTheBudgetLeavesTheFlowAlone() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenThrow(new RuntimeException("portal unreachable")); + stored.setState(CommunityGrantState.UNDER_REVIEW); + + poller.pollAndReschedule(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testTheDelayGrowsWithConsecutiveFailuresUpToACap() { + assertThat(poller.failureDelay(1)).isEqualTo(3000L); + assertThat(poller.failureDelay(3)).isEqualTo(12000L); + assertThat(poller.failureDelay(30)).isEqualTo(CommunityGrantPoller.MAX_FAILURE_BACKOFF_MS); + } + + @Test + void testInitArmsOnlyFromAPollableStoredState() { + poller.disarm(); + stored.setState(CommunityGrantState.NOT_STARTED); + poller.init(); + assertThat(poller.isArmed()).isFalse(); + + stored.setState(CommunityGrantState.VALIDATING); + poller.init(); + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testInitDoesNotArmFromATerminalState() { + poller.disarm(); + stored.setState(CommunityGrantState.REGISTERED); + poller.init(); + assertThat(poller.isArmed()).isFalse(); + verify(reportRunner, never()).runAndUpload(anyString(), any()); + verify(portalClient, never()).getStatus(eq(TOKEN), any()); + } + + @Test + void testInitDoesNotResumeOnANodeThatDoesNotOwnTheSystemTenantPartition() { + poller.disarm(); + stored.setState(CommunityGrantState.VALIDATING); + ownsSystemTenantPartition(false); + + poller.init(); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testTakingOverTheSystemTenantPartitionResumesAPollableFlow() { + poller.disarm(); + stored.setState(CommunityGrantState.VALIDATING); + + poller.onTbApplicationEvent(corePartitionChangeEvent()); + + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testLosingTheSystemTenantPartitionStopsTheLoop() { + ownsSystemTenantPartition(false); + + poller.onTbApplicationEvent(corePartitionChangeEvent()); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testArmDoesNothingWhenDisabled() { + poller.disarm(); + ReflectionTestUtils.setField(poller, "enabled", false); + + poller.arm(); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testAnOfflineDeploymentArmsSoItsDeadlineIsStillEnforced() { + poller.disarm(); + stored.setMode(CommunityGrantMode.OFFLINE); + + poller.arm(); + + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testInitArmsAnOfflineDeploymentStillWaitingOnTheSignUpForm() { + poller.disarm(); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + + poller.init(); + + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testInitLeavesAnOfflineDeploymentPastTheSignUpFormDisarmed() { + poller.disarm(); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.VALIDATING); + + poller.init(); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testInitArmsAnOnlineDeploymentAndItsPollReachesThePortal() { + poller.disarm(); + stored.setMode(CommunityGrantMode.ONLINE); + when(portalClient.getStatus(TOKEN, CLUSTER_ID)) + .thenReturn(status("AWAITING_SIGNUP", null)); + + poller.init(); + assertThat(poller.isArmed()).isTrue(); + + poller.poll(); + verify(portalClient).getStatus(TOKEN, CLUSTER_ID); + } + + @Test + void testArmDoesNothingOnANodeThatDoesNotOwnTheSystemTenantPartition() { + poller.disarm(); + clearInvocations(scheduler); // setUp() armed this node while it did own the partition + ownsSystemTenantPartition(false); + + poller.arm(); + + assertThat(poller.isArmed()).isFalse(); + verify(scheduler, never()).schedule(any(Runnable.class), anyLong(), any()); + } + + @Test + void testTheOwnersSupervisorPicksUpAFlowBegunOnAnotherNode() { + poller.disarm(); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + + poller.supervise(); + + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testTheSupervisorDoesNotArmATerminalFlow() { + poller.disarm(); + stored.setState(CommunityGrantState.REGISTERED); + + poller.supervise(); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testAHandedOverFlowIsWatchedOnlineAndLeftAloneOffline() { + poller.disarm(); + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + stored.setMode(CommunityGrantMode.OFFLINE); + + poller.supervise(); + assertThat(poller.isArmed()).isFalse(); + + stored.setMode(CommunityGrantMode.ONLINE); + poller.supervise(); + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testInitStartsTheSupervisor() { + poller.init(); + + verify(scheduler).scheduleWithFixedDelay(any(), eq(30000L), eq(30000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testGainingTheSystemTenantPartitionStartsTheSupervisor() { + poller.onTbApplicationEvent(corePartitionChangeEvent()); + + verify(scheduler).scheduleWithFixedDelay(any(), eq(30000L), eq(30000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testTheSupervisorIsStartedOnlyOnce() { + poller.init(); + poller.init(); + + verify(scheduler, times(1)).scheduleWithFixedDelay(any(), anyLong(), anyLong(), any()); + } + + @Test + void testLosingTheSystemTenantPartitionStopsTheSupervisor() { + poller.init(); + ownsSystemTenantPartition(false); + + poller.onTbApplicationEvent(corePartitionChangeEvent()); + + verify(supervisorFuture).cancel(false); + } + + @Test + void testArmingAgainCancelsThePendingPollRatherThanAddingASecondChain() { + clearInvocations(scheduler, scheduledPoll); // setUp() already armed, so one chain is queued + + poller.disarm(); + poller.arm(); + + verify(scheduledPoll).cancel(false); + verify(scheduler, times(1)).schedule(any(Runnable.class), eq(3000L), eq(TimeUnit.MILLISECONDS)); + } + + // Run through the captured Runnable: pollAndReschedule() passes the current generation and cannot mismatch. + @Test + void testAPollLeftOverFromAReplacedChainNeitherReschedulesItselfNorDisarms() { + ArgumentCaptor queuedPoll = ArgumentCaptor.forClass(Runnable.class); + verify(scheduler).schedule(queuedPoll.capture(), anyLong(), any()); // setUp()'s arm() queued it + + poller.disarm(); + poller.arm(); + clearInvocations(scheduler); // the re-arm's own chain is the one allowed to be queued + queuedPoll.getValue().run(); + + verify(scheduler, never()).schedule(any(Runnable.class), anyLong(), any()); + verifyNoInteractions(portalClient); + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testARejectedScheduleLeavesTheLoopDisarmed() { + poller.disarm(); + doThrow(new RejectedExecutionException("shutting down")) + .when(scheduler).schedule(any(Runnable.class), anyLong(), any()); + + poller.arm(); + + assertThat(poller.isArmed()).isFalse(); + } + + private void ownsSystemTenantPartition(boolean mine) { + lenient().when(partitionService.resolve(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID)) + .thenReturn(new TopicPartitionInfo("tb_core", TenantId.SYS_TENANT_ID, 0, mine)); + } + + private PartitionChangeEvent corePartitionChangeEvent() { + return new PartitionChangeEvent(this, ServiceType.TB_CORE, Map.of(), Map.of()); + } + + private CommunityGrantPortalStatus status(String status, Integer retryAfterSec) { + return new CommunityGrantPortalStatus(status, null, retryAfterSec); + } + + private static CommunityGrantPortalStatus verificationRequired() { + return new CommunityGrantPortalStatus("VERIFICATION_REQUIRED", JacksonUtil.toJsonNode(CHECKER_INPUT_JSON), null); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java new file mode 100644 index 0000000000..3aa6239987 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java @@ -0,0 +1,600 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.apache.hc.client5.http.config.ConnectionConfig; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.core5.function.Resolver; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.test.web.client.ResponseCreator; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; + +import java.io.IOException; +import java.io.InputStream; +import java.net.SocketTimeoutException; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.headerDoesNotExist; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +class CommunityGrantPortalClientTest { + + private static final String BASE_URL = "https://portal.example"; + private static final String SIGN_UP_PATH = "/communityGrant"; + private static final String TOKEN = "AAAA-BBBB_CCCC"; + private static final String CLAIM_TOKEN_HEADER = "X-TB-Claim-Token"; + + private CommunityGrantPortalClient client; + private MockRestServiceServer mockServer; + + /** Captured before {@link MockRestServiceServer#createServer} replaces the request factory with its own. */ + private ClientHttpRequestFactory realRequestFactory; + + @BeforeEach + void setUp() { + client = new CommunityGrantPortalClient(); + // Without it initRestClient() skips the base-URL validation. + ReflectionTestUtils.setField(client, "enabled", true); + ReflectionTestUtils.setField(client, "baseUrl", BASE_URL); + ReflectionTestUtils.setField(client, "connectTimeoutSec", 5); + ReflectionTestUtils.setField(client, "readTimeoutSec", 10); + ReflectionTestUtils.setField(client, "maxCheckerSizeBytes", 1024L); + client.initRestClient(); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(client, "restTemplate"); + realRequestFactory = restTemplate.getRequestFactory(); + mockServer = MockRestServiceServer.createServer(restTemplate); + } + + @Test + void testSignUpUrlPinsItsParameterNamesAndOrder() { + UUID clusterId = UUID.randomUUID(); + + onPlatform("Linux", "amd64", () -> { + assertThat(client.buildSignUpUrl(clusterId, TOKEN, CommunityGrantMode.ONLINE)) + .isEqualTo(BASE_URL + SIGN_UP_PATH + "?clusterId=" + clusterId + "&claimToken=" + TOKEN + + "&os=linux&arch=amd64"); + assertThat(client.buildSignUpUrl(clusterId, TOKEN, CommunityGrantMode.OFFLINE)) + .isEqualTo(BASE_URL + SIGN_UP_PATH + "?clusterId=" + clusterId + "&claimToken=" + TOKEN + + "&offline=true&os=linux&arch=amd64"); + }); + } + + @Test + void testSignUpUrlCarriesThePlatformEvenWhenTheDeploymentIsOnline() { + onPlatform("Mac OS X", "aarch64", () -> + assertThat(client.buildSignUpUrl(UUID.randomUUID(), TOKEN, CommunityGrantMode.ONLINE)) + .endsWith("&os=darwin&arch=arm64")); + } + + // The portal refuses a link carrying only one of os and arch, so both are dropped. + @Test + void testSignUpUrlOmitsThePlatformOnAnUnsupportedArchitecture() { + UUID clusterId = UUID.randomUUID(); + + onPlatform("Linux", "s390x", () -> + assertThat(client.buildSignUpUrl(clusterId, TOKEN, CommunityGrantMode.OFFLINE)) + .isEqualTo(BASE_URL + SIGN_UP_PATH + "?clusterId=" + clusterId + "&claimToken=" + TOKEN + + "&offline=true")); + } + + @Test + void testSignUpUrlHasNoDoubleSlashWhenTheBaseUrlEndsInOne() { + ReflectionTestUtils.setField(client, "baseUrl", BASE_URL + "/"); + UUID clusterId = UUID.randomUUID(); + + onPlatform("Linux", "amd64", () -> + assertThat(client.buildSignUpUrl(clusterId, TOKEN, CommunityGrantMode.ONLINE)) + .isEqualTo(BASE_URL + SIGN_UP_PATH + "?clusterId=" + clusterId + "&claimToken=" + TOKEN + + "&os=linux&arch=amd64")); + } + + private static void onPlatform(String osName, String osArch, Runnable body) { + String originalName = System.getProperty("os.name"); + String originalArch = System.getProperty("os.arch"); + System.setProperty("os.name", osName); + System.setProperty("os.arch", osArch); + try { + body.run(); + } finally { + restoreProperty("os.name", originalName); + restoreProperty("os.arch", originalArch); + } + } + + private static void restoreProperty(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } + + @Test + void testSignUpUrlRefusesAMalformedBaseUrl() { + ReflectionTestUtils.setField(client, "baseUrl", "ht!tp://bad host"); + + assertThatThrownBy(() -> client.buildSignUpUrl(UUID.randomUUID(), TOKEN, CommunityGrantMode.ONLINE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void testClusterStatus() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=" + clusterId)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess("{\"alreadyRegistered\":true}", MediaType.APPLICATION_JSON)); + + assertThat(client.isAlreadyRegistered(clusterId)).isTrue(); + mockServer.verify(); + } + + @Test + void testClusterStatusReturnsFalseWhenNotRegistered() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=" + clusterId)) + .andRespond(withSuccess("{\"alreadyRegistered\":false}", MediaType.APPLICATION_JSON)); + + assertThat(client.isAlreadyRegistered(clusterId)).isFalse(); + mockServer.verify(); + } + + @Test + void testStatusIsParsedWithTheCheckerInput() { + UUID clusterId = UUID.randomUUID(); + String checkerInput = "{\"clusterId\":\"" + clusterId + "\",\"keyId\":7,\"publicKey\":\"cHVi\"," + + "\"challenge\":\"Y2hh\",\"referenceMillis\":1787788800000}"; + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/status?clusterId=" + clusterId)) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess("{\"status\":\"VERIFICATION_REQUIRED\",\"checkerInput\": " + + checkerInput.replace(",", ", ") + ",\"retryAfterSec\":15}", MediaType.APPLICATION_JSON)); + + CommunityGrantPortalStatus status = client.getStatus(TOKEN, clusterId); + + assertThat(status.status()).isEqualTo("VERIFICATION_REQUIRED"); + assertThat(CommunityGrantCheckerInput.from(status.checkerInput())) + .contains(new CommunityGrantCheckerInput(checkerInput)); + assertThat(status.retryAfterSec()).isEqualTo(15); + mockServer.verify(); + } + + @Test + void testStatusToleratesNullsAndUnknownFields() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/status?clusterId=" + clusterId)) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess("{\"status\":\"AWAITING_SIGNUP\",\"checkerInput\":null," + + "\"retryAfterSec\":null,\"somethingNew\":123}", MediaType.APPLICATION_JSON)); + + CommunityGrantPortalStatus status = client.getStatus(TOKEN, clusterId); + + assertThat(status.status()).isEqualTo("AWAITING_SIGNUP"); + assertThat(CommunityGrantCheckerInput.from(status.checkerInput())).isEmpty(); + assertThat(status.retryAfterSec()).isNull(); + mockServer.verify(); + } + + @Test + void testUploadReportSendsTokenAndReportAndReturnsStatus() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/report")) + .andExpect(method(HttpMethod.POST)) + .andExpect(content().json("{\"token\":\"AAAA-BBBB_CCCC\",\"report\":\"-----BEGIN TB INSTANCE CHECK-----\\nbody\"}")) + .andRespond(withSuccess("{\"status\":\"VALIDATING\"}", MediaType.APPLICATION_JSON)); + + String status = client.uploadReport(TOKEN, "-----BEGIN TB INSTANCE CHECK-----\nbody"); + + assertThat(status).isEqualTo("VALIDATING"); + mockServer.verify(); + } + + @Test + void testUploadReportReturnsNullOnEmptyBody() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/report")) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess()); + + String status = client.uploadReport(TOKEN, "-----BEGIN TB INSTANCE CHECK-----\nbody"); + + assertThat(status).isNull(); + mockServer.verify(); + } + + @Test + void testClaimLicenseSendsTheTokenInTheBodyAndReturnsTheKey() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim")) + .andExpect(method(HttpMethod.POST)) + .andExpect(content().json("{\"claimToken\":\"" + TOKEN + "\"}")) + .andExpect(headerDoesNotExist(CLAIM_TOKEN_HEADER)) + .andRespond(withSuccess("{\"activated\":true,\"secret\":\"granted-key\"}", MediaType.APPLICATION_JSON)); + + assertThat(client.claimLicense(TOKEN)).isEqualTo("granted-key"); + mockServer.verify(); + } + + @Test + void testClaimLicenseReturnsNothingWhileThePortalHasNoKeyYet() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim")) + .andRespond(withSuccess("{\"activated\":false}", MediaType.APPLICATION_JSON)); + + assertThat(client.claimLicense(TOKEN)).isNull(); + mockServer.verify(); + } + + @Test + void testClaimLicenseTurnsAClientErrorIntoARefusal() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim")) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + assertThatThrownBy(() -> client.claimLicense(TOKEN)) + .isInstanceOf(CommunityGrantLicenseClaimRefusedException.class); + mockServer.verify(); + } + + @Test + void testClaimLicenseLeavesARetryableAnswerToTheCaller() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim")) + .andRespond(withStatus(HttpStatus.TOO_MANY_REQUESTS)); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim")) + .andRespond(withServerError()); + + assertThatThrownBy(() -> client.claimLicense(TOKEN)) + .isInstanceOf(HttpStatusCodeException.class) + .isNotInstanceOf(CommunityGrantLicenseClaimRefusedException.class); + assertThatThrownBy(() -> client.claimLicense(TOKEN)) + .isInstanceOf(HttpStatusCodeException.class) + .isNotInstanceOf(CommunityGrantLicenseClaimRefusedException.class); + mockServer.verify(); + } + + @Test + void testDownloadChecker() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess("binary-bytes".getBytes(StandardCharsets.UTF_8), MediaType.APPLICATION_OCTET_STREAM)); + + byte[] checker = client.downloadChecker(TOKEN, "linux", "amd64"); + + assertThat(new String(checker, StandardCharsets.UTF_8)).isEqualTo("binary-bytes"); + mockServer.verify(); + } + + @Test + void testDownloadCheckerSignature() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checkerSignature?os=linux&arch=amd64")) + .andExpect(method(HttpMethod.GET)) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess(CommunityGrantSigningFixtures.SIGNATURE, MediaType.APPLICATION_OCTET_STREAM)); + + assertThat(client.downloadCheckerSignature(TOKEN, "linux", "amd64")) + .isEqualTo(CommunityGrantSigningFixtures.SIGNATURE); + mockServer.verify(); + } + + @Test + void testDownloadCheckerSignatureFailsWhenThePortalHasNoneStaged() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checkerSignature?os=linux&arch=amd64")) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + assertThatThrownBy(() -> client.downloadCheckerSignature(TOKEN, "linux", "amd64")) + .isInstanceOf(HttpStatusCodeException.class); + mockServer.verify(); + } + + @Test + void testDownloadCheckerSignatureIsBoundedLikeTheDownloadItAccompanies() { + ReflectionTestUtils.setField(client, "maxCheckerSizeBytes", 4L); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checkerSignature?os=linux&arch=amd64")) + .andRespond(withSuccess("way-too-many-bytes".getBytes(StandardCharsets.UTF_8), MediaType.APPLICATION_OCTET_STREAM)); + + assertThatThrownBy(() -> client.downloadCheckerSignature(TOKEN, "linux", "amd64")) + .isInstanceOf(CommunityGrantCheckerTooLargeException.class) + .hasMessageContaining("release signature stream exceeded"); + mockServer.verify(); + } + + @Test + void testDownloadCheckerRejectsAnOversizedContentLength() { + ReflectionTestUtils.setField(client, "maxCheckerSizeBytes", 4L); + byte[] body = "way-too-many-bytes".getBytes(StandardCharsets.UTF_8); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andRespond(withSuccess(body, MediaType.APPLICATION_OCTET_STREAM) + .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length))); + + assertThatThrownBy(() -> client.downloadChecker(TOKEN, "linux", "amd64")) + .isInstanceOf(CommunityGrantCheckerTooLargeException.class) + .hasMessageContaining("checker size " + body.length + " bytes exceeds"); + mockServer.verify(); + } + + @Test + void testDownloadCheckerRejectsAnOversizedStreamWithNoContentLength() { + ReflectionTestUtils.setField(client, "maxCheckerSizeBytes", 4L); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andRespond(withSuccess("way-too-many-bytes".getBytes(StandardCharsets.UTF_8), MediaType.APPLICATION_OCTET_STREAM)); + + assertThatThrownBy(() -> client.downloadChecker(TOKEN, "linux", "amd64")) + .isInstanceOf(CommunityGrantCheckerTooLargeException.class) + .hasMessageContaining("checker stream exceeded"); + mockServer.verify(); + } + + @Test + void testDownloadCheckerWrapsAStreamReadFailureAsResourceAccessException() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andRespond(respondWith(new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("connection reset"); + } + })); + + assertThatThrownBy(() -> client.downloadChecker(TOKEN, "linux", "amd64")) + .isInstanceOf(ResourceAccessException.class) + .hasMessageContaining("Failed to read the instance checker") + // The un-expanded url template; the claim token travels in a header. + .hasMessageContaining("GET " + BASE_URL + "/api/noauth/communityGrant/checker?os={os}") + .hasMessageNotContaining(TOKEN) + .hasCauseInstanceOf(IOException.class); + mockServer.verify(); + } + + @Test + void testDownloadCheckerKeepsACompletedDownloadWhenOnlyCloseFails() { + byte[] body = "a-complete-checker".getBytes(StandardCharsets.UTF_8); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andRespond(respondWith(new InputStream() { + private int position; + + @Override + public int read() { + return position < body.length ? body[position++] & 0xFF : -1; + } + + @Override + public void close() throws IOException { + throw new IOException("failed to release the connection"); + } + })); + + assertThat(client.downloadChecker(TOKEN, "linux", "amd64")).isEqualTo(body); + mockServer.verify(); + } + + @Test + void testRequestAccessSendsTheClusterId() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/requestAccess?clusterId=" + clusterId)) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess()); + + client.requestAccess(clusterId); + + mockServer.verify(); + } + + @Test + void testRequestAccessPropagatesATransportFailure() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/requestAccess?clusterId=" + clusterId)) + .andExpect(method(HttpMethod.POST)) + .andRespond(request -> { + throw new SocketTimeoutException("connect timed out"); + }); + + assertThatThrownBy(() -> client.requestAccess(clusterId)).isInstanceOf(ResourceAccessException.class); + mockServer.verify(); + } + + @Test + void testProbeTreatsAnyHttpAnswerAsReachable() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=00000000-0000-0000-0000-000000000000")) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + assertThat(client.isPortalReachable()).isTrue(); + mockServer.verify(); + } + + @Test + void testProbeTreatsAServerErrorAsReachable() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=00000000-0000-0000-0000-000000000000")) + .andRespond(withServerError()); + + assertThat(client.isPortalReachable()).isTrue(); + mockServer.verify(); + } + + @Test + void testProbeFailsOnAConnectionError() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=00000000-0000-0000-0000-000000000000")) + .andRespond(request -> { + throw new SocketTimeoutException("connect timed out"); + }); + + assertThat(client.isPortalReachable()).isFalse(); + mockServer.verify(); + } + + @Test + void testProbeDrainsOnlyABoundedPrefixOfTheBody() { + AtomicInteger bytesRead = new AtomicInteger(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=00000000-0000-0000-0000-000000000000")) + .andRespond(respondWith(new InputStream() { + @Override + public int read() { + return bytesRead.incrementAndGet() <= 65536 ? 'x' : -1; + } + })); + + assertThat(client.isPortalReachable()).isTrue(); + assertThat(bytesRead).hasValueLessThan(8192); + mockServer.verify(); + } + + @Test + void testStatusReturnsNullOnEmptyBody() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/status?clusterId=" + clusterId)) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess()); + + assertThat(client.getStatus(TOKEN, clusterId)).isNull(); + mockServer.verify(); + } + + @Test + void testClusterStatusReturnsFalseOnEmptyBody() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=" + clusterId)) + .andRespond(withSuccess()); + + assertThat(client.isAlreadyRegistered(clusterId)).isFalse(); + mockServer.verify(); + } + + @Test + void testATrailingSlashInTheBaseUrlIsTrimmedAtStartup() { + CommunityGrantPortalClient trailingSlashClient = newClient(BASE_URL + "/"); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(trailingSlashClient, "restTemplate"); + MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate); + UUID clusterId = UUID.randomUUID(); + server.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=" + clusterId)) + .andRespond(withSuccess("{\"alreadyRegistered\":false}", MediaType.APPLICATION_JSON)); + + trailingSlashClient.isAlreadyRegistered(clusterId); + + server.verify(); + } + + @Test + void testABaseUrlThatIsNotAnAbsoluteHttpUrlIsRefusedAtStartup() { + assertThatThrownBy(() -> newClient("license.thingsboard.io")).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> newClient("ftp://license.thingsboard.io")).isInstanceOf(IllegalStateException.class); + } + + @Test + void testADisabledClientAcceptsABlankBaseUrlAtStartup() { + CommunityGrantPortalClient disabledClient = new CommunityGrantPortalClient(); + ReflectionTestUtils.setField(disabledClient, "enabled", false); + ReflectionTestUtils.setField(disabledClient, "baseUrl", ""); + ReflectionTestUtils.setField(disabledClient, "connectTimeoutSec", 5); + ReflectionTestUtils.setField(disabledClient, "readTimeoutSec", 10); + + assertThatNoException().isThrownBy(disabledClient::initRestClient); + } + + @Test + void testTimeoutsAreAppliedToTheBuiltRequestFactory() { + assertThat(extractConnectTimeout(realRequestFactory)).isEqualTo(Duration.ofSeconds(5)); + assertThat(extractReadTimeout(realRequestFactory)).isEqualTo(Duration.ofSeconds(10)); + } + + private static Duration extractConnectTimeout(ClientHttpRequestFactory requestFactory) { + if (requestFactory instanceof SimpleClientHttpRequestFactory) { + Integer millis = (Integer) ReflectionTestUtils.getField(requestFactory, "connectTimeout"); + return Duration.ofMillis(millis); + } + if (requestFactory instanceof HttpComponentsClientHttpRequestFactory) { + return Duration.ofMillis(httpComponentsDefaultConnectionConfig(requestFactory).getConnectTimeout().toMilliseconds()); + } + if (requestFactory instanceof JdkClientHttpRequestFactory) { + HttpClient httpClient = (HttpClient) ReflectionTestUtils.getField(requestFactory, "httpClient"); + return httpClient.connectTimeout() + .orElseThrow(() -> new AssertionError("JdkClientHttpRequestFactory's HttpClient has no connect timeout configured")); + } + throw new AssertionError("Unrecognized request factory type, extend this test: " + requestFactory.getClass()); + } + + private static Duration extractReadTimeout(ClientHttpRequestFactory requestFactory) { + if (requestFactory instanceof SimpleClientHttpRequestFactory) { + Integer millis = (Integer) ReflectionTestUtils.getField(requestFactory, "readTimeout"); + return Duration.ofMillis(millis); + } + if (requestFactory instanceof HttpComponentsClientHttpRequestFactory) { + return Duration.ofMillis(httpComponentsDefaultConnectionConfig(requestFactory).getSocketTimeout().toMilliseconds()); + } + if (requestFactory instanceof JdkClientHttpRequestFactory) { + return (Duration) ReflectionTestUtils.getField(requestFactory, "readTimeout"); + } + throw new AssertionError("Unrecognized request factory type, extend this test: " + requestFactory.getClass()); + } + + /** Spring Boot's builder puts the timeouts on the connection manager's {@link ConnectionConfig}, not the factory. */ + private static ConnectionConfig httpComponentsDefaultConnectionConfig(ClientHttpRequestFactory requestFactory) { + Object httpClient = ReflectionTestUtils.getField(requestFactory, "httpClient"); + Object connManager = ReflectionTestUtils.getField(httpClient, "connManager"); + if (!(connManager instanceof PoolingHttpClientConnectionManager)) { + throw new AssertionError("Unrecognized connection manager type, extend this test: " + connManager); + } + @SuppressWarnings("unchecked") + Resolver resolver = + (Resolver) ReflectionTestUtils.getField(connManager, "connectionConfigResolver"); + return resolver.resolve(null); + } + + private static CommunityGrantPortalClient newClient(String baseUrl) { + CommunityGrantPortalClient client = new CommunityGrantPortalClient(); + ReflectionTestUtils.setField(client, "enabled", true); + ReflectionTestUtils.setField(client, "baseUrl", baseUrl); + ReflectionTestUtils.setField(client, "connectTimeoutSec", 5); + ReflectionTestUtils.setField(client, "readTimeoutSec", 10); + client.initRestClient(); + return client; + } + + private static ResponseCreator respondWith(InputStream body) { + return request -> new ClientHttpResponse() { + @Override + public HttpStatusCode getStatusCode() { + return HttpStatus.OK; + } + + @Override + public String getStatusText() { + return "OK"; + } + + @Override + public void close() { + } + + @Override + public InputStream getBody() { + return body; + } + + @Override + public HttpHeaders getHeaders() { + return new HttpHeaders(); + } + }; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifierTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifierTest.java new file mode 100644 index 0000000000..96b2043976 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifierTest.java @@ -0,0 +1,260 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.Base64; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.CHECKER; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.OTHER_CHECKER; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.OTHER_SIGNATURE; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.PUBLIC_KEY_A; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.PUBLIC_KEY_B; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.SIGNATURE; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.SIGNATURE_UNDER_KEY_ID_2; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.TRUSTS_A; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.TRUSTS_A_AND_B; + +class CommunityGrantReleaseSignatureVerifierTest { + + @Test + void testAGenuineReleaseSignatureVerifies() { + assertThatCode(() -> verifierTrusting(TRUSTS_A).verify(CHECKER, SIGNATURE)).doesNotThrowAnyException(); + } + + @Test + void testASingleFlippedBitInTheBinaryIsRejected() { + byte[] tampered = CHECKER.clone(); + tampered[10] ^= 0x01; + + assertRejected(TRUSTS_A, tampered, SIGNATURE, "does not match its release signature"); + } + + @Test + void testATruncatedBinaryIsRejected() { + byte[] truncated = Arrays.copyOf(CHECKER, CHECKER.length - 1); + + assertRejected(TRUSTS_A, truncated, SIGNATURE, "does not match its release signature"); + } + + @Test + void testABinaryWithBytesAppendedIsRejected() { + byte[] extended = Arrays.copyOf(CHECKER, CHECKER.length + 1); + + assertRejected(TRUSTS_A, extended, SIGNATURE, "does not match its release signature"); + } + + @Test + void testASignatureForADifferentBinaryIsRejected() { + assertRejected(TRUSTS_A, CHECKER, OTHER_SIGNATURE, "does not match its release signature"); + // The swapped signature still verifies against its own binary, so the rejection is about the pairing. + assertThatCode(() -> verifierTrusting(TRUSTS_A).verify(OTHER_CHECKER, OTHER_SIGNATURE)) + .doesNotThrowAnyException(); + } + + @Test + void testASignatureFromTheWrongPrivateKeyUnderATrustedKeyIdIsRejected() { + assertRejected(TRUSTS_A, CHECKER, SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1, + "does not match its release signature"); + } + + // An all-ones S is not a valid encoding, so the provider throws instead of returning false. + @Test + void testASignatureWhoseEncodingTheProviderRejectsOutrightIsStillARejection() { + byte[] unencodable = SIGNATURE.clone(); + Arrays.fill(unencodable, 42, 74, (byte) 0xFF); + + assertRejected(TRUSTS_A, CHECKER, unencodable, "does not match its release signature"); + } + + @Test + void testACorruptedMagicIsRejected() { + byte[] corrupted = SIGNATURE.clone(); + corrupted[3] = 'X'; + + assertRejected(TRUSTS_A, CHECKER, corrupted, "not a ThingsBoard release signature"); + } + + @Test + void testAnUnknownVersionIsRejected() { + byte[] futureVersion = SIGNATURE.clone(); + futureVersion[8] = 0x02; + + assertRejected(TRUSTS_A, CHECKER, futureVersion, "version 2"); + } + + // The untrusted-key message also names key id 0, so the reserved phrase is asserted and the untrusted one excluded. + @Test + void testTheReservedKeyIdZeroIsRejectedAsReservedRatherThanAsUntrusted() { + byte[] reservedKeyId = SIGNATURE.clone(); + reservedKeyId[9] = 0x00; + + for (String trustedKeys : new String[]{TRUSTS_A, TRUSTS_A_AND_B, ""}) { + assertThatThrownBy(() -> verifierTrusting(trustedKeys).verify(CHECKER, reservedKeyId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("reserved and never valid") + .hasMessageNotContaining("does not trust") + .hasMessageNotContaining(CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY); + } + } + + @Test + void testAKeyIdTheTrustStoreDoesNotHoldIsRejectedAsUntrusted() { + byte[] unknownKeyId = SIGNATURE.clone(); + unknownKeyId[9] = 0x09; + + assertThatThrownBy(() -> verifierTrusting(TRUSTS_A).verify(CHECKER, unknownKeyId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("key id 9") + .hasMessageContaining("does not trust") + .hasMessageNotContaining("reserved"); + assertRejected(TRUSTS_A, CHECKER, SIGNATURE_UNDER_KEY_ID_2, "key id 2"); + } + + @Test + void testASignatureFileOfAnyOtherLengthIsRejected() { + assertRejected(TRUSTS_A, CHECKER, Arrays.copyOf(SIGNATURE, 73), "73 bytes"); + assertRejected(TRUSTS_A, CHECKER, Arrays.copyOf(SIGNATURE, 75), "75 bytes"); + assertRejected(TRUSTS_A, CHECKER, new byte[]{0x54}, "1 bytes"); + } + + @Test + void testAnAbsentOrEmptySignatureFileIsRejected() { + assertRejected(TRUSTS_A, CHECKER, null, "carries no release signature"); + assertRejected(TRUSTS_A, CHECKER, new byte[0], "carries no release signature"); + } + + @Test + void testAnEmptyOrAbsentBinaryIsRejected() { + assertRejected(TRUSTS_A, new byte[0], SIGNATURE, "empty"); + assertRejected(TRUSTS_A, null, SIGNATURE, "empty"); + } + + @Test + void testNothingVerifiesWhenNoKeyIsConfigured() { + for (String unconfigured : new String[]{"", " ", null}) { + assertThatThrownBy(() -> verifierTrusting(unconfigured).verify(CHECKER, SIGNATURE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY) + .hasMessageContaining("refuses"); + } + } + + @Test + void testAnUnparseablePropertyRefusesEveryUploadAndSaysSo() { + assertThatThrownBy(() -> verifierTrusting("1:" + PUBLIC_KEY_A + ",2:not base64!").verify(CHECKER, SIGNATURE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY) + .hasMessageContaining("could not be parsed"); + } + + // init() runs once per bean in production; calling it again is the only way to observe a failed reparse. + @Test + void testAFailedReparseLeavesNothingTrustedRatherThanThePreviousKeys() { + CommunityGrantReleaseSignatureVerifier verifier = verifierTrusting(TRUSTS_A); + assertThatCode(() -> verifier.verify(CHECKER, SIGNATURE)).doesNotThrowAnyException(); + + ReflectionTestUtils.setField(verifier, "checkerReleasePublicKeys", "1:" + PUBLIC_KEY_A + ",2:not base64!"); + verifier.init(); + + assertThatThrownBy(() -> verifier.verify(CHECKER, SIGNATURE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("could not be parsed"); + } + + @Test + void testATrustStoreWithTwoKeysAcceptsReleasesSignedUnderEither() { + CommunityGrantReleaseSignatureVerifier verifier = verifierTrusting(TRUSTS_A_AND_B); + + assertThatCode(() -> verifier.verify(CHECKER, SIGNATURE)).doesNotThrowAnyException(); + assertThatCode(() -> verifier.verify(CHECKER, SIGNATURE_UNDER_KEY_ID_2)).doesNotThrowAnyException(); + // Each key id resolves to its own key. + assertRejected(TRUSTS_A_AND_B, CHECKER, SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1, + "does not match its release signature"); + } + + @Test + void testWhitespaceAroundEntriesIsTolerated() { + assertThatCode(() -> verifierTrusting(" 1 : " + PUBLIC_KEY_A + " , 2 : " + PUBLIC_KEY_B + " ") + .verify(CHECKER, SIGNATURE_UNDER_KEY_ID_2)).doesNotThrowAnyException(); + } + + @Test + void testAKeyIdOutsideOneToTwoFiveFiveCannotBeConfigured() { + assertUnparseable("0:" + PUBLIC_KEY_A, "reserved"); + assertUnparseable("256:" + PUBLIC_KEY_A, "1-255"); + assertUnparseable("-1:" + PUBLIC_KEY_A, "1-255"); + } + + @Test + void testMalformedEntriesAreRefusedRatherThanSkipped() { + assertUnparseable(PUBLIC_KEY_A, "keyId:base64PublicKey"); + assertUnparseable("one:" + PUBLIC_KEY_A, "not a number"); + assertUnparseable("1:" + PUBLIC_KEY_A + ",", "empty entry"); + assertUnparseable("1:" + PUBLIC_KEY_A + ",1:" + PUBLIC_KEY_B, "more than once"); + assertUnparseable("1:", "0 bytes"); + assertUnparseable("1:AAAA", "3 bytes"); + } + + @Test + void testAnX509WrappedPublicKeyIsRefused() { + byte[] raw = Base64.getDecoder().decode(PUBLIC_KEY_A); + byte[] wrapped = new byte[12 + raw.length]; + System.arraycopy(new byte[]{0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00}, + 0, wrapped, 0, 12); + System.arraycopy(raw, 0, wrapped, 12, raw.length); + + assertUnparseable("1:" + Base64.getEncoder().encodeToString(wrapped), "44 bytes"); + } + + // KeyFactory accepts some off-curve values and only fails at verification time. + @Test + void testAKeyThatIsNotAValidEd25519PointIsRefused() { + byte[] notAPoint = new byte[32]; + Arrays.fill(notAPoint, (byte) 0xFF); + + assertUnparseable("1:" + Base64.getEncoder().encodeToString(notAPoint), "not a usable Ed25519 public key"); + } + + @Test + void testRefusalMessagesCarryNoKeyMaterialOrUploadedBytes() { + byte[][] rejectedSignatures = {null, new byte[0], Arrays.copyOf(SIGNATURE, 75), OTHER_SIGNATURE, + SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1, SIGNATURE_UNDER_KEY_ID_2}; + for (byte[] rejected : rejectedSignatures) { + assertThatThrownBy(() -> verifierTrusting(TRUSTS_A).verify(CHECKER, rejected)) + .isInstanceOf(IllegalArgumentException.class) + .satisfies(e -> { + assertThat(e.getMessage()).doesNotContain(PUBLIC_KEY_A); + assertThat(e.getMessage()).doesNotContain(PUBLIC_KEY_B); + assertThat(e.getMessage()).doesNotContain("#!/bin/sh"); + }); + } + } + + private static void assertRejected(String trustedKeys, byte[] checker, byte[] signature, String expectedInMessage) { + assertThatThrownBy(() -> verifierTrusting(trustedKeys).verify(checker, signature)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(expectedInMessage); + } + + private static void assertUnparseable(String configured, String expectedInMessage) { + assertThatThrownBy(() -> CommunityGrantReleaseSignatureVerifier.parsePublicKeys(configured)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(expectedInMessage); + } + + private static CommunityGrantReleaseSignatureVerifier verifierTrusting(String configured) { + CommunityGrantReleaseSignatureVerifier verifier = new CommunityGrantReleaseSignatureVerifier(); + ReflectionTestUtils.setField(verifier, "checkerReleasePublicKeys", configured); + verifier.init(); + return verifier; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunnerTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunnerTest.java new file mode 100644 index 0000000000..922f0fb1db --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunnerTest.java @@ -0,0 +1,529 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.SystemUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; +import org.springframework.boot.info.BuildProperties; +import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.client.HttpClientErrorException; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CommunityGrantReportRunnerTest { + + private static final String TOKEN = "token-one"; + private static final String REPORT = "-----BEGIN TB INSTANCE CHECK-----\nZmFrZS1yZXBvcnQtYm9keQ==\n-----END TB INSTANCE CHECK-----"; + private static final UUID CLUSTER_ID = UUID.randomUUID(); + private static final String CHECKER_INPUT_JSON = "{\"clusterId\":\"" + CLUSTER_ID + "\",\"keyId\":7," + + "\"publicKey\":\"cHVi\",\"challenge\":\"Y2hh\",\"referenceMillis\":1787788800000}"; + private static final CommunityGrantCheckerInput CHECKER_INPUT = new CommunityGrantCheckerInput(CHECKER_INPUT_JSON); + private static final String TB_VERSION = "4.3.1.4"; + + private static final String RELEASE_PUBLIC_KEY = CommunityGrantSigningFixtures.PUBLIC_KEY_A; + private static final String TRUSTED_KEYS = CommunityGrantSigningFixtures.TRUSTS_A; + private static final byte[] SIGNED_CHECKER = CommunityGrantSigningFixtures.CHECKER; + private static final byte[] RELEASE_SIGNATURE = CommunityGrantSigningFixtures.SIGNATURE; + + @Mock + private CommunityGrantPortalClient portalClient; + + /** Real, not stubbed, so the refusal assertions depend on actual verification. */ + @Spy + private CommunityGrantReleaseSignatureVerifier releaseSignatureVerifier = + new CommunityGrantReleaseSignatureVerifier(); + + @Spy + @InjectMocks + private CommunityGrantReportRunner runner; + + private ListAppender testLogAppender; + + // No class-wide POSIX assumption: most tests never execute a script and must run on Windows too. + @BeforeEach + void setUp() { + ReflectionTestUtils.setField(runner, "dbUrl", "jdbc:postgresql://localhost:5432/thingsboard"); + ReflectionTestUtils.setField(runner, "dbUserName", "postgres"); + ReflectionTestUtils.setField(runner, "dbPassword", "secret"); + ReflectionTestUtils.setField(runner, "checkerTimeoutSec", 30); + ReflectionTestUtils.setField(runner, "maxReportSizeBytes", 1048576); + ReflectionTestUtils.setField(runner, "maxCheckerSizeBytes", 33554432L); + ReflectionTestUtils.setField(runner, "buildProperties", buildProperties(TB_VERSION)); + trustReleaseKeys(TRUSTED_KEYS); + Logger logger = (Logger) LoggerFactory.getLogger(CommunityGrantReportRunner.class); + testLogAppender = new ListAppender<>(); + testLogAppender.start(); + logger.addAppender(testLogAppender); + } + + @AfterEach + void tearDown() { + if (testLogAppender != null) { + testLogAppender.stop(); + Logger logger = (Logger) LoggerFactory.getLogger(CommunityGrantReportRunner.class); + logger.detachAppender(testLogAppender); + } + } + + @Test + void testRunAndUploadRunsTheCheckerAndUploadsItsOutput() throws IOException { + Path checker = fakeChecker("#!/bin/sh\ncat <<'EOF'\n" + REPORT + "\nEOF\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + when(portalClient.uploadReport(TOKEN, REPORT)).thenReturn("DONE"); + + String status = runner.runAndUpload(TOKEN, CHECKER_INPUT); + + assertThat(status).isEqualTo("DONE"); + verify(portalClient).uploadReport(TOKEN, REPORT); + } + + @Test + void testTheCheckerBinaryIsDeletedAfterTheRun() throws IOException { + Path checker = fakeChecker("#!/bin/sh\ncat <<'EOF'\n" + REPORT + "\nEOF\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + when(portalClient.uploadReport(anyString(), anyString())).thenReturn("DONE"); + + runner.runAndUpload(TOKEN, CHECKER_INPUT); + + assertThat(Files.exists(checker)).isFalse(); + assertThat(Files.exists(checker.getParent())).isFalse(); + } + + @Test + void testTheDsnAndTheInputArePassedThroughTheEnvironmentAndOnlyTheVersionOnArgv() throws IOException { + String report = runCheckerEchoingItsInvocation(); + + assertThat(report).contains("env=postgres://postgres:secret@localhost:5432/thingsboard"); + assertThat(report).contains("input=" + CHECKER_INPUT_JSON); + + // The checker refuses a flag it does not know, so argv is pinned exactly. + String argvLine = argvLine(report); + assertThat(argvLine).isEqualTo("argv=--tb-version " + TB_VERSION); + assertThat(argvLine).doesNotContain("secret"); + } + + @Test + void testTheVersionIsLeftOffWhereTheBuildCarriesNone() throws IOException { + ReflectionTestUtils.setField(runner, "buildProperties", null); + + String report = runCheckerEchoingItsInvocation(); + + assertThat(argvLine(report)).isEqualTo("argv="); + } + + // A constructed map: a spawned child would only see the PG* variables this host happens to export. + @Test + void testThePgEnvironmentIsStrippedWhileTheRestOfItSurvives() { + Map environment = new HashMap<>(); + environment.put("PGHOST", "attacker.example"); + environment.put("PGPASSWORD", "not-the-configured-one"); + environment.put("PGSERVICE", "redirected"); + environment.put("PGSSLMODE", "disable"); + // The Windows environment is case-insensitive, so this would reach the child as PGHOST. + environment.put("Pghost", "attacker.example"); + environment.put("PATH", "/usr/bin"); + environment.put("HOME", "/home/thingsboard"); + environment.put("HTTPS_PROXY", "http://proxy.internal:3128"); + environment.put("TB_IC_INPUT", "{\"inherited\":true}"); + + CommunityGrantReportRunner.prepareCheckerEnvironment(environment, "postgres://u:p@localhost:5432/tb", + CHECKER_INPUT); + + assertThat(environment).doesNotContainKeys("PGHOST", "PGPASSWORD", "PGSERVICE", "PGSSLMODE", "Pghost"); + assertThat(environment) + .containsEntry("PATH", "/usr/bin") + .containsEntry("HOME", "/home/thingsboard") + .containsEntry("HTTPS_PROXY", "http://proxy.internal:3128") + .containsEntry("TB_IC_DSN", "postgres://u:p@localhost:5432/tb") + .containsEntry("TB_IC_INPUT", CHECKER_INPUT_JSON); + } + + @Test + void testANonZeroExitIsAFailureAndNothingIsUploaded() throws IOException { + Path checker = fakeChecker("#!/bin/sh\necho \"-----BEGIN TB INSTANCE CHECK-----\"\nexit 3\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("3"); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + assertThat(Files.exists(checker.getParent())).isFalse(); + } + + @Test + void testACheckerThatHangsIsKilledAtTheTimeout() throws IOException { + ReflectionTestUtils.setField(runner, "checkerTimeoutSec", 1); + Path checker = fakeChecker("#!/bin/sh\nsleep 30\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not finish"); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testOversizedOutputIsRefused() throws IOException { + ReflectionTestUtils.setField(runner, "maxReportSizeBytes", 64); + Path checker = fakeChecker("#!/bin/sh\necho \"-----BEGIN TB INSTANCE CHECK-----\"\n" + + "i=0\nwhile [ $i -lt 5000 ]; do echo \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"; i=$((i+1)); done\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("more output than the configured limit"); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testOutputThatIsNotAReportIsRefused() throws IOException { + Path checker = fakeChecker("#!/bin/sh\necho \"hello from somewhere else\"\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testOutputThatIsMissingTheTrailerIsRefused() throws IOException { + Path checker = fakeChecker("#!/bin/sh\necho \"-----BEGIN TB INSTANCE CHECK-----\"\n" + + "echo \"ZmFrZS1yZXBvcnQtYm9keQ==\"\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unexpected output"); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testFetchCheckerWritesThePortalsBytesAsAnExecutableChecker() throws IOException { + assumeFalse(SystemUtils.IS_OS_WINDOWS, "The downloaded fixture is a POSIX shell script and is executed"); + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + when(portalClient.downloadChecker(TOKEN, platform.os(), platform.arch())).thenReturn(SIGNED_CHECKER); + when(portalClient.downloadCheckerSignature(TOKEN, platform.os(), platform.arch())) + .thenReturn(RELEASE_SIGNATURE); + + Path checker = runner.fetchChecker(TOKEN); + + try { + assertThat(checker).exists(); + assertThat(Files.isExecutable(checker)).isTrue(); + assertThat(runner.runChecker(checker, CHECKER_INPUT)).isEqualTo(REPORT); + } finally { + FileUtils.deleteQuietly(checker.getParent().toFile()); + } + } + + @Test + void testADownloadedCheckerThatDoesNotMatchItsReleaseSignatureIsRefusedAndNeverWritten() throws IOException { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + when(portalClient.downloadChecker(TOKEN, platform.os(), platform.arch())).thenReturn(SIGNED_CHECKER); + when(portalClient.downloadCheckerSignature(TOKEN, platform.os(), platform.arch())) + .thenReturn(CommunityGrantSigningFixtures.OTHER_SIGNATURE); + + assertThatThrownBy(() -> runner.fetchChecker(TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the release signature"); + verify(runner, never()).writeChecker(any(), anyString()); + } + + @Test + void testADownloadedCheckerWithNoReleaseSignatureStagedIsRefusedAndNeverWritten() throws IOException { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + when(portalClient.downloadChecker(TOKEN, platform.os(), platform.arch())).thenReturn(SIGNED_CHECKER); + when(portalClient.downloadCheckerSignature(TOKEN, platform.os(), platform.arch())) + .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); + + assertThatThrownBy(() -> runner.fetchChecker(TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no release signature"); + verify(runner, never()).writeChecker(any(), anyString()); + } + + @Test + void testTheOnlineRouteRefusesToRunWhenNoReleaseKeyIsConfigured() throws IOException { + for (String unusable : new String[]{"", "1:not base64!"}) { + trustReleaseKeys(unusable); + + assertThatThrownBy(() -> runner.fetchChecker(TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY) + .hasMessageContaining("was not run"); + } + verify(portalClient, never()).downloadChecker(anyString(), anyString(), anyString()); + verify(runner, never()).writeChecker(any(), anyString()); + } + + @Test + void testTheStagedCheckerIsOwnerOnlyAndNotWritable() throws IOException { + assumeFalse(SystemUtils.IS_OS_WINDOWS, "POSIX permissions"); + Path checker = runner.writeChecker("#!/bin/sh\n".getBytes(StandardCharsets.UTF_8), "tb-instance-check"); + + try { + assertThat(Files.getPosixFilePermissions(checker)) + .isEqualTo(PosixFilePermissions.fromString("r-x------")); + assertThat(Files.getPosixFilePermissions(checker.getParent())) + .isEqualTo(PosixFilePermissions.fromString("rwx------")); + } finally { + FileUtils.deleteQuietly(checker.getParent().toFile()); + } + } + + @Test + void testCurrentPlatformIsMappedToThePortalVocabulary() { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + assertThat(platform.os()).isIn("linux", "darwin", "windows"); + assertThat(platform.arch()).isIn("amd64", "arm64"); + } + + @Test + void testUploadedCheckerRunsWhenItsReleaseSignatureVerifies() { + assumeFalse(SystemUtils.IS_OS_WINDOWS, "The signed fixture is a POSIX shell script and is actually executed"); + String report = runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT); + + assertThat(report).isEqualTo(REPORT); + } + + @Test + void testATamperedUploadedCheckerIsRefusedAndNeverExecuted() throws IOException { + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + + assertThatThrownBy(() -> runner.runUploadedChecker(tampered, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match its release signature"); + // Never written either, which pins the check ahead of writeChecker. + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testVerifyingAnUploadRefusesATamperedCheckerAndNeverWritesOrRunsOne() throws IOException { + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + + assertThatThrownBy(() -> runner.verifyUploadedChecker(tampered, RELEASE_SIGNATURE, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match its release signature"); + runner.verifyUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null); + + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + } + + // Refusals ahead of the signature check do not log; the controller's audit row records them. + @Test + void testAnEmptyUploadIsRefusedWithoutWritingOrExecutingAnything() throws IOException { + assertThatThrownBy(() -> runner.runUploadedChecker(new byte[0], RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("is empty"); + + assertNothingWasWrittenExecutedOrLogged(); + } + + @Test + void testAnOversizedUploadIsRefusedWithoutWritingOrExecutingAnything() throws IOException { + ReflectionTestUtils.setField(runner, "maxCheckerSizeBytes", (long) SIGNED_CHECKER.length - 1); + + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("larger than the configured limit"); + + assertNothingWasWrittenExecutedOrLogged(); + } + + @Test + void testAnUploadNamingAnotherPlatformIsRefusedWithoutWritingOrExecutingAnything() throws IOException { + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, + anotherPlatformFileName(), CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match this server's platform"); + + assertNothingWasWrittenExecutedOrLogged(); + } + + @Test + void testAFileNameNamingNoOtherPlatformReachesTheSignatureCheck() { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + + for (String fileName : List.of(platform.checkerFileName(), + "tb-instance-check_" + platform.os() + "_" + platform.arch())) { + assertThatThrownBy(() -> runner.runUploadedChecker(tampered, RELEASE_SIGNATURE, fileName, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match its release signature"); + } + } + + @Test + void testAnUploadedCheckerWithNoSignatureIsRefusedAndNeverExecuted() throws IOException { + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, null, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("carries no release signature"); + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + } + + @Test + void testARefusedUploadIsLoggedAtWarnWithTheUploadedDigestAndNoSecrets() { + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + String uploadedDigest = sha256Hex(tampered); + + assertThatThrownBy(() -> runner.runUploadedChecker(tampered, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class); + + assertThat(testLogAppender.list).hasSize(1); + ILoggingEvent event = testLogAppender.list.get(0); + assertThat(event.getLevel()).isEqualTo(Level.WARN); + String formatted = event.getFormattedMessage(); + assertThat(formatted).contains("Refused").contains(uploadedDigest); + assertThat(formatted).doesNotContain(RELEASE_PUBLIC_KEY); + assertNoSecretsLeaked(formatted); + } + + @Test + void testAnUploadedCheckerIsRefusedWhenNoReleaseKeyIsConfigured() throws IOException { + trustReleaseKeys(""); + + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("community-grant.checker-release-public-keys"); + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + } + + @Test + void testAnUnconfiguredAndAMisconfiguredDeploymentAreRefusedDifferently() throws IOException { + trustReleaseKeys(""); + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .hasMessageContaining("refuses to run one") + .hasMessageNotContaining("could not be parsed"); + + trustReleaseKeys("1:" + RELEASE_PUBLIC_KEY + ",2:not base64!"); + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .hasMessageContaining("could not be parsed") + .hasMessageNotContaining("refuses to run one"); + + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + } + + @Test + void testTheRefusalMessagesNeverLeakTheDatasourcePasswordOrDsn() { + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + + assertThatThrownBy(() -> runner.runUploadedChecker(tampered, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .satisfies(e -> assertNoSecretsLeaked(e.getMessage())); + + trustReleaseKeys(""); + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .satisfies(e -> assertNoSecretsLeaked(e.getMessage())); + } + + private static String anotherPlatformFileName() { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + return "tb-instance-check_" + ("linux".equals(platform.os()) ? "windows" : "linux") + "_" + platform.arch(); + } + + private void trustReleaseKeys(String configured) { + ReflectionTestUtils.setField(releaseSignatureVerifier, "checkerReleasePublicKeys", configured); + releaseSignatureVerifier.init(); + } + + private void assertNoSecretsLeaked(String message) { + assertThat(message).doesNotContain("secret"); + assertThat(message).doesNotContain("postgres://"); + assertThat(message).doesNotContain(TOKEN); + } + + private static String sha256Hex(byte[] data) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(data)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static BuildProperties buildProperties(String version) { + Properties properties = new Properties(); + properties.setProperty("version", version); + return new BuildProperties(properties); + } + + private String runCheckerEchoingItsInvocation() throws IOException { + Path checker = fakeChecker("#!/bin/sh\n" + + "echo \"-----BEGIN TB INSTANCE CHECK-----\"\n" + + "echo \"env=$TB_IC_DSN\"\n" + + "echo \"input=$TB_IC_INPUT\"\n" + + "echo \"argv=$*\"\n" + + "echo \"-----END TB INSTANCE CHECK-----\"\n"); + try { + return runner.runChecker(checker, CHECKER_INPUT); + } finally { + FileUtils.deleteQuietly(checker.getParent().toFile()); + } + } + + private static String argvLine(String report) { + return Arrays.stream(report.split("\n")) + .filter(line -> line.startsWith("argv=")) + .findFirst() + .orElseThrow(() -> new AssertionError("The fake checker's output has no argv line")); + } + + private Path fakeChecker(String script) throws IOException { + assumeFalse(SystemUtils.IS_OS_WINDOWS, "The fake checker is a POSIX shell script with POSIX permissions"); + return runner.writeChecker(script.getBytes(StandardCharsets.UTF_8), "tb-instance-check"); + } + + private void assertNothingWasWrittenExecutedOrLogged() throws IOException { + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + assertThat(testLogAppender.list).isEmpty(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantSigningFixtures.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantSigningFixtures.java new file mode 100644 index 0000000000..58b2ddd782 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantSigningFixtures.java @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import java.util.Base64; + +/** + * Test-only keypairs; only the public halves appear here. + */ +final class CommunityGrantSigningFixtures { + + static final String PUBLIC_KEY_A = "jHpPieuz8lNtJdrhzz0vi0hzXAxljhABo1FfIRtjBb0="; + static final String PUBLIC_KEY_B = "aqbhyeoLeaeAqQhjO3vDN+PX3U66ptqY8rHSbfrbpMI="; + + static final String TRUSTS_A = "1:" + PUBLIC_KEY_A; + static final String TRUSTS_A_AND_B = "1:" + PUBLIC_KEY_A + ",2:" + PUBLIC_KEY_B; + + /** A shell script that prints a well-formed report, so a runner can execute it. */ + static final byte[] CHECKER = decode( + "IyEvYmluL3NoCmNhdCA8PCdFT0YnCi0tLS0tQkVHSU4gVEIgSU5TVEFOQ0UgQ0hFQ0stLS0tLQpabUZyWlMxeVpYQnZjb" + + "lF0WW05a2VRPT0KLS0tLS1FTkQgVEIgSU5TVEFOQ0UgQ0hFQ0stLS0tLQpFT0YK"); + + static final byte[] OTHER_CHECKER = decode( + "IyEvYmluL3NoCmVjaG8gIi0tLS0tQkVHSU4gVEIgSU5TVEFOQ0UgQ0hFQ0stLS0tLSIKZWNobyAiYSBkaWZmZXJlbnQgY" + + "2hlY2tlciBidWlsZCIK"); + + static final byte[] SIGNATURE = decode( + "VEJJQ1NJRzEBAWRjh7y4j1vNYnedESE5qBZss7R7LeimEWHJcX9du8OyGFpbWAxdi49A40GotXjo7EhXw9sUFxDiPuz1p" + + "wAjzgs="); + + static final byte[] OTHER_SIGNATURE = decode( + "VEJJQ1NJRzEBATCrpGddBA5MxIwkJOTMQZq/pg6b4IYEwA8a29TxsyYL2H52QRENSnlUCpl4y+IVgkKFdTMEp+0AmNft/" + + "FE64wc="); + + static final byte[] SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1 = decode( + "VEJJQ1NJRzEBASiAzItE5P7weSOkVkY8W6V9aOQ45jlwt6IW5POZkctc9inj2C5jrMaHNRK3tJ03ljhAOl9Ugsq3oYtCG" + + "9JFIgo="); + + static final byte[] SIGNATURE_UNDER_KEY_ID_2 = decode( + "VEJJQ1NJRzEBAiiAzItE5P7weSOkVkY8W6V9aOQ45jlwt6IW5POZkctc9inj2C5jrMaHNRK3tJ03ljhAOl9Ugsq3oYtCG" + + "9JFIgo="); + + private CommunityGrantSigningFixtures() { + } + + private static byte[] decode(String base64) { + return Base64.getDecoder().decode(base64); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateInfoTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateInfoTest.java new file mode 100644 index 0000000000..113dda0614 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateInfoTest.java @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +class CommunityGrantStateInfoTest { + + @Test + void testStateInfoSerializesExactlyTheNineAllowedFields() { + CommunityGrantFlowState flowState = CommunityGrantFlowState.initial(); + flowState.setSignUpUrl("https://portal.example/signup"); + flowState.setLastPolledAt(7L); + flowState.setParkReason(CommunityGrantParkReason.CHECK_FAILED); + // Must not reach the widget. + flowState.setStartedAt(3L); + flowState.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), 5L)); + + JsonNode json = JacksonUtil.valueToTree( + CommunityGrantStateInfo.of(flowState, "https://portal.example")); + + List fieldNames = new ArrayList<>(); + json.fieldNames().forEachRemaining(fieldNames::add); + assertThat(fieldNames).containsExactlyInAnyOrder("mode", "state", "signUpUrl", "lastPolledAt", + "parkReason", "portalUrl", "offlineReport", "offlineRunInProgress", "offlineRunError"); + assertThat(json.get("parkReason").asText()).isEqualTo("CHECK_FAILED"); + assertThat(json.get("portalUrl").asText()).isEqualTo("https://portal.example"); + assertThat(json.get("offlineReport").isNull()).isTrue(); + assertThat(json.get("offlineRunInProgress").asBoolean()).isFalse(); + assertThat(json.get("offlineRunError").isNull()).isTrue(); + } + + @Test + void testOnlyARecordedByHandRunOnTheReportStepCarriesTheReport() { + CommunityGrantFlowState flowState = CommunityGrantFlowState.initial(); + flowState.setState(CommunityGrantState.VALIDATING); + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isFalse(); + + flowState.setLastOfflineCheckAt(11L); + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isTrue(); + + flowState.setState(CommunityGrantState.COLLECTING); + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isFalse(); + flowState.setState(CommunityGrantState.REGISTERED); + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isFalse(); + } + + @Test + void testTheHandedOverStepKeepsCarryingTheReport() { + CommunityGrantFlowState flowState = CommunityGrantFlowState.initial(); + flowState.setState(CommunityGrantState.REPORT_HANDED_OVER); + flowState.setLastOfflineCheckAt(11L); + + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isTrue(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateTest.java new file mode 100644 index 0000000000..51e5b853b2 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateTest.java @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.Test; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; + +import static org.assertj.core.api.Assertions.assertThat; + +class CommunityGrantStateTest { + + @Test + void testTerminalAndPollableFlags() { + assertThat(CommunityGrantState.REGISTERED.isTerminal()).isTrue(); + assertThat(CommunityGrantState.ALREADY_REGISTERED.isTerminal()).isTrue(); + assertThat(CommunityGrantState.WRONG_INSTALLATION.isTerminal()).isTrue(); + assertThat(CommunityGrantState.RESUME.isTerminal()).isFalse(); + assertThat(CommunityGrantState.RESUME.isPollable()).isFalse(); + assertThat(CommunityGrantState.NOT_STARTED.isPollable()).isFalse(); + assertThat(CommunityGrantState.AWAITING_SIGNUP.isPollable()).isTrue(); + assertThat(CommunityGrantState.COLLECTING.isPollable()).isTrue(); + assertThat(CommunityGrantState.VALIDATING.isPollable()).isTrue(); + } + + @Test + void testUnderReviewIsPollableAndNotTerminal() { + assertThat(CommunityGrantState.UNDER_REVIEW.isTerminal()).isFalse(); + assertThat(CommunityGrantState.UNDER_REVIEW.isPollable()).isTrue(); + } + + @Test + void testTheHandOverIsPolledAndIsNotAnEnding() { + assertThat(CommunityGrantState.REPORT_HANDED_OVER.isTerminal()).isFalse(); + assertThat(CommunityGrantState.REPORT_HANDED_OVER.isPollable()).isTrue(); + assertThat(CommunityGrantState.REPORT_HANDED_OVER.isAwaitingOrPastDecision()).isTrue(); + } + + @Test + void testAwaitingOrPastDecisionCoversTheDecidedStatesAndUnderReview() { + assertThat(CommunityGrantState.REGISTERED.isAwaitingOrPastDecision()).isTrue(); + assertThat(CommunityGrantState.ALREADY_REGISTERED.isAwaitingOrPastDecision()).isTrue(); + assertThat(CommunityGrantState.UNDER_REVIEW.isAwaitingOrPastDecision()).isTrue(); + assertThat(CommunityGrantState.VALIDATING.isAwaitingOrPastDecision()).isFalse(); + assertThat(CommunityGrantState.RESUME.isAwaitingOrPastDecision()).isFalse(); + assertThat(CommunityGrantState.NOT_STARTED.isAwaitingOrPastDecision()).isFalse(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantUploadPayloadLimitTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantUploadPayloadLimitTest.java new file mode 100644 index 0000000000..7353c95711 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantUploadPayloadLimitTest.java @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.Test; +import org.thingsboard.server.transport.http.config.PayloadSizeFilter; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The offline upload carries a whole checker, so it needs its own {@code server.http.max_payload_size} entry. + * Not a MockMvc test: a mock multipart request's content length does not reflect the parts attached to it. + */ +class CommunityGrantUploadPayloadLimitTest { + + private static final String OFFLINE_RUN_URI = "/api/communityGrant/offline/run"; + + private static final long API_DEFAULT_LIMIT = 16777216L; + + @Test + void testTheCheckerCapPlusTheBundlesOwnOverheadFitsUnderTheEndpointsEntry() { + assertThat(maxCheckerSizeFromYaml() + CommunityGrantOfflineBundle.MAX_OVERHEAD_BYTES) + .as("community-grant.max-checker-size-bytes plus the bundle header and manifest must leave " + + "room under the %s entry in server.http.max_payload_size, which is compared " + + "against the whole request body", OFFLINE_RUN_URI) + .isLessThan(limitFor(OFFLINE_RUN_URI)); + } + + @Test + void testABundleAtTheDocumentedMaximumReachesTheControllerRatherThanA413() throws Exception { + FilterChain chain = mock(FilterChain.class); + // With a writer, a 413 fails the assertions below instead of throwing an NPE inside the filter. + HttpServletResponse response = mockResponseWithWriter(); + + filter().doFilterInternal(requestOf(OFFLINE_RUN_URI, + maxCheckerSizeFromYaml() + CommunityGrantOfflineBundle.MAX_OVERHEAD_BYTES + 65536), response, chain); + + verify(chain).doFilter(any(), any()); + verify(response, never()).setStatus(413); + } + + @Test + void testABodyPastTheEndpointsOwnEntryIsStillRefused() throws Exception { + FilterChain chain = mock(FilterChain.class); + HttpServletResponse response = mockResponseWithWriter(); + + filter().doFilterInternal(requestOf(OFFLINE_RUN_URI, 64L * 1024 * 1024), response, chain); + + verify(chain, never()).doFilter(any(), any()); + verify(response).setStatus(413); + } + + @Test + void testEveryOtherApiPathKeepsTheStockSixteenMegabyteCap() throws Exception { + FilterChain chain = mock(FilterChain.class); + HttpServletResponse response = mockResponseWithWriter(); + + filter().doFilterInternal(requestOf("/api/plugins/telemetry/DEVICE/x/values/timeseries", + API_DEFAULT_LIMIT + 1), response, chain); + + verify(chain, never()).doFilter(any(), any()); + verify(response).setStatus(413); + } + + @Test + void testTheEndpointsEntryPrecedesTheCatchAllItWouldOtherwiseFallTo() { + String limits = payloadLimitsFromYaml(); + + int endpointEntry = limits.indexOf(OFFLINE_RUN_URI + "="); + int catchAllEntry = limits.indexOf("/api/**="); + + assertThat(endpointEntry).as("the offline upload needs its own entry in server.http.max_payload_size") + .isNotNegative(); + assertThat(endpointEntry).as("it is ignored unless it precedes /api/**, which matches the same URI") + .isLessThan(catchAllEntry); + } + + private static PayloadSizeFilter filter() { + return new PayloadSizeFilter(payloadLimitsFromYaml()); + } + + private static HttpServletRequest requestOf(String uri, long contentLength) { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURI()).thenReturn(uri); + when(request.getContentLength()).thenReturn(Math.toIntExact(contentLength)); + return request; + } + + private static HttpServletResponse mockResponseWithWriter() throws Exception { + HttpServletResponse response = mock(HttpServletResponse.class); + when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter())); + return response; + } + + private static long limitFor(String pattern) { + for (String entry : payloadLimitsFromYaml().split(";")) { + if (entry.startsWith(pattern + "=")) { + return Long.parseLong(entry.substring(pattern.length() + 1)); + } + } + throw new IllegalStateException("server.http.max_payload_size has no entry for " + pattern); + } + + private static long maxCheckerSizeFromYaml() { + return Long.parseLong(matchInYaml( + "max-checker-size-bytes:\\s*\"\\$\\{COMMUNITY_GRANT_MAX_CHECKER_SIZE_BYTES:(\\d+)}\"", + "community-grant.max-checker-size-bytes")); + } + + private static String payloadLimitsFromYaml() { + return matchInYaml("max_payload_size:\\s*\"\\$\\{HTTP_MAX_PAYLOAD_SIZE_LIMIT_CONFIGURATION:([^}]*)}\"", + "server.http.max_payload_size"); + } + + private static String matchInYaml(String regex, String property) { + String yaml; + try (var in = CommunityGrantUploadPayloadLimitTest.class.getResourceAsStream("/thingsboard.yml")) { + yaml = new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (Exception e) { + throw new IllegalStateException("thingsboard.yml is not on the test classpath", e); + } + Matcher matcher = Pattern.compile(regex).matcher(yaml); + if (!matcher.find()) { + throw new IllegalStateException(property + " is not declared the way this test reads it"); + } + return matcher.group(1); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceConcurrencyTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceConcurrencyTest.java new file mode 100644 index 0000000000..f301dd4967 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceConcurrencyTest.java @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.google.common.util.concurrent.FluentFuture; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.AdminSettingsId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.HasId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.dao.subscription.TbClusterStore; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Uses a real {@link CommunityGrantFlowStateStore} over an in-memory settings map, so racing callers genuinely contend. + */ +class DefaultCommunityGrantServiceConcurrencyTest { + + private static final UUID CLUSTER_ID = UUID.randomUUID(); + private static final int THREADS = 8; + + @Test + void testConcurrentRequestAccessReachesThePortalExactlyOnce() throws Exception { + InMemoryAdminSettingsService adminSettingsService = new InMemoryAdminSettingsService(); + CommunityGrantFlowStateStore flowStateStore = new CommunityGrantFlowStateStore(adminSettingsService); + flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.ONLINE); + state.setState(CommunityGrantState.ALREADY_REGISTERED); + return state; + }); + + TbClusterStore tbClusterStore = mock(TbClusterStore.class); + when(tbClusterStore.getClusterId()).thenReturn(Optional.of(CLUSTER_ID)); + CommunityGrantPortalClient portalClient = mock(CommunityGrantPortalClient.class); + CommunityGrantPoller poller = mock(CommunityGrantPoller.class); + CommunityGrantReportRunner reportRunner = mock(CommunityGrantReportRunner.class); + CommunityGrantOfflineReportStore offlineReportStore = + new CommunityGrantOfflineReportStore(adminSettingsService); + DefaultCommunityGrantService service = new DefaultCommunityGrantService( + tbClusterStore, flowStateStore, portalClient, poller, reportRunner, offlineReportStore); + ReflectionTestUtils.setField(service, "enabled", true); + + CyclicBarrier barrier = new CyclicBarrier(THREADS); + ExecutorService executor = Executors.newFixedThreadPool(THREADS); + try { + List> futures = new ArrayList<>(); + for (int i = 0; i < THREADS; i++) { + futures.add(executor.submit(() -> { + barrier.await(); + try { + service.requestAccess(); + } catch (ThingsboardException expectedForAllButOneCaller) { + } + return null; + })); + } + for (Future future : futures) { + future.get(10, TimeUnit.SECONDS); + } + } finally { + executor.shutdown(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + + verify(portalClient, times(1)).requestAccess(eq(CLUSTER_ID)); + } + + private static final class InMemoryAdminSettingsService implements AdminSettingsService { + + private final Map rows = new ConcurrentHashMap<>(); + + @Override + public AdminSettings findAdminSettingsByKey(TenantId tenantId, String key) { + return rows.get(key); + } + + @Override + public AdminSettings saveAdminSettings(TenantId tenantId, AdminSettings adminSettings) { + if (adminSettings.getId() == null) { + adminSettings.setId(new AdminSettingsId(UUID.randomUUID())); + } + rows.put(adminSettings.getKey(), adminSettings); + return adminSettings; + } + + @Override + public AdminSettings findAdminSettingsById(TenantId tenantId, AdminSettingsId adminSettingsId) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public AdminSettings findAdminSettingsByTenantIdAndKey(TenantId tenantId, String key) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public PageData findAllByTenantId(TenantId tenantId, PageLink pageLink) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public boolean deleteAdminSettingsByTenantIdAndKey(TenantId tenantId, String key) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public Optional> findEntity(TenantId tenantId, EntityId entityId) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public FluentFuture>> findEntityAsync(TenantId tenantId, EntityId entityId) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public EntityType getEntityType() { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java new file mode 100644 index 0000000000..456585c195 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java @@ -0,0 +1,1171 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.google.common.util.concurrent.MoreExecutors; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRunStatus; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.dao.subscription.TbClusterStore; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.UnaryOperator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class DefaultCommunityGrantServiceTest { + + private static final UUID CLUSTER_ID = UUID.randomUUID(); + private static final CommunityGrantCheckerInput CHECKER_INPUT = new CommunityGrantCheckerInput("{\"keyId\":7}"); + private static final int CHECKER_TIMEOUT_SEC = 600; + /** A run still marked running after this long has lost its node. */ + private static final long STALE_AFTER_MS = + TimeUnit.SECONDS.toMillis(CHECKER_TIMEOUT_SEC) + DefaultCommunityGrantService.OFFLINE_RUN_GRACE_MS; + + @Mock + private TbClusterStore tbClusterStore; + @Mock + private CommunityGrantFlowStateStore flowStateStore; + @Mock + private CommunityGrantPortalClient portalClient; + @Mock + private CommunityGrantPoller poller; + @Mock + private CommunityGrantReportRunner reportRunner; + @Mock + private CommunityGrantOfflineReportStore offlineReportStore; + + @InjectMocks + private DefaultCommunityGrantService service; + + private CommunityGrantFlowState stored; + /** What each background run reported on completion: {@code null} for a success. */ + private final List completion = new ArrayList<>(); + + @BeforeEach + void setUp() { + ReflectionTestUtils.setField(service, "enabled", true); + ReflectionTestUtils.setField(service, "offlineRunExecutor", MoreExecutors.newDirectExecutorService()); + when(reportRunner.getCheckerTimeoutSec()).thenReturn(CHECKER_TIMEOUT_SEC); + stored = CommunityGrantFlowState.initial(); + when(flowStateStore.get()).thenAnswer(invocation -> stored); + when(flowStateStore.update(any())).thenAnswer(invocation -> { + UnaryOperator updater = invocation.getArgument(0); + stored = updater.apply(stored); + return stored; + }); + when(tbClusterStore.getClusterId()).thenReturn(Optional.of(CLUSTER_ID)); + } + + private void givenReachablePortal() { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(false); + givenSignUpUrl(); + } + + private void givenSignUpUrl() { + when(portalClient.buildSignUpUrl(any(), anyString(), any())).thenAnswer(invocation -> + signUpUrl(invocation.getArgument(1), invocation.getArgument(2))); + } + + private static String signUpUrl(String token, CommunityGrantMode mode) { + return "https://portal.example/signup?clusterId=" + CLUSTER_ID + "&claimToken=" + token + + (mode == CommunityGrantMode.OFFLINE ? "&offline=true" : ""); + } + + /** With the direct executor, the background run has finished by the time this returns. */ + private CommunityGrantStateInfo runChecker() throws ThingsboardException { + return service.runOfflineChecker(new byte[]{1}, new byte[]{2}, "checker", CHECKER_INPUT, completion::add); + } + + @Test + void testStateCarriesTheReportOnceAByHandRunHasBeenRecorded() { + stored.setState(CommunityGrantState.VALIDATING); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + assertThat(service.getStateInfo().offlineReport()).isEqualTo("report-body"); + } + + @Test + void testStateCarriesNoReportBeforeAnyRun() { + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + + assertThat(service.getStateInfo().offlineReport()).isNull(); + verifyNoInteractions(offlineReportStore); + } + + @Test + void testTheOnlineWaitCarriesNoReportAndNeverReadsTheStore() { + stored.setState(CommunityGrantState.VALIDATING); + stored.setMode(CommunityGrantMode.ONLINE); + + assertThat(service.getStateInfo().offlineReport()).isNull(); + verifyNoInteractions(offlineReportStore); + } + + @Test + void testStartClearsTheByHandRunTimestampSoNoReportLeaksIntoTheNextEnrollment() throws ThingsboardException { + stored.setState(CommunityGrantState.RESUME); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + givenReachablePortal(); + + service.start(); + + assertThat(stored.getLastOfflineCheckAt()).isNull(); + stored.setState(CommunityGrantState.VALIDATING); + assertThat(service.getStateInfo().offlineReport()).isNull(); + verify(offlineReportStore, never()).get(); + } + + @Test + void testTheStateCarriesThePortalThisDeploymentIsConfiguredAgainst() { + when(portalClient.getPortalUrl()).thenReturn("https://portal.staging.example"); + + assertThat(service.getStateInfo().portalUrl()).isEqualTo("https://portal.staging.example"); + } + + @Test + void testAnUnreadableReportStoreStillAnswersWithTheState() { + stored.setState(CommunityGrantState.VALIDATING); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + when(offlineReportStore.get()).thenThrow(new IllegalStateException("boom")); + + CommunityGrantStateInfo info = service.getStateInfo(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(info.offlineReport()).isNull(); + } + + @Test + void testStartAsksAboutTheInstallationBeforeMintingAToken() throws ThingsboardException { + givenReachablePortal(); + + CommunityGrantStateInfo info = service.start(); + + InOrder inOrder = inOrder(tbClusterStore, portalClient); + inOrder.verify(portalClient).isAlreadyRegistered(CLUSTER_ID); + inOrder.verify(tbClusterStore).saveLicenseClaimToken(anyString()); + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(info.mode()).isEqualTo(CommunityGrantMode.ONLINE); + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + verify(tbClusterStore).saveLicenseClaimToken(tokenCaptor.capture()); + verify(portalClient).buildSignUpUrl(CLUSTER_ID, tokenCaptor.getValue(), CommunityGrantMode.ONLINE); + assertThat(info.signUpUrl()).isEqualTo(signUpUrl(tokenCaptor.getValue(), CommunityGrantMode.ONLINE)); + verify(poller).arm(); + } + + @Test + void testMintedTokenIsUrlSafeAndLongEnough() throws ThingsboardException { + givenReachablePortal(); + + service.start(); + + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + verify(tbClusterStore).saveLicenseClaimToken(tokenCaptor.capture()); + String token = tokenCaptor.getValue(); + assertThat(token).hasSize(43).matches("[A-Za-z0-9_-]+"); + } + + @Test + void testStartFallsBackToOfflineWhenThePortalIsUnreachable() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(false); + givenSignUpUrl(); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.mode()).isEqualTo(CommunityGrantMode.OFFLINE); + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + verify(tbClusterStore).saveLicenseClaimToken(tokenCaptor.capture()); + verify(portalClient).buildSignUpUrl(CLUSTER_ID, tokenCaptor.getValue(), CommunityGrantMode.OFFLINE); + assertThat(info.signUpUrl()).isEqualTo(signUpUrl(tokenCaptor.getValue(), CommunityGrantMode.OFFLINE)); + verify(portalClient, never()).isAlreadyRegistered(any()); + // Armed offline too: the tick enforces the sign-up deadline. + verify(poller).arm(); + verify(poller, never()).disarm(); + } + + // Asserts the mode arm() reads when it is called, not just the order of the calls. + @Test + void testRecoveringFromOfflineToOnlineWritesTheNewModeBeforeArming() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + givenReachablePortal(); + AtomicReference modeVisibleToArm = new AtomicReference<>(); + doAnswer(invocation -> { + modeVisibleToArm.set(flowStateStore.get().getMode()); + return null; + }).when(poller).arm(); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.mode()).isEqualTo(CommunityGrantMode.ONLINE); + verify(poller).arm(); + assertThat(modeVisibleToArm).hasValue(CommunityGrantMode.ONLINE); + } + + @Test + void testAStoreFailureOnTheAlreadyRegisteredPathIsReportedCleanly() { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(true); + doThrow(new IllegalStateException("db down")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("Failed to start") + .hasNoCause(); + } + + @Test + void testStartStopsAtAlreadyRegisteredWithoutEverMintingAToken() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(true); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.ALREADY_REGISTERED); + assertThat(info.signUpUrl()).isNull(); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + verify(tbClusterStore).forceClearLicenseClaimToken(); + verify(poller, never()).arm(); + verify(poller).disarm(); + } + + @Test + void testStartContinuesWhenTheClusterStatusCallFails() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + givenSignUpUrl(); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)) + .thenThrow(new RuntimeException("portal hiccup")); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(poller).arm(); + } + + @Test + void testStartFailsWithoutAdvancingWhenTheTokenCannotBeStored() { + givenReachablePortal(); + doThrow(new IllegalStateException("empty table")).when(tbClusterStore).saveLicenseClaimToken(anyString()); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("Failed to start") + .hasNoCause(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + verify(poller, never()).arm(); + } + + @Test + void testStartClearsTheExactTokenWhenTheFlowStateCannotBePersisted() { + givenReachablePortal(); + // doThrow(): re-stubbing with when() would run setUp()'s answer with a null updater. + doThrow(new IllegalStateException("stored document is unreadable")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class).hasNoCause(); + + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + verify(tbClusterStore).saveLicenseClaimToken(tokenCaptor.capture()); + verify(tbClusterStore).clearLicenseClaimToken(tokenCaptor.getValue()); + verify(poller, never()).arm(); + } + + @Test + void testStartFailsCleanlyWhenThePortalBaseUrlIsMalformed() { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(false); + when(portalClient.buildSignUpUrl(any(), anyString(), any())) + .thenThrow(new IllegalArgumentException("URI is not absolute")); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("misconfigured") + .hasNoCause(); + + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + verify(poller, never()).arm(); + } + + @Test + void testStartFailsWhenTheDeploymentHasNoClusterId() { + when(tbClusterStore.getClusterId()).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + } + + @Test + void testStartFromResumeMintsAFreshToken() throws ThingsboardException { + stored.setState(CommunityGrantState.RESUME); + givenReachablePortal(); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(info.signUpUrl()).contains("claimToken="); + } + + @Test + void testStartingAgainClearsTheParkReason() throws ThingsboardException { + givenReachablePortal(); + stored.setState(CommunityGrantState.RESUME); + stored.setParkReason(CommunityGrantParkReason.CHECK_FAILED); + + service.start(); + + assertThat(stored.getParkReason()).isNull(); + } + + // The pre-flight cannot say whose registration it found; on a flow begun here it is most likely this one's. + @Test + void testStartAgainOutOfAParkReMintsInsteadOfDeadEndingOnThePreFlight() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + givenSignUpUrl(); + stored.setState(CommunityGrantState.RESUME); + stored.setParkReason(CommunityGrantParkReason.LINK_EXPIRED); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(info.parkReason()).isNull(); + verify(portalClient, never()).isAlreadyRegistered(any()); + verify(tbClusterStore).saveLicenseClaimToken(anyString()); + } + + @Test + void testThePreFlightStillRefusesADeploymentThatHasNeverEnrolledFromHere() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(true); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.ALREADY_REGISTERED); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + } + + @Test + void testStartIsRefusedOnATerminalState() { + stored.setState(CommunityGrantState.REGISTERED); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + } + + @Test + void testStartIsRefusedWhileTheRegistrationIsUnderReview() { + stored.setState(CommunityGrantState.UNDER_REVIEW); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.UNDER_REVIEW_MESSAGE); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + verify(poller, never()).disarm(); + } + + @Test + void testStartIsRefusedWhenTheFeatureIsDisabled() { + ReflectionTestUtils.setField(service, "enabled", false); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class); + verify(portalClient, never()).isPortalReachable(); + } + + @Test + void testStartingRetiresThePreviousRunsReport() throws ThingsboardException { + givenReachablePortal(); + + service.start(); + + verify(offlineReportStore).clear(); + } + + @Test + void testStartingAsAlreadyRegisteredRetiresThePreviousRunsReport() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(true); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.ALREADY_REGISTERED); + verify(offlineReportStore).clear(); + } + + @Test + void testAFailedStartLeavesTheReportAlone() { + givenReachablePortal(); + doThrow(new IllegalStateException("connection refused")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class); + + verify(offlineReportStore, never()).clear(); + } + + @Test + void testRunOfflineCheckerMovesToValidatingOnSuccess() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + verify(reportRunner).runUploadedChecker(any(), any(), any(), eq(CHECKER_INPUT)); + verify(offlineReportStore).put("report-body"); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(stored.getMode()).isEqualTo(CommunityGrantMode.OFFLINE); + assertThat(stored.getLastOfflineCheckAt()).isNotNull(); + } + + @Test + void testTheUploadAnswersWithARunInProgressAndTheReportArrivesThroughTheState() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + CommunityGrantStateInfo answer = runChecker(); + + assertThat(answer.offlineRunInProgress()).isTrue(); + assertThat(answer.offlineRunError()).isNull(); + verify(reportRunner).verifyUploadedChecker(any(), any(), any()); + verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + assertThat(service.getStateInfo().offlineRunInProgress()).isTrue(); + + runQueuedTasks(); + + CommunityGrantStateInfo state = service.getStateInfo(); + assertThat(state.offlineRunInProgress()).isFalse(); + assertThat(state.offlineRunError()).isNull(); + assertThat(state.state()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(state.offlineReport()).isEqualTo("report-body"); + assertThat(stored.getOfflineRun()).isNull(); + assertThat(completion).containsExactly((Exception) null); + } + + @Test + void testAFailedRunIsReportedThroughTheState() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("The instance check failed with exit code 3")); + + CommunityGrantStateInfo answer = runChecker(); + + assertThat(answer.offlineRunInProgress()).isTrue(); + CommunityGrantStateInfo state = service.getStateInfo(); + assertThat(state.offlineRunInProgress()).isFalse(); + assertThat(state.offlineRunError()) + .isEqualTo("Failed to run the check. The instance check failed with exit code 3"); + assertThat(state.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.FAILED); + assertThat(completion).hasSize(1); + assertThat(completion.get(0)).isInstanceOf(ThingsboardException.class) + .hasMessage(state.offlineRunError()); + verify(offlineReportStore, never()).put(any()); + } + + @Test + void testARunningRecordPastItsTimeIsReportedAsInterrupted() { + long now = System.currentTimeMillis(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), now - STALE_AFTER_MS - 1000)); + + CommunityGrantStateInfo state = service.getStateInfo(); + + assertThat(state.offlineRunInProgress()).isFalse(); + assertThat(state.offlineRunError()).isEqualTo(DefaultCommunityGrantService.OFFLINE_RUN_INTERRUPTED_MESSAGE); + } + + @Test + void testARunningRecordWithinItsTimeIsReportedAsInProgress() { + long now = System.currentTimeMillis(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), now - STALE_AFTER_MS + 60_000)); + + CommunityGrantStateInfo state = service.getStateInfo(); + + assertThat(state.offlineRunInProgress()).isTrue(); + assertThat(state.offlineRunError()).isNull(); + } + + @Test + void testASecondStartIsRefusedWhileARunIsInProgress() { + UUID otherRun = UUID.randomUUID(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(otherRun, System.currentTimeMillis())); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_IN_PROGRESS_MESSAGE) + .satisfies(e -> assertThat(((ThingsboardException) e).getErrorCode()) + .isEqualTo(ThingsboardErrorCode.TOO_MANY_REQUESTS)); + + assertThat(stored.getOfflineRun().getRunId()).isEqualTo(otherRun); + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.RUNNING); + verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + assertThat(completion).isEmpty(); + } + + @Test + void testAStaleRunDoesNotRefuseTheNextStart() throws ThingsboardException { + stored.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), + System.currentTimeMillis() - STALE_AFTER_MS - 1000)); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + + runChecker(); + + verify(reportRunner).runUploadedChecker(any(), any(), any(), any()); + assertThat(stored.getOfflineRun()).isNull(); + } + + @Test + void testASecondStartOnTheSameNodeIsRefusedWhileItsRunIsQueued() throws ThingsboardException { + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + runChecker(); + // Stands in for another node's clear, so only the permit is left to refuse. + stored.setOfflineRun(null); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_IN_PROGRESS_MESSAGE); + verify(reportRunner, times(1)).verifyUploadedChecker(any(), any(), any()); + } + + // Two starts on two nodes can both pass the per-node lock; the later record wins. + @Test + void testACompletionLeavesAnotherRunsRecordAlone() throws ThingsboardException { + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("The instance check failed with exit code 3")); + runChecker(); + UUID newerRun = UUID.randomUUID(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(newerRun, System.currentTimeMillis())); + + runQueuedTasks(); + + assertThat(stored.getOfflineRun().getRunId()).isEqualTo(newerRun); + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.RUNNING); + assertThat(completion).hasSize(1); + } + + @Test + void testASupersededSuccessfulRunDiscardsItsResult() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + runChecker(); + UUID newerRun = UUID.randomUUID(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(newerRun, System.currentTimeMillis())); + + runQueuedTasks(); + + assertThat(stored.getOfflineRun().getRunId()).isEqualTo(newerRun); + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.RUNNING); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getLastOfflineCheckAt()).isNull(); + verify(offlineReportStore, never()).put(any()); + assertThat(completion).hasSize(1); + assertThat(completion.get(0)).hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_SUPERSEDED_MESSAGE); + } + + @Test + void testARunThatAStartReplacedDiscardsItsResult() throws ThingsboardException { + givenReachablePortal(); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + runChecker(); + + service.start(); + runQueuedTasks(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getOfflineRun()).isNull(); + assertThat(stored.getLastOfflineCheckAt()).isNull(); + verify(offlineReportStore, never()).put(any()); + assertThat(completion).hasSize(1); + assertThat(completion.get(0)).hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_SUPERSEDED_MESSAGE); + } + + @Test + void testAStartLandingBetweenTheOwnershipCheckAndTheWriteLeavesTheStateAlone() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + // Stands in for a start() clearing the record right after the report was put. + doAnswer(invocation -> { + stored.setOfflineRun(null); + return null; + }).when(offlineReportStore).put(any()); + + runChecker(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getLastOfflineCheckAt()).isNull(); + assertThat(completion.get(0)).hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_SUPERSEDED_MESSAGE); + } + + @Test + void testARunThatCannotBeScheduledIsRecordedAsFailedAndReleasesThePermit() throws ThingsboardException { + ExecutorService rejecting = MoreExecutors.newDirectExecutorService(); + rejecting.shutdown(); + ReflectionTestUtils.setField(service, "offlineRunExecutor", rejecting); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_NOT_SCHEDULED_MESSAGE); + + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.FAILED); + assertThat(stored.getOfflineRun().getError()) + .isEqualTo(DefaultCommunityGrantService.OFFLINE_RUN_NOT_SCHEDULED_MESSAGE); + assertThat(service.getStateInfo().offlineRunError()) + .isEqualTo(DefaultCommunityGrantService.OFFLINE_RUN_NOT_SCHEDULED_MESSAGE); + + ReflectionTestUtils.setField(service, "offlineRunExecutor", MoreExecutors.newDirectExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + runChecker(); + + verify(reportRunner).runUploadedChecker(any(), any(), any(), any()); + } + + @Test + void testStartClearsTheOfflineRun() throws ThingsboardException { + givenReachablePortal(); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), System.currentTimeMillis())); + + service.start(); + + assertThat(stored.getOfflineRun()).isNull(); + } + + @Test + void testARefusedBundleRecordsNoRun() { + doThrow(new IllegalArgumentException("The uploaded checker does not match its release signature")) + .when(reportRunner).verifyUploadedChecker(any(), any(), any()); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage("The uploaded checker does not match its release signature") + .satisfies(e -> assertThat(((ThingsboardException) e).getErrorCode()) + .isEqualTo(ThingsboardErrorCode.BAD_REQUEST_PARAMS)); + + assertThat(stored.getOfflineRun()).isNull(); + verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + assertThat(completion).isEmpty(); + } + + @Test + void testARefusedBundleReleasesThePermit() throws ThingsboardException { + doThrow(new IllegalArgumentException("refused")).doNothing() + .when(reportRunner).verifyUploadedChecker(any(), any(), any()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + + assertThatThrownBy(this::runChecker).isInstanceOf(ThingsboardException.class); + runChecker(); + + verify(reportRunner).runUploadedChecker(any(), any(), any(), any()); + } + + private void runQueuedTasks() { + ExecutorService executor = (ExecutorService) ReflectionTestUtils.getField(service, "offlineRunExecutor"); + ((QueuedExecutorService) executor).runAll(); + } + + @Test + void testRunOfflineCheckerIsRefusedWhenTheFeatureIsDisabled() { + ReflectionTestUtils.setField(service, "enabled", false); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("not available on this deployment"); + verifyNoInteractions(reportRunner); + } + + @Test + void testRunOfflineCheckerPreservesAnAlreadyOnlineMode() throws ThingsboardException { + stored.setMode(CommunityGrantMode.ONLINE); + stored.setState(CommunityGrantState.COLLECTING); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + assertThat(stored.getMode()).isEqualTo(CommunityGrantMode.ONLINE); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + } + + // The audit log renders the whole cause chain, so no cause may be attached. + @Test + void testOfflineStateWriteFailureIsReportedCleanlyWithoutACause() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + failUpdatesAfterTheFirst(new IllegalStateException( + "connection refused: jdbc:postgresql://db.internal:5432/tb?user=tb&password=hunter2")); + + runChecker(); + + assertThat(completion).hasSize(1); + assertThat(completion.get(0)) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_STATE_NOT_PERSISTED_MESSAGE) + .hasNoCause() + .satisfies(e -> { + assertThat(e.getMessage()).doesNotContain("hunter2"); + assertThat(e.getMessage()).doesNotContain("jdbc:postgresql"); + }); + } + + @Test + void testTheReportIsStoredEvenWhenTheStateWriteFails() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + failUpdatesAfterTheFirst(new IllegalStateException("connection refused")); + + runChecker(); + + assertThat(completion.get(0)).isInstanceOf(ThingsboardException.class); + verify(offlineReportStore).put("report-body"); + } + + @Test + void testAFailedReadAfterTheRunStoresNothingAndPromisesNoDownload() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenAnswer(invocation -> { + // The checker has run; the database goes away before its result is recorded. + doThrow(new IllegalStateException("connection refused: jdbc:postgresql://db.internal:5432/tb")) + .when(flowStateStore).get(); + return "report-body"; + }); + + runChecker(); + + verify(offlineReportStore, never()).put(any()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getOfflineRun().getError()) + .isEqualTo(DefaultCommunityGrantService.OFFLINE_RESULT_NOT_RECORDED_MESSAGE) + .doesNotContain("download"); + assertThat(completion.get(0)) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RESULT_NOT_RECORDED_MESSAGE) + .hasNoCause(); + } + + @Test + void testAStartThatCannotBeRecordedIsRefusedWithoutACause() { + doThrow(new IllegalStateException("connection refused: jdbc:postgresql://db.internal:5432/tb")) + .when(flowStateStore).update(any()); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_START_FAILED_MESSAGE) + .hasNoCause(); + + verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + assertThat(completion).isEmpty(); + } + + @Test + void testRunOfflineCheckerDoesNotAdvanceTheStateWhenTheRunFails() throws ThingsboardException { + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenThrow(new IllegalArgumentException("the uploaded checker does not match its release signature")); + + runChecker(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getLastOfflineCheckAt()).isNull(); + assertThat(stored.getOfflineRun().getError()) + .isEqualTo("the uploaded checker does not match its release signature"); + verify(offlineReportStore, never()).put(any()); + } + + /** The first write - the one recording the start - lands; every later one throws {@code failure}. */ + private void failUpdatesAfterTheFirst(RuntimeException failure) { + AtomicInteger calls = new AtomicInteger(); + doAnswer(invocation -> { + if (calls.incrementAndGet() > 1) { + throw failure; + } + UnaryOperator updater = invocation.getArgument(0); + stored = updater.apply(stored); + return stored; + }).when(flowStateStore).update(any()); + } + + @Test + void testRunOfflineCheckerCanBeRunAgainFromValidating() throws ThingsboardException { + stored.setState(CommunityGrantState.VALIDATING); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("second-report-body"); + + runChecker(); + + verify(offlineReportStore).put("second-report-body"); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + } + + @Test + void testRunOfflineCheckerFromAParkedResumeClearsTheParkReason() throws ThingsboardException { + stored.setState(CommunityGrantState.RESUME); + stored.setParkReason(CommunityGrantParkReason.LINK_EXPIRED); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(stored.getParkReason()).isNull(); + } + + @Test + void testRunOfflineCheckerLeavesATerminalStateAlone() throws ThingsboardException { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + verify(offlineReportStore).put("report-body"); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.ALREADY_REGISTERED); + assertThat(stored.getLastOfflineCheckAt()).isNotNull(); + } + + @Test + void testRunOfflineCheckerLeavesAnUnderReviewFlowAlone() throws ThingsboardException { + stored.setState(CommunityGrantState.UNDER_REVIEW); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + verify(offlineReportStore).put("report-body"); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + } + + @Test + void testRequestAccessIsRefusedOnTheWrongInstallationRefusal() { + stored.setState(CommunityGrantState.WRONG_INSTALLATION); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NOT_ALREADY_REGISTERED_MESSAGE); + verifyNoInteractions(portalClient); + } + + @Test + void testRequestAccessCallsThePortalWithTheClusterId() throws ThingsboardException { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + + service.requestAccess(); + + verify(portalClient).requestAccess(CLUSTER_ID); + } + + @Test + void testRequestAccessFailsCleanlyWhenThePortalCallFails() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + doThrow(new RuntimeException("connect timed out")).when(portalClient).requestAccess(CLUSTER_ID); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REQUEST_ACCESS_FAILED_MESSAGE); + } + + @Test + void testRequestAccessIsRefusedWhenNotAlreadyRegistered() { + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NOT_ALREADY_REGISTERED_MESSAGE); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessIsRefusedWhenTheFeatureIsDisabled() { + ReflectionTestUtils.setField(service, "enabled", false); + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + + assertThatThrownBy(() -> service.requestAccess()).isInstanceOf(ThingsboardException.class); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessIsRateLimitedWithinCooldownWindow() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + stored.setLastRequestAccessAt(System.currentTimeMillis() - 1000); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REQUEST_ACCESS_RATE_LIMITED_MESSAGE); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessIsAllowedAfterTheCooldownWindowElapses() throws ThingsboardException { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + stored.setLastRequestAccessAt(System.currentTimeMillis() + - DefaultCommunityGrantService.REQUEST_ACCESS_COOLDOWN_MS - 1000); + + service.requestAccess(); + + verify(portalClient).requestAccess(CLUSTER_ID); + } + + @Test + void testRequestAccessRecordsTheTimestampEvenWhenThePortalCallFails() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + doThrow(new RuntimeException("connect timed out")).when(portalClient).requestAccess(CLUSTER_ID); + + assertThatThrownBy(() -> service.requestAccess()).isInstanceOf(ThingsboardException.class); + + assertThat(stored.getLastRequestAccessAt()).isNotNull(); + } + + @Test + void testRequestAccessFailsWhenTheDeploymentHasNoClusterId() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + when(tbClusterStore.getClusterId()).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NO_CLUSTER_ID_MESSAGE); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessFailsCleanlyWhenTheFlowStateCannotBePersisted() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + doThrow(new IllegalStateException("stored document is unreadable")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REQUEST_ACCESS_STORE_FAILED_MESSAGE) + .hasNoCause(); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessFailsCleanlyWhenTheClusterIdLookupFails() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + when(tbClusterStore.getClusterId()).thenThrow(new RuntimeException("connection refused")); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REQUEST_ACCESS_STORE_FAILED_MESSAGE); + verify(portalClient, never()).requestAccess(any()); + verify(flowStateStore, never()).update(any()); + } + + @Test + void testGetOfflineReportReturnsTheStoredReportVerbatim() throws ThingsboardException { + when(offlineReportStore.get()).thenReturn(Optional.of("-----BEGIN TB INSTANCE CHECK-----\nbody")); + + assertThat(service.getOfflineReport()).isEqualTo("-----BEGIN TB INSTANCE CHECK-----\nbody"); + } + + @Test + void testGetOfflineReportRefusesWhenNoCheckHasRun() { + when(offlineReportStore.get()).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.getOfflineReport()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NO_OFFLINE_REPORT_MESSAGE) + .extracting(e -> ((ThingsboardException) e).getErrorCode()) + .isEqualTo(ThingsboardErrorCode.ITEM_NOT_FOUND); + } + + @Test + void testConfirmOfflineHandoffRecordsTheClaimAndAnswersWithTheReport() throws ThingsboardException { + stored.setState(CommunityGrantState.VALIDATING); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + CommunityGrantStateInfo info = service.confirmOfflineHandoff(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(info.state()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(info.offlineReport()).isEqualTo("report-body"); + // Online the poller is already armed; offline it stays disarmed. + verifyNoInteractions(poller); + } + + @Test + void testConfirmOfflineHandoffIsIdempotent() throws ThingsboardException { + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + CommunityGrantStateInfo info = service.confirmOfflineHandoff(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(info.offlineReport()).isEqualTo("report-body"); + verify(flowStateStore, never()).update(any()); + } + + @ParameterizedTest + @EnumSource(value = CommunityGrantState.class, mode = EnumSource.Mode.EXCLUDE, + names = {"VALIDATING", "REPORT_HANDED_OVER"}) + void testConfirmOfflineHandoffIsRefusedFromEveryOtherState(CommunityGrantState state) { + stored.setState(state); + + assertThatThrownBy(() -> service.confirmOfflineHandoff()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NOTHING_TO_HAND_OVER_MESSAGE); + verify(flowStateStore, never()).update(any()); + } + + @Test + void testConfirmOfflineHandoffIsRefusedWhenTheFeatureIsDisabled() { + ReflectionTestUtils.setField(service, "enabled", false); + stored.setState(CommunityGrantState.VALIDATING); + + assertThatThrownBy(() -> service.confirmOfflineHandoff()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NOT_AVAILABLE_MESSAGE) + .extracting(e -> ((ThingsboardException) e).getErrorCode()) + .isEqualTo(ThingsboardErrorCode.ITEM_NOT_FOUND); + verify(flowStateStore, never()).update(any()); + } + + // A poll can land between this call's read and write; the updater re-tests under the store's lock. + @Test + void testConfirmOfflineHandoffLosesToADecisionThatLandsMidCall() throws ThingsboardException { + stored.setState(CommunityGrantState.VALIDATING); + doAnswer(invocation -> { + // The poller's retire() landing between the read and the write. + stored.setState(CommunityGrantState.REGISTERED); + UnaryOperator updater = invocation.getArgument(0); + stored = updater.apply(stored); + return stored; + }).when(flowStateStore).update(any()); + + CommunityGrantStateInfo info = service.confirmOfflineHandoff(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + assertThat(info.state()).isEqualTo(CommunityGrantState.REGISTERED); + } + + @Test + void testConfirmOfflineHandoffFailsCleanlyWhenTheFlowStateCannotBePersisted() { + stored.setState(CommunityGrantState.VALIDATING); + doThrow(new IllegalStateException("connection refused")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.confirmOfflineHandoff()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.HANDOFF_FAILED_MESSAGE) + .hasNoCause(); + } + + @Test + void testStartIsRefusedAfterTheReportHasBeenHandedOverAndLeavesTheReportInPlace() { + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + givenReachablePortal(); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REPORT_HANDED_OVER_MESSAGE); + + verify(offlineReportStore, never()).clear(); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(service.getStateInfo().offlineReport()).isEqualTo("report-body"); + } + + /** Holds submitted tasks until the test runs them, so a test can act between a start and its completion. */ + private static final class QueuedExecutorService extends AbstractExecutorService { + private final List tasks = new ArrayList<>(); + + void runAll() { + List queued = new ArrayList<>(tasks); + tasks.clear(); + queued.forEach(Runnable::run); + } + + @Override + public void execute(Runnable command) { + tasks.add(command); + } + + @Override + public void shutdown() { + } + + @Override + public List shutdownNow() { + return List.of(); + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java new file mode 100644 index 0000000000..8b471d0548 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java @@ -0,0 +1,325 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.edge.rpc; + +import com.google.common.util.concurrent.Futures; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; +import org.thingsboard.server.cache.TbTransactionalCache; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; +import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg; +import org.thingsboard.server.queue.TbQueueConsumer; +import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.common.consumer.QueueConsumerManager; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.executors.GrpcCallbackExecutorService; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Covers the reconnect race between a session that is being torn down and the session that has already + * taken the edge over: the teardown must not detach, cancel the edge event check of, or consume the new + * events flag of the session that replaced it. + */ +class EdgeGrpcServiceReconnectTest { + + // long enough that an armed check never actually fires during a test + private static final long NO_RECORDS_SLEEP_INTERVAL_MS = 60_000L; + private static final String THIS_NODE = "test-core"; + + private EdgeGrpcService service; + private ScheduledExecutorService edgeEventProcessingExecutorService; + private TbTransactionalCache edgeIdServiceIdCache; + + private TenantId tenantId; + private EdgeId edgeId; + private Edge edge; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + tenantId = TenantId.fromUUID(UUID.randomUUID()); + edgeId = new EdgeId(UUID.randomUUID()); + edge = new Edge(edgeId); + edge.setTenantId(tenantId); + edge.setName("test-edge"); + + EdgeEventStorageSettings storageSettings = new EdgeEventStorageSettings(); + ReflectionTestUtils.setField(storageSettings, "noRecordsSleepInterval", NO_RECORDS_SLEEP_INTERVAL_MS); + + GrpcCallbackExecutorService grpcCallbackExecutorService = mock(GrpcCallbackExecutorService.class); + // run future callbacks inline so the re-arm is observable without waiting on a pool + doAnswer(invocation -> { + invocation.getArgument(0, Runnable.class).run(); + return null; + }).when(grpcCallbackExecutorService).execute(any()); + + EdgeContextComponent ctx = mock(EdgeContextComponent.class); + when(ctx.getEdgeEventStorageSettings()).thenReturn(storageSettings); + when(ctx.getGrpcCallbackExecutorService()).thenReturn(grpcCallbackExecutorService); + when(ctx.getRuleProcessor()).thenReturn(mock(NotificationRuleProcessor.class)); + + TbServiceInfoProvider serviceInfoProvider = mock(TbServiceInfoProvider.class); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + + edgeIdServiceIdCache = mock(TbTransactionalCache.class); + // this node is the recorded owner of the edge, which is what a live local session implies + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + edgeEventProcessingExecutorService = Executors.newSingleThreadScheduledExecutor(); + + service = new EdgeGrpcService(); + ReflectionTestUtils.setField(service, "ctx", ctx); + ReflectionTestUtils.setField(service, "tsSubService", mock(TelemetrySubscriptionService.class)); + ReflectionTestUtils.setField(service, "clusterService", mock(TbClusterService.class)); + ReflectionTestUtils.setField(service, "serviceInfoProvider", serviceInfoProvider); + ReflectionTestUtils.setField(service, "edgeIdServiceIdCache", edgeIdServiceIdCache); + ReflectionTestUtils.setField(service, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService); + } + + @AfterEach + void tearDown() { + edgeEventProcessingExecutorService.shutdownNow(); + } + + @Test + void checkIsArmedForTheCurrentSession() { + EdgeGrpcSession session = newSession(); + sessions().put(edgeId, session); + + scheduleEdgeEventsCheck(session); + + ScheduledFuture armed = edgeEventChecks().get(edgeId); + assertThat((Object) armed).as("check armed for the session that owns the edge").isNotNull(); + assertThat(armed.isCancelled()).isFalse(); + } + + @Test + void checkIsNotArmedForASupersededSession() { + EdgeGrpcSession current = newSession(); + EdgeGrpcSession superseded = newSession(); + sessions().put(edgeId, current); + scheduleEdgeEventsCheck(current); + ScheduledFuture armedByCurrent = edgeEventChecks().get(edgeId); + + scheduleEdgeEventsCheck(superseded); + + assertThat((Object) edgeEventChecks().get(edgeId)) + .as("the superseded session must neither cancel nor replace the current session's check") + .isSameAs(armedByCurrent); + assertThat(armedByCurrent.isCancelled()).isFalse(); + } + + @Test + void disconnectOfTheCurrentSessionDetachesItAndCancelsItsCheck() { + EdgeGrpcSession session = newSession(); + onEdgeConnect(session); + ScheduledFuture armedCheck = edgeEventChecks().get(edgeId); + + onEdgeDisconnect(session); + + assertThat(sessions()).doesNotContainKey(edgeId); + assertThat(sessionsById()).doesNotContainKey(session.getSessionId()); + assertThat(armedCheck.isCancelled()).as("the detached session's check is cancelled").isTrue(); + verify(edgeIdServiceIdCache).evict(edgeId); + verify(session).destroy(); + } + + @Test + void disconnectOfASupersededSessionKeepsTheReconnectedSessionAndItsCheck() { + EdgeGrpcSession first = newSession(); + onEdgeConnect(first); + // the edge reconnects before the gRPC stream of the first session is closed + EdgeGrpcSession second = newSession(); + onEdgeConnect(second); + ScheduledFuture armedBySecond = edgeEventChecks().get(edgeId); + + onEdgeDisconnect(first); + + assertThat(sessions().get(edgeId)).as("the reconnected session stays registered").isSameAs(second); + assertThat(sessionsById()).containsKey(second.getSessionId()); + assertThat((Object) edgeEventChecks().get(edgeId)) + .as("the check armed by the reconnected session survives the teardown of the one it replaced") + .isSameAs(armedBySecond); + assertThat(armedBySecond.isCancelled()).isFalse(); + verify(edgeIdServiceIdCache, never()).evict(edgeId); + } + + @Test + void disconnectDoesNotClearTheNewEventsFlag() { + EdgeGrpcSession session = newSession(); + onEdgeConnect(session); + assertThat(newEvents()).containsEntry(edgeId, true); + + onEdgeDisconnect(session); + + assertThat(newEvents()) + .as("clearing the flag here would wipe the one a reconnecting session has just raised") + .containsEntry(edgeId, true); + } + + @Test + void checkOfTheCurrentSessionConsumesTheFlagAndReArms() throws Exception { + EdgeGrpcSession session = newSession(); + when(session.processEdgeEvents()).thenReturn(Futures.immediateFuture(false)); + sessions().put(edgeId, session); + newEvents().put(edgeId, true); + migrationProcessed().put(edgeId, Boolean.TRUE); + + processEvents(session); + + assertThat(newEvents()).containsEntry(edgeId, false); + verify(session).processHighPriorityEvents(); + verify(session).processEdgeEvents(); + assertThat((Object) edgeEventChecks().get(edgeId)).as("the check re-arms itself").isNotNull(); + } + + @Test + void checkOfASupersededSessionLeavesTheFlagForTheSessionThatOwnsTheEdge() throws Exception { + EdgeGrpcSession superseded = newSession(); + EdgeGrpcSession current = newSession(); + sessions().put(edgeId, current); + newEvents().put(edgeId, true); + migrationProcessed().put(edgeId, Boolean.TRUE); + + // cancel(true) cannot stop a check that has already started, so it runs against the old session + processEvents(superseded); + + assertThat(newEvents()) + .as("consuming the flag here would leave the reconnected session with nothing to fetch") + .containsEntry(edgeId, true); + verify(superseded, never()).processHighPriorityEvents(); + verify(superseded, never()).processEdgeEvents(); + assertThat(edgeEventChecks()).doesNotContainKey(edgeId); + } + + @Test + void zombieCleanupCancelsTheCheckOfTheSessionItRemoves() { + KafkaEdgeGrpcSession zombie = newZombieSession(); + when(zombie.destroy()).thenReturn(true); + sessions().put(edgeId, zombie); + scheduleEdgeEventsCheck(zombie); + ScheduledFuture armedByZombie = edgeEventChecks().get(edgeId); + + cleanupZombieSessions(); + + assertThat(sessions()).doesNotContainKey(edgeId); + assertThat(armedByZombie.isCancelled()) + .as("the removed zombie must not leave an armed check behind") + .isTrue(); + } + + @Test + void zombieCleanupKeepsASessionThatReconnectedDuringTheSweep() { + KafkaEdgeGrpcSession zombie = newZombieSession(); + EdgeGrpcSession reconnected = newSession(); + sessions().put(edgeId, zombie); + // the edge reconnects while the zombie is being destroyed, i.e. after the scan picked it up + when(zombie.destroy()).thenAnswer(invocation -> { + sessions().put(edgeId, reconnected); + scheduleEdgeEventsCheck(reconnected); + return true; + }); + + cleanupZombieSessions(); + + assertThat(sessions().get(edgeId)).isSameAs(reconnected); + ScheduledFuture armedByReconnected = edgeEventChecks().get(edgeId); + assertThat((Object) armedByReconnected).as("the reconnected session keeps its check").isNotNull(); + assertThat(armedByReconnected.isCancelled()).isFalse(); + } + + private EdgeGrpcSession newSession() { + EdgeGrpcSession session = mock(EdgeGrpcSession.class); + stubSession(session); + return session; + } + + private KafkaEdgeGrpcSession newZombieSession() { + KafkaEdgeGrpcSession session = mock(KafkaEdgeGrpcSession.class); + stubSession(session); + @SuppressWarnings("unchecked") + QueueConsumerManager> consumerManager = mock(QueueConsumerManager.class); + @SuppressWarnings("unchecked") + TbQueueConsumer> consumer = mock(TbQueueConsumer.class); + when(consumerManager.getConsumer()).thenReturn(consumer); + when(consumer.isStopped()).thenReturn(false); + when(session.getConsumer()).thenReturn(consumerManager); + return session; + } + + private void stubSession(EdgeGrpcSession session) { + when(session.getEdge()).thenReturn(edge); + when(session.getTenantId()).thenReturn(tenantId); + when(session.getSessionId()).thenReturn(UUID.randomUUID()); + when(session.isConnected()).thenReturn(false); + when(session.destroy()).thenReturn(true); + } + + private void onEdgeConnect(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "onEdgeConnect", edgeId, session); + } + + private void onEdgeDisconnect(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "onEdgeDisconnect", edge, session.getSessionId()); + } + + private void scheduleEdgeEventsCheck(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "scheduleEdgeEventsCheck", session); + } + + private void processEvents(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "processEvents", session, edgeId, tenantId); + } + + private void cleanupZombieSessions() { + ReflectionTestUtils.invokeMethod(service, "cleanupZombieSessions"); + } + + private ConcurrentMap sessions() { + return field("sessions"); + } + + private ConcurrentMap sessionsById() { + return field("sessionsById"); + } + + private ConcurrentMap> edgeEventChecks() { + return field("sessionEdgeEventChecks"); + } + + private Map newEvents() { + return field("sessionNewEvents"); + } + + private ConcurrentMap migrationProcessed() { + return field("edgeEventsMigrationProcessed"); + } + + @SuppressWarnings("unchecked") + private T field(String name) { + return (T) ReflectionTestUtils.getField(service, name); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 9cf7d81f66..ab89068f24 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -24,10 +24,6 @@ import org.thingsboard.server.common.data.notification.rule.trigger.Notification import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; import org.thingsboard.server.common.msg.queue.ServiceType; -import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg; -import org.thingsboard.server.queue.TbQueueConsumer; -import org.thingsboard.server.queue.common.TbProtoQueueMsg; -import org.thingsboard.server.queue.common.consumer.QueueConsumerManager; import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.service.edge.EdgeContextComponent; @@ -43,7 +39,6 @@ import java.util.concurrent.ConcurrentMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.argThat; @@ -227,17 +222,14 @@ public class EdgeGrpcServiceTest { @Test public void givenSessionReplacedDuringDisconnect_whenStaleCallbackRuns_thenLiveSessionKept() { - // Reproduces the get()/remove() interleaving on a single node: onEdgeConnect swaps in a new session - // right after the stale callback's id check passes. The stale callback must not evict or tear down - // the live session, nor clear the activity state. + // onEdgeConnect has already swapped in a new session on this node when the stale callback runs. + // The check-and-remove is a single atomic step against the same map that onEdgeConnect writes + // through, so the swap can only land before or after it. The stale callback must not evict or + // tear down the live session, nor clear the activity state. UUID staleSessionId = UUID.randomUUID(); EdgeGrpcSession live = mock(EdgeGrpcSession.class); - EdgeGrpcSession stale = mock(EdgeGrpcSession.class); - when(stale.getSessionId()).thenAnswer(invocation -> { - sessions().put(edgeId, live); - return staleSessionId; - }); - sessions().put(edgeId, stale); + when(live.getSessionId()).thenReturn(UUID.randomUUID()); + sessions().put(edgeId, live); onEdgeDisconnect(staleSessionId); @@ -246,20 +238,11 @@ public class EdgeGrpcServiceTest { } @Test - public void givenSessionReplacedOnThisNodeAfterRemoval_whenStaleCallbackRuns_thenNoDisconnectSideEffects() { - // The stale callback wins the compare-and-remove, then tearing its own session down takes a while - // (for the Kafka session this stops a consumer). The edge reconnects to THIS node in that gap, so the - // ownership cache legitimately names us and isOwnedByAnotherNode cannot help. None of the disconnect - // side effects may run: not the flag, not the timestamp, not the DISCONNECT_EVENT push. + public void givenSessionReplacedOnThisNodeDuringDisconnect_whenStaleCallbackRuns_thenNoDisconnectSideEffects() { + // the edge reconnects to this node after the stale session was detached, so the cache names this node UUID sessionId = UUID.randomUUID(); - EdgeGrpcSession stale = mock(EdgeGrpcSession.class); - when(stale.getSessionId()).thenReturn(sessionId); - when(stale.getEdge()).thenReturn(edge); - when(stale.destroy()).thenAnswer(invocation -> { - sessions().put(edgeId, mock(EdgeGrpcSession.class)); - return true; - }); - sessions().put(edgeId, stale); + sessions().put(edgeId, sessionFor(sessionId)); + reconnectToThisNodeOnOwnershipCheck(); onEdgeDisconnect(sessionId); @@ -271,124 +254,33 @@ public class EdgeGrpcServiceTest { @Test public void givenEdgeReconnectedToAnotherNode_whenDisconnect_thenDisconnectEventNotPushed() { - // The DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE, so a rule chain wiring - // Disconnect Event -> Save Attributes would persist active=false back and re-create the bug. - EdgeSessionStub stub = registerSession(); + // DISCONNECT_EVENT carries active=false, a Save Attributes node would write it back + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE)); - onEdgeDisconnect(stub.sessionId()); + onEdgeDisconnect(sessionId); verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); } @Test public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenDisconnectEventPushed() { - // Also proves the never() assertions above are not vacuous: the push does happen on this path. - EdgeSessionStub stub = registerSession(); - when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); - when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); - - onEdgeDisconnect(stub.sessionId()); - - verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); - } - - @Test - public void givenSessionReplacedOnThisNode_whenStaleCallbackRuns_thenReplacementEdgeEventsCheckNotCancelled() { - // sessionEdgeEventChecks is keyed by edgeId, not by session, so the replacement's check sits under the - // same key as the one this callback is tearing down. The check loop only reschedules itself from inside - // the task, so cancelling it here would leave a connected edge with nothing to restart downlink - // delivery - the same silent stall this guard exists to prevent. - UUID sessionId = UUID.randomUUID(); - EdgeGrpcSession stale = mock(EdgeGrpcSession.class); - when(stale.getSessionId()).thenReturn(sessionId); - when(stale.getEdge()).thenReturn(edge); - ScheduledFuture replacementCheck = mock(ScheduledFuture.class); - when(stale.destroy()).thenAnswer(invocation -> { - sessions().put(edgeId, mock(EdgeGrpcSession.class)); - sessionEdgeEventChecks().put(edgeId, replacementCheck); - return true; - }); - sessions().put(edgeId, stale); - - onEdgeDisconnect(sessionId); - - verify(replacementCheck, never()).cancel(anyBoolean()); - assertThat(sessionEdgeEventChecks()).containsEntry(edgeId, replacementCheck); - } - - @Test - public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenEdgeEventsCheckCancelled() { - // Counterpart to the test above: proves the cancel still runs on a real disconnect, so the guard is - // not simply disabling it. UUID sessionId = UUID.randomUUID(); sessions().put(edgeId, sessionFor(sessionId)); - ScheduledFuture check = mock(ScheduledFuture.class); - sessionEdgeEventChecks().put(edgeId, check); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); onEdgeDisconnect(sessionId); - verify(check, times(1)).cancel(anyBoolean()); - assertThat(sessionEdgeEventChecks()).doesNotContainKey(edgeId); - } - - // --- zombie session cleanup --- - - @Test - @SuppressWarnings("unchecked") - public void givenZombieSessionReplacedDuringDestroy_whenCleanupRuns_thenReplacementKept() { - // destroy() stops a Kafka consumer and is not instantaneous. If the edge reconnects in that gap, an - // unconditional sessions.remove(edgeId) would drop the live session, leaving a connected edge with no - // map entry - every downlink lookup then silently no-ops. - KafkaEdgeGrpcSession zombie = mock(KafkaEdgeGrpcSession.class); - when(zombie.getEdge()).thenReturn(edge); - when(zombie.isConnected()).thenReturn(false); - QueueConsumerManager> consumerManager = mock(QueueConsumerManager.class); - TbQueueConsumer> consumer = mock(TbQueueConsumer.class); - when(consumer.isStopped()).thenReturn(false); - when(consumerManager.getConsumer()).thenReturn(consumer); - when(zombie.getConsumer()).thenReturn(consumerManager); - EdgeGrpcSession replacement = mock(EdgeGrpcSession.class); - when(zombie.destroy()).thenAnswer(invocation -> { - sessions().put(edgeId, replacement); - return true; - }); - sessions().put(edgeId, zombie); - - ReflectionTestUtils.invokeMethod(edgeGrpcService, "cleanupZombieSessions"); - - assertThat(sessions()).containsEntry(edgeId, replacement); - } - - @Test - @SuppressWarnings("unchecked") - public void givenZombieSessionStillCurrent_whenCleanupRuns_thenItIsRemoved() { - // Counterpart: with no replacement, the compare-and-remove must still drop the zombie. - KafkaEdgeGrpcSession zombie = mock(KafkaEdgeGrpcSession.class); - when(zombie.getEdge()).thenReturn(edge); - when(zombie.isConnected()).thenReturn(false); - QueueConsumerManager> consumerManager = mock(QueueConsumerManager.class); - TbQueueConsumer> consumer = mock(TbQueueConsumer.class); - when(consumer.isStopped()).thenReturn(false); - when(consumerManager.getConsumer()).thenReturn(consumer); - when(zombie.getConsumer()).thenReturn(consumerManager); - when(zombie.destroy()).thenReturn(true); - sessions().put(edgeId, zombie); - - ReflectionTestUtils.invokeMethod(edgeGrpcService, "cleanupZombieSessions"); - - assertThat(sessions()).doesNotContainKey(edgeId); + verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); } - // --- onEdgeConnect ownership publish order --- - @Test public void givenConnect_whenClaimingOwnership_thenCachePutHappensBeforeActiveStateWrite() { - // Load-bearing ordering: the previous node's onEdgeDisconnect reads this cache entry to decide whether - // to clear the flag, so the claim must be visible before active=true is written. Nothing else pins the - // order, and a tidy-up that groups the save(...) calls together would silently restore the race. + // the previous node reads this cache entry on disconnect, so the claim must be visible before active=true EdgeGrpcSession session = mock(EdgeGrpcSession.class); when(session.getSessionId()).thenReturn(UUID.randomUUID()); when(session.getEdge()).thenReturn(edge); @@ -405,8 +297,6 @@ public class EdgeGrpcServiceTest { inOrder.verify(tsSubService).saveAttributes(argThat(activeStateWrite())); } - // --- service-id cache eviction guard --- - @Test public void givenEdgeOwnedByThisNode_whenDisconnect_thenInactiveStateIsPersisted() { UUID sessionId = UUID.randomUUID(); @@ -434,23 +324,13 @@ public class EdgeGrpcServiceTest { verify(tsSubService, times(1)).saveAttributes(argThat(lastDisconnectTimeWrite())); } - // --- disconnect notification guard --- - @Test public void givenZeroDelayAndSessionReplacedOnThisNode_whenStaleCallbackRuns_thenNoDisconnectNotification() { - // EDGES_DISCONNECT_NOTIFICATION_DELAY_MS=0 makes scheduleDisconnectNotification notify immediately and - // skip fireDelayedDisconnectNotification's liveness re-verify, so the disconnect guard is the only - // thing standing between a live replacement and a false 'edge disconnected' notification. + // with zero delay the notification skips the liveness re-check, so only the disconnect guard prevents it UUID sessionId = UUID.randomUUID(); - EdgeGrpcSession stale = mock(EdgeGrpcSession.class); - when(stale.getSessionId()).thenReturn(sessionId); - when(stale.getEdge()).thenReturn(edge); - when(stale.destroy()).thenAnswer(invocation -> { - sessions().put(edgeId, mock(EdgeGrpcSession.class)); - return true; - }); + sessions().put(edgeId, sessionFor(sessionId)); + reconnectToThisNodeOnOwnershipCheck(); lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); - sessions().put(edgeId, stale); onEdgeDisconnect(sessionId); @@ -459,7 +339,6 @@ public class EdgeGrpcServiceTest { @Test public void givenZeroDelayAndEdgeGenuinelyDisconnected_whenDisconnect_thenNotificationSent() { - // Counterpart: the immediate path must still fire for a real disconnect. UUID sessionId = UUID.randomUUID(); sessions().put(edgeId, sessionFor(sessionId)); when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); @@ -474,13 +353,13 @@ public class EdgeGrpcServiceTest { ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, sessionId); } - private EdgeSessionStub registerSession() { - UUID sessionId = UUID.randomUUID(); - sessions().put(edgeId, sessionFor(sessionId)); - return new EdgeSessionStub(sessionId); - } - - private record EdgeSessionStub(UUID sessionId) { + // simulates a reconnect to this node landing after the stale session was detached, before the guard runs + private void reconnectToThisNodeOnOwnershipCheck() { + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenAnswer(invocation -> { + sessions().put(edgeId, mock(EdgeGrpcSession.class)); + return SimpleTbCacheValueWrapper.wrap(THIS_NODE); + }); } private ArgumentMatcher activeStateWrite() { @@ -498,11 +377,6 @@ public class EdgeGrpcServiceTest { return session; } - @SuppressWarnings("unchecked") - private ConcurrentMap> sessionEdgeEventChecks() { - return (ConcurrentMap>) ReflectionTestUtils.getField(edgeGrpcService, "sessionEdgeEventChecks"); - } - private ArgumentMatcher inactiveStateWrite() { return request -> request != null && edgeId.equals(request.getEntityId()) diff --git a/application/src/test/java/org/thingsboard/server/service/install/AbstractInstallPostgresTest.java b/application/src/test/java/org/thingsboard/server/service/install/AbstractInstallPostgresTest.java new file mode 100644 index 0000000000..107b858cab --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/AbstractInstallPostgresTest.java @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import org.junit.jupiter.api.BeforeAll; +import org.testcontainers.containers.PostgreSQLContainer; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +abstract class AbstractInstallPostgresTest { + + private static final String POSTGRES_IMAGE = "postgres:18"; + + protected static PostgreSQLContainer postgres; + + @BeforeAll + static void startDatabase() { + if (postgres == null) { + postgres = new PostgreSQLContainer<>(POSTGRES_IMAGE); + postgres.start(); + } + } + + protected static void execute(String sql) throws SQLException { + try (Connection conn = DriverManager.getConnection(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = conn.createStatement()) { + statement.execute(sql); + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/InstallTestSupport.java b/application/src/test/java/org/thingsboard/server/service/install/InstallTestSupport.java new file mode 100644 index 0000000000..4c4ee42e6c --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/InstallTestSupport.java @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +final class InstallTestSupport { + + private static final Pattern TB_CLUSTER_DDL = Pattern.compile( + "^\\s*(CREATE\\s+(?:TABLE|UNIQUE\\s+INDEX)[^;]*\\btb_cluster\\b[^;]*;)", + Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); + + private InstallTestSupport() { + } + + // The working directory is either the repository root or the application module, depending on how tests are run. + static Path dataDir() { + String workDir = System.getProperty("user.dir"); + Path applicationDir = workDir.endsWith("application") ? Paths.get(workDir) : Paths.get(workDir, "application"); + return applicationDir.resolve(Paths.get("src", "main", "data")); + } + + static String readFile(Path path) { + try { + return Files.readString(path); + } catch (IOException e) { + throw new UncheckedIOException("Failed to read " + path, e); + } + } + + static String readResource(String name) { + try (InputStream in = InstallTestSupport.class.getClassLoader().getResourceAsStream(name)) { + return new String(Objects.requireNonNull(in, name + " is missing from the test classpath").readAllBytes(), + StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException("Failed to read " + name, e); + } + } + + static List tbClusterStatements(String sql) { + List statements = new ArrayList<>(); + Matcher matcher = TB_CLUSTER_DDL.matcher(sql); + while (matcher.find()) { + statements.add(matcher.group(1)); + } + return statements; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/SchemaUpdateSqlUpgradeOrderTest.java b/application/src/test/java/org/thingsboard/server/service/install/SchemaUpdateSqlUpgradeOrderTest.java new file mode 100644 index 0000000000..3f061e7bd4 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/SchemaUpdateSqlUpgradeOrderTest.java @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.SQLException; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.thingsboard.server.service.install.InstallTestSupport.dataDir; +import static org.thingsboard.server.service.install.InstallTestSupport.readResource; + +/** + * {@code basic/schema_update.sql} runs before {@code schema-entities.sql}, so it must not reference a table + * that only the latter creates. The fixture schema predates {@code tb_cluster}. + */ +class SchemaUpdateSqlUpgradeOrderTest extends AbstractInstallPostgresTest { + + @BeforeEach + void setUp() throws SQLException { + execute("DROP SCHEMA public CASCADE; CREATE SCHEMA public;"); + execute(readResource("install/pre-upgrade-schema-entities.sql")); + } + + @Test + void testSchemaUpdateRunsCleanlyBeforeTbClusterExists() throws IOException { + String sql = Files.readString(schemaUpdateSqlFile()); + + assertThatCode(() -> execute(sql)).doesNotThrowAnyException(); + } + + @Test + void testALegitimateStatementAgainstALongStandingTableIsNotFlagged() throws IOException { + String sql = Files.readString(schemaUpdateSqlFile()) + + "\nALTER TABLE device ADD COLUMN IF NOT EXISTS probe_column varchar(1);\n"; + + assertThatCode(() -> execute(sql)).doesNotThrowAnyException(); + } + + @Test + void testLtsSchemaUpdateCreatesTbClusterBeforeItsIndex() throws IOException { + String sql = Files.readString(ltsSchemaUpdateSqlFile("4.3.1.6")); + + assertThatCode(() -> execute(sql)).doesNotThrowAnyException(); + } + + private static Path schemaUpdateSqlFile() { + return dataDir().resolve(Paths.get("upgrade", "basic", "schema_update.sql")); + } + + private static Path ltsSchemaUpdateSqlFile(String version) { + return dataDir().resolve(Paths.get("upgrade", "lts", version, "schema_update.sql")); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java b/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java new file mode 100644 index 0000000000..389d4abee1 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.thingsboard.server.service.install.InstallTestSupport.readResource; +import static org.thingsboard.server.service.install.InstallTestSupport.tbClusterStatements; + +class SqlEntityDatabaseSchemaServiceClusterIdTest extends AbstractInstallPostgresTest { + + private SqlEntityDatabaseSchemaService schemaService; + + @BeforeEach + void setUp() throws SQLException { + execute("DROP TABLE IF EXISTS tb_cluster;"); + for (String statement : productionClusterDdl()) { + execute(statement); + } + schemaService = new SqlEntityDatabaseSchemaService(); + ReflectionTestUtils.setField(schemaService, "dbUrl", postgres.getJdbcUrl()); + ReflectionTestUtils.setField(schemaService, "dbUserName", postgres.getUsername()); + ReflectionTestUtils.setField(schemaService, "dbPassword", postgres.getPassword()); + } + + @Test + void testFreshInstallMintsExactlyOneClusterId() throws SQLException { + schemaService.generateClusterIdIfNotExist(); + List ids = readClusterIds(); + assertThat(ids).hasSize(1); + assertThat(ids.get(0)).isNotNull(); + } + + @Test + void testSecondCallIsANoOp() throws SQLException { + schemaService.generateClusterIdIfNotExist(); + UUID first = readClusterIds().get(0); + schemaService.generateClusterIdIfNotExist(); + schemaService.generateClusterIdIfNotExist(); + List ids = readClusterIds(); + assertThat(ids).containsExactly(first); + } + + @Test + void testExistingClusterIdSurvivesAnUpgrade() throws SQLException { + UUID existing = UUID.randomUUID(); + execute("INSERT INTO tb_cluster (cluster_id) VALUES ('" + existing + "');"); + schemaService.generateClusterIdIfNotExist(); + assertThat(readClusterIds()).containsExactly(existing); + } + + @Test + void testSecondRowInsertIsRejectedByUniqueIndex() throws SQLException { + UUID existing = UUID.randomUUID(); + execute("INSERT INTO tb_cluster (cluster_id) VALUES ('" + existing + "');"); + + UUID other = UUID.randomUUID(); + assertThatThrownBy(() -> execute("INSERT INTO tb_cluster (cluster_id) VALUES ('" + other + "');")) + .isInstanceOf(SQLException.class) + .hasMessageContaining("tb_cluster_single_row"); + + assertThat(readClusterIds()).containsExactly(existing); + } + + @Test + void testConnectionFailurePropagatesInsteadOfBeingSwallowed() { + ReflectionTestUtils.setField(schemaService, "dbUrl", "jdbc:postgresql://localhost:1/does-not-exist"); + + assertThatThrownBy(() -> schemaService.generateClusterIdIfNotExist()) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Failed to generate Cluster id") + .hasCauseInstanceOf(SQLException.class); + } + + private static List productionClusterDdl() { + String resourceName = "sql/" + SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_SQL; + List statements = tbClusterStatements(readResource(resourceName)); + assertThat(statements).as("tb_cluster DDL found in %s", resourceName).hasSize(2); + return statements; + } + + private static List readClusterIds() throws SQLException { + List ids = new ArrayList<>(); + try (Connection conn = DriverManager.getConnection(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = conn.createStatement(); + ResultSet rs = statement.executeQuery("SELECT cluster_id FROM tb_cluster ORDER BY cluster_id")) { + while (rs.next()) { + ids.add(rs.getObject("cluster_id", UUID.class)); + } + } + return ids; + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/TbClusterDdlDriftTest.java b/application/src/test/java/org/thingsboard/server/service/install/TbClusterDdlDriftTest.java new file mode 100644 index 0000000000..3a035f80d5 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/TbClusterDdlDriftTest.java @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import org.junit.jupiter.api.Test; + +import java.nio.file.Paths; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.thingsboard.server.service.install.InstallTestSupport.dataDir; +import static org.thingsboard.server.service.install.InstallTestSupport.readFile; +import static org.thingsboard.server.service.install.InstallTestSupport.readResource; +import static org.thingsboard.server.service.install.InstallTestSupport.tbClusterStatements; + +/** + * When {@code tb_cluster} changes, put the {@code ALTER} in a new upgrade script and point this test at it: + * the 4.3.1.6 script is {@code IF NOT EXISTS}, so editing it is a no-op on databases that already ran it. + */ +class TbClusterDdlDriftTest { + + @Test + void testLtsSchemaUpdateTbClusterDdlMatchesSchemaEntities() { + String schemaEntities = "sql/" + SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_SQL; + List fromSchemaEntities = normalized(tbClusterStatements(readResource(schemaEntities))); + List fromLtsScript = normalized(tbClusterStatements(readFile( + dataDir().resolve(Paths.get("upgrade", "lts", "4.3.1.6", "schema_update.sql"))))); + + assertThat(fromSchemaEntities).as("tb_cluster statements found in %s", schemaEntities).hasSize(2); + assertThat(fromLtsScript) + .as("tb_cluster DDL in the 4.3.1.6 upgrade script matches %s", schemaEntities) + .isEqualTo(fromSchemaEntities); + } + + private static List normalized(List statements) { + return statements.stream().map(statement -> statement.replaceAll("\\s+", " ").trim()).toList(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java index 771a239e5d..0fe732b355 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java @@ -36,10 +36,14 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; @DaoSqlTest public class LtsMigrationIntegrationTest extends AbstractControllerTest { + private static final Runnable NO_POST_SCHEMA_WORK = () -> { + }; + private static final long V_4_2_2_2 = 4_002_002_002L; private static final long V_4_2_2_3 = 4_002_002_003L; private static final String OBSOLETE_ALIAS = "air_quality"; @@ -62,6 +66,8 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { private List migrations; private Long originalSchemaVersion; + private String originalClusterId; + private String originalLicenseClaimToken; private WidgetsBundleId bundleId; private WidgetTypeId widgetTypeId; @@ -75,6 +81,15 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { jdbcTemplate.execute("INSERT INTO tb_schema_settings (schema_version, product) VALUES (" + V_4_2_2_2 + ", 'CE')"); } + // The 4.3.1.6 tests drop and re-create tb_cluster, so keep the row the shared test DB already has. + jdbcTemplate.query("SELECT cluster_id, license_claim_token FROM tb_cluster", rs -> { + if (rs.next()) { + originalClusterId = rs.getString("cluster_id"); + originalLicenseClaimToken = rs.getString("license_claim_token"); + } + return null; + }); + // Seed an obsolete system widget bundle with one (non-deprecated) widget type linked to it. WidgetsBundle bundle = new WidgetsBundle(); bundle.setTenantId(TenantId.SYS_TENANT_ID); @@ -103,6 +118,14 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { } else { jdbcTemplate.execute("DELETE FROM tb_schema_settings"); } + // Guarded so that a migration that failed to recreate tb_cluster reports its own assertion, not a tear-down error. + if (tableExists("tb_cluster")) { + jdbcTemplate.execute("DELETE FROM tb_cluster"); + if (originalClusterId != null) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id, license_claim_token) VALUES (?::uuid, ?)", + originalClusterId, originalLicenseClaimToken); + } + } if (widgetTypeId != null && widgetTypeService.findWidgetTypeDetailsById(TenantId.SYS_TENANT_ID, widgetTypeId) != null) { widgetTypeService.deleteWidgetType(TenantId.SYS_TENANT_ID, widgetTypeId); } @@ -114,7 +137,11 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { @Test public void appliesSqlDeprecatesTypesDeletesBundleAndRecordsVersion() { - ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3"); + ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", () -> { + assertTrue(tableExists("iot_hub_installed_item")); + assertEquals(Long.valueOf(V_4_2_2_2), + jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); + }); // 1. The version's SQL ran: iot_hub_installed_item table now exists. assertTrue(tableExists("iot_hub_installed_item")); @@ -131,9 +158,9 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { @Test public void reRunFromCurrentVersionIsNoOp() { - ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3"); + ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); // Re-running from the now-current version selects an empty range — nothing changes, nothing throws. - ltsMigrationService.applyMigrations("4.2.2.3", "4.2.2.3"); + ltsMigrationService.applyMigrations("4.2.2.3", "4.2.2.3", NO_POST_SCHEMA_WORK); assertEquals(Long.valueOf(V_4_2_2_3), jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); @@ -141,6 +168,30 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { assertTrue(widgetTypeService.findWidgetTypeDetailsById(TenantId.SYS_TENANT_ID, widgetTypeId).isDeprecated()); } + @Test + public void postSchemaWorkFailureLeavesTheVersionUnrecordedSoTheNextBootRetries() { + IllegalStateException failure = new IllegalStateException("post-schema work failed"); + try { + ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", () -> { + throw failure; + }); + fail("Expected the post-schema failure to propagate"); + } catch (IllegalStateException e) { + assertEquals(failure, e); + } + + assertTrue(tableExists("iot_hub_installed_item")); + assertNull(widgetsBundleService.findWidgetsBundleByTenantIdAndAlias(TenantId.SYS_TENANT_ID, OBSOLETE_ALIAS)); + assertEquals(Long.valueOf(V_4_2_2_2), + jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); + + ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); + + assertEquals(Long.valueOf(V_4_2_2_3), + jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); + assertTrue(widgetTypeService.findWidgetTypeDetailsById(TenantId.SYS_TENANT_ID, widgetTypeId).isDeprecated()); + } + @Test public void offlinePathRunsSchemaThenDataButRecordsNoVersion() { // Drive the offline major-upgrade path over the real supported range against the real DB. @@ -170,12 +221,36 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { assertFalse(columnExists("calculated_field", "additional_info")); // Drive the runner over a range whose target (4.3.1.2) selects only the 4.3.1.2 migration. - ltsMigrationService.applyMigrations("4.3.1.1", "4.3.1.2"); + ltsMigrationService.applyMigrations("4.3.1.1", "4.3.1.2", NO_POST_SCHEMA_WORK); // The 4.3.1.2 schema SQL ran: the column exists again. assertTrue(columnExists("calculated_field", "additional_info")); } + @Test + public void appliesSchemaForV4316CreatesTbClusterAndMintsOneClusterId() { + jdbcTemplate.execute("DROP TABLE IF EXISTS tb_cluster"); + assertFalse(tableExists("tb_cluster")); + + ltsMigrationService.applyMigrations("4.3.1.3", "4.3.1.6", NO_POST_SCHEMA_WORK); + + assertTrue(tableExists("tb_cluster")); + assertEquals(Long.valueOf(1L), jdbcTemplate.queryForObject("SELECT COUNT(*) FROM tb_cluster", Long.class)); + } + + @Test + public void v4316KeepsAnExistingClusterId() { + UUID existing = UUID.randomUUID(); + jdbcTemplate.execute("DROP TABLE IF EXISTS tb_cluster"); + ltsMigrationService.applyMigrations("4.3.1.3", "4.3.1.6", NO_POST_SCHEMA_WORK); + jdbcTemplate.update("UPDATE tb_cluster SET cluster_id = ?::uuid", existing.toString()); + + ltsMigrationService.applyMigrations("4.3.1.3", "4.3.1.6", NO_POST_SCHEMA_WORK); + + assertEquals(List.of(existing.toString()), + jdbcTemplate.queryForList("SELECT cluster_id FROM tb_cluster", String.class)); + } + @Test public void migrationDirectoriesAndBeansStayInSyncBothWays() { Path ltsDir = Paths.get(installScripts.getDataDir(), "upgrade", "lts"); diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java index ee03750d6c..c9129131fc 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java @@ -5,6 +5,7 @@ package org.thingsboard.server.service.install.lts; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.InOrder; import org.mockito.Mockito; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; @@ -23,12 +24,17 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class LtsMigrationServiceTest { + private static final Runnable NO_POST_SCHEMA_WORK = () -> { + }; + private JdbcTemplate jdbcTemplate; private InstallScripts installScripts; private DatabaseSchemaSettingsService schemaSettingsService; @@ -61,6 +67,11 @@ class LtsMigrationServiceTest { }; } + private void recordVersionsInto(List events) { + doAnswer(invocation -> events.add("record:" + invocation.getArgument(0))) + .when(schemaSettingsService).updateSchemaVersion(anyString()); + } + private LtsMigrationService service(List migrations) { return new LtsMigrationService(jdbcTemplate, installScripts, schemaSettingsService, txManager, migrations); } @@ -76,7 +87,7 @@ class LtsMigrationServiceTest { migration("4.2.2.2", applied), migration("4.2.2.3", applied))); - service.applyMigrations("4.2.2.2", "4.2.2.3"); + service.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); // only 4.2.2.3 is in (4.2.2.2, 4.2.2.3] assertEquals(List.of("4.2.2.3"), applied); @@ -93,7 +104,7 @@ class LtsMigrationServiceTest { LtsMigrationService service = service(List.of( migration("4.2.2.3", applied), migration("4.2.2.4", applied))); - service.applyMigrations("4.2.2.2", "4.2.2.4"); + service.applyMigrations("4.2.2.2", "4.2.2.4", NO_POST_SCHEMA_WORK); assertEquals(List.of("4.2.2.3", "4.2.2.4"), applied); verify(jdbcTemplate).execute("SELECT 1;"); @@ -126,7 +137,7 @@ class LtsMigrationServiceTest { migration("4.3.1.2", applied), migration("4.3.1.3", applied))); - service.applyMigrations("4.2.2.2", "4.3.1.3"); + service.applyMigrations("4.2.2.2", "4.3.1.3", NO_POST_SCHEMA_WORK); assertEquals(List.of("4.3.1.2", "4.3.1.3"), applied); verify(schemaSettingsService, never()).updateSchemaVersion("4.2.2.3"); @@ -172,14 +183,57 @@ class LtsMigrationServiceTest { @Test void reRunAtCurrentVersionIsNoOp() throws Exception { List applied = new ArrayList<>(); + List events = new ArrayList<>(); writeSql("4.2.2.3", "SELECT 1;"); LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); - service.applyMigrations("4.2.2.3", "4.2.2.3"); + service.applyMigrations("4.2.2.3", "4.2.2.3", () -> events.add("afterSchemaPhase")); assertEquals(List.of(), applied); verify(jdbcTemplate, never()).execute(anyString()); verify(schemaSettingsService, never()).updateSchemaVersion(anyString()); + assertEquals(List.of("afterSchemaPhase"), events); + } + + @Test + void recordsNoVersionUntilTheAfterSchemaPhaseHasRun() throws Exception { + List events = new ArrayList<>(); + recordVersionsInto(events); + writeSql("4.2.2.3", "SELECT 1;"); + writeSql("4.2.2.4", "SELECT 2;"); + LtsMigrationService service = service(List.of( + migration("4.2.2.3", events), migration("4.2.2.4", events))); + + service.applyMigrations("4.2.2.2", "4.2.2.4", () -> events.add("afterSchemaPhase")); + + assertEquals(List.of("4.2.2.3", "4.2.2.4", "afterSchemaPhase", "record:4.2.2.3", "record:4.2.2.4"), events); + } + + @Test + void recordsVersionOutsideTheMigrationTransaction() throws Exception { + List applied = new ArrayList<>(); + writeSql("4.2.2.3", "SELECT 1;"); + LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + + service.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); + + InOrder inOrder = inOrder(txManager, schemaSettingsService); + inOrder.verify(txManager).commit(any()); + inOrder.verify(schemaSettingsService).updateSchemaVersion("4.2.2.3"); + } + + @Test + void afterSchemaPhaseFailureLeavesEveryVersionUnrecorded() throws Exception { + List applied = new ArrayList<>(); + writeSql("4.2.2.3", "SELECT 1;"); + LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + + assertThrows(IllegalStateException.class, () -> service.applyMigrations("4.2.2.2", "4.2.2.3", () -> { + throw new IllegalStateException("post-schema work failed"); + })); + + assertEquals(List.of("4.2.2.3"), applied); + verify(schemaSettingsService, never()).updateSchemaVersion(anyString()); } @Test @@ -213,7 +267,7 @@ class LtsMigrationServiceTest { List applied = new ArrayList<>(); LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); - service.applyMigrations("4.2.2.2", "4.2.2.3"); + service.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); assertEquals(List.of("4.2.2.3"), applied); verify(jdbcTemplate, never()).execute(anyString()); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index e0efa4575b..559215e526 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -15,8 +15,8 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.service.security.model.SecurityUser; @@ -89,7 +89,7 @@ class DefaultIotHubServiceTest { mockTenant(); String versionId = UUID.randomUUID().toString(); String itemId = UUID.randomUUID().toString(); - when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "DASHBOARD", "Root", "1.0")); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "RULE_CHAIN", "Root", "1.0")); when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); InstallPlan plan = service.resolveInstallPlan(user, versionId); @@ -107,7 +107,7 @@ class DefaultIotHubServiceTest { String versionId = UUID.randomUUID().toString(); String rootItemId = UUID.randomUUID().toString(); String relatedItemId = UUID.randomUUID().toString(); - ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0"); + ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0"); root.putArray("relatedItems").add(relatedItemId); when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root); when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)) @@ -129,7 +129,7 @@ class DefaultIotHubServiceTest { String versionId = UUID.randomUUID().toString(); String rootItemId = UUID.randomUUID().toString(); String relatedItemId = UUID.randomUUID().toString(); - ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0"); + ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0"); root.putArray("relatedItems").add(relatedItemId); when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root); when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)).thenReturn(null); @@ -149,7 +149,7 @@ class DefaultIotHubServiceTest { String versionId = UUID.randomUUID().toString(); String rootItemId = UUID.randomUUID().toString(); String relatedItemId = UUID.randomUUID().toString(); - ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0"); + ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0"); root.putArray("relatedItems").add(relatedItemId); when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root); when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)).thenThrow(new RuntimeException("boom")); @@ -280,7 +280,7 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); IotHubInstalledItem depItem = installedItem(UUID.randomUUID()); IotHubInstalledItem rootItem = installedItem(UUID.randomUUID()); - DashboardInstalledItemDescriptor rootDescriptor = new DashboardInstalledItemDescriptor(); + RuleChainInstalledItemDescriptor rootDescriptor = new RuleChainInstalledItemDescriptor(); rootItem.setDescriptor(rootDescriptor); doReturn(depItem).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any()); doReturn(rootItem).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); @@ -331,6 +331,64 @@ class DefaultIotHubServiceTest { inOrder.verify(service).deleteInstalledItem(user, dep1Item.getId()); } + @Test + void installPlan_errorMessageIsTheFailureItselfWithoutAnyPrefix() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the sentence around the failure belongs to the dialog, which localizes it + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + } + + @Test + void installPlan_dependencyFails_failureIsReportedOnTheEntryAndAsTheResultMessage() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String depVersionId = UUID.randomUUID().toString(); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry dep = willInstall(depVersionId, false); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); + + // the dialog names the failing dependency itself, from the entry it finds in the result + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + assertThat(result.getEntries()).anySatisfy(entry -> { + assertThat(entry.getName()).isEqualTo("Dep"); + assertThat(entry.isRoot()).isFalse(); + assertThat(entry.getErrorMessage()).isEqualTo("install failed"); + }); + verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + } + + @Test + void installPlan_failureWithoutMessage_reportsTheExceptionType() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new NullPointerException()).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the dialog looks the failing entry up by its error message, so it must never be blank + assertThat(result.getErrorMessage()).isEqualTo("NullPointerException"); + assertThat(result.getEntries()).allSatisfy(entry -> + assertThat(entry.getErrorMessage()).isEqualTo("NullPointerException")); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java b/application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java index d1c22a7374..88c88df49e 100644 --- a/application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java +++ b/application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java @@ -152,10 +152,13 @@ public class JobManagerTest extends AbstractControllerTest { int tasksCount = 200; JobId jobId = submitJob(DummyJobConfiguration.builder() .successfulTasksCount(tasksCount) - .taskProcessingTimeMs(50) + .taskProcessingTimeMs(TimeUnit.SECONDS.toMillis(30)) // keeps tasks in flight when the job is cancelled, whatever the partitioning strategy + .taskProcessingTimeoutMs(TimeUnit.SECONDS.toMillis(60)) .build()).getId(); - Thread.sleep(500); + await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> { + assertThat(findJobById(jobId).getStatus()).isEqualTo(JobStatus.RUNNING); + }); cancelJob(jobId); await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> { Job job = findJobById(jobId); diff --git a/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java b/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java index a5c78b49e2..28008681d5 100644 --- a/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java @@ -32,6 +32,7 @@ import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; +import org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse; import org.thingsboard.server.dao.cf.CalculatedFieldService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.gen.transport.TransportProtos; @@ -42,6 +43,7 @@ import org.thingsboard.server.queue.common.TbProtoQueueMsg; import org.thingsboard.server.queue.common.TbRuleEngineProducerService; import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.TopicService; +import org.thingsboard.server.queue.discovery.event.ServiceListChangedEvent; import org.thingsboard.server.queue.provider.TbQueueProducerProvider; import org.thingsboard.server.service.gateway_device.GatewayNotificationsService; import org.thingsboard.server.service.ota.OtaPackageStateService; @@ -77,6 +79,8 @@ public class DefaultTbClusterServiceTest { public static final String TRANSPORT = "transport"; + public static final String UNKNOWN_SERVICE_ID = "not-a-cluster-member"; + @MockitoBean protected TbDeviceProfileCache deviceProfileCache; @MockitoBean @@ -277,6 +281,7 @@ public class DefaultTbClusterServiceTest { TbQueueProducer> tbCoreQueueProducer = mock(TbQueueProducer.class); doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class)); + when(partitionService.isKnownServiceId(ServiceType.TB_CORE, CORE)).thenReturn(true); when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer); TransportProtos.RestApiCallResponseMsgProto responseMsgProto = TransportProtos.RestApiCallResponseMsgProto.getDefaultInstance(); TransportProtos.ToCoreNotificationMsg toCoreNotificationMsg = TransportProtos.ToCoreNotificationMsg.newBuilder().setRestApiCallResponseMsg(responseMsgProto).build(); @@ -291,6 +296,206 @@ public class DefaultTbClusterServiceTest { assertThat(protoQueueMsgArgumentCaptorValue.getKey()).isNotNull(); assertThat(protoQueueMsgArgumentCaptorValue.getValue()).isEqualTo(toCoreNotificationMsg); assertThat(protoQueueMsgArgumentCaptorValue.getHeaders().getData()).isEqualTo(new DefaultTbQueueMsgHeaders().getData()); + // a live member is accepted without falling back to the fail-open / recently-seen checks + verify(partitionService, never()).getAllServiceIds(ServiceType.TB_CORE); + } + + @Test + public void testPushNotificationToCoreToUnknownServiceIdIsSkipped() { + when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(CORE)); + TbQueueCallback callback = mock(TbQueueCallback.class); + + clusterService.pushNotificationToCore(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback); + + verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_CORE), eq(UNKNOWN_SERVICE_ID)); + verify(producerProvider, never()).getTbCoreNotificationsMsgProducer(); + verify(callback, times(1)).onSuccess(isNull()); + verify(callback, never()).onFailure(any(Throwable.class)); + } + + @Test + public void testPushNotificationToCoreToRecentlySeenButOfflineServiceIdIsSent() { + String offlineCore = "core-offline"; + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbCoreQueueProducer = mock(TbQueueProducer.class); + + // offlineCore was a cluster member moments ago but has dropped out of the current live snapshot + ((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent( + List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineCore).addServiceTypes(ServiceType.TB_CORE.name()).build()), + TransportProtos.ServiceInfo.newBuilder().setServiceId(CORE).addServiceTypes(ServiceType.TB_CORE.name()).build())); + + when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(CORE)); + doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_CORE, offlineCore); + when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer); + + clusterService.pushNotificationToCore(offlineCore, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback); + + verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); + } + + @Test + public void testPushNotificationToCoreToKnownServiceIdIsSent() { + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbCoreQueueProducer = mock(TbQueueProducer.class); + + when(partitionService.isKnownServiceId(ServiceType.TB_CORE, CORE)).thenReturn(true); + doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_CORE, CORE); + when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer); + + clusterService.pushNotificationToCore(CORE, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback); + + verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); + // a live member is accepted without falling back to the fail-open / recently-seen checks + verify(partitionService, never()).getAllServiceIds(ServiceType.TB_CORE); + } + + @Test + public void testPushNotificationToCoreFailsOpenWhenClusterTopologyIsUnknown() { + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbCoreQueueProducer = mock(TbQueueProducer.class); + + when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet()); + doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class)); + when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer); + + clusterService.pushNotificationToCore(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback); + + verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); + } + + @Test + public void testPushNotificationToRuleEngineToUnknownServiceIdIsSkipped() { + when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(RULE_ENGINE)); + TbQueueCallback callback = mock(TbQueueCallback.class); + + clusterService.pushNotificationToRuleEngine(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback); + + verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_RULE_ENGINE), eq(UNKNOWN_SERVICE_ID)); + verify(producerProvider, never()).getRuleEngineNotificationsMsgProducer(); + verify(callback, times(1)).onSuccess(isNull()); + verify(callback, never()).onFailure(any(Throwable.class)); + } + + @Test + public void testPushNotificationToRuleEngineToRecentlySeenButOfflineServiceIdIsSent() { + String offlineRuleEngine = "rule-engine-offline"; + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbRuleEngineQueueProducer = mock(TbQueueProducer.class); + + // offlineRuleEngine was a cluster member moments ago but has dropped out of the current live snapshot + ((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent( + List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineRuleEngine).addServiceTypes(ServiceType.TB_RULE_ENGINE.name()).build()), + TransportProtos.ServiceInfo.newBuilder().setServiceId(RULE_ENGINE).addServiceTypes(ServiceType.TB_RULE_ENGINE.name()).build())); + + when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(RULE_ENGINE)); + doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_RULE_ENGINE, offlineRuleEngine); + when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer); + + clusterService.pushNotificationToRuleEngine(offlineRuleEngine, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback); + + verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); + } + + @Test + public void testPushNotificationToRuleEngineToKnownServiceIdIsSent() { + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbRuleEngineQueueProducer = mock(TbQueueProducer.class); + + when(partitionService.isKnownServiceId(ServiceType.TB_RULE_ENGINE, RULE_ENGINE)).thenReturn(true); + doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_RULE_ENGINE, RULE_ENGINE); + when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer); + + clusterService.pushNotificationToRuleEngine(RULE_ENGINE, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback); + + verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); + // a live member is accepted without falling back to the fail-open / recently-seen checks + verify(partitionService, never()).getAllServiceIds(ServiceType.TB_RULE_ENGINE); + } + + @Test + public void testPushNotificationToRuleEngineFailsOpenWhenClusterTopologyIsUnknown() { + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbRuleEngineQueueProducer = mock(TbQueueProducer.class); + + when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet()); + doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class)); + when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer); + + clusterService.pushNotificationToRuleEngine(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback); + + verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); + } + + @Test + public void testPushNotificationToTransportToUnknownServiceIdIsSkipped() { + when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(TRANSPORT)); + TbQueueCallback callback = mock(TbQueueCallback.class); + + clusterService.pushNotificationToTransport(UNKNOWN_SERVICE_ID, TransportProtos.ToTransportMsg.getDefaultInstance(), callback); + + verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_TRANSPORT), eq(UNKNOWN_SERVICE_ID)); + verify(producerProvider, never()).getTransportNotificationsMsgProducer(); + verify(callback, times(1)).onSuccess(isNull()); + verify(callback, never()).onFailure(any(Throwable.class)); + } + + @Test + public void testPushNotificationToTransportToKnownServiceIdIsSent() { + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbTransportQueueProducer = mock(TbQueueProducer.class); + + when(partitionService.isKnownServiceId(ServiceType.TB_TRANSPORT, TRANSPORT)).thenReturn(true); + doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_TRANSPORT, TRANSPORT); + when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer); + + clusterService.pushNotificationToTransport(TRANSPORT, TransportProtos.ToTransportMsg.getDefaultInstance(), callback); + + verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); + // a live member is accepted without falling back to the fail-open / recently-seen checks + verify(partitionService, never()).getAllServiceIds(ServiceType.TB_TRANSPORT); + } + + @Test + public void testPushNotificationToTransportToRecentlySeenButOfflineServiceIdIsSent() { + String offlineTransport = "transport-offline"; + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbTransportQueueProducer = mock(TbQueueProducer.class); + + // offlineTransport was a cluster member moments ago but has dropped out of the current live snapshot + ((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent( + List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineTransport).addServiceTypes(ServiceType.TB_TRANSPORT.name()).build()), + TransportProtos.ServiceInfo.newBuilder().setServiceId(TRANSPORT).addServiceTypes(ServiceType.TB_TRANSPORT.name()).build())); + + when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(TRANSPORT)); + doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_TRANSPORT, offlineTransport); + when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer); + + clusterService.pushNotificationToTransport(offlineTransport, TransportProtos.ToTransportMsg.getDefaultInstance(), callback); + + verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); + } + + @Test + public void testPushNotificationToTransportFailsOpenWhenClusterTopologyIsUnknown() { + TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); + TbQueueCallback callback = mock(TbQueueCallback.class); + TbQueueProducer> tbTransportQueueProducer = mock(TbQueueProducer.class); + + when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet()); + doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class)); + when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer); + + clusterService.pushNotificationToTransport(UNKNOWN_SERVICE_ID, TransportProtos.ToTransportMsg.getDefaultInstance(), callback); + + verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback)); } @Test diff --git a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java index 90c2888a51..e973ee13dc 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java @@ -4,13 +4,17 @@ package org.thingsboard.server.service.script; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import delight.nashornsandbox.NashornSandbox; +import delight.nashornsandbox.NashornSandboxes; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.TestPropertySource; +import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.TbStopWatch; +import org.thingsboard.script.api.RuleNodeScriptFactory; import org.thingsboard.script.api.ScriptType; import org.thingsboard.script.api.TbScriptException; import org.thingsboard.script.api.js.NashornJsInvokeService; @@ -18,6 +22,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.controller.AbstractControllerTest; import org.thingsboard.server.dao.service.DaoSqlTest; +import javax.script.ScriptEngine; import javax.script.ScriptException; import java.util.ArrayList; import java.util.List; @@ -209,6 +214,87 @@ class NashornJsInvokeServiceTest extends AbstractControllerTest { }); } + @Test + void whenScriptIsReleased_thenGlobalPropertyIsRemoved() throws Exception { + UUID scriptId = evalScript("return msg;"); + String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_'); + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(true); + + invokeService.release(scriptId).get(); + + // the property must be deleted, not just set to undefined: an abandoned binding keeps + // its slot in the Global's PropertyMap forever + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(false); + } + + @Test + void givenIifeWrappedEval_whenInvoking_thenResultIsUnchanged() throws Exception { + UUID scriptId = evalScript("return {doubled: msg.temperature * 2};"); + assertThat(invokeScript(scriptId, "{\"temperature\":21}")).contains("\"doubled\":42"); + } + + @Test + void givenIifeWrappedEval_thenImplicitGlobalStateIsStillSharedBetweenScripts() throws Exception { + UUID writer = evalScript("compatSharedState = 777; return msg;"); + UUID reader = evalScript("return {seen: (typeof compatSharedState === 'undefined') ? null : compatSharedState};"); + invokeScript(writer, "{}"); + assertThat(invokeScript(reader, "{}")).contains("\"seen\":777"); + } + + @Test + void givenIifeWrappedEval_thenCompilationErrorUnchanged() { + String badScript = "var a = 1;\nvar b = 2;\nreturn msg.temperature?.value;"; + + String legacyScript = RuleNodeScriptFactory.generateRuleNodeScript("invokeInternal_legacy", badScript, + "msg", "metadata", "msgType"); + NashornSandbox legacySandbox = NashornSandboxes.create(); + legacySandbox.allowNoBraces(false); + legacySandbox.allowLoadFunctions(true); + legacySandbox.setMaxPreparedStatements(30); + int legacyErrorLine = -1; + try { + legacySandbox.eval(legacyScript); + } catch (ScriptException e) { + legacyErrorLine = e.getLineNumber(); + } + assertThat(legacyErrorLine).isGreaterThan(0); + final int expectedLine = legacyErrorLine; + + assertThatThrownBy(() -> evalScript(badScript)) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class) + .asInstanceOf(type(TbScriptException.class)) + .satisfies(ex -> { + assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.COMPILATION); + assertThat(ex.getBody()).contains(badScript); + assertThat(ex.getCause()).isInstanceOf(ScriptException.class); + // The IIFE wrapper shifts sandbox-reported line numbers by a constant +2 + // (the beautifier splits the wrapper prefix onto its own lines). Reported + // lines never matched the user's source anyway (the sandbox instrumentation + // already offsets them), so only the small constant shift is tolerated here. + assertThat(((ScriptException) ex.getCause()).getLineNumber()).isBetween(expectedLine, expectedLine + 2); + }); + } + + @Test + void whenInvokingAfterRelease_thenFailsWithNoCompiledScriptFound() throws Exception { + UUID scriptId = evalScript("return msg;"); + invokeScript(scriptId, "{}"); + invokeService.release(scriptId).get(); + assertThatThrownBy(() -> invokeScript(scriptId, "{}")) + .isInstanceOf(ExecutionException.class) + .hasMessageContaining("No compiled script found"); + } + + private Object evalInEngine(String expression) throws Exception { + Object sandbox = ReflectionTestUtils.getField(invokeService, "sandbox"); + if (sandbox != null) { + return ((NashornSandbox) sandbox).eval(expression); + } + return ((ScriptEngine) ReflectionTestUtils.getField(invokeService, "engine")).eval(expression); + } + private void assertThatScriptIsBlocked(UUID scriptId) { assertThatThrownBy(() -> { invokeScript(scriptId, "{}"); diff --git a/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java index 00ff00b9e4..2ab081f686 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java @@ -288,6 +288,20 @@ class TbelInvokeServiceTest extends AbstractTbelInvokeTest { }); } + @Test + void givenForbiddenFormatter_whenInvoking_thenThrowsRuntimeError() throws ExecutionException, InterruptedException { + UUID scriptId = evalScript("new java.util.Formatter(\"/tmp/test.txt\")"); + assertThatThrownBy(() -> invokeScript(scriptId, "{\"temperature\":25}")) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class) + .asInstanceOf(type(TbScriptException.class)) + .satisfies(ex -> { + assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.RUNTIME); + assertThat(ex.getCause().getMessage()).contains("could not resolve class: java.util.Formatter"); + }); + } + private void assertThatScriptIsBlocked(UUID scriptId) { assertThatThrownBy(() -> { invokeScriptResultString(scriptId, "{}"); diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java deleted file mode 100644 index 9bae84d44d..0000000000 --- a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The Thingsboard Authors -// SPDX-License-Identifier: Apache-2.0 -package org.thingsboard.server.service.security.auth.oauth2; - -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; - -import java.util.LinkedHashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME; - -public class CookieUtilsTest { - - @Test - public void serializeDeserializeOAuth2AuthorizationRequestTest() { - HttpCookieOAuth2AuthorizationRequestRepository cookieRequestRepo = new HttpCookieOAuth2AuthorizationRequestRepository(); - HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class); - - Map additionalParameters = new LinkedHashMap<>(); - additionalParameters.put("param1", "value1"); - additionalParameters.put("param2", "value2"); - var request = OAuth2AuthorizationRequest.authorizationCode() - .authorizationUri("testUri").clientId("testId") - .scope("read", "write") - .additionalParameters(additionalParameters).build(); - - - Cookie cookie = new Cookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(request)); - Mockito.when(servletRequest.getCookies()).thenReturn(new Cookie[]{cookie}); - - OAuth2AuthorizationRequest deserializedRequest = cookieRequestRepo.loadAuthorizationRequest(servletRequest); - - assertNotNull(deserializedRequest); - assertEquals(request.getGrantType(), deserializedRequest.getGrantType()); - assertEquals(request.getAuthorizationUri(), deserializedRequest.getAuthorizationUri()); - assertEquals(request.getClientId(), deserializedRequest.getClientId()); - } - -} \ No newline at end of file diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java index 7cb38fa428..4b292712af 100644 --- a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java +++ b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java @@ -2,27 +2,50 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.security.auth.oauth2; +import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; +import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; +import org.thingsboard.server.common.data.security.model.JwtSettings; +import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService; + +import java.security.SecureRandom; +import java.time.Clock; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME; import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_COOKIE_NAME; import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_PARAMETER; public class HttpCookieOAuth2AuthorizationRequestRepositoryTest { - private final HttpCookieOAuth2AuthorizationRequestRepository repository = new HttpCookieOAuth2AuthorizationRequestRepository(); + private static final long NOW = 1_700_000_000_000L; + + private final JwtSettingsService jwtSettingsService = mock(JwtSettingsService.class); + private final Clock clock = mock(Clock.class); + private final HttpCookieOAuth2AuthorizationRequestRepository repository = + new HttpCookieOAuth2AuthorizationRequestRepository(jwtSettingsService, clock); + + @BeforeEach + public void before() { + givenSigningKey(randomSigningKey()); + when(clock.millis()).thenReturn(NOW); + } @Test public void testPrevUriSavedForInAppPath() { @@ -37,20 +60,140 @@ public class HttpCookieOAuth2AuthorizationRequestRepositoryTest { assertThat(savePrevUri(prevUri)).isNull(); } + @Test + public void testAuthorizationRequestRoundTrip() { + Map additionalParameters = new LinkedHashMap<>(); + additionalParameters.put("param1", "value1"); + additionalParameters.put("param2", "value2"); + OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode() + .authorizationUri("testUri").clientId("testId") + .scope("read", "write") + .state("testState") + .additionalParameters(additionalParameters) + .attributes(attributes -> attributes.put(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME, "tbmobile")) + .build(); + + OAuth2AuthorizationRequest loaded = load(save(authorizationRequest)); + + assertThat(loaded).isNotNull(); + assertThat(loaded.getGrantType()).isEqualTo(authorizationRequest.getGrantType()); + assertThat(loaded.getAuthorizationUri()).isEqualTo(authorizationRequest.getAuthorizationUri()); + assertThat(loaded.getClientId()).isEqualTo(authorizationRequest.getClientId()); + assertThat(loaded.getScopes()).isEqualTo(authorizationRequest.getScopes()); + assertThat(loaded.getState()).isEqualTo(authorizationRequest.getState()); + assertThat(loaded.getAdditionalParameters()).isEqualTo(additionalParameters); + assertThat(CallbackUrlSchemeValidator.getCallbackUrlScheme(loaded)).isEqualTo("tbmobile"); + } + + @Test + public void testCookieIsNotPlainJson() { + String cookieValue = save(authorizationRequest()); + assertThat(new String(Base64.getUrlDecoder().decode(cookieValue))).doesNotContain("testId"); + } + + @Test + public void testEachCookieUsesFreshNonce() { + assertThat(save(authorizationRequest())).isNotEqualTo(save(authorizationRequest())); + } + + @Test + public void testTamperedCookieIsRejected() { + byte[] envelope = Base64.getUrlDecoder().decode(save(authorizationRequest())); + for (int i = 0; i < envelope.length; i++) { + byte[] tampered = envelope.clone(); + tampered[i] ^= 0x01; + assertThat(load(Base64.getUrlEncoder().withoutPadding().encodeToString(tampered))).as("bit flipped at byte %s", i).isNull(); + } + } + + @Test + public void testTruncatedCookieIsRejected() { + String cookieValue = save(authorizationRequest()); + assertThat(load(cookieValue.substring(0, cookieValue.length() - 4))).isNull(); + } + + @Test + public void testCookieEncryptedWithDifferentKeyIsRejected() { + String cookieValue = save(authorizationRequest()); + givenSigningKey(randomSigningKey()); + assertThat(load(cookieValue)).isNull(); + } + + @Test + public void testNewCookieIsAcceptedAfterKeyRotation() { + givenSigningKey(randomSigningKey()); + String cookieValue = save(authorizationRequest()); + assertThat(load(cookieValue)).isNotNull(); + } + + @Test + public void testUnencryptedCookieIsRejected() throws Exception { + ObjectMapper mapper = new ObjectMapper().registerModules(SecurityJackson2Modules.getModules(getClass().getClassLoader())); + String plainCookieValue = Base64.getUrlEncoder().encodeToString(mapper.writeValueAsBytes(authorizationRequest())); + assertThat(load(plainCookieValue)).isNull(); + } + + @ParameterizedTest + @ValueSource(strings = {"", "a", "AAAA", "not base64 !", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}) + public void testMalformedCookieIsRejected(String cookieValue) { + assertThat(load(cookieValue)).isNull(); + } + + @Test + public void testExpiredCookieIsRejected() { + String cookieValue = save(authorizationRequest()); + when(clock.millis()).thenReturn(NOW + 180_000); + assertThat(load(cookieValue)).isNotNull(); + when(clock.millis()).thenReturn(NOW + 180_001); + assertThat(load(cookieValue)).isNull(); + } + + private OAuth2AuthorizationRequest authorizationRequest() { + return OAuth2AuthorizationRequest.authorizationCode().authorizationUri("testUri").clientId("testId").build(); + } + + private String save(OAuth2AuthorizationRequest authorizationRequest) { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + repository.saveAuthorizationRequest(authorizationRequest, request, response); + return findCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); + } + + private OAuth2AuthorizationRequest load(String cookieValue) { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getCookies()).thenReturn(new Cookie[]{new Cookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, cookieValue)}); + return repository.loadAuthorizationRequest(request); + } + private String savePrevUri(String prevUri) { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getParameter(PREV_URI_PARAMETER)).thenReturn(prevUri); - repository.saveAuthorizationRequest(OAuth2AuthorizationRequest.authorizationCode() - .authorizationUri("testUri").clientId("testId").build(), request, response); + repository.saveAuthorizationRequest(authorizationRequest(), request, response); + return findCookie(response, PREV_URI_COOKIE_NAME); + } + + private String findCookie(HttpServletResponse response, String name) { ArgumentCaptor cookieCaptor = ArgumentCaptor.forClass(Cookie.class); verify(response, atLeastOnce()).addCookie(cookieCaptor.capture()); return cookieCaptor.getAllValues().stream() - .filter(cookie -> PREV_URI_COOKIE_NAME.equals(cookie.getName())) + .filter(cookie -> name.equals(cookie.getName())) .map(Cookie::getValue) .findAny().orElse(null); } + private void givenSigningKey(String signingKey) { + JwtSettings jwtSettings = new JwtSettings(); + jwtSettings.setTokenSigningKey(signingKey); + when(jwtSettingsService.getJwtSettings()).thenReturn(jwtSettings); + } + + private static String randomSigningKey() { + byte[] key = new byte[64]; + new SecureRandom().nextBytes(key); + return Base64.getEncoder().encodeToString(key); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java new file mode 100644 index 0000000000..d65868a7fb --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -0,0 +1,294 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.solutions; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.DashboardInfo; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.common.data.asset.AssetProfile; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainType; +import org.thingsboard.server.dao.asset.AssetProfileService; +import org.thingsboard.server.dao.asset.AssetService; +import org.thingsboard.server.dao.customer.CustomerService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceProfileService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.rule.RuleChainService; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DefaultSolutionServiceTest { + + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + // mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it + private static final int LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @Mock + private CustomerService customerService; + @Mock + private DeviceService deviceService; + @Mock + private AssetService assetService; + @Mock + private DashboardService dashboardService; + @Mock + private RuleChainService ruleChainService; + @Mock + private DeviceProfileService deviceProfileService; + @Mock + private AssetProfileService assetProfileService; + @Mock + private EdgeService edgeService; + + @InjectMocks + private DefaultSolutionService service; + + @TempDir + private Path tempDir; + + @Test + void testValidateSolutionNamesEveryConflictingEntity() throws IOException { + writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); + writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]"); + + Customer customer = new Customer(); + customer.setTitle("Existing customer"); + + when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + Asset asset = new Asset(); + asset.setName("Existing asset"); + when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); + when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")) + .thenReturn(existingDevice("Existing device")); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) + .containsSubsequence( + CONFLICTS_INTRO, + "- **Customer**: 'Existing customer'", + "- **Asset**: 'Existing asset'", + "- **Device**: 'Existing device'"); + // the randomized customer title and the entities that do not exist yet are not reported + assertThat(result.getConflictReport()) + .doesNotContain("Customer $random") + .doesNotContain("New device") + .doesNotContain("New asset"); + } + + @Test + void testValidateSolutionReportsConflictingDashboard() throws IOException { + writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]"); + + DashboardInfo dashboard = new DashboardInfo(); + dashboard.setTitle("Overview"); + when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); + } + + @Test + void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Name the install creates"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) + .thenReturn(List.of(ruleChain)); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); + } + + @Test + void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]"); + writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]"); + writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]"); + + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.setName("thermostat"); + AssetProfile assetProfile = new AssetProfile(); + assetProfile.setName("building"); + Edge edge = new Edge(); + edge.setName("Main edge"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile); + when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); + when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()).containsSubsequence( + "- **Device profile**: 'thermostat'", + "- **Asset profile**: 'building'", + "- **Edge**: 'Main edge'"); + } + + @Test + void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); + + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'"); + verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); + } + + @Test + void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," + + "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); + writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); + + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); + verifyNoInteractions(ruleChainService); + } + + @Test + void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Edge chain"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) + .thenReturn(List.of(ruleChain)); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + } + + @Test + void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { + writeEntitiesFile("devices.json", "null"); + + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); + verifyNoInteractions(deviceService); + } + + @ParameterizedTest + @ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2}) + void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException { + List names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList(); + writeEntitiesFile("devices.json", names.stream() + .map(name -> "{\"name\": \"" + name + "\"}") + .collect(Collectors.joining(",", "[", "]"))); + names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) + .thenReturn(existingDevice(name))); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + int hidden = conflictCount - LISTED_NAMES_PER_TYPE; + String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) + .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed + + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); + if (hidden > 0) { + assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE); + } else { + assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE); + } + } + + /** + * The profile lists are the json file plus every file in the directory of the same name merged into one list, so + * this is where the same name genuinely can appear twice. + */ + @Test + void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]"); + writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}"); + + DeviceProfile profile = new DeviceProfile(); + profile.setName("Sensor profile"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); + } + + @Test + void testValidateSolutionWithoutConflicts() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); + } + + @Test + void testValidateSolutionWithoutEntityFiles() { + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, + deviceProfileService, assetProfileService, edgeService); + } + + private static Device existingDevice(String name) { + Device device = new Device(); + device.setName(name); + return device; + } + + private void writeFile(String relativePath, String content) throws IOException { + Path file = tempDir.resolve(relativePath); + Files.createDirectories(file.getParent()); + Files.writeString(file, content); + } + + private void writeEntitiesFile(String fileName, String content) throws IOException { + Path entitiesDir = Files.createDirectories(tempDir.resolve("entities")); + Files.writeString(entitiesDir.resolve(fileName), content); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java b/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java index 32789ba181..9ba676a611 100644 --- a/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java +++ b/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -51,6 +52,8 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -86,6 +89,13 @@ public class SystemPatchApplierTest { @TempDir Path tempDir; + private void runPostSchemaCallback() { + doAnswer(invocation -> { + invocation.getArgument(2, Runnable.class).run(); + return null; + }).when(ltsMigrationService).applyMigrations(anyString(), anyString(), any()); + } + @Test void whenLockIsNotAcquired_thenAcquiredIsSuccess() { when(jdbcTemplate.queryForObject(anyString(), eq(Boolean.class), anyLong())).thenReturn(true); @@ -449,20 +459,41 @@ public class SystemPatchApplierTest { // --- applyPatchIfNeeded flow tests --- @Test - void whenVersionIncreased_thenAppliesMigrationsBeforeViewsAndWidgets() { + void whenVersionIncreased_thenSystemDataIsSyncedOnlyByTheMigrationCallback() { when(schemaSettingsService.getPackageSchemaVersion()).thenReturn("4.3.1.0"); when(schemaSettingsService.getDbSchemaVersion()).thenReturn("4.3.0.0"); when(jdbcTemplate.queryForObject(contains("pg_try_advisory_lock"), eq(Boolean.class), anyLong())).thenReturn(true); when(jdbcTemplate.queryForObject(contains("pg_advisory_unlock"), eq(Boolean.class), anyLong())).thenReturn(true); - when(installScripts.getWidgetTypesDir()).thenReturn(tempDir.resolve("widget_types")); when(installScripts.getWidgetBundlesDir()).thenReturn(tempDir.resolve("widget_bundles_missing")); when(installScripts.getDataDir()).thenReturn(tempDir.resolve("data").toString()); ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); - verify(ltsMigrationService).applyMigrations("4.3.0.0", "4.3.1.0"); - verify(schemaSettingsService).updateSchemaVersion(); + ArgumentCaptor postSchemaPhase = ArgumentCaptor.forClass(Runnable.class); + verify(ltsMigrationService).applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), postSchemaPhase.capture()); + verify(jdbcTemplate, never()).execute(anyString()); + + postSchemaPhase.getValue().run(); + + verify(jdbcTemplate).execute(contains("CREATE OR REPLACE VIEW")); + } + + @Test + void whenMigrationCallbackNotInvoked_thenNothingIsSyncedOutsideIt() { + when(schemaSettingsService.getPackageSchemaVersion()).thenReturn("4.3.1.0"); + when(schemaSettingsService.getDbSchemaVersion()).thenReturn("4.3.0.0"); + when(jdbcTemplate.queryForObject(contains("pg_try_advisory_lock"), eq(Boolean.class), anyLong())).thenReturn(true); + when(jdbcTemplate.queryForObject(contains("pg_advisory_unlock"), eq(Boolean.class), anyLong())).thenReturn(true); + // Lenient: only reached if system data were synced outside the callback. + lenient().when(installScripts.getWidgetTypesDir()).thenReturn(tempDir.resolve("widget_types_missing")); + lenient().when(installScripts.getWidgetBundlesDir()).thenReturn(tempDir.resolve("widget_bundles_missing")); + lenient().when(installScripts.getDataDir()).thenReturn(tempDir.resolve("data_missing").toString()); + + ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); + + verify(ltsMigrationService).applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), any()); + verify(jdbcTemplate, never()).execute(anyString()); } @Test @@ -497,6 +528,8 @@ public class SystemPatchApplierTest { when(jdbcTemplate.queryForObject(contains("pg_try_advisory_lock"), eq(Boolean.class), anyLong())).thenReturn(true); when(jdbcTemplate.queryForObject(contains("pg_advisory_unlock"), eq(Boolean.class), anyLong())).thenReturn(true); + runPostSchemaCallback(); + Path widgetTypesDir = tempDir.resolve("widget_types"); Files.createDirectories(widgetTypesDir); when(installScripts.getWidgetTypesDir()).thenReturn(widgetTypesDir); @@ -506,7 +539,7 @@ public class SystemPatchApplierTest { ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); verify(schemaSettingsService).updateSchemaVersion(); - verify(ltsMigrationService).applyMigrations("4.3.1.0", "4.3.2.0"); + verify(ltsMigrationService).applyMigrations(eq("4.3.1.0"), eq("4.3.2.0"), any()); } @Test @@ -719,6 +752,7 @@ public class SystemPatchApplierTest { when(schemaSettingsService.getDbSchemaVersion()).thenReturn("4.3.0.0"); when(jdbcTemplate.queryForObject(contains("pg_try_advisory_lock"), eq(Boolean.class), anyLong())).thenReturn(true); when(jdbcTemplate.queryForObject(contains("pg_advisory_unlock"), eq(Boolean.class), anyLong())).thenReturn(true); + runPostSchemaCallback(); Path dataDir = tempDir.resolve("data"); Path imagesDir = dataDir.resolve(InstallScripts.RESOURCES_DIR).resolve("images"); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java index 15123175af..1ac74466d3 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import jnr.ffi.annotations.In; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.awaitility.core.ConditionTimeoutException; @@ -712,28 +711,28 @@ public abstract class AbstractLwM2MIntegrationTest extends AbstractTransportInte List bootstrap = new ArrayList<>(); switch (bootstrapConfigType) { case BOTH: - bootstrap.add(getBootstrapServerCredentialNoSec(false)); - bootstrap.add(getBootstrapServerCredentialNoSec(true)); + bootstrap.add(getBootstrapSectionServerCredentialNoSec(false)); + bootstrap.add(getBootstrapSectionServerCredentialNoSec(true)); break; case BOOTSTRAP_ONLY: - bootstrap.add(getBootstrapServerCredentialNoSec(true)); + bootstrap.add(getBootstrapSectionServerCredentialNoSec(true)); break; case LWM2M_ONLY: - bootstrap.add(getBootstrapServerCredentialNoSec(false)); + bootstrap.add(getBootstrapSectionServerCredentialNoSec(false)); break; case NONE: } return bootstrap; } - protected AbstractLwM2MBootstrapServerCredential getBootstrapServerCredentialNoSec(boolean isBootstrap) { - AbstractLwM2MBootstrapServerCredential bootstrapServerCredential = new NoSecLwM2MBootstrapServerCredential(); - bootstrapServerCredential.setServerPublicKey(""); - bootstrapServerCredential.setShortServerId(isBootstrap ? null : shortServerId); - bootstrapServerCredential.setBootstrapServerIs(isBootstrap); - bootstrapServerCredential.setHost(isBootstrap ? LWM2M_BOOTSTRAP_HOST : LWM2M_HOST); - bootstrapServerCredential.setPort(isBootstrap ? LWM2M_BOOTSTRAP_PORT : LWM2M_PORT); - return bootstrapServerCredential; + protected AbstractLwM2MBootstrapServerCredential getBootstrapSectionServerCredentialNoSec(boolean isBootstrap) { + AbstractLwM2MBootstrapServerCredential bootstrapSectionServerCredential = new NoSecLwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential.setServerPublicKey(""); + bootstrapSectionServerCredential.setShortServerId(isBootstrap ? null : shortServerId); + bootstrapSectionServerCredential.setBootstrapServerIs(isBootstrap); + bootstrapSectionServerCredential.setHost(isBootstrap ? LWM2M_BOOTSTRAP_HOST : LWM2M_HOST); + bootstrapSectionServerCredential.setPort(isBootstrap ? LWM2M_BOOTSTRAP_PORT : LWM2M_PORT); + return bootstrapSectionServerCredential; } protected LwM2MDeviceCredentials getDeviceCredentialsNoSec(LwM2MClientCredential clientCredentials) { diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java index adb116caba..f123c241f0 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java @@ -226,10 +226,10 @@ public abstract class AbstractSecurityLwM2MIntegrationTest extends AbstractLwM2M public void basicTestConnectionBootstrapRequestTriggerBefore(String clientEndpoint, String awaitAlias, LwM2MProfileBootstrapConfigType type, int cnt) throws Exception { List bootstrapServerCredentialsNoSec = getBootstrapServerCredentialsNoSec(type); for (int i = 2; i <= cnt; i++) { - AbstractLwM2MBootstrapServerCredential bsCredential = getBootstrapServerCredentialNoSec(false); - bsCredential.setHost("0.0.0." + i); - bsCredential.setShortServerId(bsCredential.getShortServerId() + i); - bootstrapServerCredentialsNoSec.add(bsCredential); + AbstractLwM2MBootstrapServerCredential bsSectionCredential = getBootstrapSectionServerCredentialNoSec(false); + bsSectionCredential.setHost("0.0.0." + i); + bsSectionCredential.setShortServerId(bsSectionCredential.getShortServerId() + i); + bootstrapServerCredentialsNoSec.add(bsSectionCredential); } Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, bootstrapServerCredentialsNoSec); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(clientEndpoint)); @@ -303,46 +303,46 @@ public abstract class AbstractSecurityLwM2MIntegrationTest extends AbstractLwM2M Assert.assertTrue(lwM2MTestClient.getClientStates().containsAll(expectedStatusesBs)); } - protected List getBootstrapServerCredentialsSecure(LwM2MSecurityMode mode, LwM2MProfileBootstrapConfigType bootstrapConfigType) { - List bootstrap = new ArrayList<>(); + protected List getBootstrapSectionsServerCredentialsSecure(LwM2MSecurityMode mode, LwM2MProfileBootstrapConfigType bootstrapConfigType) { + List bootstrapSections = new ArrayList<>(); switch (bootstrapConfigType) { case BOTH: - bootstrap.add(getBootstrapServerCredential(mode, false)); - bootstrap.add(getBootstrapServerCredential(mode, true)); + bootstrapSections.add(getBootstrapSectionServerCredential(mode, false)); + bootstrapSections.add(getBootstrapSectionServerCredential(mode, true)); break; case BOOTSTRAP_ONLY: - bootstrap.add(getBootstrapServerCredential(mode, true)); + bootstrapSections.add(getBootstrapSectionServerCredential(mode, true)); break; case LWM2M_ONLY: - bootstrap.add(getBootstrapServerCredential(mode, false)); + bootstrapSections.add(getBootstrapSectionServerCredential(mode, false)); break; case NONE: } - return bootstrap; + return bootstrapSections; } - private AbstractLwM2MBootstrapServerCredential getBootstrapServerCredential(LwM2MSecurityMode mode, boolean isBootstrap) { - AbstractLwM2MBootstrapServerCredential bootstrapServerCredential; + private AbstractLwM2MBootstrapServerCredential getBootstrapSectionServerCredential(LwM2MSecurityMode mode, boolean isBootstrap) { + AbstractLwM2MBootstrapServerCredential bootstrapSectionServerCredential; switch (mode) { case PSK: - bootstrapServerCredential = new PSKLwM2MBootstrapServerCredential(); - bootstrapServerCredential.setServerPublicKey(""); + bootstrapSectionServerCredential = new PSKLwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential.setServerPublicKey(""); break; case RPK: - bootstrapServerCredential = new RPKLwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential = new RPKLwM2MBootstrapServerCredential(); if (isBootstrap) { - bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCertBs.getEncoded())); + bootstrapSectionServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCertBs.getEncoded())); } else { - bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCert.getEncoded())); + bootstrapSectionServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCert.getEncoded())); } break; case X509: - bootstrapServerCredential = new X509LwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential = new X509LwM2MBootstrapServerCredential(); try { if (isBootstrap) { - bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509CertBs.getEncoded())); + bootstrapSectionServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509CertBs.getEncoded())); } else { - bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509Cert.getEncoded())); + bootstrapSectionServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509Cert.getEncoded())); } } catch (CertificateEncodingException e) { e.printStackTrace(); @@ -351,11 +351,11 @@ public abstract class AbstractSecurityLwM2MIntegrationTest extends AbstractLwM2M default: throw new IllegalStateException("Unexpected value: " + mode); } - bootstrapServerCredential.setShortServerId(isBootstrap ? null : shortServerId); - bootstrapServerCredential.setBootstrapServerIs(isBootstrap); - bootstrapServerCredential.setHost(isBootstrap ? LWM2M_BOOTSTRAP_HOST : LWM2M_HOST); - bootstrapServerCredential.setPort(isBootstrap ? LWM2MS_BOOTSTRAP_PORT : LWM2MS_PORT); - return bootstrapServerCredential; + bootstrapSectionServerCredential.setShortServerId(isBootstrap ? null : shortServerId); + bootstrapSectionServerCredential.setBootstrapServerIs(isBootstrap); + bootstrapSectionServerCredential.setHost(isBootstrap ? LWM2M_BOOTSTRAP_HOST : LWM2M_HOST); + bootstrapSectionServerCredential.setPort(isBootstrap ? LWM2MS_BOOTSTRAP_PORT : LWM2MS_PORT); + return bootstrapSectionServerCredential; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/NoSecLwM2MIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/NoSecLwM2MIntegrationDtlsCidLengthTest.java index 461d24d665..fc2fe701d6 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/NoSecLwM2MIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/NoSecLwM2MIntegrationDtlsCidLengthTest.java @@ -13,7 +13,7 @@ public class NoSecLwM2MIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2 @Before public void setUpNoSecDtlsCidLength() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(NO_SEC, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(NO_SEC, NONE)); awaitAlias = "await on client state (NoSec_Lwm2m) serverDtlsCidLength = 0"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/PskLwm2mIntegrationDtlsCidLengthTest.java index 12500f0847..00766092b8 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -13,7 +13,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 0"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_1/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_1/PskLwm2mIntegrationDtlsCidLengthTest.java index cfb62e3626..2c45646373 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_1/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_1/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -4,7 +4,6 @@ package org.thingsboard.server.transport.lwm2m.security.cid.serverDtlsCidLength_ import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength0Test; import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength1Test; import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.PSK; @@ -14,7 +13,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 1"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/NoSecLwM2MIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/NoSecLwM2MIntegrationDtlsCidLengthTest.java index cb7ad71940..800efbbb65 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/NoSecLwM2MIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/NoSecLwM2MIntegrationDtlsCidLengthTest.java @@ -5,7 +5,6 @@ package org.thingsboard.server.transport.lwm2m.security.cid.serverDtlsCidLength_ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength16Test; -import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength4Test; import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.NO_SEC; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; @@ -14,7 +13,7 @@ public class NoSecLwM2MIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2 @Before public void setUpNoSecDtlsCidLength() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(NO_SEC, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(NO_SEC, NONE)); awaitAlias = "await on client state (NoSec_Lwm2m) serverDtlsCidLength = 16"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/PskLwm2mIntegrationDtlsCidLengthTest.java index 96e4411934..3ab605001e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -5,7 +5,6 @@ package org.thingsboard.server.transport.lwm2m.security.cid.serverDtlsCidLength_ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength16Test; -import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength4Test; import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.PSK; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; @@ -14,7 +13,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 16"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_2/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_2/PskLwm2mIntegrationDtlsCidLengthTest.java index 48b595c116..a46bb0ae18 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_2/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_2/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -13,7 +13,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 2"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_4/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_4/PskLwm2mIntegrationDtlsCidLengthTest.java index d05ca17d05..c09fdfcf71 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_4/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_4/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -13,7 +13,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 4"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/NoSecLwM2MIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/NoSecLwM2MIntegrationDtlsCidLengthTest.java index ee68a72c97..9039834c8f 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/NoSecLwM2MIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/NoSecLwM2MIntegrationDtlsCidLengthTest.java @@ -13,7 +13,7 @@ public class NoSecLwM2MIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2 @Before public void setUpNoSecDtlsCidLength() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(NO_SEC, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(NO_SEC, NONE)); awaitAlias = "await on client state (NoSec_Lwm2m) serverDtlsCidLength = Null"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/PskLwm2mIntegrationDtlsCidLengthTest.java index 16a28d3533..e9f8b241e3 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -13,7 +13,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = Null"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/diffPort/LwM2MIntegrationDiffPortTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/diffPort/LwM2MIntegrationDiffPortTest.java index 79971bd369..608cf77464 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/diffPort/LwM2MIntegrationDiffPortTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/diffPort/LwM2MIntegrationDiffPortTest.java @@ -14,7 +14,7 @@ public class LwM2MIntegrationDiffPortTest extends AbstractLwM2MIntegrationDiffPo @Test public void testWithNoSecConnectLwm2mSuccess_AfterRegistration_UpdateRegistrationFromDifferentPort_Ok() throws Exception { String awaitAlias = "await on client state (NoSec different port)"; - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(NO_SEC, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(NO_SEC, NONE)); initDeviceCredentialsNoSek(); basicTestConnectionDifferentPort( transportConfiguration, @@ -23,7 +23,7 @@ public class LwM2MIntegrationDiffPortTest extends AbstractLwM2MIntegrationDiffPo @Test public void testWithPskConnectLwm2mSuccess_AfterRegistration_UpdateRegistrationFromDifferentPort_Ok() throws Exception { String awaitAlias = "await on client state (Psk different port)"; - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); initDeviceCredentialsPsk(); basicTestConnectionDifferentPort( transportConfiguration, diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java index ff8c2a2e6f..a94c3b1dcd 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java @@ -43,7 +43,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes shortServerId, identity.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(keyPsk.toCharArray())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); this.basicTestConnection(security, null, deviceCredentials, @@ -70,7 +70,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes shortServerId, identity.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(keyPsk.toCharArray())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_ONE_OBSERVE, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_ONE_OBSERVE, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); String awaitAlias = "await on client state (Psk_Lwm2m)"; Device lwm2mDevice = this.basicTestConnection(security, null, @@ -85,7 +85,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes awaitObserveReadAll(1, lwm2mDevice.getId().getId().toString()); DeviceProfile foundDeviceProfile = doGet("/api/deviceProfile/" + lwm2mDevice.getDeviceProfileId().getId().toString(), DeviceProfile.class); - transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_MANY_OBSERVE, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_MANY_OBSERVE, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); foundDeviceProfile.getProfileData().setTransportConfiguration(transportConfiguration); DeviceProfile lwm2mDeviceProfileManyParams = doPost("/api/deviceProfile", foundDeviceProfile, DeviceProfile.class); Assert.assertNotNull(lwm2mDeviceProfileManyParams); @@ -107,7 +107,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes shortServerId, identity.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(keyPsk.toCharArray())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_ONE_OBSERVE, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_ONE_OBSERVE, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); String awaitAlias = "await on client state (Psk_Lwm2m)"; Device lwm2mDevice = this.basicTestConnection(security, null, @@ -124,7 +124,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes lwM2MTestClient.stop(true); DeviceProfile foundDeviceProfile = doGet("/api/deviceProfile/" + lwm2mDevice.getDeviceProfileId().getId().toString(), DeviceProfile.class); - transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_MANY_OBSERVE, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_MANY_OBSERVE, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); foundDeviceProfile.getProfileData().setTransportConfiguration(transportConfiguration); DeviceProfile lwm2mDeviceProfileManyParams = doPost("/api/deviceProfile", foundDeviceProfile, DeviceProfile.class); Assert.assertNotNull(lwm2mDeviceProfileManyParams); @@ -143,7 +143,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setIdentity(identity); clientCredentials.setKey(keyPsk); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); // Wait for the profile to become available. This synchronizes asynchronous processes and prevents TenantNotFoundException during tearDown. @@ -179,7 +179,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes Security securityPskBs = pskBootstrap(SECURE_URI_BS, identity.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(keyPsk.toCharArray())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, BOTH)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, BOTH)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); this.basicTestConnection(null, securityPskBs, deviceCredentials, diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java index 80ff7e59b8..7d2cff27f1 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java @@ -43,7 +43,7 @@ public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTes certificate.getPublicKey().getEncoded(), privateKey.getEncoded(), serverX509Cert.getPublicKey().getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(RPK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(RPK, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, false); this.basicTestConnection(security, null, deviceCredentials, @@ -64,7 +64,7 @@ public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTes RPKClientCredential clientCredentials = new RPKClientCredential(); clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setKey(Hex.encodeHexString(certificate.getPublicKey().getEncoded())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, false); @@ -82,7 +82,7 @@ public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTes RPKClientCredential clientCredentials = new RPKClientCredential(); clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setKey(Base64.encodeBase64String(certificate.getPublicKey().getEncoded())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, true); MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint, deviceProfile.getId()); @@ -104,7 +104,7 @@ public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTes certificate.getPublicKey().getEncoded(), privateKey.getEncoded(), serverX509CertBs.getPublicKey().getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(RPK, BOTH)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(RPK, BOTH)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, clientPrivateKeyFromCertTrust, certificate, RPK, false); this.basicTestConnection(null, securityRpkBs, deviceCredentials, diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java index fd97cab81e..450f324393 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java @@ -43,7 +43,7 @@ public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MInteg certificate.getEncoded(), privateKey.getEncoded(), serverX509Cert.getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(X509, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); this.basicTestConnection(securityX509, null, deviceCredentials, @@ -65,7 +65,7 @@ public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MInteg clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setCert(Hex.encodeHexString(certificate.getEncoded())); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint, deviceProfile.getId()); assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); @@ -82,7 +82,7 @@ public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MInteg clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setCert(Base64.getEncoder().encodeToString(certificate.getEncoded())); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, true); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint, deviceProfile.getId()); assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); @@ -103,7 +103,7 @@ public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MInteg certificate.getEncoded(), privateKey.getEncoded(), serverX509CertBs.getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, BOTH)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(X509, BOTH)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); this.basicTestConnection(security, null, deviceCredentials, diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java index 570f6647b6..73216e406d 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java @@ -35,7 +35,7 @@ public class X509_TrustLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegra certificate.getEncoded(), privateKey.getEncoded(), serverX509Cert.getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(X509, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); this.basicTestConnection(security, null, deviceCredentials, @@ -61,7 +61,7 @@ public class X509_TrustLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegra certificate.getEncoded(), privateKey.getEncoded(), serverX509CertBs.getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, BOTH)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(X509, BOTH)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); this.basicTestConnection(security,null, deviceCredentials, diff --git a/application/src/test/resources/community-grant/01-valid.tbicb b/application/src/test/resources/community-grant/01-valid.tbicb new file mode 100644 index 0000000000..dc454a0e47 Binary files /dev/null and b/application/src/test/resources/community-grant/01-valid.tbicb differ diff --git a/application/src/test/resources/community-grant/02-too-short.tbicb b/application/src/test/resources/community-grant/02-too-short.tbicb new file mode 100644 index 0000000000..38922346a2 Binary files /dev/null and b/application/src/test/resources/community-grant/02-too-short.tbicb differ diff --git a/application/src/test/resources/community-grant/03-bad-magic.tbicb b/application/src/test/resources/community-grant/03-bad-magic.tbicb new file mode 100644 index 0000000000..dca067eed8 Binary files /dev/null and b/application/src/test/resources/community-grant/03-bad-magic.tbicb differ diff --git a/application/src/test/resources/community-grant/04-unknown-version.tbicb b/application/src/test/resources/community-grant/04-unknown-version.tbicb new file mode 100644 index 0000000000..dd8b5d6716 Binary files /dev/null and b/application/src/test/resources/community-grant/04-unknown-version.tbicb differ diff --git a/application/src/test/resources/community-grant/05-manifest-len-zero.tbicb b/application/src/test/resources/community-grant/05-manifest-len-zero.tbicb new file mode 100644 index 0000000000..21ea898826 Binary files /dev/null and b/application/src/test/resources/community-grant/05-manifest-len-zero.tbicb differ diff --git a/application/src/test/resources/community-grant/06-manifest-len-too-large.tbicb b/application/src/test/resources/community-grant/06-manifest-len-too-large.tbicb new file mode 100644 index 0000000000..6eb42e2947 Binary files /dev/null and b/application/src/test/resources/community-grant/06-manifest-len-too-large.tbicb differ diff --git a/application/src/test/resources/community-grant/07-checker-len-zero.tbicb b/application/src/test/resources/community-grant/07-checker-len-zero.tbicb new file mode 100644 index 0000000000..9a520a592f Binary files /dev/null and b/application/src/test/resources/community-grant/07-checker-len-zero.tbicb differ diff --git a/application/src/test/resources/community-grant/08-truncated-mid-manifest.tbicb b/application/src/test/resources/community-grant/08-truncated-mid-manifest.tbicb new file mode 100644 index 0000000000..086edd1a1e Binary files /dev/null and b/application/src/test/resources/community-grant/08-truncated-mid-manifest.tbicb differ diff --git a/application/src/test/resources/community-grant/09-truncated-mid-checker.tbicb b/application/src/test/resources/community-grant/09-truncated-mid-checker.tbicb new file mode 100644 index 0000000000..d7479bc64d Binary files /dev/null and b/application/src/test/resources/community-grant/09-truncated-mid-checker.tbicb differ diff --git a/application/src/test/resources/community-grant/10-trailing-byte.tbicb b/application/src/test/resources/community-grant/10-trailing-byte.tbicb new file mode 100644 index 0000000000..ac01341853 Binary files /dev/null and b/application/src/test/resources/community-grant/10-trailing-byte.tbicb differ diff --git a/application/src/test/resources/community-grant/11-manifest-not-utf8.tbicb b/application/src/test/resources/community-grant/11-manifest-not-utf8.tbicb new file mode 100644 index 0000000000..6599580147 Binary files /dev/null and b/application/src/test/resources/community-grant/11-manifest-not-utf8.tbicb differ diff --git a/application/src/test/resources/community-grant/12-manifest-not-json.tbicb b/application/src/test/resources/community-grant/12-manifest-not-json.tbicb new file mode 100644 index 0000000000..74ce524da8 Binary files /dev/null and b/application/src/test/resources/community-grant/12-manifest-not-json.tbicb differ diff --git a/application/src/test/resources/community-grant/13-manifest-missing-field.tbicb b/application/src/test/resources/community-grant/13-manifest-missing-field.tbicb new file mode 100644 index 0000000000..7e124c51a3 Binary files /dev/null and b/application/src/test/resources/community-grant/13-manifest-missing-field.tbicb differ diff --git a/application/src/test/resources/community-grant/14-expired-challenge.tbicb b/application/src/test/resources/community-grant/14-expired-challenge.tbicb new file mode 100644 index 0000000000..c1865ef41e Binary files /dev/null and b/application/src/test/resources/community-grant/14-expired-challenge.tbicb differ diff --git a/application/src/test/resources/community-grant/15-relsig-not-tbicsig1.tbicb b/application/src/test/resources/community-grant/15-relsig-not-tbicsig1.tbicb new file mode 100644 index 0000000000..f5157bf012 Binary files /dev/null and b/application/src/test/resources/community-grant/15-relsig-not-tbicsig1.tbicb differ diff --git a/application/src/test/resources/community-grant/vectors.json b/application/src/test/resources/community-grant/vectors.json new file mode 100644 index 0000000000..83d20712a3 --- /dev/null +++ b/application/src/test/resources/community-grant/vectors.json @@ -0,0 +1,142 @@ +{ + "format": "TBICBDL1", + "formatVersion": 1, + "fixtureMaterial": { + "releaseSigningPublicKeyBase64": "Nqbrd0SVV4w9yZWl0cgu9I7G/URhdL3PN8mWRwnWDzE=", + "releaseSigningKeyId": 1, + "communityGrantCheckerReleasePublicKeysProperty": "1:Nqbrd0SVV4w9yZWl0cgu9I7G/URhdL3PN8mWRwnWDzE=", + "checkerStandInRule": "64 bytes; checker[i] = (i * 7 + 3) mod 256", + "checkerStandInSha256": "39e3d7b6b5d075d37d053ad89b24b41bef4f3c29760c84447cab3f3be1882241", + "checkerStandInHex": "030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bc", + "portalPublicKeyRule": "32 bytes; key[i] = (i * 7 + 0x29) mod 256", + "portalPublicKeyBase64": "KTA3PkVMU1phaG92fYSLkpmgp661vMPK0djf5u30+wI=", + "clusterId": "3f2a1c44-9f3b-11ee-8c90-0242ac120002", + "challenge": "Y2hhbGxlbmdlLTAwMS1ieXRlcw==", + "referenceMillis": 1787788800000, + "validManifestBytes": 420, + "validManifestJson": "{\"bundleVersion\":1,\"os\":\"linux\",\"arch\":\"amd64\",\"clusterId\":\"3f2a1c44-9f3b-11ee-8c90-0242ac120002\",\"checkerInput\":{\"clusterId\":\"3f2a1c44-9f3b-11ee-8c90-0242ac120002\",\"keyId\":1,\"publicKey\":\"KTA3PkVMU1phaG92fYSLkpmgp661vMPK0djf5u30+wI=\",\"challenge\":\"Y2hhbGxlbmdlLTAwMS1ieXRlcw==\",\"referenceMillis\":1787788800000},\"challengeExpiresAt\":4102531200000,\"issuedAt\":4102444800000,\"checkerFileName\":\"tb-instance-check_linux_amd64\"}", + "validRelsigHex": "544249435349473101013ab2afc43727f37b9388510b6c0e0b7d920a738eedf45aae5169aa7d97abe3f73796b907168188e0685566bbf792ae0977b6c38072e684ee149d6bcf161fc004" + }, + "fixtures": [ + { + "file": "01-valid.tbicb", + "sizeBytes": 575, + "sha256": "3e747e7bef600c7a7026558592ac91593922f74c360b0a1746ea3f22e7405dad", + "expectedOutcome": "ACCEPT", + "expectedReason": null, + "note": "The reference bundle; the release signature verifies over the 64-byte checker and the challenge expires in 2100." + }, + { + "file": "02-too-short.tbicb", + "sizeBytes": 90, + "sha256": "38d08ef0ee6f0013b1702ed46f7e6452124f73ae5f19c038b301f17a55e5ba9a", + "expectedOutcome": "REJECT", + "expectedReason": "E_TOO_SHORT", + "note": "90 bytes, one short of the fixed header, although the magic present is correct." + }, + { + "file": "03-bad-magic.tbicb", + "sizeBytes": 575, + "sha256": "464d3034a07911c75062ba54e2bc1e5cc2da04e146d4c5671bd012a1419809b9", + "expectedOutcome": "REJECT", + "expectedReason": "E_BAD_MAGIC", + "note": "Byte 0 changed from 'T' to 'X'; everything else is valid." + }, + { + "file": "04-unknown-version.tbicb", + "sizeBytes": 575, + "sha256": "57f64567e6a50273e3ae26f2e5f32a964f95b7c0d8e878a062654636760c9ad4", + "expectedOutcome": "REJECT", + "expectedReason": "E_UNSUPPORTED_VERSION", + "note": "VERSION = 0x02; the reason names both the declared and the supported version." + }, + { + "file": "05-manifest-len-zero.tbicb", + "sizeBytes": 575, + "sha256": "6bfe256e9d96c801ae56c76c3ed56df50e099551a1ff383792e7312697de1412", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_LEN_RANGE", + "note": "MANIFEST_LEN = 0 with the body intact, so the length range check fires before the total length check." + }, + { + "file": "06-manifest-len-too-large.tbicb", + "sizeBytes": 575, + "sha256": "be383e132528933d6a7468e02fb920621dd33502696631678056f028e0ba4de3", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_LEN_RANGE", + "note": "MANIFEST_LEN = 8193, one past the ceiling, with the body intact." + }, + { + "file": "07-checker-len-zero.tbicb", + "sizeBytes": 575, + "sha256": "e998d83843ecd4c2c14deb240cc2dbf037ff466a7537c1a0e9a27049cfc62051", + "expectedOutcome": "REJECT", + "expectedReason": "E_CHECKER_LEN_RANGE", + "note": "CHECKER_LEN = 0 with the body intact, so the range check fires before the total length check." + }, + { + "file": "08-truncated-mid-manifest.tbicb", + "sizeBytes": 301, + "sha256": "68c0c107ebdcb7c2299638a6a218e8bccb5a2adf641c5ad6659e68138e878087", + "expectedOutcome": "REJECT", + "expectedReason": "E_LENGTH_MISMATCH", + "note": "Truncated inside the manifest; both declared lengths describe the missing bytes." + }, + { + "file": "09-truncated-mid-checker.tbicb", + "sizeBytes": 543, + "sha256": "8ef37a7f629b547db387326f27248df6b2dae4d3eef09c87ef0746e1d479e362", + "expectedOutcome": "REJECT", + "expectedReason": "E_LENGTH_MISMATCH", + "note": "Truncated inside the checker; the manifest is complete and parseable." + }, + { + "file": "10-trailing-byte.tbicb", + "sizeBytes": 576, + "sha256": "a0c5440286f7e1949333036f4329956b0771ff411ea77150bb1b3f9ca9012600", + "expectedOutcome": "REJECT", + "expectedReason": "E_LENGTH_MISMATCH", + "note": "One 0x00 appended after the checker." + }, + { + "file": "11-manifest-not-utf8.tbicb", + "sizeBytes": 575, + "sha256": "d333b7dfdb4f5434944aaa56c70eb54ec6af84c68ce6a4ec329f6290f48a863b", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_NOT_UTF8", + "note": "The manifest region is 0xFF repeated, which is not valid UTF-8 at any offset." + }, + { + "file": "12-manifest-not-json.tbicb", + "sizeBytes": 575, + "sha256": "b18a78cb214fe5c6bd2c37ecdb7c662b525ae09c33ff7ac2fc900f41b574d7a3", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_NOT_JSON", + "note": "Valid UTF-8 of the right length that is not a JSON object." + }, + { + "file": "13-manifest-missing-field.tbicb", + "sizeBytes": 524, + "sha256": "fc4078744b432e9aae55617709237b6b5c3914bf42c6233185cdc5ee1d4e4c06", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_FIELD", + "note": "clusterId removed with every declared length recomputed; the reason names the missing field." + }, + { + "file": "14-expired-challenge.tbicb", + "sizeBytes": 575, + "sha256": "0389de376b9043f38cf383ef0a1282ce44d1dfb35d227ce1a0dc719758078289", + "expectedOutcome": "ACCEPT_WITH_WARNING", + "expectedReason": "W_CHALLENGE_EXPIRED", + "note": "A well-formed bundle whose challenge expired on 2021-01-02; expiry is a warning, not a rejection." + }, + { + "file": "15-relsig-not-tbicsig1.tbicb", + "sizeBytes": 575, + "sha256": "626c7a570eade192fc048cadf134d738fd1b853d42a33ad4ef8dd1624aa36dff", + "expectedOutcome": "ACCEPT", + "expectedReason": null, + "note": "RELSIG's magic is corrupted; the parser passes RELSIG through unchecked and the release-signature verifier refuses it." + } + ] +} diff --git a/application/src/test/resources/install/pre-upgrade-schema-entities.sql b/application/src/test/resources/install/pre-upgrade-schema-entities.sql new file mode 100644 index 0000000000..7784bd87c4 --- /dev/null +++ b/application/src/test/resources/install/pre-upgrade-schema-entities.sql @@ -0,0 +1,997 @@ +-- +-- Copyright © 2016-2026 The Thingsboard Authors +-- +-- Licensed under the Apache License, Version 2.0 (the "License"); +-- you may not use this file except in compliance with the License. +-- You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. +-- + +-- schema-entities.sql as it was before tb_cluster was added. Never update it: SchemaUpdateSqlUpgradeOrderTest +-- relies on tb_cluster being absent. + + +CREATE TABLE IF NOT EXISTS tb_schema_settings +( + schema_version bigint NOT NULL, + product varchar(2) NOT NULL, + CONSTRAINT tb_schema_settings_pkey PRIMARY KEY (schema_version) +); + +CREATE TABLE IF NOT EXISTS admin_settings ( + id uuid NOT NULL CONSTRAINT admin_settings_pkey PRIMARY KEY, + tenant_id uuid NOT NULL, + created_time bigint NOT NULL, + json_value varchar, + key varchar(255) +); + +CREATE TABLE IF NOT EXISTS alarm ( + id uuid NOT NULL CONSTRAINT alarm_pkey PRIMARY KEY, + created_time bigint NOT NULL, + ack_ts bigint, + clear_ts bigint, + additional_info varchar, + end_ts bigint, + originator_id uuid, + originator_type integer, + propagate boolean, + severity varchar(255), + start_ts bigint, + assign_ts bigint DEFAULT 0, + assignee_id uuid, + tenant_id uuid, + customer_id uuid, + propagate_relation_types varchar, + type varchar(255), + propagate_to_owner boolean, + propagate_to_tenant boolean, + acknowledged boolean, + cleared boolean +); + +CREATE TABLE IF NOT EXISTS alarm_comment ( + id uuid NOT NULL, + created_time bigint NOT NULL, + alarm_id uuid NOT NULL, + user_id uuid, + type varchar(255) NOT NULL, + comment varchar(10000), + CONSTRAINT fk_alarm_comment_alarm_id FOREIGN KEY (alarm_id) REFERENCES alarm(id) ON DELETE CASCADE +) PARTITION BY RANGE (created_time); + +CREATE TABLE IF NOT EXISTS entity_alarm ( + tenant_id uuid NOT NULL, + entity_type varchar(32), + entity_id uuid NOT NULL, + created_time bigint NOT NULL, + alarm_type varchar(255) NOT NULL, + customer_id uuid, + alarm_id uuid, + CONSTRAINT entity_alarm_pkey PRIMARY KEY (entity_id, alarm_id), + CONSTRAINT fk_entity_alarm_id FOREIGN KEY (alarm_id) REFERENCES alarm(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS audit_log ( + id uuid NOT NULL, + created_time bigint NOT NULL, + tenant_id uuid, + customer_id uuid, + entity_id uuid, + entity_type varchar(255), + entity_name varchar(255), + user_id uuid, + user_name varchar(255), + action_type varchar(255), + action_data varchar(1000000), + action_status varchar(255), + action_failure_details varchar(1000000) +) PARTITION BY RANGE (created_time); + +CREATE SEQUENCE IF NOT EXISTS attribute_kv_version_seq cache 1; + +CREATE TABLE IF NOT EXISTS attribute_kv ( + entity_id uuid, + attribute_type int, + attribute_key int, + bool_v boolean, + str_v varchar(10000000), + long_v bigint, + dbl_v double precision, + json_v json, + last_update_ts bigint, + version bigint default 0, + CONSTRAINT attribute_kv_pkey PRIMARY KEY (entity_id, attribute_type, attribute_key) +); + +CREATE TABLE IF NOT EXISTS component_descriptor ( + id uuid NOT NULL CONSTRAINT component_descriptor_pkey PRIMARY KEY, + created_time bigint NOT NULL, + actions varchar(255), + clazz varchar UNIQUE, + configuration_descriptor varchar, + configuration_version int DEFAULT 0, + name varchar(255), + scope varchar(255), + type varchar(255), + clustering_mode varchar(255), + has_queue_name boolean DEFAULT false +); + +CREATE TABLE IF NOT EXISTS customer ( + id uuid NOT NULL CONSTRAINT customer_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + address varchar, + address2 varchar, + city varchar(255), + country varchar(255), + email varchar(255), + phone varchar(255), + state varchar(255), + tenant_id uuid, + title varchar(255), + zip varchar(255), + external_id uuid, + is_public boolean, + version BIGINT DEFAULT 1, + CONSTRAINT customer_title_unq_key UNIQUE (tenant_id, title), + CONSTRAINT customer_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS dashboard ( + id uuid NOT NULL CONSTRAINT dashboard_pkey PRIMARY KEY, + created_time bigint NOT NULL, + configuration varchar, + assigned_customers varchar(1000000), + tenant_id uuid, + title varchar(255), + mobile_hide boolean DEFAULT false, + mobile_order int, + image varchar(1000000), + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT dashboard_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS rule_chain ( + id uuid NOT NULL CONSTRAINT rule_chain_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + configuration varchar(10000000), + name varchar(255), + type varchar(255), + first_rule_node_id uuid, + root boolean, + debug_mode boolean, + tenant_id uuid, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT rule_chain_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS rule_node ( + id uuid NOT NULL CONSTRAINT rule_node_pkey PRIMARY KEY, + created_time bigint NOT NULL, + rule_chain_id uuid, + additional_info varchar, + configuration_version int DEFAULT 0, + configuration varchar(10000000), + type varchar(255), + name varchar(255), + debug_settings varchar(1024), + singleton_mode boolean, + queue_name varchar(255), + external_id uuid +); + +CREATE TABLE IF NOT EXISTS rule_node_state ( + id uuid NOT NULL CONSTRAINT rule_node_state_pkey PRIMARY KEY, + created_time bigint NOT NULL, + rule_node_id uuid NOT NULL, + entity_type varchar(32) NOT NULL, + entity_id uuid NOT NULL, + state_data varchar(16384) NOT NULL, + CONSTRAINT rule_node_state_unq_key UNIQUE (rule_node_id, entity_id), + CONSTRAINT fk_rule_node_state_node_id FOREIGN KEY (rule_node_id) REFERENCES rule_node(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS ota_package ( + id uuid NOT NULL CONSTRAINT ota_package_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + device_profile_id uuid , + type varchar(32) NOT NULL, + title varchar(255) NOT NULL, + version varchar(255) NOT NULL, + tag varchar(255), + url varchar(255), + file_name varchar(255), + content_type varchar(255), + checksum_algorithm varchar(32), + checksum varchar(1020), + data oid, + data_size bigint, + additional_info varchar, + external_id uuid, + CONSTRAINT ota_package_tenant_title_version_unq_key UNIQUE (tenant_id, title, version), + CONSTRAINT ota_package_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS queue ( + id uuid NOT NULL CONSTRAINT queue_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + name varchar(255), + topic varchar(255), + poll_interval int, + partitions int, + consumer_per_partition boolean, + pack_processing_timeout bigint, + submit_strategy varchar(255), + processing_strategy varchar(255), + additional_info varchar +); + +CREATE TABLE IF NOT EXISTS asset_profile ( + id uuid NOT NULL CONSTRAINT asset_profile_pkey PRIMARY KEY, + created_time bigint NOT NULL, + name varchar(255), + image varchar(1000000), + description varchar, + is_default boolean, + tenant_id uuid, + default_rule_chain_id uuid, + default_dashboard_id uuid, + default_queue_name varchar(255), + default_edge_rule_chain_id uuid, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT asset_profile_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT asset_profile_external_id_unq_key UNIQUE (tenant_id, external_id), + CONSTRAINT fk_default_rule_chain_asset_profile FOREIGN KEY (default_rule_chain_id) REFERENCES rule_chain(id), + CONSTRAINT fk_default_dashboard_asset_profile FOREIGN KEY (default_dashboard_id) REFERENCES dashboard(id), + CONSTRAINT fk_default_edge_rule_chain_asset_profile FOREIGN KEY (default_edge_rule_chain_id) REFERENCES rule_chain(id) + ); + +CREATE TABLE IF NOT EXISTS asset ( + id uuid NOT NULL CONSTRAINT asset_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + customer_id uuid, + asset_profile_id uuid NOT NULL, + name varchar(255), + label varchar(255), + tenant_id uuid, + type varchar(255), + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT asset_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT asset_external_id_unq_key UNIQUE (tenant_id, external_id), + CONSTRAINT fk_asset_profile FOREIGN KEY (asset_profile_id) REFERENCES asset_profile(id) +); + +CREATE TABLE IF NOT EXISTS device_profile ( + id uuid NOT NULL CONSTRAINT device_profile_pkey PRIMARY KEY, + created_time bigint NOT NULL, + name varchar(255), + type varchar(255), + image varchar(1000000), + transport_type varchar(255), + provision_type varchar(255), + profile_data jsonb, + description varchar, + is_default boolean, + tenant_id uuid, + firmware_id uuid, + software_id uuid, + default_rule_chain_id uuid, + default_dashboard_id uuid, + default_queue_name varchar(255), + provision_device_key varchar, + default_edge_rule_chain_id uuid, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT device_profile_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT device_provision_key_unq_key UNIQUE (provision_device_key), + CONSTRAINT device_profile_external_id_unq_key UNIQUE (tenant_id, external_id), + CONSTRAINT fk_default_rule_chain_device_profile FOREIGN KEY (default_rule_chain_id) REFERENCES rule_chain(id), + CONSTRAINT fk_default_dashboard_device_profile FOREIGN KEY (default_dashboard_id) REFERENCES dashboard(id), + CONSTRAINT fk_firmware_device_profile FOREIGN KEY (firmware_id) REFERENCES ota_package(id), + CONSTRAINT fk_software_device_profile FOREIGN KEY (software_id) REFERENCES ota_package(id), + CONSTRAINT fk_default_edge_rule_chain_device_profile FOREIGN KEY (default_edge_rule_chain_id) REFERENCES rule_chain(id) +); + +DO +$$ + BEGIN + IF NOT EXISTS(SELECT 1 FROM pg_constraint WHERE conname = 'fk_device_profile_ota_package') THEN + ALTER TABLE ota_package + ADD CONSTRAINT fk_device_profile_ota_package + FOREIGN KEY (device_profile_id) REFERENCES device_profile (id) + ON DELETE CASCADE; + END IF; + END; +$$; + +-- We will use one-to-many relation in the first release and extend this feature in case of user requests +-- CREATE TABLE IF NOT EXISTS device_profile_firmware ( +-- device_profile_id uuid NOT NULL, +-- firmware_id uuid NOT NULL, +-- CONSTRAINT device_profile_firmware_unq_key UNIQUE (device_profile_id, firmware_id), +-- CONSTRAINT fk_device_profile_firmware_device_profile FOREIGN KEY (device_profile_id) REFERENCES device_profile(id) ON DELETE CASCADE, +-- CONSTRAINT fk_device_profile_firmware_firmware FOREIGN KEY (firmware_id) REFERENCES firmware(id) ON DELETE CASCADE, +-- ); + +CREATE TABLE IF NOT EXISTS device ( + id uuid NOT NULL CONSTRAINT device_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + customer_id uuid, + device_profile_id uuid NOT NULL, + device_data jsonb, + type varchar(255), + name varchar(255), + label varchar(255), + tenant_id uuid, + firmware_id uuid, + software_id uuid, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT device_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT device_external_id_unq_key UNIQUE (tenant_id, external_id), + CONSTRAINT fk_device_profile FOREIGN KEY (device_profile_id) REFERENCES device_profile(id), + CONSTRAINT fk_firmware_device FOREIGN KEY (firmware_id) REFERENCES ota_package(id), + CONSTRAINT fk_software_device FOREIGN KEY (software_id) REFERENCES ota_package(id) +); + +CREATE TABLE IF NOT EXISTS device_credentials ( + id uuid NOT NULL CONSTRAINT device_credentials_pkey PRIMARY KEY, + created_time bigint NOT NULL, + credentials_id varchar, + credentials_type varchar(255), + credentials_value varchar, + device_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT device_credentials_id_unq_key UNIQUE (credentials_id), + CONSTRAINT device_credentials_device_id_unq_key UNIQUE (device_id) +); + +CREATE TABLE IF NOT EXISTS rule_node_debug_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL , + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar, + e_type varchar, + e_entity_id uuid, + e_entity_type varchar, + e_msg_id uuid, + e_msg_type varchar, + e_data_type varchar, + e_relation_type varchar, + e_data varchar, + e_metadata varchar, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS rule_chain_debug_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL, + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar NOT NULL, + e_message varchar, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS stats_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL, + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar NOT NULL, + e_messages_processed bigint NOT NULL, + e_errors_occurred bigint NOT NULL +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS lc_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL, + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar NOT NULL, + e_type varchar NOT NULL, + e_success boolean NOT NULL, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS error_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL, + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar NOT NULL, + e_method varchar NOT NULL, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE SEQUENCE IF NOT EXISTS relation_version_seq cache 1; + +CREATE TABLE IF NOT EXISTS relation ( + from_id uuid, + from_type varchar(255), + to_id uuid, + to_type varchar(255), + relation_type_group varchar(255), + relation_type varchar(255), + additional_info varchar, + version bigint default 0, + CONSTRAINT relation_pkey PRIMARY KEY (from_id, from_type, relation_type_group, relation_type, to_id, to_type) +); + +CREATE TABLE IF NOT EXISTS tb_user ( + id uuid NOT NULL CONSTRAINT tb_user_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + authority varchar(255), + customer_id uuid, + email varchar(255) UNIQUE, + first_name varchar(255), + last_name varchar(255), + phone varchar(255), + tenant_id uuid, + version BIGINT DEFAULT 1 +); + +CREATE TABLE IF NOT EXISTS tenant_profile ( + id uuid NOT NULL CONSTRAINT tenant_profile_pkey PRIMARY KEY, + created_time bigint NOT NULL, + name varchar(255), + profile_data jsonb, + description varchar, + is_default boolean, + isolated_tb_core boolean, + isolated_tb_rule_engine boolean, + CONSTRAINT tenant_profile_name_unq_key UNIQUE (name) +); + +CREATE TABLE IF NOT EXISTS tenant ( + id uuid NOT NULL CONSTRAINT tenant_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + tenant_profile_id uuid NOT NULL, + address varchar, + address2 varchar, + city varchar(255), + country varchar(255), + email varchar(255), + phone varchar(255), + region varchar(255), + state varchar(255), + title varchar(255), + zip varchar(255), + version BIGINT DEFAULT 1, + CONSTRAINT fk_tenant_profile FOREIGN KEY (tenant_profile_id) REFERENCES tenant_profile(id) +); + +CREATE TABLE IF NOT EXISTS user_credentials ( + id uuid NOT NULL CONSTRAINT user_credentials_pkey PRIMARY KEY, + created_time bigint NOT NULL, + activate_token varchar(255) UNIQUE, + activate_token_exp_time BIGINT, + enabled boolean, + password varchar(255), + reset_token varchar(255) UNIQUE, + reset_token_exp_time BIGINT, + user_id uuid UNIQUE, + additional_info varchar DEFAULT '{}', + last_login_ts BIGINT, + failed_login_attempts INT +); + +CREATE TABLE IF NOT EXISTS widget_type ( + id uuid NOT NULL CONSTRAINT widget_type_pkey PRIMARY KEY, + created_time bigint NOT NULL, + fqn varchar(512), + descriptor varchar(1000000), + name varchar(255), + tenant_id uuid, + image varchar(1000000), + scada boolean NOT NULL DEFAULT false, + deprecated boolean NOT NULL DEFAULT false, + description varchar(1024), + tags text[], + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT uq_widget_type_fqn UNIQUE (tenant_id, fqn), + CONSTRAINT widget_type_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS widgets_bundle ( + id uuid NOT NULL CONSTRAINT widgets_bundle_pkey PRIMARY KEY, + created_time bigint NOT NULL, + alias varchar(255), + tenant_id uuid, + title varchar(255), + image varchar(1000000), + scada boolean NOT NULL DEFAULT false, + description varchar(1024), + widgets_bundle_order int, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT uq_widgets_bundle_alias UNIQUE (tenant_id, alias), + CONSTRAINT widgets_bundle_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS widgets_bundle_widget ( + widgets_bundle_id uuid NOT NULL, + widget_type_id uuid NOT NULL, + widget_type_order int NOT NULL DEFAULT 0, + CONSTRAINT widgets_bundle_widget_pkey PRIMARY KEY (widgets_bundle_id, widget_type_id), + CONSTRAINT fk_widgets_bundle FOREIGN KEY (widgets_bundle_id) REFERENCES widgets_bundle(id) ON DELETE CASCADE, + CONSTRAINT fk_widget_type FOREIGN KEY (widget_type_id) REFERENCES widget_type(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS entity_view ( + id uuid NOT NULL CONSTRAINT entity_view_pkey PRIMARY KEY, + created_time bigint NOT NULL, + entity_id uuid, + entity_type varchar(255), + tenant_id uuid, + customer_id uuid, + type varchar(255), + name varchar(255), + keys varchar(10000000), + start_ts bigint, + end_ts bigint, + additional_info varchar, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT entity_view_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE SEQUENCE IF NOT EXISTS ts_kv_latest_version_seq cache 1; + +CREATE TABLE IF NOT EXISTS ts_kv_latest +( + entity_id uuid NOT NULL, + key int NOT NULL, + ts bigint NOT NULL, + bool_v boolean, + str_v varchar(10000000), + long_v bigint, + dbl_v double precision, + json_v json, + version bigint default 0, + CONSTRAINT ts_kv_latest_pkey PRIMARY KEY (entity_id, key) +); + +CREATE TABLE IF NOT EXISTS key_dictionary +( + key varchar(255) NOT NULL, + key_id serial UNIQUE, + CONSTRAINT key_dictionary_id_pkey PRIMARY KEY (key) +); + +CREATE TABLE IF NOT EXISTS oauth2_client ( + id uuid NOT NULL CONSTRAINT oauth2_client_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + title varchar(100) NOT NULL, + additional_info varchar, + client_id varchar(255), + client_secret varchar(2048), + authorization_uri varchar(255), + token_uri varchar(255), + scope varchar(255), + platforms varchar(255), + user_info_uri varchar(255), + user_name_attribute_name varchar(255), + jwk_set_uri varchar(255), + client_authentication_method varchar(255), + login_button_label varchar(255), + login_button_icon varchar(255), + allow_user_creation boolean, + activate_user boolean, + type varchar(31), + basic_email_attribute_key varchar(31), + basic_first_name_attribute_key varchar(31), + basic_last_name_attribute_key varchar(31), + basic_tenant_name_strategy varchar(31), + basic_tenant_name_pattern varchar(255), + basic_customer_name_pattern varchar(255), + basic_default_dashboard_name varchar(255), + basic_always_full_screen boolean, + custom_url varchar(255), + custom_username varchar(255), + custom_password varchar(255), + custom_send_token boolean +); + +CREATE TABLE IF NOT EXISTS domain ( + id uuid NOT NULL CONSTRAINT domain_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + name varchar(255) UNIQUE, + oauth2_enabled boolean, + edge_enabled boolean +); + +CREATE TABLE IF NOT EXISTS mobile_app ( + id uuid NOT NULL CONSTRAINT mobile_app_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + pkg_name varchar(255), + title varchar(255), + app_secret varchar(2048), + platform_type varchar(32), + status varchar(32), + version_info varchar(100000), + store_info varchar(16384), + CONSTRAINT mobile_app_pkg_name_platform_unq_key UNIQUE (pkg_name, platform_type) +); + +CREATE TABLE IF NOT EXISTS mobile_app_bundle ( + id uuid NOT NULL CONSTRAINT mobile_app_bundle_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + title varchar(255), + description varchar(1024), + android_app_id uuid UNIQUE, + ios_app_id uuid UNIQUE, + layout_config varchar(16384), + oauth2_enabled boolean, + CONSTRAINT fk_android_app_id FOREIGN KEY (android_app_id) REFERENCES mobile_app(id) ON DELETE SET NULL, + CONSTRAINT fk_ios_app_id FOREIGN KEY (ios_app_id) REFERENCES mobile_app(id) ON DELETE SET NULL +); + +CREATE TABLE IF NOT EXISTS domain_oauth2_client ( + domain_id uuid NOT NULL, + oauth2_client_id uuid NOT NULL, + CONSTRAINT fk_domain FOREIGN KEY (domain_id) REFERENCES domain(id) ON DELETE CASCADE, + CONSTRAINT fk_oauth2_client FOREIGN KEY (oauth2_client_id) REFERENCES oauth2_client(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS mobile_app_bundle_oauth2_client ( + mobile_app_bundle_id uuid NOT NULL, + oauth2_client_id uuid NOT NULL, + CONSTRAINT fk_domain FOREIGN KEY (mobile_app_bundle_id) REFERENCES mobile_app_bundle(id) ON DELETE CASCADE, + CONSTRAINT fk_oauth2_client FOREIGN KEY (oauth2_client_id) REFERENCES oauth2_client(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS oauth2_client_registration_template ( + id uuid NOT NULL CONSTRAINT oauth2_client_registration_template_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + provider_id varchar(255), + authorization_uri varchar(255), + token_uri varchar(255), + scope varchar(255), + user_info_uri varchar(255), + user_name_attribute_name varchar(255), + jwk_set_uri varchar(255), + client_authentication_method varchar(255), + type varchar(31), + basic_email_attribute_key varchar(31), + basic_first_name_attribute_key varchar(31), + basic_last_name_attribute_key varchar(31), + basic_tenant_name_strategy varchar(31), + basic_tenant_name_pattern varchar(255), + basic_customer_name_pattern varchar(255), + basic_default_dashboard_name varchar(255), + basic_always_full_screen boolean, + comment varchar, + login_button_icon varchar(255), + login_button_label varchar(255), + help_link varchar(255), + CONSTRAINT oauth2_template_provider_id_unq_key UNIQUE (provider_id) +); + +CREATE TABLE IF NOT EXISTS api_usage_state ( + id uuid NOT NULL CONSTRAINT usage_record_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + entity_type varchar(32), + entity_id uuid, + transport varchar(32), + db_storage varchar(32), + re_exec varchar(32), + js_exec varchar(32), + tbel_exec varchar(32), + email_exec varchar(32), + sms_exec varchar(32), + alarm_exec varchar(32), + version BIGINT DEFAULT 1, + CONSTRAINT api_usage_state_unq_key UNIQUE (tenant_id, entity_id) +); + +CREATE TABLE IF NOT EXISTS api_key ( + id uuid NOT NULL CONSTRAINT api_key_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + user_id uuid, + value varchar(512), + enabled boolean NOT NULL DEFAULT TRUE, + expiration_time bigint DEFAULT 0, + description varchar(255), + CONSTRAINT api_key_value_unq_key UNIQUE (value) +); + +CREATE TABLE IF NOT EXISTS resource ( + id uuid NOT NULL CONSTRAINT resource_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + title varchar(255) NOT NULL, + resource_type varchar(32) NOT NULL, + resource_sub_type varchar(32), + resource_key varchar(255) NOT NULL, + search_text varchar(255), + file_name varchar(255) NOT NULL, + data bytea, + etag varchar, + descriptor varchar, + preview bytea, + is_public boolean default true, + public_resource_key varchar(32) unique, + external_id uuid, + CONSTRAINT resource_unq_key UNIQUE (tenant_id, resource_type, resource_key) +); + +CREATE TABLE IF NOT EXISTS edge ( + id uuid NOT NULL CONSTRAINT edge_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + customer_id uuid, + root_rule_chain_id uuid, + type varchar(255), + name varchar(255), + label varchar(255), + routing_key varchar(255), + secret varchar(255), + tenant_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT edge_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT edge_routing_key_unq_key UNIQUE (routing_key) +); + +CREATE TABLE IF NOT EXISTS edge_event ( + seq_id INT GENERATED ALWAYS AS IDENTITY, + id uuid NOT NULL, + created_time bigint NOT NULL, + edge_id uuid, + edge_event_type varchar(255), + edge_event_uid varchar(255), + entity_id uuid, + edge_event_action varchar(255), + body varchar(10000000), + tenant_id uuid, + ts bigint NOT NULL +) PARTITION BY RANGE(created_time); +ALTER TABLE IF EXISTS edge_event ALTER COLUMN seq_id SET CYCLE; + +CREATE TABLE IF NOT EXISTS rpc ( + id uuid NOT NULL CONSTRAINT rpc_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + device_id uuid NOT NULL, + expiration_time bigint NOT NULL, + request varchar(10000000) NOT NULL, + response varchar(10000000), + additional_info varchar(10000000), + status varchar(255) NOT NULL +); + +CREATE OR REPLACE FUNCTION to_uuid(IN entity_id varchar, OUT uuid_id uuid) AS +$$ +BEGIN + uuid_id := substring(entity_id, 8, 8) || '-' || substring(entity_id, 4, 4) || '-1' || substring(entity_id, 1, 3) || + '-' || substring(entity_id, 16, 4) || '-' || substring(entity_id, 20, 12); +END; +$$ LANGUAGE plpgsql; + + +CREATE OR REPLACE PROCEDURE cleanup_edge_events_by_ttl(IN ttl bigint, INOUT deleted bigint) + LANGUAGE plpgsql AS +$$ +DECLARE + ttl_ts bigint; + ttl_deleted_count bigint DEFAULT 0; +BEGIN + IF ttl > 0 THEN + ttl_ts := (EXTRACT(EPOCH FROM current_timestamp) * 1000 - ttl::bigint * 1000)::bigint; + EXECUTE format( + 'WITH deleted AS (DELETE FROM edge_event WHERE ts < %L::bigint RETURNING *) SELECT count(*) FROM deleted', ttl_ts) into ttl_deleted_count; + END IF; + RAISE NOTICE 'Edge events removed by ttl: %', ttl_deleted_count; + deleted := ttl_deleted_count; +END +$$; + + +CREATE TABLE IF NOT EXISTS user_auth_settings ( + id uuid NOT NULL CONSTRAINT user_auth_settings_pkey PRIMARY KEY, + created_time bigint NOT NULL, + user_id uuid UNIQUE NOT NULL CONSTRAINT fk_user_auth_settings_user_id REFERENCES tb_user(id), + two_fa_settings varchar +); + +CREATE TABLE IF NOT EXISTS notification_target ( + id UUID NOT NULL CONSTRAINT notification_target_pkey PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + name VARCHAR(255) NOT NULL, + configuration VARCHAR(10000) NOT NULL, + external_id UUID, + CONSTRAINT uq_notification_target_name UNIQUE (tenant_id, name), + CONSTRAINT uq_notification_target_external_id UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS notification_template ( + id UUID NOT NULL CONSTRAINT notification_template_pkey PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + name VARCHAR(255) NOT NULL, + notification_type VARCHAR(50) NOT NULL, + configuration VARCHAR(10000000) NOT NULL, + external_id UUID, + CONSTRAINT uq_notification_template_name UNIQUE (tenant_id, name), + CONSTRAINT uq_notification_template_external_id UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS notification_rule ( + id UUID NOT NULL CONSTRAINT notification_rule_pkey PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + name VARCHAR(255) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT true, + template_id UUID NOT NULL CONSTRAINT fk_notification_rule_template_id REFERENCES notification_template(id), + trigger_type VARCHAR(50) NOT NULL, + trigger_config VARCHAR(1000) NOT NULL, + recipients_config VARCHAR(10000) NOT NULL, + additional_config VARCHAR(255), + external_id UUID, + CONSTRAINT uq_notification_rule_name UNIQUE (tenant_id, name), + CONSTRAINT uq_notification_rule_external_id UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS notification_request ( + id UUID NOT NULL CONSTRAINT notification_request_pkey PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + targets VARCHAR(10000) NOT NULL, + template_id UUID, + template VARCHAR(10000000), + info VARCHAR(1000000), + additional_config VARCHAR(1000), + originator_entity_id UUID, + originator_entity_type VARCHAR(32), + rule_id UUID NULL, + status VARCHAR(32), + stats VARCHAR(10000) +); + +CREATE TABLE IF NOT EXISTS notification ( + id UUID NOT NULL, + created_time BIGINT NOT NULL, + request_id UUID, + recipient_id UUID NOT NULL, + type VARCHAR(50) NOT NULL, + delivery_method VARCHAR(50) NOT NULL, + subject VARCHAR(255), + body VARCHAR(1000) NOT NULL, + additional_config VARCHAR(1000), + status VARCHAR(32) +) PARTITION BY RANGE (created_time); + +CREATE TABLE IF NOT EXISTS user_settings ( + user_id uuid NOT NULL, + type VARCHAR(50) NOT NULL, + settings jsonb, + CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES tb_user(id) ON DELETE CASCADE, + CONSTRAINT user_settings_pkey PRIMARY KEY (user_id, type) +); + +CREATE TABLE IF NOT EXISTS alarm_types ( + tenant_id uuid NOT NULL, + type varchar(255) NOT NULL, + CONSTRAINT tenant_id_type_unq_key UNIQUE (tenant_id, type), + CONSTRAINT fk_entity_tenant_id FOREIGN KEY (tenant_id) REFERENCES tenant(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS queue_stats ( + id uuid NOT NULL CONSTRAINT queue_stats_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + queue_name varchar(255) NOT NULL, + service_id varchar(255) NOT NULL, + CONSTRAINT queue_stats_name_unq_key UNIQUE (tenant_id, queue_name, service_id) +); + +CREATE TABLE IF NOT EXISTS qr_code_settings ( + id uuid NOT NULL CONSTRAINT qr_code_settings_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + use_default_app boolean, + android_enabled boolean, + ios_enabled boolean, + mobile_app_bundle_id uuid, + qr_code_config VARCHAR(100000), + CONSTRAINT qr_code_settings_tenant_id_unq_key UNIQUE (tenant_id) +); + +CREATE TABLE IF NOT EXISTS calculated_field ( + id uuid NOT NULL CONSTRAINT calculated_field_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + entity_type VARCHAR(32), + entity_id uuid NOT NULL, + type varchar(32) NOT NULL, + name varchar(255) NOT NULL, + configuration_version int DEFAULT 0, + configuration varchar(1000000), + version BIGINT DEFAULT 1, + debug_settings varchar(1024), + additional_info varchar, + CONSTRAINT calculated_field_unq_key UNIQUE (entity_id, type, name) +); + +CREATE TABLE IF NOT EXISTS cf_debug_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL , + ts bigint NOT NULL, + entity_id uuid NOT NULL, -- calculated field id + service_id varchar, + cf_id uuid NOT NULL, + e_entity_id uuid, -- target entity id + e_entity_type varchar, + e_msg_id uuid, + e_msg_type varchar, + e_args varchar, + e_result varchar, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS job ( + id uuid NOT NULL CONSTRAINT job_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + type varchar NOT NULL, + key varchar NOT NULL, + entity_id uuid NOT NULL, + entity_type varchar NOT NULL, + status varchar NOT NULL, + configuration varchar NOT NULL, + result varchar +); + +CREATE TABLE IF NOT EXISTS ai_model ( + id UUID NOT NULL PRIMARY KEY, + external_id UUID, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + version BIGINT NOT NULL DEFAULT 1, + name VARCHAR(255) NOT NULL, + configuration JSONB NOT NULL, + CONSTRAINT ai_model_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT ai_model_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS iot_hub_installed_item ( + id UUID NOT NULL PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + item_id UUID NOT NULL, + item_version_id UUID NOT NULL, + item_name VARCHAR NOT NULL, + item_type VARCHAR NOT NULL, + version VARCHAR NOT NULL, + descriptor JSONB NOT NULL +); diff --git a/common/actor/pom.xml b/common/actor/pom.xml index ecb8aac7f7..10f5bb5fa4 100644 --- a/common/actor/pom.xml +++ b/common/actor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/cache/pom.xml b/common/cache/pom.xml index 850d3be5ab..77861f9675 100644 --- a/common/cache/pom.xml +++ b/common/cache/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/cluster-api/pom.xml b/common/cluster-api/pom.xml index 2700315dec..1df31d4a53 100644 --- a/common/cluster-api/pom.xml +++ b/common/cluster-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/coap-server/pom.xml b/common/coap-server/pom.xml index 33cb81b4dd..7d7e725a7e 100644 --- a/common/coap-server/pom.xml +++ b/common/coap-server/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/dao-api/pom.xml b/common/dao-api/pom.xml index ea4594e763..5bc2030203 100644 --- a/common/dao-api/pom.xml +++ b/common/dao-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common @@ -41,6 +41,10 @@ com.google.guava guava + + org.checkerframework + checker-qual + jakarta.annotation jakarta.annotation-api diff --git a/common/data/pom.xml b/common/data/pom.xml index 19824553ab..6e30c03734 100644 --- a/common/data/pom.xml +++ b/common/data/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common @@ -79,6 +79,10 @@ com.squareup.wire wire-schema-jvm + + org.checkerframework + checker-qual + org.thingsboard protobuf-dynamic diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/audit/ActionType.java b/common/data/src/main/java/org/thingsboard/server/common/data/audit/ActionType.java index 712c5b72a1..ca5df45181 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/audit/ActionType.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/audit/ActionType.java @@ -206,7 +206,19 @@ public enum ActionType { /** * SMS sent. Does not push to rule engine. */ - SMS_SENT; + SMS_SENT, + /** + * Community Grant instance checker run from an uploaded bundle. Does not push to rule engine. + */ + COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + /** + * Community Grant access request to the registered owner. Does not push to rule engine. + */ + COMMUNITY_GRANT_REQUEST_ACCESS, + /** + * Community Grant enrollment started or its report declared handed over. Does not push to rule engine. + */ + COMMUNITY_GRANT_ENROLLMENT; @Getter private final boolean read; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantFlowState.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantFlowState.java new file mode 100644 index 0000000000..6c0edeeaae --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantFlowState.java @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * The persisted community grant state, stored as a single JSON document in {@code admin_settings}. The claim + * token lives in {@code tb_cluster}, though the sign-up URL stored here quotes it. + */ +@Data +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class CommunityGrantFlowState implements Serializable { + + private static final long serialVersionUID = 1L; + + private CommunityGrantMode mode; + private CommunityGrantState state; + private String signUpUrl; + /** When {@code start()} minted the current token; bounds how long an abandoned sign-up is polled. */ + private Long startedAt; + private Long lastPolledAt; + private Long lastOfflineCheckAt; + /** When {@code requestAccess()} last attempted to reach the portal, successful or not; the cooldown's base. */ + private Long lastRequestAccessAt; + + /** + * Set on {@code RESUME} only. Outside {@link #clearClaim()}: it is written by the same update that sets + * {@code RESUME}. + */ + private CommunityGrantParkReason parkReason; + + /** The last by-hand checker run that is running or failed. */ + private CommunityGrantOfflineRun offlineRun; + + /** Drops everything scoped to the current claim token. */ + public void clearClaim() { + signUpUrl = null; + startedAt = null; + } + + public static CommunityGrantFlowState initial() { + CommunityGrantFlowState flowState = new CommunityGrantFlowState(); + flowState.setMode(CommunityGrantMode.ONLINE); + flowState.setState(CommunityGrantState.NOT_STARTED); + return flowState; + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantMode.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantMode.java new file mode 100644 index 0000000000..faa142e4eb --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantMode.java @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * How this deployment runs the community grant flow, chosen by the server from a reachability probe. + */ +public enum CommunityGrantMode { + + ONLINE, + OFFLINE + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRun.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRun.java new file mode 100644 index 0000000000..afd1dd08e1 --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRun.java @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.UUID; + +/** + * A by-hand checker run, recorded on the flow state so every node can report a run executing on one of them. + */ +@Data +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class CommunityGrantOfflineRun implements Serializable { + + private static final long serialVersionUID = 1L; + + /** A completion updates the record only while it still carries its own id. */ + private UUID runId; + private CommunityGrantOfflineRunStatus status; + private Long startedAt; + /** Why the run failed, safe to show to the operator. Set only on {@code FAILED}. */ + private String error; + + public static CommunityGrantOfflineRun running(UUID runId, long startedAt) { + CommunityGrantOfflineRun run = new CommunityGrantOfflineRun(); + run.setRunId(runId); + run.setStatus(CommunityGrantOfflineRunStatus.RUNNING); + run.setStartedAt(startedAt); + return run; + } + + public boolean isOwnedBy(UUID runId) { + return this.runId != null && this.runId.equals(runId); + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRunStatus.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRunStatus.java new file mode 100644 index 0000000000..10eeafbac6 --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRunStatus.java @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * There is no success value: a run that succeeds is cleared from the flow state. + */ +public enum CommunityGrantOfflineRunStatus { + + RUNNING, + FAILED + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantParkReason.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantParkReason.java new file mode 100644 index 0000000000..46bdb63943 --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantParkReason.java @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * Why a flow parked at {@link CommunityGrantState#RESUME}. + */ +public enum CommunityGrantParkReason { + + /** The portal says the claim token expired. */ + LINK_EXPIRED, + /** + * The sign-up form was never completed within this deployment's own deadline, which also ends an + * enrollment whose portal was never reachable. + */ + SIGNUP_ABANDONED, + /** The instance checker failed its whole retry budget. Retryable. */ + CHECK_FAILED, + /** The portal stopped answering for the whole failure budget after sign-up. Retryable. */ + PORTAL_UNREACHABLE +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantState.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantState.java new file mode 100644 index 0000000000..bb57f02d2f --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantState.java @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * The instance-local view of the community grant flow, largely a projection of the portal's answer. + */ +public enum CommunityGrantState { + + NOT_STARTED, + AWAITING_SIGNUP, + COLLECTING, + VALIDATING, + /** + * The operator handed a by-hand report to the portal. A wait, not an ending: where the portal is + * reachable a later poll resolves it; offline, the answer is read at the portal. + */ + REPORT_HANDED_OVER, + REGISTERED, + UNDER_REVIEW, + /** This cluster id is already enrolled by somebody else, found by the probe before any token is minted. */ + ALREADY_REGISTERED, + /** The polled claim token is bound to a different installation; this one is not registered at all. */ + WRONG_INSTALLATION, + RESUME; + + /** A state the flow never leaves on its own. Nothing polls from here and no token is held past it. */ + public boolean isTerminal() { + return this == REGISTERED || this == ALREADY_REGISTERED || this == WRONG_INSTALLATION; + } + + /** A state from which the portal is worth asking again. {@link #RESUME}'s token is already gone. */ + public boolean isPollable() { + return this == AWAITING_SIGNUP || this == COLLECTING || this == VALIDATING || this == UNDER_REVIEW + || this == REPORT_HANDED_OVER; + } + + /** + * A state no local action may move the flow out of: the portal has decided, or still owes a decision on a + * registration or report it already has. + */ + public boolean isAwaitingOrPastDecision() { + return isTerminal() || this == UNDER_REVIEW || this == REPORT_HANDED_OVER; + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantStateInfo.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantStateInfo.java new file mode 100644 index 0000000000..bc5354451e --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantStateInfo.java @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * Everything the widget is allowed to know: never a license key, an owner identity or a policy detail. Keep + * the TypeScript mirror in {@code community-grant.models.ts} in step. + */ +public record CommunityGrantStateInfo(CommunityGrantMode mode, + CommunityGrantState state, + String signUpUrl, + Long lastPolledAt, + CommunityGrantParkReason parkReason, + String portalUrl, + String offlineReport, + boolean offlineRunInProgress, + String offlineRunError) { + + public static CommunityGrantStateInfo of(CommunityGrantFlowState flowState, String portalUrl) { + return of(flowState, portalUrl, null, false, null); + } + + public static CommunityGrantStateInfo of(CommunityGrantFlowState flowState, String portalUrl, + String offlineReport, boolean offlineRunInProgress, + String offlineRunError) { + return new CommunityGrantStateInfo(flowState.getMode(), flowState.getState(), + flowState.getSignUpUrl(), flowState.getLastPolledAt(), flowState.getParkReason(), + portalUrl, offlineReport, offlineRunInProgress, offlineRunError); + } + + /** Only the report and hand-off screens show the report, and only once a run has been recorded. */ + public static boolean carriesOfflineReport(CommunityGrantFlowState flowState) { + CommunityGrantState state = flowState.getState(); + return (state == CommunityGrantState.VALIDATING || state == CommunityGrantState.REPORT_HANDED_OVER) + && flowState.getLastOfflineCheckAt() != null; + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java index 27758126d5..e2bdb9a6fd 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java @@ -12,9 +12,9 @@ import java.io.Serializable; public class LwM2MServerSecurityConfig implements Serializable { @Schema(description = "Server short Id. Used as link to associate server Object Instance. This identifier uniquely identifies each LwM2M Server configured for the LwM2M Client. " + - "This Resource MUST be set when the Bootstrap-Server Resource has a value of 'false'. " + - "The values ID:0 and ID:65535 values MUST NOT be used for identifying the LwM2M Server.", example = "123", accessMode = Schema.AccessMode.READ_ONLY) - protected Integer shortServerId = 123; + "This Resource MUST be set when the Bootstrap-Server Resource has a value of 'false' and MUST be null when Bootstrap-Server is 'true'. " + + "The values 0 and 65535 MUST NOT be used for identifying the LwM2M Server.", example = "1", accessMode = Schema.AccessMode.READ_ONLY) + protected Integer shortServerId; /** Security -> ObjectId = 0 'LWM2M Security' */ @Schema(description = "Is Bootstrap Server or Lwm2m Server. " + "The LwM2M Client MAY be configured to use one or more LwM2M Server Account(s). " + diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java deleted file mode 100644 index 654f36f31e..0000000000 --- a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The Thingsboard Authors -// SPDX-License-Identifier: Apache-2.0 -package org.thingsboard.server.common.data.iot_hub; - -import lombok.Data; -import org.thingsboard.server.common.data.id.DashboardId; - -@Data -public class DashboardInstalledItemDescriptor implements IotHubInstalledItemDescriptor { - - private DashboardId dashboardId; - -} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java index 0ef245c0ac..ca8b3a1b83 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java @@ -15,7 +15,6 @@ import java.io.Serializable; property = "type") @JsonSubTypes({ @Type(name = "WIDGET", value = WidgetInstalledItemDescriptor.class), - @Type(name = "DASHBOARD", value = DashboardInstalledItemDescriptor.class), @Type(name = "CALCULATED_FIELD", value = CalculatedFieldInstalledItemDescriptor.class), @Type(name = "ALARM_RULE", value = AlarmRuleInstalledItemDescriptor.class), @Type(name = "RULE_CHAIN", value = RuleChainInstalledItemDescriptor.class), diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java index 9b6e376365..5a6b04f1ac 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java @@ -15,11 +15,16 @@ public enum RpcStatus { FAILED(false), DELETED(false); + /** + * {@code true} while the RPC is still pending in the device actor (not yet delivered/answered). + * Note: TIMEOUT is not intermediate, but it is not final either - the device actor may retry + * the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED) until retries are exhausted (then FAILED). + */ @Getter - private final boolean pushDeleteNotificationToCore; + private final boolean intermediate; - RpcStatus(boolean pushDeleteNotificationToCore) { - this.pushDeleteNotificationToCore = pushDeleteNotificationToCore; + RpcStatus(boolean intermediate) { + this.intermediate = intermediate; } } diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java index 35073196c2..dbfe8ad4ee 100644 --- a/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java +++ b/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java @@ -13,20 +13,20 @@ import static org.thingsboard.server.common.data.rpc.RpcStatus.SENT; class RpcStatusTest { - private static final List pushDeleteNotificationToCoreStatuses = List.of( + private static final List intermediateStatuses = List.of( QUEUED, SENT, DELIVERED ); @Test - void isPushDeleteNotificationToCoreStatusTest() { + void isIntermediateStatusTest() { var rpcStatuses = RpcStatus.values(); for (var status : rpcStatuses) { - if (pushDeleteNotificationToCoreStatuses.contains(status)) { - assertThat(status.isPushDeleteNotificationToCore()).isTrue(); + if (intermediateStatuses.contains(status)) { + assertThat(status.isIntermediate()).isTrue(); } else { - assertThat(status.isPushDeleteNotificationToCore()).isFalse(); + assertThat(status.isIntermediate()).isFalse(); } } } diff --git a/common/discovery-api/pom.xml b/common/discovery-api/pom.xml index ab46e7b338..dd24f5d1ee 100644 --- a/common/discovery-api/pom.xml +++ b/common/discovery-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/pom.xml b/common/edge-api/pom.xml index feb630ed8b..6d2a9b9aad 100644 --- a/common/edge-api/pom.xml +++ b/common/edge-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index 6c489f45c8..58d5ace78b 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -40,6 +40,7 @@ enum EdgeVersion { V_4_2_2_4 = 4224; V_4_2_2_5 = 4225; V_4_2_2_6 = 4226; + V_4_2_2_7 = 4227; V_4_3_0_1 = 15; V_4_3_1 = 4310; V_4_3_1_1 = 4311; @@ -48,6 +49,7 @@ enum EdgeVersion { V_4_3_1_4 = 4314; V_4_3_1_5 = 4315; V_4_3_1_6 = 4316; + V_4_3_1_7 = 4317; V_LATEST = 99999; } @@ -402,6 +404,7 @@ message DeviceRpcCallMsg { optional string additionalInfo = 12; optional string serviceId = 13; optional string sessionId = 14; + optional string rpcStatus = 15; } message RpcRequestMsg { diff --git a/common/edqs/pom.xml b/common/edqs/pom.xml index c5389fe411..9c3c0205bc 100644 --- a/common/edqs/pom.xml +++ b/common/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/message/pom.xml b/common/message/pom.xml index 92bd1e22cf..6d7d70c76c 100644 --- a/common/message/pom.xml +++ b/common/message/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/pom.xml b/common/pom.xml index 91d7922812..5f9887435e 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard common diff --git a/common/proto/pom.xml b/common/proto/pom.xml index f61d74ba26..6ebb95f965 100644 --- a/common/proto/pom.xml +++ b/common/proto/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/queue/pom.xml b/common/queue/pom.xml index 8eba1c8dbb..063c8fb97f 100644 --- a/common/queue/pom.xml +++ b/common/queue/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common @@ -123,6 +123,11 @@ awaitility test + + org.apache.curator + curator-test + test + diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java index 5617a3d148..ff1746d54c 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java @@ -96,7 +96,7 @@ public class HashPartitionService implements PartitionService { private final ConcurrentMap tenantRoutingInfoMap = new ConcurrentHashMap<>(); - private List currentOtherServices; + private volatile List currentOtherServices; private final Map> tbTransportServicesByType = new HashMap<>(); private volatile Map> responsibleServices = Collections.emptyMap(); @@ -537,6 +537,23 @@ public class HashPartitionService implements PartitionService { return getAllServices(serviceType).stream().map(ServiceInfo::getServiceId).collect(Collectors.toSet()); } + @Override + public boolean isKnownServiceId(ServiceType serviceType, String serviceId) { + ServiceInfo current = serviceInfoProvider.getServiceInfo(); + if (serviceId.equals(current.getServiceId()) && current.getServiceTypesList().contains(serviceType.name())) { + return true; + } + List others = currentOtherServices; + if (others != null) { + for (ServiceInfo serviceInfo : others) { + if (serviceId.equals(serviceInfo.getServiceId()) && serviceInfo.getServiceTypesList().contains(serviceType.name())) { + return true; + } + } + } + return false; + } + @Override public Set getAllServices(ServiceType serviceType) { Set result = getOtherServices(serviceType); diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java index 73e585568b..73ccf32373 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java @@ -48,6 +48,12 @@ public interface PartitionService { */ Set getAllServiceIds(ServiceType serviceType); + /** + * Cheaper alternative to {@link #getAllServiceIds} when only membership of a single id needs to be checked - + * avoids building the full service id set. + */ + boolean isKnownServiceId(ServiceType serviceType, String serviceId); + Set getAllServices(ServiceType serviceType); Set getOtherServices(ServiceType serviceType); diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java index 512bac6edd..1233e2878a 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java @@ -20,7 +20,7 @@ import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryForever; import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.data.Stat; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.event.ApplicationReadyEvent; @@ -32,12 +32,14 @@ import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.queue.discovery.event.OtherServiceShutdownEvent; import org.thingsboard.server.queue.util.AfterStartUp; +import java.util.LinkedHashMap; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import java.util.stream.Collectors; import static org.apache.curator.framework.recipes.cache.CuratorCacheAccessor.parentPathFilter; @@ -103,20 +105,32 @@ public class ZkDiscoveryService implements DiscoveryService { @Override public List getOtherServers() { + String currentServiceId = serviceInfoProvider.getServiceInfo().getServiceId(); return cache.stream() .filter(parentPathFilter(zkNodesDir)) .filter(cd -> !cd.getPath().equals(nodePath)) .map(cd -> { try { - return TransportProtos.ServiceInfo.parseFrom(cd.getData()); + return new Registration(cd, TransportProtos.ServiceInfo.parseFrom(cd.getData())); } catch (NoSuchElementException | InvalidProtocolBufferException e) { log.error("Failed to decode ZK node", e); throw new RuntimeException(e); } }) + .filter(r -> !r.info().getServiceId().equals(currentServiceId)) + // Orders ZK registrations by creation, so that a re-registration wins over a stale node of the same service. + // Uses the creation zxid: ZooKeeper's transaction id, which grows across leader changes and is the same + // on every client. ctime/mtime are not used, as they come from the leader's wall clock and may go backwards. + .collect(Collectors.toMap(r -> r.info().getServiceId(), Function.identity(), + (a, b) -> b.data().getStat().getCzxid() > a.data().getStat().getCzxid() ? b : a, + LinkedHashMap::new)) + .values().stream() + .map(Registration::info) .collect(Collectors.toList()); } + private record Registration(ChildData data, TransportProtos.ServiceInfo info) {} + @Override public boolean isMonolith() { return false; @@ -146,21 +160,26 @@ public class ZkDiscoveryService implements DiscoveryService { @SneakyThrows public synchronized void publishCurrentServer() { TransportProtos.ServiceInfo self = serviceInfoProvider.getServiceInfo(); - if (currentServerExists()) { - log.trace("[{}] Updating ZK node for current instance: {}", self.getServiceId(), nodePath); - client.setData().forPath(nodePath, serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo().toByteArray()); - } else { - try { - log.info("[{}] Creating ZK node for current instance", self.getServiceId()); - nodePath = client.create() - .creatingParentsIfNeeded() - .withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(zkNodesDir + "/", self.toByteArray()); - log.info("[{}] Created ZK node for current instance: {}", self.getServiceId(), nodePath); - client.getConnectionStateListenable().addListener(checkReconnect(self)); - } catch (Exception e) { - log.error("Failed to create ZK node", e); - throw new RuntimeException(e); + switch (getCurrentServerNodeState()) { + case PRESENT -> { + log.trace("[{}] Updating ZK node for current instance: {}", self.getServiceId(), nodePath); + client.setData().forPath(nodePath, serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo().toByteArray()); } + case ABSENT -> { + try { + log.info("[{}] Creating ZK node for current instance", self.getServiceId()); + nodePath = client.create() + .creatingParentsIfNeeded() + .withProtection() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(zkNodesDir + "/node-", self.toByteArray()); + log.info("[{}] Created ZK node for current instance: {}", self.getServiceId(), nodePath); + client.getConnectionStateListenable().addListener(checkReconnect(self)); + } catch (Exception e) { + log.error("Failed to create ZK node", e); + throw new RuntimeException(e); + } + } + case UNKNOWN -> log.debug("[{}] Skipping ZK node publish, node state is unknown", self.getServiceId()); } } @@ -177,23 +196,35 @@ public class ZkDiscoveryService implements DiscoveryService { } } - private boolean currentServerExists() { + private NodeState getCurrentServerNodeState() { if (nodePath == null) { - return false; + return NodeState.ABSENT; } try { - TransportProtos.ServiceInfo self = serviceInfoProvider.getServiceInfo(); - TransportProtos.ServiceInfo registeredServerInfo = null; - registeredServerInfo = TransportProtos.ServiceInfo.parseFrom(client.getData().forPath(nodePath)); - if (self.equals(registeredServerInfo)) { - return true; + Stat stat = client.checkExists().forPath(nodePath); + if (stat == null) { + log.info("ZK node does not exist: {}", nodePath); + return NodeState.ABSENT; } - } catch (KeeperException.NoNodeException e) { - log.info("ZK node does not exist: {}", nodePath); + long sessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); + if (stat.getEphemeralOwner() != sessionId) { + log.warn("ZK node {} is owned by another session 0x{}, current session 0x{}", + nodePath, Long.toHexString(stat.getEphemeralOwner()), Long.toHexString(sessionId)); + return NodeState.ABSENT; + } + return NodeState.PRESENT; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.error("Interrupted while checking if ZK node exists", e); + return NodeState.UNKNOWN; } catch (Exception e) { log.error("Couldn't check if ZK node exists", e); + return NodeState.UNKNOWN; } - return false; + } + + private enum NodeState { + PRESENT, ABSENT, UNKNOWN } private ConnectionStateListener checkReconnect(TransportProtos.ServiceInfo self) { @@ -313,6 +344,14 @@ public class ZkDiscoveryService implements DiscoveryService { String serviceId = instance.getServiceId(); ProtocolStringList serviceTypesList = instance.getServiceTypesList(); + if (serviceId.equals(serviceInfoProvider.getServiceInfo().getServiceId())) { + if (type == CuratorCacheListener.Type.NODE_CREATED) { + log.error("[{}] Ignoring ZK node {} registered with the current service id. " + + "It is either a stale registration of this service or another service uses the same service id", serviceId, data.getPath()); + } + return; + } + log.trace("Processing [{}] event for [{}]", type, serviceId); switch (type) { case NODE_CREATED: @@ -333,16 +372,19 @@ public class ZkDiscoveryService implements DiscoveryService { } break; case NODE_DELETED: + if (getOtherServers().stream().anyMatch(s -> s.getServiceId().equals(serviceId))) { + log.debug("[{}] Ignoring removal of duplicate ZK node {}, service is still registered", serviceId, data.getPath()); + break; + } zkExecutorService.submit(() -> applicationEventPublisher.publishEvent(new OtherServiceShutdownEvent(this, serviceId, serviceTypesList))); - ScheduledFuture future = zkExecutorService.schedule(() -> { + delayedTasks.compute(serviceId, (id, previous) -> zkExecutorService.schedule(() -> { log.debug("[{}] Going to recalculate partitions due to removed node [{}]", serviceId, serviceTypesList); ScheduledFuture removedTask = delayedTasks.remove(serviceId); if (removedTask != null) { recalculatePartitions(); } - }, recalculateDelay, TimeUnit.MILLISECONDS); - delayedTasks.put(serviceId, future); + }, recalculateDelay, TimeUnit.MILLISECONDS)); break; default: break; diff --git a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java index 55edc5e4ad..37af643ff0 100644 --- a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java +++ b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java @@ -2,11 +2,19 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.queue.discovery; +import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.api.CreateBuilder; +import org.apache.curator.framework.api.ExistsBuilder; +import org.apache.curator.framework.api.SetDataBuilder; import org.apache.curator.framework.imps.CuratorFrameworkState; +import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.CuratorCache; import org.apache.curator.framework.recipes.cache.CuratorCacheListener; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -17,6 +25,7 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.queue.discovery.event.OtherServiceShutdownEvent; import java.util.ArrayList; import java.util.Collections; @@ -29,6 +38,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; @@ -56,6 +68,8 @@ public class ZkDiscoveryServiceTest { private List dataList; private static final long RECALCULATE_DELAY = 100L; + private static final long SESSION_ID = 0x100L; + private static final long OTHER_SESSION_ID = 0x200L; final TransportProtos.ServiceInfo currentInfo = TransportProtos.ServiceInfo.newBuilder().setServiceId("tb-rule-engine-0").build(); final ChildData currentData = new ChildData("/thingsboard/nodes/0000000010", null, currentInfo.toByteArray()); @@ -66,7 +80,7 @@ public class ZkDiscoveryServiceTest { public void setup() { zkDiscoveryService = Mockito.spy(new ZkDiscoveryService(applicationEventPublisher, serviceInfoProvider, partitionService)); ScheduledExecutorService zkExecutorService = ThingsBoardExecutors.newSingleThreadScheduledExecutor("zk-discovery"); - when(client.getState()).thenReturn(CuratorFrameworkState.STARTED); + lenient().when(client.getState()).thenReturn(CuratorFrameworkState.STARTED); ReflectionTestUtils.setField(zkDiscoveryService, "stopped", false); ReflectionTestUtils.setField(zkDiscoveryService, "client", client); ReflectionTestUtils.setField(zkDiscoveryService, "cache", cache); @@ -76,11 +90,11 @@ public class ZkDiscoveryServiceTest { ReflectionTestUtils.setField(zkDiscoveryService, "zkDir", "/thingsboard"); ReflectionTestUtils.setField(zkDiscoveryService, "zkNodesDir", "/thingsboard/nodes"); - when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo); + lenient().when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo); dataList = new ArrayList<>(); dataList.add(currentData); - when(cache.stream()).thenAnswer(inv -> dataList.stream()); + lenient().when(cache.stream()).thenAnswer(inv -> dataList.stream()); } @Test @@ -164,6 +178,175 @@ public class ZkDiscoveryServiceTest { verify(partitionService, times(1)).recalculatePartitions(eq(currentInfo), eq(List.of(anotherInfo, childInfo))); } + @Test + public void publishCurrentServerUpdatesExistingNodeTest() throws Exception { + ExistsBuilder existsBuilder = mockExistsBuilder(); + when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(SESSION_ID)); + mockSessionId(); + SetDataBuilder setDataBuilder = mock(SetDataBuilder.class); + when(client.setData()).thenReturn(setDataBuilder); + when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(currentInfo); + + zkDiscoveryService.publishCurrentServer(); + + verify(setDataBuilder).forPath(currentData.getPath(), currentInfo.toByteArray()); + verify(client, never()).create(); + } + + @Test + public void publishCurrentServerUpdatesNodeWithOutdatedDataTest() throws Exception { + TransportProtos.ServiceInfo updatedInfo = currentInfo.toBuilder().setReady(true).build(); + when(serviceInfoProvider.getServiceInfo()).thenReturn(updatedInfo); + ExistsBuilder existsBuilder = mockExistsBuilder(); + when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(SESSION_ID)); + mockSessionId(); + SetDataBuilder setDataBuilder = mock(SetDataBuilder.class); + when(client.setData()).thenReturn(setDataBuilder); + when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(updatedInfo); + + zkDiscoveryService.publishCurrentServer(); + + verify(setDataBuilder).forPath(currentData.getPath(), updatedInfo.toByteArray()); + verify(client, never()).create(); + } + + @Test + public void publishCurrentServerCreatesNodeWhenAbsentTest() throws Exception { + String newPath = "/thingsboard/nodes/0000000011"; + ExistsBuilder existsBuilder = mockExistsBuilder(); + when(existsBuilder.forPath(currentData.getPath())).thenReturn(null); + CreateBuilder createBuilder = mock(CreateBuilder.class, RETURNS_DEEP_STUBS); + when(client.create()).thenReturn(createBuilder); + when(createBuilder.creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/thingsboard/nodes/node-", currentInfo.toByteArray())) + .thenReturn(newPath); + when(client.getConnectionStateListenable()).thenReturn(mock(Listenable.class)); + + zkDiscoveryService.publishCurrentServer(); + + assertEquals(newPath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath")); + verify(client, never()).setData(); + } + + @Test + public void publishCurrentServerCreatesNodeWhenExistingNodeOwnedByAnotherSessionTest() throws Exception { + String newPath = "/thingsboard/nodes/0000000011"; + ExistsBuilder existsBuilder = mockExistsBuilder(); + when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(OTHER_SESSION_ID)); + mockSessionId(); + CreateBuilder createBuilder = mock(CreateBuilder.class, RETURNS_DEEP_STUBS); + when(client.create()).thenReturn(createBuilder); + when(createBuilder.creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/thingsboard/nodes/node-", currentInfo.toByteArray())) + .thenReturn(newPath); + when(client.getConnectionStateListenable()).thenReturn(mock(Listenable.class)); + + zkDiscoveryService.publishCurrentServer(); + + assertEquals(newPath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath")); + verify(client, never()).setData(); + } + + @Test + public void publishCurrentServerSkipsWhenNodeStateUnknownTest() throws Exception { + ExistsBuilder existsBuilder = mockExistsBuilder(); + when(existsBuilder.forPath(currentData.getPath())).thenThrow(new InterruptedException()); + + zkDiscoveryService.publishCurrentServer(); + + assertTrue(Thread.interrupted()); + assertEquals(currentData.getPath(), ReflectionTestUtils.getField(zkDiscoveryService, "nodePath")); + verify(client, never()).create(); + verify(client, never()).setData(); + } + + @Test + public void getOtherServersIgnoresNodesWithCurrentServiceIdTest() { + dataList.add(new ChildData("/thingsboard/nodes/0000000011", statWithCzxid(1), currentInfo.toByteArray())); + dataList.add(childData); + + assertEquals(List.of(childInfo), zkDiscoveryService.getOtherServers()); + } + + @Test + public void getOtherServersKeepsLatestNodeForDuplicatedServiceIdTest() { + TransportProtos.ServiceInfo latestInfo = childInfo.toBuilder().setReady(true).build(); + dataList.add(new ChildData("/thingsboard/nodes/0000000020", statWithCzxid(1), childInfo.toByteArray())); + dataList.add(new ChildData("/thingsboard/nodes/0000000021", statWithCzxid(2), latestInfo.toByteArray())); + + assertEquals(List.of(latestInfo), zkDiscoveryService.getOtherServers()); + + Collections.swap(dataList, 1, 2); + + assertEquals(List.of(latestInfo), zkDiscoveryService.getOtherServers()); + } + + @Test + public void getOtherServersKeepsLatestCreatedNodeEvenIfItsMtimeIsOlderTest() { + TransportProtos.ServiceInfo latestInfo = childInfo.toBuilder().setReady(true).build(); + Stat staleStat = statWithCzxid(1); + staleStat.setMtime(2000); + Stat latestStat = statWithCzxid(2); + latestStat.setMtime(1000); + dataList.add(new ChildData("/thingsboard/nodes/0000000020", staleStat, childInfo.toByteArray())); + dataList.add(new ChildData("/thingsboard/nodes/0000000021", latestStat, latestInfo.toByteArray())); + + assertEquals(List.of(latestInfo), zkDiscoveryService.getOtherServers()); + } + + @Test + public void nodeWithCurrentServiceIdDoesNotTriggerRecalculationTest() { + ChildData orphanData = new ChildData("/thingsboard/nodes/0000000011", statWithCzxid(1), currentInfo.toByteArray()); + + startNode(orphanData); + stopNode(orphanData); + + assertTrue(zkDiscoveryService.delayedTasks.isEmpty()); + verify(partitionService, never()).recalculatePartitions(any(), any()); + verify(applicationEventPublisher, never()).publishEvent(any(OtherServiceShutdownEvent.class)); + } + + @Test + public void removalOfDuplicatedNodeDoesNotPublishShutdownEventTest() { + ChildData staleData = new ChildData("/thingsboard/nodes/0000000019", statWithCzxid(1), childInfo.toByteArray()); + ChildData liveData = new ChildData("/thingsboard/nodes/0000000020", statWithCzxid(2), childInfo.toByteArray()); + startNode(staleData); + startNode(liveData); + + stopNode(staleData); + + assertTrue(zkDiscoveryService.delayedTasks.isEmpty()); + verify(applicationEventPublisher, never()).publishEvent(any(OtherServiceShutdownEvent.class)); + + stopNode(liveData); + + assertEquals(1, zkDiscoveryService.delayedTasks.size()); + } + + private ExistsBuilder mockExistsBuilder() { + ExistsBuilder existsBuilder = mock(ExistsBuilder.class); + when(client.checkExists()).thenReturn(existsBuilder); + return existsBuilder; + } + + private void mockSessionId() throws Exception { + CuratorZookeeperClient zookeeperClient = mock(CuratorZookeeperClient.class); + ZooKeeper zooKeeper = mock(ZooKeeper.class); + when(client.getZookeeperClient()).thenReturn(zookeeperClient); + when(zookeeperClient.getZooKeeper()).thenReturn(zooKeeper); + when(zooKeeper.getSessionId()).thenReturn(SESSION_ID); + } + + private static Stat statOwnedBy(long sessionId) { + Stat stat = new Stat(); + stat.setEphemeralOwner(sessionId); + return stat; + } + + private static Stat statWithCzxid(long czxid) { + Stat stat = new Stat(); + stat.setCzxid(czxid); + return stat; + } + private void startNode(ChildData data) { dataList.add(data); zkDiscoveryService.onCacheEvent(NODE_CREATED, null, data); diff --git a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java new file mode 100644 index 0000000000..380d13176d --- /dev/null +++ b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java @@ -0,0 +1,109 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.queue.discovery; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.TestingServer; +import org.apache.curator.utils.CloseableUtils; +import org.apache.zookeeper.data.Stat; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.gen.transport.TransportProtos; + +import java.time.Duration; +import java.util.List; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.lenient; + +@ExtendWith(MockitoExtension.class) +public class ZkDiscoveryServiceZkTest { + + private static final String ZK_NODES_DIR = "/thingsboard/nodes"; + private static final String PROTECTED_NODE_NAME_REGEX = "_c_[0-9a-f-]{36}-node-\\d{10}"; + + @Mock + private ApplicationEventPublisher applicationEventPublisher; + @Mock + private TbServiceInfoProvider serviceInfoProvider; + @Mock + private PartitionService partitionService; + + private final TransportProtos.ServiceInfo currentInfo = TransportProtos.ServiceInfo.newBuilder().setServiceId("tb-core-0").build(); + + private TestingServer zkServer; + private CuratorFramework observer; + private ZkDiscoveryService zkDiscoveryService; + + @BeforeEach + public void setup() throws Exception { + zkServer = new TestingServer(true); + observer = CuratorFrameworkFactory.newClient(zkServer.getConnectString(), new RetryOneTime(100)); + observer.start(); + + lenient().when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo); + lenient().when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(currentInfo); + + zkDiscoveryService = new ZkDiscoveryService(applicationEventPublisher, serviceInfoProvider, partitionService); + ReflectionTestUtils.setField(zkDiscoveryService, "zkUrl", zkServer.getConnectString()); + ReflectionTestUtils.setField(zkDiscoveryService, "zkRetryInterval", 100); + ReflectionTestUtils.setField(zkDiscoveryService, "zkConnectionTimeout", 3000); + ReflectionTestUtils.setField(zkDiscoveryService, "zkSessionTimeout", 3000); + ReflectionTestUtils.setField(zkDiscoveryService, "zkDir", "/thingsboard"); + ReflectionTestUtils.setField(zkDiscoveryService, "recalculateDelay", 0L); + zkDiscoveryService.init(); + zkDiscoveryService.onApplicationEvent(null); + } + + @AfterEach + public void tearDown() throws Exception { + ReflectionTestUtils.invokeMethod(zkDiscoveryService, "destroy"); + CloseableUtils.closeQuietly(observer); + zkServer.close(); + } + + @Test + public void publishCreatesSingleProtectedNodeAndExcludesItFromOtherServersTest() throws Exception { + List nodes = observer.getChildren().forPath(ZK_NODES_DIR); + + assertEquals(1, nodes.size()); + assertTrue(nodes.get(0).matches(PROTECTED_NODE_NAME_REGEX), nodes.get(0)); + assertEquals(ZK_NODES_DIR + "/" + nodes.get(0), ReflectionTestUtils.getField(zkDiscoveryService, "nodePath")); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> + assertTrue(zkDiscoveryService.getOtherServers().isEmpty())); + } + + @Test + public void sessionExpiryLeavesSingleNodeOwnedByCurrentSessionTest() throws Exception { + String nodeBeforeExpiry = observer.getChildren().forPath(ZK_NODES_DIR).get(0); + + zkDiscoveryService.getClient().getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); + + await().atMost(Duration.ofSeconds(30)) + .during(Duration.ofSeconds(2)) + .ignoreExceptions() + .untilAsserted(() -> { + List nodes = observer.getChildren().forPath(ZK_NODES_DIR); + assertEquals(1, nodes.size()); + String nodePath = ZK_NODES_DIR + "/" + nodes.get(0); + assertNotEquals(nodeBeforeExpiry, nodes.get(0)); + assertEquals(nodePath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath")); + Stat stat = observer.checkExists().forPath(nodePath); + long sessionId = zkDiscoveryService.getClient().getZookeeperClient().getZooKeeper().getSessionId(); + assertEquals(sessionId, stat.getEphemeralOwner()); + assertTrue(zkDiscoveryService.getOtherServers().isEmpty()); + }); + } + +} diff --git a/common/script/pom.xml b/common/script/pom.xml index 91d981539a..69ec57f099 100644 --- a/common/script/pom.xml +++ b/common/script/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/script/remote-js-client/pom.xml b/common/script/remote-js-client/pom.xml index 8e95509c70..34bad4c937 100644 --- a/common/script/remote-js-client/pom.xml +++ b/common/script/remote-js-client/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT script org.thingsboard.common.script diff --git a/common/script/script-api/pom.xml b/common/script/script-api/pom.xml index fa382f901e..aa740fd6e9 100644 --- a/common/script/script-api/pom.xml +++ b/common/script/script-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT script org.thingsboard.common.script diff --git a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java index cbdd753346..8075e70fe4 100644 --- a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java +++ b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java @@ -127,14 +127,22 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { @Override protected ListenableFuture doEval(UUID scriptId, JsScriptInfo scriptInfo, String jsScript) { + // A top-level function declaration creates a non-configurable property on the Nashorn Global + // that can never be deleted, so every eval/release cycle would grow the Global's PropertyMap + // shape history forever. Declaring the function inside an IIFE and assigning it to a global + // property keeps the property configurable, allowing doRelease() to actually delete it. + // The prefix stays on the first line to preserve line numbering on the raw engine path; + // the sandbox beautifier reformats the wrapper and shifts reported error lines anyway. + String wrappedScript = "this['" + scriptInfo.getFunctionName() + "'] = (function() { " + jsScript + + "\nreturn " + scriptInfo.getFunctionName() + ";\n})();"; return jsExecutor.submit(() -> { try { evalLock.lock(); try { if (useJsSandbox) { - sandbox.eval(jsScript); + sandbox.eval(wrappedScript); } else { - engine.eval(jsScript); + engine.eval(wrappedScript); } } finally { evalLock.unlock(); @@ -169,10 +177,16 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { } protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException { - if (useJsSandbox) { - sandbox.eval(scriptInfo.getFunctionName() + " = undefined;"); - } else { - engine.eval(scriptInfo.getFunctionName() + " = undefined;"); + String deleteScript = "delete this['" + scriptInfo.getFunctionName() + "'];"; + evalLock.lock(); + try { + if (useJsSandbox) { + sandbox.eval(deleteScript); + } else { + engine.eval(deleteScript); + } + } finally { + evalLock.unlock(); } } diff --git a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java new file mode 100644 index 0000000000..673e06d5a8 --- /dev/null +++ b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java @@ -0,0 +1,109 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.script.api.js; + +import delight.nashornsandbox.NashornSandbox; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.script.api.ScriptType; +import org.thingsboard.script.api.TbScriptException; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.stats.StatsFactory; + +import javax.script.ScriptEngine; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ExecutionException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +/** + * Covers the JS global scope lifecycle against both backends the service can be configured with. + * The Spring-wired {@code NashornJsInvokeServiceTest} only exercises the sandbox, since + * {@code js.local.use_js_sandbox} defaults to true. + */ +class NashornJsInvokeServiceLifecycleTest { + + private static final String[] ARG_NAMES = {"msg", "metadata", "msgType"}; + + private NashornJsInvokeService service; + private boolean useJsSandbox; + + @AfterEach + void tearDown() { + if (service != null) { + service.stop(); + } + } + + @ParameterizedTest(name = "useJsSandbox = {0}") + @ValueSource(booleans = {true, false}) + void whenScriptIsReleased_thenGlobalPropertyIsRemovedAndFunctionIsGone(boolean useJsSandbox) throws Exception { + givenService(useJsSandbox); + UUID scriptId = UUID.randomUUID(); + + JsScriptInfo scriptInfo = eval(scriptId, "return {doubled: msg.temperature * 2};"); + assertThat(hasGlobalProperty(scriptInfo)).isTrue(); + assertThat(invoke(scriptId, scriptInfo, "{\"temperature\":21}")).asString().contains("\"doubled\":42"); + + service.doRelease(scriptId); + + assertThat(hasGlobalProperty(scriptInfo)).isFalse(); + assertThatThrownBy(() -> invoke(scriptId, scriptInfo, "{\"temperature\":21}")) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class); + } + + @ParameterizedTest(name = "useJsSandbox = {0}") + @ValueSource(booleans = {true, false}) + void whenOneOfTwoScriptsIsReleased_thenTheOtherKeepsWorking(boolean useJsSandbox) throws Exception { + givenService(useJsSandbox); + UUID releasedId = UUID.randomUUID(); + UUID retainedId = UUID.randomUUID(); + + JsScriptInfo released = eval(releasedId, "return {v: 1};"); + JsScriptInfo retained = eval(retainedId, "return {v: 2};"); + + service.doRelease(releasedId); + + assertThat(hasGlobalProperty(released)).isFalse(); + assertThat(hasGlobalProperty(retained)).isTrue(); + assertThat(invoke(retainedId, retained, "{}")).asString().contains("\"v\":2"); + } + + private void givenService(boolean useJsSandbox) { + this.useJsSandbox = useJsSandbox; + service = new NashornJsInvokeService(Optional.empty(), Optional.empty()); + ReflectionTestUtils.setField(service, "statsFactory", mock(StatsFactory.class, Mockito.RETURNS_DEEP_STUBS)); + ReflectionTestUtils.setField(service, "useJsSandbox", useJsSandbox); + ReflectionTestUtils.setField(service, "jsExecutorThreadPoolSize", 4); + ReflectionTestUtils.setField(service, "monitorThreadPoolSize", 2); + ReflectionTestUtils.setField(service, "maxCpuTime", 8000L); + ReflectionTestUtils.setField(service, "maxMemory", 104857600L); + service.init(); + } + + private JsScriptInfo eval(UUID scriptId, String scriptBody) throws Exception { + service.doEvalScript(TenantId.SYS_TENANT_ID, ScriptType.RULE_NODE_SCRIPT, scriptBody, scriptId, ARG_NAMES).get(); + return service.scriptInfoMap.get(scriptId); + } + + private Object invoke(UUID scriptId, JsScriptInfo scriptInfo, String msg) throws Exception { + return service.doInvokeFunction(scriptId, scriptInfo, new Object[]{msg, "{}", "POST_TELEMETRY_REQUEST"}).get(); + } + + private boolean hasGlobalProperty(JsScriptInfo scriptInfo) throws Exception { + String expression = "this.hasOwnProperty('" + scriptInfo.getFunctionName() + "')"; + Object result = useJsSandbox + ? ((NashornSandbox) ReflectionTestUtils.getField(service, "sandbox")).eval(expression) + : ((ScriptEngine) ReflectionTestUtils.getField(service, "engine")).eval(expression); + return Boolean.TRUE.equals(result); + } + +} diff --git a/common/stats/pom.xml b/common/stats/pom.xml index a4952dd00c..54899d513d 100644 --- a/common/stats/pom.xml +++ b/common/stats/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/coap/pom.xml b/common/transport/coap/pom.xml index f20de1b5be..04ef7414f3 100644 --- a/common/transport/coap/pom.xml +++ b/common/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/http/pom.xml b/common/transport/http/pom.xml index 3caf3f5075..a5d1d80138 100644 --- a/common/transport/http/pom.xml +++ b/common/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/lwm2m/pom.xml b/common/transport/lwm2m/pom.xml index abc120673c..d7a019b50b 100644 --- a/common/transport/lwm2m/pom.xml +++ b/common/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java index 0dbb77d667..d592183440 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java @@ -38,7 +38,7 @@ public class LwM2MBootstrapConfig implements Serializable { * clientSecretKey?: string, * serverPublicKey?: string; * clientHoldOffTime?: number, - * serverId?: number, + * shortServerId?: number, // DM server only; null for the BS entry * bootstrapServerAccountTimeout: number * */ @Getter @@ -114,7 +114,7 @@ public class LwM2MBootstrapConfig implements Serializable { private BootstrapConfig.ServerConfig setServerConfig (AbstractLwM2MBootstrapServerCredential serverCredential) { BootstrapConfig.ServerConfig serverConfig = new BootstrapConfig.ServerConfig(); - if (serverCredential.getShortServerId() != null) { + if (!serverCredential.isBootstrapServerIs() && serverCredential.getShortServerId() != null) { serverConfig.shortId = serverCredential.getShortServerId(); } serverConfig.lifetime = serverCredential.getLifetime(); diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/config/LwM2MTransportServerConfig.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/config/LwM2MTransportServerConfig.java index 15f5a03555..6f2a510783 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/config/LwM2MTransportServerConfig.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/config/LwM2MTransportServerConfig.java @@ -81,7 +81,7 @@ public class LwM2MTransportServerConfig implements LwM2MSecureServerConfig { private int cleanPeriodInSec; @Getter - @Value("${transport.lwm2m.server.id:}") + @Value("${transport.lwm2m.server.id:123}") private Integer id; @Getter diff --git a/common/transport/mqtt/pom.xml b/common/transport/mqtt/pom.xml index a9b0ca9358..810645bf4d 100644 --- a/common/transport/mqtt/pom.xml +++ b/common/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/pom.xml b/common/transport/pom.xml index e1798af997..aaf91d43ed 100644 --- a/common/transport/pom.xml +++ b/common/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/snmp/pom.xml b/common/transport/snmp/pom.xml index d1ecc23f28..face915573 100644 --- a/common/transport/snmp/pom.xml +++ b/common/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.common - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml index 740d769bc4..75231178bc 100644 --- a/common/transport/transport-api/pom.xml +++ b/common/transport/transport-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/util/pom.xml b/common/util/pom.xml index 8a85073f32..565180b346 100644 --- a/common/util/pom.xml +++ b/common/util/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common diff --git a/common/util/src/main/java/org/thingsboard/common/util/SetCache.java b/common/util/src/main/java/org/thingsboard/common/util/SetCache.java index b191709740..5322ebc4ef 100644 --- a/common/util/src/main/java/org/thingsboard/common/util/SetCache.java +++ b/common/util/src/main/java/org/thingsboard/common/util/SetCache.java @@ -14,9 +14,19 @@ public class SetCache { private final Cache cache; public SetCache(long valueTtlMs) { - this.cache = Caffeine.newBuilder() - .expireAfterWrite(valueTtlMs, TimeUnit.MILLISECONDS) - .build(); + this(Caffeine.newBuilder().expireAfterWrite(valueTtlMs, TimeUnit.MILLISECONDS)); + } + + private SetCache(Caffeine builder) { + this.cache = builder.build(); + } + + /** + * Bounded by entry count with LRU-ish eviction, instead of a TTL - for callers that want to remember + * up to N recently seen keys rather than expire entries after a fixed duration. + */ + public static SetCache boundedBySize(int maximumSize) { + return new SetCache<>(Caffeine.newBuilder().maximumSize(maximumSize)); } public void add(K key) { diff --git a/common/version-control/pom.xml b/common/version-control/pom.xml index 548f4364d1..067fafe7d9 100644 --- a/common/version-control/pom.xml +++ b/common/version-control/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT common org.thingsboard.common @@ -58,6 +58,10 @@ com.google.guava guava + + org.checkerframework + checker-qual + com.fasterxml.jackson.core jackson-databind diff --git a/dao/pom.xml b/dao/pom.xml index e4792288a1..081d33ad5b 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard dao @@ -169,6 +169,10 @@ com.google.guava guava + + org.checkerframework + checker-qual + com.google.protobuf protobuf-java diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java index b763769f57..aba492ef07 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java @@ -169,7 +169,7 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator lwM2MBootstrapServersConfigurations = ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).getBootstrap(); if (lwM2MBootstrapServersConfigurations != null) { validateLwm2mServersConfigOfBootstrapForClient(lwM2MBootstrapServersConfigurations, - ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).isBootstrapServerUpdateEnable()); + ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).isBootstrapServerUpdateEnable(), deviceProfile); for (LwM2MBootstrapServerCredential bootstrapServerCredential : lwM2MBootstrapServersConfigurations) { validateLwm2mServersCredentialOfBootstrapForClient(bootstrapServerCredential); } @@ -333,9 +333,26 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator lwM2MBootstrapServersConfigurations, boolean isBootstrapServerUpdateEnable) { + /** + Validates the list of LwM2M / Bootstrap Server configurations for client transport. + OMA LwM2M Specification Compliance & Validation Rules: + - OMA LwM2M Core TS 1.1.1 (Object 0 - LwM2M Security, Resource 10 Short Server ID): + According to section 3.2 and Object 0 Resource 10 specification, Short Server ID (range 1..65534) + identifies a regular LwM2M Server Account and links Object 0 to Object 1. + It MUST be set when Bootstrap-Server is false, but is NOT applicable to a + Bootstrap Server Account (Bootstrap-Server = true) as there is no associated Object 1 Instance. + See: http://www.openmobilealliance.org/release/LightweightM2M/V1_1_1-20190617-A/OMA-TS-LightweightM2M_Core-V1_1_1-20190617-A.pdf + - Backward Compatibility (ThingsBoard <= 4.2): + Non-null shortServerId on Bootstrap Server is normalized to null with a warning. + - Single Bootstrap Server Constraint: + Only one Bootstrap Server configuration is allowed per transport setup. + */ + private void validateLwm2mServersConfigOfBootstrapForClient(List lwM2MBootstrapServersConfigurations, + boolean isBootstrapServerUpdateEnable, DeviceProfile deviceProfile) { Set uris = new HashSet<>(); Set shortServerIds = new HashSet<>(); + boolean hasBootstrapServer = false; + for (LwM2MBootstrapServerCredential bootstrapServerCredential : lwM2MBootstrapServersConfigurations) { AbstractLwM2MBootstrapServerCredential serverConfig = (AbstractLwM2MBootstrapServerCredential) bootstrapServerCredential; if (!isBootstrapServerUpdateEnable && serverConfig.isBootstrapServerIs()) { @@ -343,14 +360,21 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator getClusterId() { + return jdbcTemplate.query("SELECT cluster_id FROM tb_cluster ORDER BY cluster_id LIMIT 1", + rs -> rs.next() ? Optional.ofNullable(rs.getObject("cluster_id", UUID.class)) : Optional.empty()); + } + + public Optional getLicenseSecret() { + return getColumn("license_secret"); + } + + public void saveLicenseSecret(String secret) { + updateColumn("license_secret", secret, "license secret"); + } + + public Optional getLicenseClaimToken() { + return getColumn("license_claim_token"); + } + + public void saveLicenseClaimToken(String claimToken) { + updateColumn("license_claim_token", claimToken, "license claim token"); + } + + public void forceClearLicenseClaimToken() { + try { + jdbcTemplate.update("UPDATE tb_cluster SET license_claim_token = NULL"); + } catch (Exception e) { + log.warn("Failed to clear the license claim token", e); + } + } + + public void clearLicenseClaimToken(String expectedClaimToken) { + try { + jdbcTemplate.update("UPDATE tb_cluster SET license_claim_token = NULL WHERE license_claim_token = ?", + expectedClaimToken); + } catch (Exception e) { + log.warn("Failed to clear the license claim token", e); + } + } + + // The column name is concatenated into the statement: pass only compile-time constants. + private Optional getColumn(String column) { + return jdbcTemplate.query("SELECT " + column + " FROM tb_cluster ORDER BY cluster_id LIMIT 1", + rs -> rs.next() ? Optional.ofNullable(rs.getString(column)) : Optional.empty()); + } + + private void updateColumn(String column, String value, String description) { + int updatedRows = jdbcTemplate.update("UPDATE tb_cluster SET " + column + " = ?", value); + if (updatedRows == 0) { + log.error("Failed to store the {}: table tb_cluster is empty; the install or upgrade that creates " + + "its row has not completed", description); + throw new IllegalStateException("Failed to store the " + description + ": table tb_cluster is empty"); + } + } +} diff --git a/dao/src/main/resources/sql/schema-entities.sql b/dao/src/main/resources/sql/schema-entities.sql index b2af919cae..7b86f84231 100644 --- a/dao/src/main/resources/sql/schema-entities.sql +++ b/dao/src/main/resources/sql/schema-entities.sql @@ -3,6 +3,18 @@ -- SPDX-License-Identifier: Apache-2.0 -- +-- Also created by upgrade/lts/4.3.1.6/schema_update.sql; keep the two in sync. +CREATE TABLE IF NOT EXISTS tb_cluster ( + cluster_id uuid NOT NULL, + license_claim_token varchar, + license_secret varchar, + CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id) +); + +-- Backstop against two concurrent install jobs both minting an id: a unique index on a constant +-- expression allows at most one row in the table, no matter how many rows race to insert. +CREATE UNIQUE INDEX IF NOT EXISTS tb_cluster_single_row ON tb_cluster ((true)); + CREATE TABLE IF NOT EXISTS tb_schema_settings ( schema_version bigint NOT NULL, diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java index a51ef9b68c..2231b52d2e 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java @@ -33,6 +33,7 @@ import java.util.List; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.verify; import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.LWM2M_SERVER_MAX; @@ -65,7 +66,7 @@ class DeviceProfileDataValidatorTest { " }"; private static final String msgErrorLwm2mRange = "LwM2M Server ShortServerId must be in range [" + PRIMARY_LWM2M_SERVER.getId() + " - " + LWM2M_SERVER_MAX.getId() + "]!"; - private static final String msgErrorBsRange = "Bootstrap Server ShortServerId must be null!"; + private static final String msgErrorBsOnlyOne = "Only one Bootstrap Server configuration is allowed!"; private static final String msgErrorNotNull = " Server ShortServerId must not be null!"; private static final String host = "localhost"; private static final String hostBs = "localhost"; @@ -115,50 +116,59 @@ class DeviceProfileDataValidatorTest { void testValidateDeviceProfile_Lwm2mBootstrap_ShortServerId_Ok() { Integer shortServerId = 123; Integer shortServerIdBs = null; - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs); + DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, false); validator.validateDataImpl(tenantId, deviceProfile); verify(validator).validateString("Device profile name", deviceProfile.getName()); } @Test - void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_validate_0_to_null_Ok() { - Integer shortServerId = 123; - Integer shortServerIdBs = 0; - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs); + void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_validate_0_to_null_Warn() { + validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(0); + } - validator.validateDataImpl(tenantId, deviceProfile); - verify(validator).validateString("Device profile name", deviceProfile.getName()); + @Test + void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_More_65535_to_null_Warn() { + validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(65536); + } + + @Test + void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_111_to_null_Warn() { + validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(111); } @Test - void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_More_65535_Error() { - verifyValidationError(123, 65536, msgErrorBsRange); + void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Less_0_to_null_Warn() { + validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(-1); } @Test - void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Less_0_Error() { - verifyValidationError(123, -1, msgErrorBsRange); + void testValidateDeviceProfile_Lwm2mShortServerId_null_Error_BootstrapShortServerId_null_Ok() { + verifyValidationError(null, null, "LwM2M" + msgErrorNotNull, false); } @Test - void testValidateDeviceProfile_Lwm2mShortServerId_null_Error_BootstrapShortServerId_Ok() { - verifyValidationError(null, 1, "LwM2M" + msgErrorNotNull); + void testValidateDeviceProfile_Lwm2mShortServerId_More_65534_Error_BootstrapShortServerId_null_Ok() { + verifyValidationError(NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(), null, msgErrorLwm2mRange, false); } @Test - void testValidateDeviceProfile_Lwm2mShortServerId_More_65534_Error_BootstrapShortServerId_Ok() { - verifyValidationError(NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(), 111, msgErrorLwm2mRange); + void testValidateDeviceProfile_Lwm2mShortServerId_Less_1_Error_BootstrapShortServerId_null_Ok() { + verifyValidationError(0, null, msgErrorLwm2mRange, false); } @Test - void testValidateDeviceProfile_Lwm2mShortServerId_Less_1_Error_BootstrapShortServerId_Ok() { - verifyValidationError(0, 111, msgErrorLwm2mRange); + void testValidateDeviceProfile_MoreThanOneBootstrapServer_Error() { + verifyValidationError(123, null, msgErrorBsOnlyOne, true); } - private DeviceProfile getDeviceProfile(Integer shortServerId, Integer shortServerIdBs) { + private DeviceProfile getDeviceProfile(Integer shortServerId, Integer shortServerIdBs, boolean withSecondBsServer) { Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsNoSec(shortServerId, shortServerIdBs)); + if (withSecondBsServer) { + AbstractLwM2MBootstrapServerCredential bootstrapServerCredentialNoSecTwo = getBootstrapServerCredentialNoSec(true, shortServerId, shortServerIdBs == null ? 111 : ++shortServerIdBs); + transportConfiguration.getBootstrap().add(bootstrapServerCredentialNoSecTwo); + } DeviceProfile deviceProfile = new DeviceProfile(); deviceProfile.setName("default"); deviceProfile.setType(DeviceProfileType.DEFAULT); @@ -198,11 +208,30 @@ class DeviceProfileDataValidatorTest { return bootstrapServerCredential; } - private void verifyValidationError(Integer shortServerId, Integer shortServerIdBs, String msgError) { - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs); + private void verifyValidationError(Integer shortServerId, Integer shortServerIdBs, String msgError, boolean withSecondBsServer) { + DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, withSecondBsServer); assertThatThrownBy(() -> validator.validateDataImpl(tenantId, deviceProfile)) .hasMessageContaining(msgError); } + private LwM2MBootstrapServerCredential getBootstrapCredential(DeviceProfile deviceProfile) { + Lwm2mDeviceProfileTransportConfiguration transportConfig = + (Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration(); + + return transportConfig.getBootstrap().stream() + .filter(credential -> ((AbstractLwM2MBootstrapServerCredential)credential).isBootstrapServerIs()) + .findFirst() + .orElseThrow(() -> new AssertionError("Bootstrap server not found in profile")); + } + + + private void validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(Integer shortServerIdBs) { + DeviceProfile deviceProfile = getDeviceProfile(123, shortServerIdBs, false); + validator.validateDataImpl(tenantId, deviceProfile); + verify(validator).validateString("Device profile name", deviceProfile.getName()); + LwM2MBootstrapServerCredential bsCredential = getBootstrapCredential(deviceProfile); + assertThat(((AbstractLwM2MBootstrapServerCredential) bsCredential).getShortServerId()).isNull(); + } + } diff --git a/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java b/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java new file mode 100644 index 0000000000..502f04de8c --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java @@ -0,0 +1,145 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.dao.subscription; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.thingsboard.server.dao.service.AbstractServiceTest; +import org.thingsboard.server.dao.service.DaoSqlTest; + +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +@DaoSqlTest +public class TbClusterStoreTest extends AbstractServiceTest { + + @Autowired + private TbClusterStore tbClusterStore; + + @Autowired + private JdbcTemplate jdbcTemplate; + + private final UUID clusterId = UUID.randomUUID(); + + @Before + public void seedClusterRow() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?)", clusterId); + } + + @After + public void cleanUpClusterRow() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + } + + @Test + public void testGetClusterId() { + assertThat(tbClusterStore.getClusterId()).contains(clusterId); + } + + @Test + public void testGetClusterIdOnEmptyTable() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + assertThat(tbClusterStore.getClusterId()).isEmpty(); + } + + @Test + public void testSecondRowInsertIsRejectedByUniqueIndex() { + UUID other = new UUID(0, 0); + assertThatThrownBy(() -> jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?)", other)) + .isInstanceOf(DataIntegrityViolationException.class); + + assertThat(tbClusterStore.getClusterId()).contains(clusterId); + } + + @Test + public void testSaveAndReadLicenseClaimToken() { + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + tbClusterStore.saveLicenseClaimToken("token-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).contains("token-one"); + tbClusterStore.saveLicenseClaimToken("token-two"); + assertThat(tbClusterStore.getLicenseClaimToken()).contains("token-two"); + } + + @Test + public void testSaveAndReadLicenseSecret() { + assertThat(tbClusterStore.getLicenseSecret()).isEmpty(); + tbClusterStore.saveLicenseSecret("secret-one"); + assertThat(tbClusterStore.getLicenseSecret()).contains("secret-one"); + tbClusterStore.saveLicenseSecret("secret-two"); + assertThat(tbClusterStore.getLicenseSecret()).contains("secret-two"); + } + + @Test + public void testLicenseSecretAndClaimTokenAreStoredApart() { + tbClusterStore.saveLicenseSecret("secret-one"); + tbClusterStore.saveLicenseClaimToken("token-one"); + tbClusterStore.clearLicenseClaimToken("token-one"); + + assertThat(tbClusterStore.getLicenseSecret()).contains("secret-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + } + + @Test + public void testSaveLicenseSecretFailsWhenClusterRowIsMissing() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + assertThatThrownBy(() -> tbClusterStore.saveLicenseSecret("secret-one")) + .isInstanceOf(IllegalStateException.class); + assertThat(tbClusterStore.getLicenseSecret()).isEqualTo(Optional.empty()); + } + + @Test + public void testClearLicenseClaimToken() { + tbClusterStore.saveLicenseClaimToken("token-one"); + tbClusterStore.forceClearLicenseClaimToken(); + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + } + + @Test + public void testCompareAndClearRetiresOnlyTheExpectedToken() { + tbClusterStore.saveLicenseClaimToken("token-one"); + tbClusterStore.clearLicenseClaimToken("token-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + + tbClusterStore.saveLicenseClaimToken("token-two"); + tbClusterStore.clearLicenseClaimToken("token-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).contains("token-two"); + } + + @Test + public void testSaveFailsWhenClusterRowIsMissing() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + assertThatThrownBy(() -> tbClusterStore.saveLicenseClaimToken("token-one")) + .isInstanceOf(IllegalStateException.class); + assertThat(tbClusterStore.getLicenseClaimToken()).isEqualTo(Optional.empty()); + } + + @Test + public void testClearNeverThrowsWhenClusterRowIsMissing() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + tbClusterStore.forceClearLicenseClaimToken(); + tbClusterStore.clearLicenseClaimToken("token-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + } + + @Test + public void testClearSwallowsAStoreFailureRatherThanPropagatingIt() { + JdbcTemplate failing = mock(JdbcTemplate.class, invocation -> { + throw new DataAccessResourceFailureException("the database is unreachable"); + }); + TbClusterStore store = new TbClusterStore(failing); + + assertThatCode(store::forceClearLicenseClaimToken).doesNotThrowAnyException(); + assertThatCode(() -> store.clearLicenseClaimToken("token-one")).doesNotThrowAnyException(); + } +} diff --git a/dao/src/test/resources/sql/psql/drop-all-tables.sql b/dao/src/test/resources/sql/psql/drop-all-tables.sql index 0387658f2d..bbdcfd751a 100644 --- a/dao/src/test/resources/sql/psql/drop-all-tables.sql +++ b/dao/src/test/resources/sql/psql/drop-all-tables.sql @@ -54,6 +54,7 @@ DROP TABLE IF EXISTS rule_node_state; DROP TABLE IF EXISTS rule_node; DROP TABLE IF EXISTS rule_chain; DROP TABLE IF EXISTS tb_schema_settings; +DROP TABLE IF EXISTS tb_cluster; DROP TABLE IF EXISTS oauth2_mobile; DROP TABLE IF EXISTS oauth2_domain; DROP TABLE IF EXISTS oauth2_registration; diff --git a/edqs/pom.xml b/edqs/pom.xml index 3efa303bfe..2025f9c907 100644 --- a/edqs/pom.xml +++ b/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard edqs diff --git a/monitoring/pom.xml b/monitoring/pom.xml index 4b3028010b..f5e26129b0 100644 --- a/monitoring/pom.xml +++ b/monitoring/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard diff --git a/msa/black-box-tests/pom.xml b/msa/black-box-tests/pom.xml index ad2bb78189..4e6333db20 100644 --- a/msa/black-box-tests/pom.xml +++ b/msa/black-box-tests/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/edqs/pom.xml b/msa/edqs/pom.xml index ac55319183..4e00abdf90 100644 --- a/msa/edqs/pom.xml +++ b/msa/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/js-executor/docker/Dockerfile b/msa/js-executor/docker/Dockerfile index 80d05f7665..36d73503af 100644 --- a/msa/js-executor/docker/Dockerfile +++ b/msa/js-executor/docker/Dockerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # -FROM thingsboard/node:22.22.2-bookworm-slim +FROM thingsboard/node:22.23.4-bookworm-slim ENV NODE_ENV production ENV DOCKER_MODE true diff --git a/msa/js-executor/package.json b/msa/js-executor/package.json index 49ee39c2a7..20cea148e3 100644 --- a/msa/js-executor/package.json +++ b/msa/js-executor/package.json @@ -1,15 +1,15 @@ { "name": "thingsboard-js-executor", "private": true, - "version": "4.3.1.6", + "version": "4.3.1.7", "description": "ThingsBoard JavaScript Executor Microservice", "main": "server.ts", "bin": "server.js", "scripts": { "pkg": "tsc && pkg -t node22-linux-x64 --output ./target/thingsboard-js-executor-linux ./target/src && pkg -t node22-win-x64 --no-bytecode --public-packages \"*\" --public --output ./target/thingsboard-js-executor-win.exe ./target/src && node install.js", "test": "mkdir -p target/surefire-reports && node --require ts-node/register --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=target/surefire-reports/TEST-js-executor.xml test/jsExecutor.test.ts", - "start": "nodemon --watch '.' --ext 'ts' --exec 'ts-node server.ts'", - "start-prod": "nodemon --watch '.' --ext 'ts' --exec 'NODE_ENV=production ts-node server.ts'", + "start": "node --watch --watch-preserve-output -r ts-node/register server.ts", + "start-prod": "NODE_ENV=production node --watch --watch-preserve-output -r ts-node/register server.ts", "build": "tsc" }, "dependencies": { @@ -38,7 +38,6 @@ "@types/uuid-parse": "^1.0.2", "@yao-pkg/pkg": "^6.6.0", "fs-extra": "^11.3.1", - "nodemon": "^3.1.10", "ts-node": "^10.9.2", "typescript": "~5.9.3" }, diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index a8b4e0b89b..e8b0dfb949 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa @@ -30,6 +30,13 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows + + ${skip.yarn} pre-integration-test @@ -112,7 +119,7 @@ test - ${maven.test.skip} + ${yarn.test.skip} --mutex network run test @@ -206,6 +213,18 @@ + + skip-yarn-test + + + maven.test.skip + true + + + + true + + yarn-start diff --git a/msa/js-executor/yarn.lock b/msa/js-executor/yarn.lock index e4f6409a3d..8324b3a83d 100644 --- a/msa/js-executor/yarn.lock +++ b/msa/js-executor/yarn.lock @@ -379,14 +379,6 @@ ansi-styles@^4.0.0: dependencies: color-convert "^2.0.1" -anymatch@~3.1.2: - version "3.1.3" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e" - integrity sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw== - dependencies: - normalize-path "^3.0.0" - picomatch "^2.0.4" - arg@^4.1.0: version "4.1.3" resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089" @@ -402,21 +394,11 @@ async@^3.2.3: resolved "https://registry.yarnpkg.com/async/-/async-3.2.6.tgz#1b0728e14929d51b85b449b7f06e27c1145e38ce" integrity sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA== -balanced-match@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" - integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== - base64-js@^1.3.1: version "1.5.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== -binary-extensions@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.3.0.tgz#f6e14a97858d327252200242d4ccfe522c445522" - integrity sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw== - bl@^4.0.3: version "4.1.0" resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a" @@ -446,21 +428,6 @@ body-parser@^2.2.0: raw-body "^3.0.0" type-is "^2.0.0" -brace-expansion@^1.1.7: - version "1.1.18" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.18.tgz#3ce74d89885136be1535341f8c3d4425c29a5cab" - integrity sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -braces@~3.0.2: - version "3.0.3" - resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.3.tgz#490332f40919452272d55a8480adc0c441358789" - integrity sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA== - dependencies: - fill-range "^7.1.1" - buffer@^5.5.0: version "5.7.1" resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0" @@ -490,21 +457,6 @@ call-bound@^1.0.2: call-bind-apply-helpers "^1.0.2" get-intrinsic "^1.3.0" -chokidar@^3.5.2: - version "3.6.0" - resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.6.0.tgz#197c6cc669ef2a8dc5e7b4d97ee4e092c3eb0d5b" - integrity sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw== - dependencies: - anymatch "~3.1.2" - braces "~3.0.2" - glob-parent "~5.1.2" - is-binary-path "~2.1.0" - is-glob "~4.0.1" - normalize-path "~3.0.0" - readdirp "~3.6.0" - optionalDependencies: - fsevents "~2.3.2" - chownr@^1.1.1: version "1.1.4" resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" @@ -572,11 +524,6 @@ colorspace@1.1.x: color "^3.1.3" text-hex "1.0.x" -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== - config@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/config/-/config-4.1.1.tgz#798f636e2a5b7baa7050280d1eb21f8e10abb8c9" @@ -616,7 +563,7 @@ create-require@^1.1.0: resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== -debug@4, debug@^4, debug@^4.3.5, debug@^4.4.0: +debug@4, debug@^4.3.5, debug@^4.4.0: version "4.4.1" resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.1.tgz#e5a8bc6cbc4c6cd3e64308b0693a3d4fa550189b" integrity sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ== @@ -780,13 +727,6 @@ file-stream-rotator@^0.6.1: dependencies: moment "^2.29.1" -fill-range@^7.1.1: - version "7.1.1" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.1.1.tgz#44265d3cac07e3ea7dc247516380643754a05292" - integrity sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg== - dependencies: - to-regex-range "^5.0.1" - finalhandler@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-2.1.0.tgz#72306373aa89d05a8242ed569ed86a1bff7c561f" @@ -836,11 +776,6 @@ fs-extra@^11.2.0, fs-extra@^11.3.1: jsonfile "^6.0.1" universalify "^2.0.0" -fsevents@~2.3.2: - version "2.3.3" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6" - integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw== - function-bind@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c" @@ -880,13 +815,6 @@ github-from-package@0.0.0: resolved "https://registry.yarnpkg.com/github-from-package/-/github-from-package-0.0.0.tgz#97fb5d96bfde8973313f20e8288ef9a167fa64ce" integrity sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw== -glob-parent@~5.1.2: - version "5.1.2" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" - integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== - dependencies: - is-glob "^4.0.1" - gopd@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1" @@ -897,11 +825,6 @@ graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.2: resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== -has-flag@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" - integrity sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw== - has-symbols@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.1.0.tgz#fc9c6a783a084951d0b971fe1018de813707a338" @@ -945,11 +868,6 @@ ieee754@^1.1.13: resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== -ignore-by-default@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/ignore-by-default/-/ignore-by-default-1.0.1.tgz#48ca6d72f6c6a3af00a9ad4ae6876be3889e2b09" - integrity sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA== - inherits@2.0.4, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" @@ -978,13 +896,6 @@ is-arrayish@^0.3.1: resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.3.2.tgz#4574a2ae56f7ab206896fb431eaeed066fdf8f03" integrity sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ== -is-binary-path@~2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" - integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== - dependencies: - binary-extensions "^2.0.0" - is-core-module@^2.16.0: version "2.16.1" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.16.1.tgz#2a98801a849f43e2add644fbb6bc6229b19a4ef4" @@ -992,28 +903,11 @@ is-core-module@^2.16.0: dependencies: hasown "^2.0.2" -is-extglob@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" - integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ== - is-fullwidth-code-point@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== -is-glob@^4.0.1, is-glob@~4.0.1: - version "4.0.3" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" - integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg== - dependencies: - is-extglob "^2.1.1" - -is-number@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" - integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== - is-promise@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-promise/-/is-promise-4.0.0.tgz#42ff9f84206c1991d26debf520dd5c01042dd2f3" @@ -1140,13 +1034,6 @@ mimic-response@^3.1.0: resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== -minimatch@^3.1.2: - version "3.1.5" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.5.tgz#580c88f8d5445f2bd6aa8f3cadefa0de79fbd69e" - integrity sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w== - dependencies: - brace-expansion "^1.1.7" - minimist@^1.2.0, minimist@^1.2.3, minimist@^1.2.6: version "1.2.8" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" @@ -1170,9 +1057,9 @@ mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== moment@^2.29.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== ms@^2.1.1, ms@^2.1.3: version "2.1.3" @@ -1216,33 +1103,12 @@ node-int64@^0.4.0: resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b" integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw== -nodemon@^3.1.10: - version "3.1.10" - resolved "https://registry.yarnpkg.com/nodemon/-/nodemon-3.1.10.tgz#5015c5eb4fffcb24d98cf9454df14f4fecec9bc1" - integrity sha512-WDjw3pJ0/0jMFmyNDp3gvY2YizjLmmOUQo6DEBY+JgdvW/yQ9mEeSw6H5ythl5Ny2ytb7f9C2nIbjSxMNzbJXw== - dependencies: - chokidar "^3.5.2" - debug "^4" - ignore-by-default "^1.0.1" - minimatch "^3.1.2" - pstree.remy "^1.1.8" - semver "^7.5.3" - simple-update-notifier "^2.0.0" - supports-color "^5.5.0" - touch "^3.1.0" - undefsafe "^2.0.5" - -normalize-path@^3.0.0, normalize-path@~3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" - integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== - object-hash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/object-hash/-/object-hash-3.0.0.tgz#73f97f753e7baffc0e2cc9d6e079079744ac82e9" integrity sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw== -object-inspect@^1.13.3: +object-inspect@^1.13.3, object-inspect@^1.13.4: version "1.13.4" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.4.tgz#8375265e21bc20d0fa582c22e1b13485d6e00213" integrity sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew== @@ -1293,11 +1159,6 @@ picocolors@^1.1.0: resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== -picomatch@^2.0.4, picomatch@^2.2.1: - version "2.3.2" - resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.2.tgz#5a942915e26b372dc0f0e6753149a16e6b1c5601" - integrity sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA== - picomatch@^4.0.2: version "4.0.4" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.4.tgz#fd6f5e00a143086e074dffe4c924b8fb293b0589" @@ -1332,18 +1193,13 @@ progress@^2.0.3: integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== proxy-addr@^2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" -pstree.remy@^1.1.8: - version "1.1.8" - resolved "https://registry.yarnpkg.com/pstree.remy/-/pstree.remy-1.1.8.tgz#c242224f4a67c21f686839bbdb4ac282b8373d3a" - integrity sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w== - pump@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.3.tgz#151d979f1a29668dc0025ec589a455b53282268d" @@ -1353,11 +1209,12 @@ pump@^3.0.0: once "^1.3.1" qs@^6.14.0: - version "6.14.2" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.14.2.tgz#b5634cf9d9ad9898e31fba3504e866e8efb6798c" - integrity sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q== + version "6.16.1" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.16.1.tgz#0643e17993e551759c85078e1f0bc4b9fe908020" + integrity sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg== dependencies: - side-channel "^1.1.0" + es-define-property "^1.0.1" + side-channel "^1.1.1" range-parser@^1.2.1: version "1.2.1" @@ -1406,13 +1263,6 @@ readable-stream@^3.1.1, readable-stream@^3.4.0, readable-stream@^3.6.0, readable string_decoder "^1.1.1" util-deprecate "^1.0.1" -readdirp@~3.6.0: - version "3.6.0" - resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" - integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA== - dependencies: - picomatch "^2.2.1" - require-directory@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" @@ -1458,7 +1308,7 @@ safe-stable-stringify@^2.3.1: resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== -semver@^7.3.5, semver@^7.5.3: +semver@^7.3.5: version "7.7.2" resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.2.tgz#67d99fdcd35cec21e6f8b87a7fd515a33f982b58" integrity sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA== @@ -1495,13 +1345,13 @@ setprototypeof@1.2.0: resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw== -side-channel-list@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.0.tgz#10cb5984263115d3b7a0e336591e290a830af8ad" - integrity sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA== +side-channel-list@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.1.tgz#c2e0b5a14a540aebee3bbc6c3f8666cc9b509127" + integrity sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w== dependencies: es-errors "^1.3.0" - object-inspect "^1.13.3" + object-inspect "^1.13.4" side-channel-map@^1.0.1: version "1.0.1" @@ -1524,14 +1374,14 @@ side-channel-weakmap@^1.0.2: object-inspect "^1.13.3" side-channel-map "^1.0.1" -side-channel@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.0.tgz#c3fcff9c4da932784873335ec9765fa94ff66bc9" - integrity sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw== +side-channel@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.1.tgz#ea02c62e05dc4bea67d4442f0fb71ee192f8e0ab" + integrity sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ== dependencies: es-errors "^1.3.0" - object-inspect "^1.13.3" - side-channel-list "^1.0.0" + object-inspect "^1.13.4" + side-channel-list "^1.0.1" side-channel-map "^1.0.1" side-channel-weakmap "^1.0.2" @@ -1556,13 +1406,6 @@ simple-swizzle@^0.2.2: dependencies: is-arrayish "^0.3.1" -simple-update-notifier@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz#d70b92bdab7d6d90dfd73931195a30b6e3d7cebb" - integrity sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w== - dependencies: - semver "^7.5.3" - stack-trace@0.0.x: version "0.0.10" resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0" @@ -1620,13 +1463,6 @@ strip-json-comments@~2.0.1: resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" integrity sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ== -supports-color@^5.5.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" - integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== - dependencies: - has-flag "^3.0.0" - supports-preserve-symlinks-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" @@ -1677,23 +1513,11 @@ tinyglobby@^0.2.11: fdir "^6.4.4" picomatch "^4.0.2" -to-regex-range@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" - integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== - dependencies: - is-number "^7.0.0" - toidentifier@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA== -touch@^3.1.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/touch/-/touch-3.1.1.tgz#097a23d7b161476435e5c1344a95c0f75b4a5694" - integrity sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA== - tr46@~0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" @@ -1744,11 +1568,6 @@ typescript@~5.9.3: resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.9.3.tgz#5b4f59e15310ab17a216f5d6cf53ee476ede670f" integrity sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw== -undefsafe@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/undefsafe/-/undefsafe-2.0.5.tgz#38733b9327bdcd226db889fb723a6efd162e6e2c" - integrity sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA== - undici-types@~6.21.0: version "6.21.0" resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.21.0.tgz#691d00af3909be93a7faa13be61b3a5b50ef12cb" diff --git a/msa/monitoring/pom.xml b/msa/monitoring/pom.xml index 8075897e21..5c18c3e215 100644 --- a/msa/monitoring/pom.xml +++ b/msa/monitoring/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa diff --git a/msa/pom.xml b/msa/pom.xml index 65d7982530..5ec171bd05 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard msa @@ -55,10 +55,7 @@ - + skip-deb @@ -71,9 +68,9 @@ none - + skip-pkg @@ -86,6 +83,31 @@ none + + + skip-pkg-without-yarn + + + skip.yarn + true + + + + none + + + + skip-pkg-without-ui-build + + + skip.ui.build + true + + + + none + + black-box-tests @@ -167,7 +189,7 @@ 4.3.1-latest - false + true diff --git a/msa/tb-node/pom.xml b/msa/tb-node/pom.xml index 3f508c9dcc..d40d203086 100644 --- a/msa/tb-node/pom.xml +++ b/msa/tb-node/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/tb/pom.xml b/msa/tb/pom.xml index 3027ff28e7..b44ecf5143 100644 --- a/msa/tb/pom.xml +++ b/msa/tb/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/coap/pom.xml b/msa/transport/coap/pom.xml index 76302d0ffb..0f4a69e1e0 100644 --- a/msa/transport/coap/pom.xml +++ b/msa/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/http/pom.xml b/msa/transport/http/pom.xml index 9a8c147bd8..cc88bda654 100644 --- a/msa/transport/http/pom.xml +++ b/msa/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/lwm2m/pom.xml b/msa/transport/lwm2m/pom.xml index 74a3b9e498..047c811fea 100644 --- a/msa/transport/lwm2m/pom.xml +++ b/msa/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/mqtt/pom.xml b/msa/transport/mqtt/pom.xml index af06f7fcf8..ae81270032 100644 --- a/msa/transport/mqtt/pom.xml +++ b/msa/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/pom.xml b/msa/transport/pom.xml index 8abef18aec..ed92e37fc4 100644 --- a/msa/transport/pom.xml +++ b/msa/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/snmp/pom.xml b/msa/transport/snmp/pom.xml index 96fdd18fb3..92de363fa9 100644 --- a/msa/transport/snmp/pom.xml +++ b/msa/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa transport - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT org.thingsboard.msa.transport diff --git a/msa/vc-executor-docker/pom.xml b/msa/vc-executor-docker/pom.xml index 630dba898c..706ab1f216 100644 --- a/msa/vc-executor-docker/pom.xml +++ b/msa/vc-executor-docker/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/vc-executor/pom.xml b/msa/vc-executor/pom.xml index 5dea597287..76cb986471 100644 --- a/msa/vc-executor/pom.xml +++ b/msa/vc-executor/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/web-ui/docker/Dockerfile b/msa/web-ui/docker/Dockerfile index 78fd5bcb90..692715ba50 100644 --- a/msa/web-ui/docker/Dockerfile +++ b/msa/web-ui/docker/Dockerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # -FROM thingsboard/node:22.22.2-bookworm-slim +FROM thingsboard/node:22.23.4-bookworm-slim ENV NODE_ENV production ENV DOCKER_MODE true diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index c32a7d20c8..b0471b02db 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -1,19 +1,19 @@ { "name": "thingsboard-web-ui", "private": true, - "version": "4.3.1.6", + "version": "4.3.1.7", "description": "ThingsBoard Web UI Microservice", "main": "server.ts", "bin": "server.js", "scripts": { "pkg": "tsc && pkg -t node22-linux-x64 --output ./target/thingsboard-web-ui-linux ./target/src && pkg -t node22-win-x64 --no-bytecode --public-packages \"*\" --public --output ./target/thingsboard-web-ui-win.exe ./target/src && node install.js", "test": "echo \"Error: no test specified\" && exit 1", - "start": "nodemon --watch '.' --ext 'ts' --exec 'WEB_FOLDER=./target/web ts-node server.ts'", - "start-prod": "nodemon --watch '.' --ext 'ts' --exec 'WEB_FOLDER=./target/web NODE_ENV=production ts-node server.ts'", + "start": "WEB_FOLDER=./target/web node --watch --watch-preserve-output -r ts-node/register server.ts", + "start-prod": "WEB_FOLDER=./target/web NODE_ENV=production node --watch --watch-preserve-output -r ts-node/register server.ts", "build": "tsc" }, "dependencies": { - "compression": "^1.8.1", + "compression": "^1.8.2", "config": "^3.3.12", "connect-history-api-fallback": "1.6.0", "express": "^5.1.0", @@ -40,7 +40,6 @@ "@types/node": "~22.17.2", "@yao-pkg/pkg": "^6.6.0", "fs-extra": "^11.3.1", - "nodemon": "^3.1.10", "ts-node": "^10.9.2", "typescript": "~5.9.3" }, diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index f3e2586759..be5bff4f85 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT msa org.thingsboard.msa @@ -60,6 +60,9 @@ target ${basedir} + + ${skip.ui.build} diff --git a/msa/web-ui/yarn.lock b/msa/web-ui/yarn.lock index 3e96bc2e85..5b60359934 100644 --- a/msa/web-ui/yarn.lock +++ b/msa/web-ui/yarn.lock @@ -311,14 +311,6 @@ ansi-styles@^4.0.0: dependencies: color-convert "^2.0.1" -anymatch@~3.1.2: - version "3.1.3" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e" - integrity sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw== - dependencies: - normalize-path "^3.0.0" - picomatch "^2.0.4" - arg@^4.1.0: version "4.1.3" resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089" @@ -334,21 +326,11 @@ async@^3.2.3: resolved "https://registry.yarnpkg.com/async/-/async-3.2.6.tgz#1b0728e14929d51b85b449b7f06e27c1145e38ce" integrity sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA== -balanced-match@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" - integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== - base64-js@^1.3.1: version "1.5.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== -binary-extensions@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.3.0.tgz#f6e14a97858d327252200242d4ccfe522c445522" - integrity sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw== - bl@^4.0.3: version "4.1.0" resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a" @@ -378,21 +360,6 @@ body-parser@^2.2.0: raw-body "^3.0.0" type-is "^2.0.0" -brace-expansion@^1.1.7: - version "1.1.18" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.18.tgz#3ce74d89885136be1535341f8c3d4425c29a5cab" - integrity sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -braces@~3.0.2: - version "3.0.3" - resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.3.tgz#490332f40919452272d55a8480adc0c441358789" - integrity sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA== - dependencies: - fill-range "^7.1.1" - buffer@^5.5.0: version "5.7.1" resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0" @@ -422,21 +389,6 @@ call-bound@^1.0.2: call-bind-apply-helpers "^1.0.2" get-intrinsic "^1.3.0" -chokidar@^3.5.2: - version "3.6.0" - resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.6.0.tgz#197c6cc669ef2a8dc5e7b4d97ee4e092c3eb0d5b" - integrity sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw== - dependencies: - anymatch "~3.1.2" - braces "~3.0.2" - glob-parent "~5.1.2" - is-binary-path "~2.1.0" - is-glob "~4.0.1" - normalize-path "~3.0.0" - readdirp "~3.6.0" - optionalDependencies: - fsevents "~2.3.2" - chownr@^1.1.1: version "1.1.4" resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" @@ -511,24 +463,20 @@ compressible@~2.0.18: dependencies: mime-db ">= 1.43.0 < 2" -compression@^1.8.1: - version "1.8.1" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.1.tgz#4a45d909ac16509195a9a28bd91094889c180d79" - integrity sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w== +compression@^1.8.2: + version "1.8.2" + resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.2.tgz#781397127ae2da00c0c5f7c76bda5b2a9b32a49f" + integrity sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ== dependencies: bytes "3.1.2" compressible "~2.0.18" debug "2.6.9" + destroy "1.2.0" negotiator "~0.6.4" on-headers "~1.1.0" safe-buffer "5.2.1" vary "~1.1.2" -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== - config@^3.3.12: version "3.3.12" resolved "https://registry.yarnpkg.com/config/-/config-3.3.12.tgz#a10ae66efcc3e48c1879fbb657c86c4ef6c7b25e" @@ -580,7 +528,7 @@ debug@2.6.9: dependencies: ms "2.0.0" -debug@4, debug@^4, debug@^4.3.5, debug@^4.4.0: +debug@4, debug@^4.3.5, debug@^4.4.0: version "4.4.1" resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.1.tgz#e5a8bc6cbc4c6cd3e64308b0693a3d4fa550189b" integrity sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ== @@ -604,6 +552,11 @@ depd@2.0.0, depd@^2.0.0: resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== +destroy@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" + integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== + detect-libc@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.4.tgz#f04715b8ba815e53b4d8109655b6508a6865a7e8" @@ -749,13 +702,6 @@ file-stream-rotator@^0.6.1: dependencies: moment "^2.29.1" -fill-range@^7.1.1: - version "7.1.1" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.1.1.tgz#44265d3cac07e3ea7dc247516380643754a05292" - integrity sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg== - dependencies: - to-regex-range "^5.0.1" - finalhandler@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-2.1.0.tgz#72306373aa89d05a8242ed569ed86a1bff7c561f" @@ -774,9 +720,9 @@ fn.name@1.x.x: integrity sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw== follow-redirects@^1.0.0: - version "1.16.0" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.16.0.tgz#28474a159d3b9d11ef62050a14ed60e4df6d61bc" - integrity sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw== + version "1.16.1" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.16.1.tgz#6e0efa40a727fb369b98dab15883ec34787d675e" + integrity sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg== forwarded@0.2.0: version "0.2.0" @@ -810,11 +756,6 @@ fs-extra@^11.2.0, fs-extra@^11.3.1: jsonfile "^6.0.1" universalify "^2.0.0" -fsevents@~2.3.2: - version "2.3.3" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6" - integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw== - function-bind@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c" @@ -854,13 +795,6 @@ github-from-package@0.0.0: resolved "https://registry.yarnpkg.com/github-from-package/-/github-from-package-0.0.0.tgz#97fb5d96bfde8973313f20e8288ef9a167fa64ce" integrity sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw== -glob-parent@~5.1.2: - version "5.1.2" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" - integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== - dependencies: - is-glob "^4.0.1" - gopd@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1" @@ -871,11 +805,6 @@ graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.2: resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== -has-flag@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" - integrity sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw== - has-symbols@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.1.0.tgz#fc9c6a783a084951d0b971fe1018de813707a338" @@ -933,11 +862,6 @@ ieee754@^1.1.13: resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== -ignore-by-default@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/ignore-by-default/-/ignore-by-default-1.0.1.tgz#48ca6d72f6c6a3af00a9ad4ae6876be3889e2b09" - integrity sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA== - inherits@2.0.4, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" @@ -966,13 +890,6 @@ is-arrayish@^0.3.1: resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.3.2.tgz#4574a2ae56f7ab206896fb431eaeed066fdf8f03" integrity sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ== -is-binary-path@~2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" - integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== - dependencies: - binary-extensions "^2.0.0" - is-core-module@^2.16.0: version "2.16.1" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.16.1.tgz#2a98801a849f43e2add644fbb6bc6229b19a4ef4" @@ -980,28 +897,11 @@ is-core-module@^2.16.0: dependencies: hasown "^2.0.2" -is-extglob@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" - integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ== - is-fullwidth-code-point@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== -is-glob@^4.0.1, is-glob@~4.0.1: - version "4.0.3" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" - integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg== - dependencies: - is-extglob "^2.1.1" - -is-number@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" - integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== - is-promise@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-promise/-/is-promise-4.0.0.tgz#42ff9f84206c1991d26debf520dd5c01042dd2f3" @@ -1097,13 +997,6 @@ mimic-response@^3.1.0: resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== -minimatch@^3.1.2: - version "3.1.5" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.5.tgz#580c88f8d5445f2bd6aa8f3cadefa0de79fbd69e" - integrity sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w== - dependencies: - brace-expansion "^1.1.7" - minimist@^1.2.0, minimist@^1.2.3, minimist@^1.2.6: version "1.2.8" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" @@ -1127,9 +1020,9 @@ mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== moment@^2.29.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== ms@2.0.0: version "2.0.0" @@ -1183,33 +1076,12 @@ node-int64@^0.4.0: resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b" integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw== -nodemon@^3.1.10: - version "3.1.10" - resolved "https://registry.yarnpkg.com/nodemon/-/nodemon-3.1.10.tgz#5015c5eb4fffcb24d98cf9454df14f4fecec9bc1" - integrity sha512-WDjw3pJ0/0jMFmyNDp3gvY2YizjLmmOUQo6DEBY+JgdvW/yQ9mEeSw6H5ythl5Ny2ytb7f9C2nIbjSxMNzbJXw== - dependencies: - chokidar "^3.5.2" - debug "^4" - ignore-by-default "^1.0.1" - minimatch "^3.1.2" - pstree.remy "^1.1.8" - semver "^7.5.3" - simple-update-notifier "^2.0.0" - supports-color "^5.5.0" - touch "^3.1.0" - undefsafe "^2.0.5" - -normalize-path@^3.0.0, normalize-path@~3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" - integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== - object-hash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/object-hash/-/object-hash-3.0.0.tgz#73f97f753e7baffc0e2cc9d6e079079744ac82e9" integrity sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw== -object-inspect@^1.13.3: +object-inspect@^1.13.3, object-inspect@^1.13.4: version "1.13.4" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.4.tgz#8375265e21bc20d0fa582c22e1b13485d6e00213" integrity sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew== @@ -1265,11 +1137,6 @@ picocolors@^1.1.0: resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== -picomatch@^2.0.4, picomatch@^2.2.1: - version "2.3.2" - resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.2.tgz#5a942915e26b372dc0f0e6753149a16e6b1c5601" - integrity sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA== - picomatch@^4.0.2: version "4.0.4" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.4.tgz#fd6f5e00a143086e074dffe4c924b8fb293b0589" @@ -1304,18 +1171,13 @@ progress@^2.0.3: integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== proxy-addr@^2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" -pstree.remy@^1.1.8: - version "1.1.8" - resolved "https://registry.yarnpkg.com/pstree.remy/-/pstree.remy-1.1.8.tgz#c242224f4a67c21f686839bbdb4ac282b8373d3a" - integrity sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w== - pump@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.3.tgz#151d979f1a29668dc0025ec589a455b53282268d" @@ -1325,11 +1187,12 @@ pump@^3.0.0: once "^1.3.1" qs@^6.14.0: - version "6.14.2" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.14.2.tgz#b5634cf9d9ad9898e31fba3504e866e8efb6798c" - integrity sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q== + version "6.16.1" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.16.1.tgz#0643e17993e551759c85078e1f0bc4b9fe908020" + integrity sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg== dependencies: - side-channel "^1.1.0" + es-define-property "^1.0.1" + side-channel "^1.1.1" range-parser@^1.2.1: version "1.2.1" @@ -1378,13 +1241,6 @@ readable-stream@^3.1.1, readable-stream@^3.4.0, readable-stream@^3.6.0, readable string_decoder "^1.1.1" util-deprecate "^1.0.1" -readdirp@~3.6.0: - version "3.6.0" - resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" - integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA== - dependencies: - picomatch "^2.2.1" - require-directory@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" @@ -1435,7 +1291,7 @@ safe-stable-stringify@^2.3.1: resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== -semver@^7.3.5, semver@^7.5.3: +semver@^7.3.5: version "7.7.2" resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.2.tgz#67d99fdcd35cec21e6f8b87a7fd515a33f982b58" integrity sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA== @@ -1472,13 +1328,13 @@ setprototypeof@1.2.0: resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw== -side-channel-list@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.0.tgz#10cb5984263115d3b7a0e336591e290a830af8ad" - integrity sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA== +side-channel-list@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.1.tgz#c2e0b5a14a540aebee3bbc6c3f8666cc9b509127" + integrity sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w== dependencies: es-errors "^1.3.0" - object-inspect "^1.13.3" + object-inspect "^1.13.4" side-channel-map@^1.0.1: version "1.0.1" @@ -1501,14 +1357,14 @@ side-channel-weakmap@^1.0.2: object-inspect "^1.13.3" side-channel-map "^1.0.1" -side-channel@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.0.tgz#c3fcff9c4da932784873335ec9765fa94ff66bc9" - integrity sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw== +side-channel@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.1.tgz#ea02c62e05dc4bea67d4442f0fb71ee192f8e0ab" + integrity sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ== dependencies: es-errors "^1.3.0" - object-inspect "^1.13.3" - side-channel-list "^1.0.0" + object-inspect "^1.13.4" + side-channel-list "^1.0.1" side-channel-map "^1.0.1" side-channel-weakmap "^1.0.2" @@ -1533,13 +1389,6 @@ simple-swizzle@^0.2.2: dependencies: is-arrayish "^0.3.1" -simple-update-notifier@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz#d70b92bdab7d6d90dfd73931195a30b6e3d7cebb" - integrity sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w== - dependencies: - semver "^7.5.3" - stack-trace@0.0.x: version "0.0.10" resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0" @@ -1597,13 +1446,6 @@ strip-json-comments@~2.0.1: resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" integrity sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ== -supports-color@^5.5.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" - integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== - dependencies: - has-flag "^3.0.0" - supports-preserve-symlinks-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" @@ -1654,23 +1496,11 @@ tinyglobby@^0.2.11: fdir "^6.4.4" picomatch "^4.0.2" -to-regex-range@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" - integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== - dependencies: - is-number "^7.0.0" - toidentifier@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA== -touch@^3.1.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/touch/-/touch-3.1.1.tgz#097a23d7b161476435e5c1344a95c0f75b4a5694" - integrity sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA== - tr46@~0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" @@ -1721,11 +1551,6 @@ typescript@~5.9.3: resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.9.3.tgz#5b4f59e15310ab17a216f5d6cf53ee476ede670f" integrity sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw== -undefsafe@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/undefsafe/-/undefsafe-2.0.5.tgz#38733b9327bdcd226db889fb723a6efd162e6e2c" - integrity sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA== - undici-types@~6.21.0: version "6.21.0" resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.21.0.tgz#691d00af3909be93a7faa13be61b3a5b50ef12cb" diff --git a/netty-mqtt/pom.xml b/netty-mqtt/pom.xml index 98b0fc3fb1..b09f3a92b0 100644 --- a/netty-mqtt/pom.xml +++ b/netty-mqtt/pom.xml @@ -8,11 +8,11 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard netty-mqtt - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT jar Netty MQTT Client diff --git a/pom.xml b/pom.xml index 3f41e2cf31..b4837dda25 100755 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT pom Thingsboard @@ -28,20 +28,27 @@ 17 17 ${basedir} + + ${skip.yarn} none none false - + false @@ -50,11 +57,6 @@ module depends on the ZIP artifact, so this flag can be toggled freely without breaking downstream modules. --> false - - ${pkg.package.phase} thingsboard ${project.name} /var/log/${pkg.name} @@ -68,21 +70,24 @@ entries below once TB migrates its tests off the deprecated @SpyBean/@MockBean to @MockitoSpyBean/@MockitoBean. --> 3.5.13 3.18.0 - 4.1.137.Final - 10.1.59 + 4.1.138.Final + 10.1.60 5.4.3 1.5.38 - 2.21.5 - 42.7.12 - 5.33.1 + 2.21.7 + 42.7.14 + 5.34.0 5.6.4 + 1.5.7-14 + 2.3.35 + 1.11.4 2.4.0-b180830.0359 0.12.5 0.10 4.17.0 4.2.25 5.0.7 - 33.1.0-jre + 33.7.2-jre 2.16.1 1.3.1 1.10.0 @@ -96,10 +101,10 @@ 2.0.0-M15 2.0.1 5.6.0 - 3.9.5 + 3.9.6 3.25.5 1.76.0 - 1.2.10 + 1.2.12 1.18.46 1.2.5 1.2.5 @@ -113,7 +118,7 @@ 2.2.30 0.8 1.19.0 - 1.85 + 1.86 2.0.1 org/thingsboard/server/gen/**/*, org/thingsboard/server/extensions/core/plugin/telemetry/gen/**/* @@ -141,7 +146,7 @@ 1.11.0 4.4 1.0.4TB - 6.3.0 + 6.4.5 10.1.3 3.7.4 4.0.2 @@ -180,7 +185,7 @@ 1.6.1 2.19.0 9.2.0 - 1.1.10.5 + 1.1.10.10 9.10.0 @@ -216,31 +221,46 @@ - + - skip-deb + skip-pkg - pkg.skip.deb + pkg.skip true - none + true + true + true + true - + - skip-pkg + skip-pkg-without-yarn - pkg.skip + skip.yarn + true + + + + true + true + true + true + + + + skip-pkg-without-ui-build + + + skip.ui.build true @@ -249,7 +269,6 @@ true true true - none @@ -539,21 +558,6 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - **/logback.xml - - - - ${pkg.implementationTitle} - ${project.version} - - - - org.springframework.boot spring-boot-maven-plugin @@ -566,6 +570,8 @@ ${pkg.skip.bootjar} ${pkg.mainClass} boot + + false ZIP true true @@ -580,7 +586,6 @@ repackage - build-info @@ -642,28 +647,9 @@ ${pkg.skip.zip} - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-deb - ${pkg.deb.phase} - - attach-artifact - - - - - ${project.build.directory}/${pkg.name}.deb - deb - deb - - + + false @@ -719,6 +705,18 @@ org.apache.maven.plugins maven-jar-plugin ${jar-plugin.version} + + + + **/logback.xml + + + + ${pkg.implementationTitle} + ${project.version} + + + org.apache.maven.plugins @@ -729,6 +727,20 @@ org.springframework.boot spring-boot-maven-plugin ${spring-boot.version} + + + + build-info + + build-info + + + + false + + + org.thingsboard @@ -881,7 +893,7 @@ -
    ${main.dir}/license-header.txt
    +
    ${main.dir}/tools/src/main/python/license-headers/templates/license-header.txt
    **/.env **/*.env @@ -1106,6 +1118,27 @@ ${httpclient5.version}
    + + + com.github.luben + zstd-jni + ${zstd-jni.version} + + + + + org.freemarker + freemarker + ${freemarker.version} + + + + + at.yawk.lz4 + lz4-java + ${lz4-java.version} + + org.springframework.boot spring-boot-dependencies diff --git a/rest-client/pom.xml b/rest-client/pom.xml index 649c7e9fdd..9b301219a8 100644 --- a/rest-client/pom.xml +++ b/rest-client/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard rest-client diff --git a/rule-engine/pom.xml b/rule-engine/pom.xml index 56c4f476cc..2a4aed144d 100644 --- a/rule-engine/pom.xml +++ b/rule-engine/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard rule-engine diff --git a/rule-engine/rule-engine-api/pom.xml b/rule-engine/rule-engine-api/pom.xml index 99154e5cb2..f0f09b57b9 100644 --- a/rule-engine/rule-engine-api/pom.xml +++ b/rule-engine/rule-engine-api/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT rule-engine org.thingsboard.rule-engine diff --git a/rule-engine/rule-engine-components/pom.xml b/rule-engine/rule-engine-components/pom.xml index f68c325278..65f5448f05 100644 --- a/rule-engine/rule-engine-components/pom.xml +++ b/rule-engine/rule-engine-components/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT rule-engine org.thingsboard.rule-engine @@ -64,6 +64,10 @@ com.google.guava guava + + org.checkerframework + checker-qual + com.google.code.gson gson diff --git a/tools/pom.xml b/tools/pom.xml index c17e7bd94f..27570c45a3 100644 --- a/tools/pom.xml +++ b/tools/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard tools diff --git a/license-header.txt b/tools/src/main/python/license-headers/templates/license-header.txt similarity index 100% rename from license-header.txt rename to tools/src/main/python/license-headers/templates/license-header.txt diff --git a/transport/coap/pom.xml b/transport/coap/pom.xml index bfda3c1510..8455ae9e50 100644 --- a/transport/coap/pom.xml +++ b/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/http/pom.xml b/transport/http/pom.xml index cb85c57cae..f0ce64ad4c 100644 --- a/transport/http/pom.xml +++ b/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/lwm2m/pom.xml b/transport/lwm2m/pom.xml index be9db8f2d0..804deea8f0 100644 --- a/transport/lwm2m/pom.xml +++ b/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml index a78aa15a07..4380cf3fb1 100644 --- a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml +++ b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml @@ -174,7 +174,7 @@ transport: #
  • A value that are > 4: MultiNodeConnectionIdGenerator is used
  • connection_id_length: "${LWM2M_DTLS_CONNECTION_ID_LENGTH:8}" server: - # LwM2M Server ID + # LwM2M Server Short Server ID. Valid range [1 - 65534]; 0 and 65535 are reserved. Default: 123. id: "${LWM2M_SERVER_ID:123}" # LwM2M server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" @@ -216,8 +216,8 @@ transport: bootstrap: # Enable/disable Bootstrap Server enabled: "${LWM2M_ENABLED_BS:true}" - # Default value in Lwm2mClient after start in mode Bootstrap for the object : name "LWM2M Security" field: "Short Server ID" (deviceProfile: Bootstrap.BOOTSTRAP SERVER.Short ID) - id: "${LWM2M_SERVER_ID_BS:111}" + # Deprecated: Short Server ID is not applicable for Bootstrap Server per OMA spec (Object 0 Resource 10) and is forced to null. + id: "${LWM2M_SERVER_ID_BS:}" # LwM2M bootstrap server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BS_BIND_ADDRESS:0.0.0.0}" # LwM2M bootstrap server bind port diff --git a/transport/mqtt/pom.xml b/transport/mqtt/pom.xml index 2632ce8598..79d3f97f69 100644 --- a/transport/mqtt/pom.xml +++ b/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/pom.xml b/transport/pom.xml index 6ad84318f8..5ea01754cd 100644 --- a/transport/pom.xml +++ b/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard transport diff --git a/transport/snmp/pom.xml b/transport/snmp/pom.xml index 1d2c35f044..1aad5403b4 100644 --- a/transport/snmp/pom.xml +++ b/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT transport diff --git a/ui-ngx/angular.json b/ui-ngx/angular.json index 08ffdd7b9a..49af337a74 100644 --- a/ui-ngx/angular.json +++ b/ui-ngx/angular.json @@ -77,6 +77,16 @@ "input": "node_modules/hugerte", "output": "/assets/hugerte/" }, + { + "glob": "maplibre-gl-worker.mjs", + "input": "node_modules/maplibre-gl/dist/", + "output": "/assets/maplibre-gl/" + }, + { + "glob": "maplibre-gl-shared.mjs", + "input": "node_modules/maplibre-gl/dist/", + "output": "/assets/maplibre-gl/" + }, { "glob": "marker-icon-2x.png", "input": "node_modules/leaflet/dist/images/", diff --git a/ui-ngx/esbuild/tb-html-fallback-middleware.ts b/ui-ngx/esbuild/tb-html-fallback-middleware.ts index 4692ccd35a..af72bfd223 100644 --- a/ui-ngx/esbuild/tb-html-fallback-middleware.ts +++ b/ui-ngx/esbuild/tb-html-fallback-middleware.ts @@ -2,9 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import type { ServerResponse } from 'node:http'; import type { Connect } from 'vite'; -import type { NextHandleFunction } from 'connect'; -const tbHtmlFallbackMiddleware: NextHandleFunction = ( +const tbHtmlFallbackMiddleware: Connect.NextHandleFunction = ( req: Connect.IncomingMessage, _res: ServerResponse, next: Connect.NextFunction diff --git a/ui-ngx/package.json b/ui-ngx/package.json index b686e63a24..5854a358b7 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -1,6 +1,6 @@ { "name": "thingsboard", - "version": "4.3.1.6", + "version": "4.3.1.7", "scripts": { "ng": "ng", "start": "node --max_old_space_size=8048 ./node_modules/@angular/cli/bin/ng serve --configuration development --host 0.0.0.0 --open", @@ -13,16 +13,16 @@ }, "private": true, "dependencies": { - "@angular/animations": "20.3.28", + "@angular/animations": "20.3.34", "@angular/cdk": "20.2.14", - "@angular/common": "20.3.28", - "@angular/compiler": "20.3.28", - "@angular/core": "20.3.28", - "@angular/forms": "20.3.28", + "@angular/common": "20.3.34", + "@angular/compiler": "20.3.34", + "@angular/core": "20.3.34", + "@angular/forms": "20.3.34", "@angular/material": "20.2.14", - "@angular/platform-browser": "20.3.28", - "@angular/platform-browser-dynamic": "20.3.28", - "@angular/router": "20.3.28", + "@angular/platform-browser": "20.3.34", + "@angular/platform-browser-dynamic": "20.3.34", + "@angular/router": "20.3.34", "@auth0/angular-jwt": "^5.2.0", "@flowjs/flow.js": "^2.14.1", "@flowjs/ngx-flow": "20.0.2", @@ -31,14 +31,14 @@ "@iplab/ngx-color-picker": "^20.0.0", "@mat-datetimepicker/core": "~16.0.1", "@mdi/svg": "^7.4.47", - "@messageformat/core": "^3.4.0", + "@messageformat/core": "^3.4.1", "@ngrx/effects": "^20.1.0", "@ngrx/store": "^20.1.0", "@ngrx/store-devtools": "^20.1.0", "@ngx-translate/core": "^17.0.0", - "@svgdotjs/svg.filter.js": "^3.0.9", - "@svgdotjs/svg.js": "3.2.4", - "@svgdotjs/svg.panzoom.js": "^2.1.2", + "@svgdotjs/svg.filter.js": "^3.0.10", + "@svgdotjs/svg.js": "3.2.8", + "@svgdotjs/svg.panzoom.js": "^2.1.3", "ace-builds": "1.43.6", "ace-diff": "^3.3.0", "angular-gridster2": "~20.2.4", @@ -61,14 +61,14 @@ "jszip": "^3.10.1", "leaflet": "1.9.4", "leaflet-polylinedecorator": "1.6.0", - "leaflet-providers": "2.0.0", + "leaflet-providers": "4.0.0", "leaflet.gridlayer.googlemutant": "0.15.0", "leaflet.markercluster": "1.5.3", "libphonenumber-js": "^1.12.35", - "maplibre-gl": "5.2.0", + "maplibre-gl": "6.11.2", "marked": "~16.4.2", - "moment": "^2.30.1", - "moment-timezone": "^0.6.0", + "moment": "^2.31.0", + "moment-timezone": "^0.6.5", "ngx-clipboard": "^16.0.0", "ngx-daterangepicker-material": "^6.0.4", "ngx-drag-drop": "^20.0.1", @@ -91,17 +91,17 @@ "tooltipster": "^4.2.8", "tslib": "^2.8.1", "typeface-roboto": "^1.1.13", + "typeface-roboto-mono": "^1.1.13", "zone.js": "~0.15.1" }, "devDependencies": { "@angular-builders/custom-esbuild": "20.0.0", - "@angular-devkit/build-angular": "20.3.34", - "@angular-devkit/core": "20.3.34", - "@angular-devkit/schematics": "20.3.34", - "@angular/build": "20.3.34", - "@angular/cli": "20.3.34", - "@angular/compiler-cli": "20.3.28", - "@angular/language-service": "20.3.28", + "@angular-devkit/core": "20.3.40", + "@angular-devkit/schematics": "20.3.40", + "@angular/build": "20.3.40", + "@angular/cli": "20.3.40", + "@angular/compiler-cli": "20.3.34", + "@angular/language-service": "20.3.34", "@types/ace-diff": "^2.1.4", "@types/canvas-gauges": "^2.1.8", "@types/flot": "^0.0.36", @@ -122,7 +122,7 @@ "angular-eslint": "~20.7.0", "autoprefixer": "^10.4.23", "directory-tree": "^3.5.2", - "eslint": "9.39.4", + "eslint": "9.39.5", "eslint-plugin-import": "^2.32.0", "eslint-plugin-jsdoc": "^62.4.1", "eslint-plugin-prefer-arrow": "^1.2.3", @@ -140,7 +140,7 @@ "@babel/core": "7.29.7", "esbuild": "0.28.1", "rollup": "4.59.0", - "less": ">=4.9.0", - "js-beautify/**/minimatch": "^9.0.7" + "js-beautify/**/minimatch": "^9.0.7", + "@modelcontextprotocol/sdk": "1.32.1" } } diff --git a/ui-ngx/patches/@angular+build+20.3.34.patch b/ui-ngx/patches/@angular+build+20.3.40.patch similarity index 100% rename from ui-ngx/patches/@angular+build+20.3.34.patch rename to ui-ngx/patches/@angular+build+20.3.40.patch diff --git a/ui-ngx/patches/@angular+core+20.3.28.patch b/ui-ngx/patches/@angular+core+20.3.34.patch similarity index 100% rename from ui-ngx/patches/@angular+core+20.3.28.patch rename to ui-ngx/patches/@angular+core+20.3.34.patch diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index e22f551068..f7c130d606 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.6-SNAPSHOT + 4.3.1.7-SNAPSHOT thingsboard org.thingsboard @@ -37,6 +37,9 @@ target ${basedir} + + ${skip.ui.build} @@ -71,6 +74,14 @@ + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + diff --git a/ui-ngx/src/app/core/auth/auth.service.spec.ts b/ui-ngx/src/app/core/auth/auth.service.spec.ts deleted file mode 100644 index cd58133fe4..0000000000 --- a/ui-ngx/src/app/core/auth/auth.service.spec.ts +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The Thingsboard Authors -// SPDX-License-Identifier: Apache-2.0 -import { TestBed } from '@angular/core/testing'; - -import { AuthService } from './auth.service'; - -describe('AuthService', () => { - beforeEach(() => TestBed.configureTestingModule({})); - - it('should be created', () => { - const service: AuthService = TestBed.get(AuthService); - expect(service).toBeTruthy(); - }); -}); diff --git a/ui-ngx/src/app/core/http/community-grant.service.ts b/ui-ngx/src/app/core/http/community-grant.service.ts new file mode 100644 index 0000000000..c842cfc7e4 --- /dev/null +++ b/ui-ngx/src/app/core/http/community-grant.service.ts @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { map } from 'rxjs/operators'; +import { defaultHttpOptionsFromConfig, defaultHttpUploadOptions, RequestConfig } from './http-utils'; +import { + CommunityGrantRegistration, + communityGrantRegistrationFrom, + CommunityGrantStateInfo +} from '@shared/models/ce-grant/community-grant.models'; + +@Injectable({ + providedIn: 'root' +}) +export class CommunityGrantService { + + constructor(private http: HttpClient) { + } + + /** + * Mints a fresh claim token and sign-up URL. An unreachable portal is not an error: it answers with + * `mode = OFFLINE`. + */ + public register(config?: RequestConfig): Observable { + return this.http.post('/api/communityGrant/start', null, defaultHttpOptionsFromConfig(config)) + .pipe(map(info => communityGrantRegistrationFrom(info))); + } + + public pollRegistration(config?: RequestConfig): Observable { + return this.http.get('/api/communityGrant/state', defaultHttpOptionsFromConfig(config)) + .pipe(map(info => communityGrantRegistrationFrom(info))); + } + + /** + * Answers once the run has started; its report or failure arrives on a later `GET /state`. Errors are not + * toasted: the dialog shows them itself. + */ + public runOfflineScaleCheck(bundle: File): Observable { + const formData = new FormData(); + formData.append('bundle', bundle); + return this.http.post('/api/communityGrant/offline/run', formData, + defaultHttpUploadOptions(false, true)) + .pipe(map(info => communityGrantRegistrationFrom(info))); + } + + public downloadOfflineReport(config?: RequestConfig): Observable { + return this.http.get('/api/communityGrant/offline/report', + {...{responseType: 'text' as const}, ...defaultHttpOptionsFromConfig(config)}); + } + + public confirmOfflineHandoff(config?: RequestConfig): Observable { + return this.http.post('/api/communityGrant/offline/handoff', null, + defaultHttpOptionsFromConfig(config)) + .pipe(map(info => communityGrantRegistrationFrom(info))); + } + + /** Success means only that the request reached the portal, never that the registered owner was notified. */ + public requestAccess(config?: RequestConfig): Observable { + return this.http.post('/api/communityGrant/requestAccess', null, defaultHttpOptionsFromConfig(config)); + } +} diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 33f19d285f..70f97ed061 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -6,7 +6,11 @@ import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; -import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { + MpItemVersionQuery, + MpItemVersionQueryOptions, + MpItemVersionView +} from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -69,36 +73,47 @@ export class IotHubApiService { } public getPublishedVersions(query: MpItemVersionQuery, config?: IotHubRequestConfig): Observable> { - if (query.options.tbVersion == null) { - query.options.tbVersion = tbVersionToInt(env.tbVersion); - } - if (query.options.peOnly == null) { - query.options.peOnly = false; - } + this.applyPlatformFilters(query.options); return this.http.get>( `${this.baseUrl}/api/versions/published${query.toQuery()}`, { params: this.buildParams(config) } ); } + /** What this platform can install: no PE-only items, nothing built for a newer ThingsBoard. */ + private platformScope(): { peOnly: boolean; tbVersion: number } { + return { peOnly: false, tbVersion: tbVersionToInt(env.tbVersion) }; + } + + /** Fills in the platform scope wherever the caller did not set it. */ + private applyPlatformFilters(options: MpItemVersionQueryOptions): void { + const scope = this.platformScope(); + options.tbVersion ??= scope.tbVersion; + options.peOnly ??= scope.peOnly; + } + + private platformScopeParams(): string[] { + const scope = this.platformScope(); + return [`peOnly=${scope.peOnly}`, `tbVersion=${scope.tbVersion}`]; + } + public getFilterInfo(itemType: ItemType, config?: IotHubRequestConfig): Observable { - const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}` - + `?peOnly=false&tbVersion=${tbVersionToInt(env.tbVersion)}`; + const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}?${this.platformScopeParams().join('&')}`; return this.http.get(url, { params: this.buildParams(config) }); } - public getWidgetCategories(textSearch?: string, scadaFirst?: boolean, + public getWidgetCategories(textSearch?: string, scadaFirst?: boolean, creatorVerified?: boolean, config?: IotHubRequestConfig): Observable { - const queryParams: string[] = [ - `peOnly=false`, - `tbVersion=${tbVersionToInt(env.tbVersion)}` - ]; + const queryParams: string[] = this.platformScopeParams(); if (textSearch?.trim()) { queryParams.push(`textSearch=${encodeURIComponent(textSearch.trim())}`); } if (scadaFirst != null) { queryParams.push(`scadaFirst=${scadaFirst}`); } + if (creatorVerified) { + queryParams.push(`creatorVerified=true`); + } const url = `${this.baseUrl}/api/item-listing/widgetCategories?${queryParams.join('&')}`; return this.http.get(url, { params: this.buildParams(config) }); } @@ -132,7 +147,7 @@ export class IotHubApiService { public getListingItemVersion(slug: string, config?: IotHubRequestConfig): Observable { const queryParams = [ 'ce=true', - `tbVersion=${tbVersionToInt(env.tbVersion)}` + `tbVersion=${this.platformScope().tbVersion}` ]; return this.http.get( `${this.baseUrl}/api/listings/public/by-slug/${encodeURIComponent(slug)}/item-version?${queryParams.join('&')}`, diff --git a/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts b/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts index bf38fbeb01..ab7c446271 100644 --- a/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts +++ b/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts @@ -108,7 +108,9 @@ export class GlobalHttpInterceptor implements HttpInterceptor { this.dialogService.forbidden(); } } else if (errorResponse.status === 0 || errorResponse.status === -1) { + if (!ignoreErrors) { this.showError('Unable to connect'); + } } else if (!(req.url.startsWith('/api/rpc') || req.url.startsWith('/api/plugins/rpc'))) { if (errorResponse.status === 404) { if (!ignoreErrors) { diff --git a/ui-ngx/src/app/core/services/calculated-field-form.service.ts b/ui-ngx/src/app/core/services/calculated-field-form.service.ts index db84823575..2075c0fee1 100644 --- a/ui-ngx/src/app/core/services/calculated-field-form.service.ts +++ b/ui-ngx/src/app/core/services/calculated-field-form.service.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 import { DestroyRef, inject, Injectable } from '@angular/core'; -import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { AbstractControl, FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms'; import { pairwise, switchMap } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { @@ -14,6 +14,7 @@ import { import { isDefined } from '@core/utils'; import { CalculatedFieldsService } from '@core/http/calculated-fields.service'; import { CalculatedFieldsTableEntity } from '@home/components/calculated-fields/calculated-fields-table-config'; +import { AlarmRule, areAlarmRuleArgumentsValid } from '@shared/models/alarm-rule.models'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { getTimezoneInfo } from '@shared/models/time/time.models'; @@ -47,10 +48,26 @@ export class CalculatedFieldFormService { propagateRelationTypes: [null], createRules: [null, Validators.required], clearRule: [null], - }), + }, {validators: this.alarmRulesArgumentsValidator()}), }); } + private alarmRulesArgumentsValidator(): ValidatorFn { + return (configuration: AbstractControl): ValidationErrors | null => { + const args = configuration.get('arguments').value; + const createRulesControl = configuration.get('createRules'); + const clearRuleControl = configuration.get('clearRule'); + const rules: AlarmRule[] = []; + if (createRulesControl.enabled) { + rules.push(...Object.values(createRulesControl.value ?? {})); + } + if (clearRuleControl.enabled) { + rules.push(clearRuleControl.value); + } + return rules.every(rule => areAlarmRuleArgumentsValid(rule, args)) ? null : {alarmRuleArguments: {valid: false}}; + }; + } + setupTypeChange(form: FormGroup, destroyRef: DestroyRef, isEditActive?: () => boolean): void { form.get('type').valueChanges.pipe( pairwise(), diff --git a/ui-ngx/src/app/modules/home/components/alarm-rules/cf-alarm-rule-condition.component.ts b/ui-ngx/src/app/modules/home/components/alarm-rules/cf-alarm-rule-condition.component.ts index bdcaad5b0e..4a9609eacc 100644 --- a/ui-ngx/src/app/modules/home/components/alarm-rules/cf-alarm-rule-condition.component.ts +++ b/ui-ngx/src/app/modules/home/components/alarm-rules/cf-alarm-rule-condition.component.ts @@ -29,7 +29,8 @@ import { AlarmRuleExpressionType, AlarmRuleSchedule, AlarmRuleScheduleType, - checkPredicates + areAlarmRuleConditionFilterArgumentsValid, + isAlarmRuleConditionScheduleArgumentValid } from "@shared/models/alarm-rule.models"; import { CalculatedFieldArgument } from "@shared/models/calculated-field.models"; import { @@ -93,7 +94,6 @@ export class CfAlarmRuleConditionComponent implements ControlValueAccessor, Vali private modelValue: AlarmRuleCondition; private propagateChange = (v: any) => { }; - private onValidatorChange = () => { }; constructor(private dialog: MatDialog, private fb: FormBuilder, @@ -108,10 +108,6 @@ export class CfAlarmRuleConditionComponent implements ControlValueAccessor, Vali registerOnTouched(fn: any): void { } - registerOnValidatorChange(fn: () => void): void { - this.onValidatorChange = fn; - } - setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; if (this.disabled) { @@ -129,46 +125,18 @@ export class CfAlarmRuleConditionComponent implements ControlValueAccessor, Vali ngOnChanges(changes: SimpleChanges) { if (changes.arguments && !changes.arguments.firstChange) { - if (this.recalculateArgumentValidity()) { - this.onValidatorChange(); - } + this.recalculateArgumentValidity(); } } - private recalculateArgumentValidity(): boolean { - const prevFiltersValid = this.filtersArgumentsValid; - const prevSchedulerValid = this.schedulerArgumentsValid; + private recalculateArgumentValidity(): void { if (!this.modelValue || !this.arguments) { this.filtersArgumentsValid = true; this.schedulerArgumentsValid = true; } else { - this.filtersArgumentsValid = this.areFilterAndPredicateArgumentsValid(this.modelValue, this.arguments); - this.schedulerArgumentsValid = this.isScheduleArgumentValid(this.modelValue, Object.keys(this.arguments)); + this.filtersArgumentsValid = areAlarmRuleConditionFilterArgumentsValid(this.modelValue, this.arguments); + this.schedulerArgumentsValid = isAlarmRuleConditionScheduleArgumentValid(this.modelValue, this.arguments); } - return prevFiltersValid !== this.filtersArgumentsValid || prevSchedulerValid !== this.schedulerArgumentsValid; - } - - private isScheduleArgumentValid(obj: any, validArguments: string[]): boolean { - const arg = obj?.schedule?.dynamicValueArgument; - return !arg || validArguments.includes(arg); - } - - private areFilterAndPredicateArgumentsValid(obj: any, args: Record): boolean { - const validSet = new Set(Object.keys(args)); - const filters = obj?.expression?.filters || obj?.filters || []; - for (const filter of filters) { - if (filter.argument && !validSet.has(filter.argument)) { - return false; - } - } - for (const filter of filters) { - if (Array.isArray(filter.predicates)) { - if (!checkPredicates(filter.predicates, validSet)) { - return false; - } - } - } - return true; } public conditionSet(): boolean { @@ -176,9 +144,7 @@ export class CfAlarmRuleConditionComponent implements ControlValueAccessor, Vali } public validate(control: AbstractControl): ValidationErrors | null { - const hasCondition = this.conditionSet(); - const argsValid = this.filtersArgumentsValid && this.schedulerArgumentsValid; - return (hasCondition && argsValid) ? null : { alarmRuleCondition: { valid: false } }; + return this.conditionSet() ? null : { alarmRuleCondition: { valid: false } }; } public openFilterDialog($event: Event) { @@ -266,7 +232,6 @@ export class CfAlarmRuleConditionComponent implements ControlValueAccessor, Vali this.updateConditionInfo(); this.recalculateArgumentValidity(); this.propagateChange(this.modelValue); - this.onValidatorChange(); this.cd.detectChanges(); } @@ -285,10 +250,7 @@ export class CfAlarmRuleConditionComponent implements ControlValueAccessor, Vali } }).afterClosed().subscribe((result) => { if (result) { - if (!this.modelValue) { - this.modelValue = {} as AlarmRuleCondition; - } - this.modelValue.schedule = result; + this.modelValue = {...this.modelValue, schedule: result} as AlarmRuleCondition; this.updateModel(); } }); diff --git a/ui-ngx/src/app/modules/home/components/alarm-rules/cf-alarm-rule.component.ts b/ui-ngx/src/app/modules/home/components/alarm-rules/cf-alarm-rule.component.ts index 51fc4ec8a2..a0d4db2a40 100644 --- a/ui-ngx/src/app/modules/home/components/alarm-rules/cf-alarm-rule.component.ts +++ b/ui-ngx/src/app/modules/home/components/alarm-rules/cf-alarm-rule.component.ts @@ -65,12 +65,11 @@ export class CfAlarmRuleComponent implements ControlValueAccessor, OnInit, Valid alarmRuleFormGroup = this.fb.group({ condition: this.fb.control(null, Validators.required), - alarmDetails: [null], - dashboardId: [null] + alarmDetails: this.fb.control(null), + dashboardId: this.fb.control(null) }); private propagateChange = (v: any) => { }; - private onValidatorChange = () => { }; constructor(private dialog: MatDialog, private fb: FormBuilder, @@ -84,20 +83,11 @@ export class CfAlarmRuleComponent implements ControlValueAccessor, OnInit, Valid registerOnTouched(fn: any): void { } - registerOnValidatorChange(fn: () => void): void { - this.onValidatorChange = fn; - } - ngOnInit() { this.alarmRuleFormGroup.valueChanges.pipe( takeUntilDestroyed(this.destroyRef) - ).subscribe(() => { - this.updateModel(); - }); - this.alarmRuleFormGroup.statusChanges.pipe( - takeUntilDestroyed(this.destroyRef) - ).subscribe(() => { - this.onValidatorChange(); + ).subscribe((value) => { + this.updateModel(value); }); } @@ -111,12 +101,14 @@ export class CfAlarmRuleComponent implements ControlValueAccessor, OnInit, Valid } writeValue(value: AlarmRule): void { - this.modelValue = value; - const model = this.modelValue ? { - ...this.modelValue, - dashboardId: this.modelValue.dashboardId?.id - } : null; - this.alarmRuleFormGroup.patchValue(model, {emitEvent: false}); + this.alarmRuleFormGroup.reset(undefined, {emitEvent: false}); + if (value) { + this.alarmRuleFormGroup.patchValue({ + ...value, + dashboardId: value.dashboardId?.id + }, {emitEvent: false}); + } + this.modelValue = value ? this.toModel(this.alarmRuleFormGroup.value) : null; } public openEditDetailsDialog($event: Event) { @@ -146,9 +138,12 @@ export class CfAlarmRuleComponent implements ControlValueAccessor, OnInit, Valid }; } - private updateModel() { - const value = this.alarmRuleFormGroup.value; - this.modelValue = {...value, dashboardId: value.dashboardId ? new DashboardId(value.dashboardId) : null} as AlarmRule; + private updateModel(value: typeof this.alarmRuleFormGroup.value): void { + this.modelValue = this.toModel(value); this.propagateChange(this.modelValue); } + + private toModel(value: typeof this.alarmRuleFormGroup.value): AlarmRule { + return {...value, dashboardId: value.dashboardId ? new DashboardId(value.dashboardId) : null} as AlarmRule; + } } diff --git a/ui-ngx/src/app/modules/home/components/alarm-rules/create-cf-alarm-rules.component.ts b/ui-ngx/src/app/modules/home/components/alarm-rules/create-cf-alarm-rules.component.ts index 5c83d1598f..77f600e5c0 100644 --- a/ui-ngx/src/app/modules/home/components/alarm-rules/create-cf-alarm-rules.component.ts +++ b/ui-ngx/src/app/modules/home/components/alarm-rules/create-cf-alarm-rules.component.ts @@ -63,16 +63,12 @@ export class CreateCfAlarmRulesComponent implements ControlValueAccessor, Valida private usedSeverities: AlarmSeverity[] = []; private propagateChange = (v: any) => { }; - private onValidatorChange = () => { }; constructor(private fb: FormBuilder, private destroyRef: DestroyRef) { this.createAlarmRulesFormGroup.valueChanges.pipe( takeUntilDestroyed(this.destroyRef) ).subscribe(() => this.updateModel()); - this.createAlarmRulesFormGroup.statusChanges.pipe( - takeUntilDestroyed(this.destroyRef) - ).subscribe(() => this.onValidatorChange()); } registerOnChange(fn: any): void { @@ -82,10 +78,6 @@ export class CreateCfAlarmRulesComponent implements ControlValueAccessor, Valida registerOnTouched(fn: any): void { } - registerOnValidatorChange(fn: () => void): void { - this.onValidatorChange = fn; - } - createAlarmRulesFormArray(): UntypedFormArray { return this.createAlarmRulesFormGroup.get('createAlarmRules') as UntypedFormArray; } diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html index aa5c1deb90..01bdcf0979 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html @@ -80,12 +80,12 @@ } @if (selectWidgetMode === 'iotHub' && iotHubSubMode !== 'default') { - @for (option of iotHubSortOptions; track option.value; let i = $index) { - + @for (option of iotHubSortOptions; track option.value) { + } } @@ -457,120 +457,129 @@ } } @else { - - - - {{ 'iot-hub.type' | translate }} - @if (iotHubAppliedWidgetTypes.size) { - {{ iotHubAppliedWidgetTypes.size }} - } - - - @if (iotHubWidgetTypeOptions.length >= 10) { - - } -
    - @for (opt of getFilteredIotHubItems(iotHubWidgetTypeOptions, 'widgetType'); track opt.key) { -
    - - {{ getIotHubWidgetTypeLabel(opt.key) }} - -
    - } -
    -
    - @if (!hideCategoriesFilterSection) { +
    + + {{ 'iot-hub.verified-creators-only' | translate }} + +
    + @if (iotHubSubMode !== 'default') { - + - {{ 'iot-hub.category' | translate }} - @if (iotHubAppliedCategories.size) { - {{ iotHubAppliedCategories.size }} + {{ 'iot-hub.type' | translate }} + @if (iotHubAppliedWidgetTypes.size) { + {{ iotHubAppliedWidgetTypes.size }} } - @if (iotHubCategoryOptions.length >= 10) { + @if (iotHubWidgetTypeOptions.length >= 10) { } -
    - @for (opt of getFilteredIotHubItems(iotHubCategoryOptions, 'category'); track opt.key) { + @for (opt of getFilteredIotHubItems(iotHubWidgetTypeOptions, 'widgetType'); track opt.key) {
    - - {{ opt.key }} + + {{ getIotHubWidgetTypeLabel(opt.key) }}
    }
    - } - - - - - {{ 'iot-hub.use-case' | translate }} - @if (iotHubAppliedUseCases.size) { - {{ iotHubAppliedUseCases.size }} - } - - - @if (iotHubUseCaseOptions.length >= 10) { - - } -
    - @for (group of getGroupedIotHubFilterItems(iotHubUseCaseOptions, 'useCase'); track group.label) { - @if (group.label) { -
    {{ group.label | translate }}
    - } - @for (opt of group.items; track opt.key) { -
    - - {{ opt.key }} - + @if (!hideCategoriesFilterSection) { + + + + + {{ 'iot-hub.category' | translate }} + @if (iotHubAppliedCategories.size) { + {{ iotHubAppliedCategories.size }} + } + + + @if (iotHubCategoryOptions.length >= 10) { + } +
    + @for (opt of getFilteredIotHubItems(iotHubCategoryOptions, 'category'); track opt.key) { +
    + + {{ opt.key }} + +
    + } +
    +
    + } + + + + + {{ 'iot-hub.use-case' | translate }} + @if (iotHubAppliedUseCases.size) { + {{ iotHubAppliedUseCases.size }} + } + + + @if (iotHubUseCaseOptions.length >= 10) { + } -
    - +
    + @for (group of getGroupedIotHubFilterItems(iotHubUseCaseOptions, 'useCase'); track group.label) { + @if (group.label) { +
    {{ group.label | translate }}
    + } + @for (opt of group.items; track opt.key) { +
    + + {{ opt.key }} + +
    + } + } +
    + + } }
    diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts index d93a1e504e..ac335b9a16 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts @@ -21,7 +21,14 @@ import { ItemSizeStrategy } from '@shared/components/grid/scroll-grid.component' import { coerceBoolean } from '@shared/decorators/coercion'; import { TranslateService } from '@ngx-translate/core'; import { MpItemVersionQuery, MpItemVersionView, widgetTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, FilterParamInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + ItemType, + RELEVANCE_SORT_PROPERTY, + SortOption, + WidgetCategory +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; @@ -34,16 +41,13 @@ import { } from '@home/components/iot-hub/iot-hub-utils'; import { IotHubBuiltInService } from '@home/components/iot-hub/iot-hub-built-in.service'; +/** The Installed list is sorted locally, and only the Hub can rank by relevance. */ +const INSTALLED_SORT_OPTIONS = IOT_HUB_SORT_OPTIONS.filter(o => o.value !== RELEVANCE_SORT_PROPERTY); + type selectWidgetMode = 'installed' | 'iotHub'; type installedSubMode = 'default' | 'allWidgets'; type iotHubSubMode = 'default' | 'allWidgets' | 'installed' | 'category'; -interface WidgetSelectSortOption { - value: string; - label: string; - direction: Direction; -} - const LOGICAL_ALL_WIDGETS = '__logical_all_widgets__'; const LOGICAL_INSTALLED_FROM_IOT_HUB = '__logical_installed_from_iot_hub__'; @@ -88,12 +92,7 @@ export class DashboardWidgetSelectComponent { includeDeprecated = false; searchFocused = false; - iotHubSortOptions: WidgetSelectSortOption[] = [ - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; - iotHubSelectedSortIndex = 0; + private iotHubSelectedSortValue = IOT_HUB_SORT_OPTIONS[0].value; @Input() aliasController: IAliasController; @@ -137,6 +136,7 @@ export class DashboardWidgetSelectComponent { this.iotHubAppliedWidgetTypes.clear(); this.iotHubAppliedCategories.clear(); this.iotHubAppliedUseCases.clear(); + this.iotHubVerifiedCreatorsOnly = false; this.iotHubFilterCount = 0; } } @@ -260,6 +260,7 @@ export class DashboardWidgetSelectComponent { iotHubAppliedWidgetTypes = new Set(); iotHubAppliedCategories = new Set(); iotHubAppliedUseCases = new Set(); + iotHubVerifiedCreatorsOnly = false; iotHubWidgetTypeOptions: FilterParamInfo[] = []; iotHubCategoryOptions: FilterParamInfo[] = []; @@ -303,7 +304,7 @@ export class DashboardWidgetSelectComponent { this.iotHubWidgetsFetchFunction = (pageSize, page, filter) => { const search = typeof filter === 'string' ? filter.split('|')[0] : filter; - const sort = this.iotHubSortOptions[this.iotHubSelectedSortIndex]; + const sort = this.iotHubSelectedSort; const sortOrder: SortOrder = { property: sort.value, direction: sort.direction }; const pageLink = new PageLink(pageSize, page, search || null, sortOrder); const effectiveCategories = this.iotHubSelectedCategory @@ -314,7 +315,8 @@ export class DashboardWidgetSelectComponent { categories: effectiveCategories, useCases: this.iotHubAppliedUseCases.size > 0 ? Array.from(this.iotHubAppliedUseCases) : undefined, widgetTypes: this.iotHubAppliedWidgetTypes.size > 0 ? Array.from(this.iotHubAppliedWidgetTypes) : undefined, - scadaFirst: this.scadaFirst ? true : undefined + scadaFirst: this.scadaFirst ? true : undefined, + creatorVerified: this.iotHubVerifiedCreatorsOnly }); return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }); }; @@ -337,7 +339,8 @@ export class DashboardWidgetSelectComponent { this.iotHubDefaultFetchFunction = (pageSize, page, filter) => { const search = typeof filter === 'string' ? filter.split('|')[0] : filter; return this.iotHubApiService.getWidgetCategories(search || undefined, - this.scadaFirst ? true : undefined, { ignoreLoading: true }).pipe( + this.scadaFirst ? true : undefined, + this.iotHubVerifiedCreatorsOnly, { ignoreLoading: true }).pipe( map(categories => ({ data: categories.slice(page * pageSize, page * pageSize + pageSize), totalPages: Math.ceil(categories.length / pageSize), @@ -554,11 +557,19 @@ export class DashboardWidgetSelectComponent { this.onIotHubFiltersChanged(); } + toggleIotHubVerifiedCreators(): void { + this.iotHubVerifiedCreatorsOnly = !this.iotHubVerifiedCreatorsOnly; + this.loadWidgetCategories(); + this.onIotHubFiltersChanged(); + } + clearIotHubFilters(): void { this.iotHubAppliedWidgetTypes.clear(); this.iotHubAppliedCategories.clear(); this.iotHubAppliedUseCases.clear(); + this.iotHubVerifiedCreatorsOnly = false; this.iotHubFilterSearch = {}; + this.loadWidgetCategories(); this.onIotHubFiltersChanged(); } @@ -566,13 +577,27 @@ export class DashboardWidgetSelectComponent { this.iotHubFilterCount = this.iotHubAppliedWidgetTypes.size + (this.iotHubSelectedCategory ? 0 : this.iotHubAppliedCategories.size) + - this.iotHubAppliedUseCases.size; + this.iotHubAppliedUseCases.size + + (this.iotHubVerifiedCreatorsOnly ? 1 : 0); this.reloadIotHubWidgets(); } - onIotHubSortChange(index: number): void { - if (this.iotHubSelectedSortIndex !== index) { - this.iotHubSelectedSortIndex = index; + get iotHubSortOptions(): SortOption[] { + return this.iotHubSubMode === 'installed' ? INSTALLED_SORT_OPTIONS : IOT_HUB_SORT_OPTIONS; + } + + /** The chosen sort, or the list's first option where the chosen one is not offered. */ + get iotHubSelectedSort(): SortOption { + const options = this.iotHubSortOptions; + return options.find(o => o.value === this.iotHubSelectedSortValue) ?? options[0]; + } + + onIotHubSortChange(option: SortOption): void { + // Store the choice even when it is already the effective sort (the Installed list's fallback + // for relevance), so it survives a switch back to the IoT Hub list; reload only on a change. + const effective = this.iotHubSelectedSort.value; + this.iotHubSelectedSortValue = option.value; + if (effective !== option.value) { this.installedWidgetVersions = null; this.reloadIotHubWidgets(); } @@ -582,6 +607,9 @@ export class DashboardWidgetSelectComponent { if (this.selectWidgetMode === 'installed') { return (this.filterWidgetTypes?.length ?? 0) + (this.includeDeprecated ? 1 : 0); } + if (this.iotHubSubMode === 'default') { + return this.iotHubVerifiedCreatorsOnly ? 1 : 0; + } return this.iotHubFilterCount; } @@ -591,7 +619,8 @@ export class DashboardWidgetSelectComponent { } return this.iotHubAppliedWidgetTypes.size > 0 || this.iotHubAppliedCategories.size > 0 - || this.iotHubAppliedUseCases.size > 0; + || this.iotHubAppliedUseCases.size > 0 + || this.iotHubVerifiedCreatorsOnly; } clearAllFilters(): void { @@ -630,7 +659,8 @@ export class DashboardWidgetSelectComponent { isFilterVisible(): boolean { if (this.selectWidgetMode === 'iotHub') { - return this.iotHubSubMode !== 'default'; + // The category landing honours only the verified filter, so the button stays while it is on + return this.iotHubSubMode !== 'default' || this.iotHubVerifiedCreatorsOnly; } return this.installedSubMode === 'allWidgets' || this.widgetsBundle !== null; } @@ -838,6 +868,9 @@ export class DashboardWidgetSelectComponent { if (this.iotHubAppliedUseCases.size > 0) { filtered = filtered.filter(v => v.useCases?.some(u => this.iotHubAppliedUseCases.has(u))); } + if (this.iotHubVerifiedCreatorsOnly) { + filtered = filtered.filter(v => v.creatorVerified); + } filtered = this.sortInstalledVersions(filtered); const start = page * pageSize; const data = filtered.slice(start, start + pageSize); @@ -845,7 +878,7 @@ export class DashboardWidgetSelectComponent { } private sortInstalledVersions(versions: MpItemVersionView[]): MpItemVersionView[] { - const sort = this.iotHubSortOptions[this.iotHubSelectedSortIndex]; + const sort = this.iotHubSelectedSort; const sign = sort.direction === Direction.ASC ? 1 : -1; const copy = [...versions]; copy.sort((a, b) => { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss index d247f20112..b6264d6ce3 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss @@ -119,3 +119,33 @@ pointer-events: none; } } + +// Scroll area whose thumb shows only while the container is hovered (the filter panels'). +@mixin tb-iot-hub-hover-scrollbar { + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background-color: transparent; + } + + &::-webkit-scrollbar-thumb { + background-color: transparent; + border-radius: 3px; + } + + &:hover { + &::-webkit-scrollbar-track { + background-color: rgba(0, 0, 0, 0.04); + } + + &::-webkit-scrollbar-thumb { + background-color: rgba(0, 0, 0, 0.2); + + &:hover { + background-color: rgba(0, 0, 0, 0.35); + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index bb72d65ea3..28e7f61ceb 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -190,7 +190,8 @@
    + labelPosition="bottom" + (selectionChange)="onStepSelectionChange($event)"> done diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index dacb092d36..a55d5ce2a3 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -12,6 +12,7 @@ import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; import { MatStepper } from '@angular/material/stepper'; +import { StepperSelectionEvent } from '@angular/cdk/stepper'; import { firstValueFrom } from 'rxjs'; import { TranslateService } from '@ngx-translate/core'; import { PageLink } from '@shared/models/page/page-link'; @@ -95,6 +96,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -255,10 +262,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - this.stepper?.next(); - this.onStepActivated(); - }, 0); + setTimeout(() => this.stepper?.next(), 0); return; } this.startWizard(); @@ -309,12 +313,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent
    + + {{ 'iot-hub.verified-creators-only' | translate }} + +
    + @if (!fixedSubType && subtypeOptions.length > 0 && activeType !== ItemType.ALARM_RULE) { @@ -43,8 +50,8 @@ }
    } -
    @for (opt of getFilteredItems(subtypeOptions, 'subtype'); track opt.key) { } -
    @for (group of getGroupedFilterItems(vendorOptions, 'vendor'); track group.label) { @if (group.label) { @@ -114,8 +121,8 @@ }
    } -
    @for (ht of getFilteredItems(hardwareTypeOptions, 'hardwareType'); track ht.key) { } -
    @for (group of getFilteredConnectivityGroups('connectivity'); track group.group) {
    {{ group.group }}
    @@ -182,8 +189,8 @@ }
    } -
    @for (cat of getFilteredItems(categoryOptions, 'category'); track cat.key) { } -
    @for (group of getGroupedFilterItems(useCaseOptions, 'useCase'); track group.label) { @if (group.label) { @@ -253,6 +260,12 @@
    + @if (verifiedCreatorsOnly) { + + {{ 'iot-hub.verified-creators-only' | translate }} + close + + } @for (key of getActiveSubtypesArray(); track key) { {{ getSubtypeLabel(key) }} @@ -305,6 +318,8 @@
    +
    {{ 'iot-hub.filter' | translate }}
    +
    @@ -347,6 +362,12 @@ @if (hasActiveDropdownFilters()) { + @if (verifiedCreatorsOnly) { + + {{ 'iot-hub.verified-creators-only' | translate }} + close + + } @for (key of getActiveSubtypesArray(); track key) { {{ getSubtypeLabel(key) }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.scss index d16491e4a3..2808db8ae4 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.scss @@ -97,6 +97,17 @@ } } +.tb-iot-hub-filters-header { + padding: 16px 16px 12px 56px; + font-size: 18px; + font-weight: 500; + color: rgba(0, 0, 0, 0.87); +} + +.tb-iot-hub-filters-desktop .tb-iot-hub-filters-inner { + padding-top: 8px; +} + .tb-iot-hub-filters-wrapper { position: sticky; max-height: calc(100vh - var(--mat-toolbar-standard-height, 64px)); @@ -167,6 +178,10 @@ padding: 0; } + .tb-iot-hub-filter-standalone { + margin-left: 13px; + } + .tb-iot-hub-filter-panel.mat-expansion-panel { .mat-expansion-panel-header { padding-left: 24px; @@ -199,6 +214,21 @@ background: rgba(0, 0, 0, 0.12); } +// 56px section-title inset minus the checkbox's own 11px +.tb-iot-hub-filter-standalone { + margin-left: 45px; +} + +.tb-iot-hub-filter-panel.mat-expansion-panel mat-checkbox, +.tb-iot-hub-filter-standalone { + display: block; + overflow: hidden; + + &:hover { + background: rgba(0, 0, 0, 0.04); + } +} + // Filter expansion panels — Design: no shadow, pl-40 for content .tb-iot-hub-filter-panel.mat-expansion-panel { box-shadow: none; @@ -221,15 +251,6 @@ padding: 0 8px 0 0; } - mat-checkbox { - display: block; - overflow: hidden; - - &:hover { - background: rgba(0, 0, 0, 0.04); - } - } - .tb-iot-hub-filter-items { padding-left: 44px; max-height: 340px; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 11352f1d04..d311ab325d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -4,23 +4,29 @@ import { AfterViewInit, Component, ElementRef, EventEmitter, Input, NgZone, OnDe import { Subject } from 'rxjs'; import { debounceTime, takeUntil } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { SortOrder } from '@shared/models/page/sort-order'; import { PageData } from '@shared/models/page/page-data'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, FilterParamInfo, CREATOR_VISIBLE_ITEM_TYPES } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + CREATOR_VISIBLE_ITEM_TYPES, + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + isCompactItemType, + ItemType +} from '@shared/models/iot-hub/iot-hub-item.models'; import { widgetTypeTranslations, cfTypeTranslations, ruleChainTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; import { IotHubInstalledItem, DeviceInstalledItemDescriptor } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; import { ActivatedRoute, Router } from '@angular/router'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; -import { filterIotHubItemsBySearch, groupIotHubFilterItems, IotHubFilterGroup } from '@home/components/iot-hub/iot-hub-utils'; - -interface SortOption { - value: string; - label: string; - direction: Direction; -} +import { + filterIotHubItemsBySearch, + groupIotHubFilterItems, + IOT_HUB_FILTER_SCROLL_THRESHOLD, + IotHubFilterGroup, + measureGridColumns +} from '@home/components/iot-hub/iot-hub-utils'; @Component({ selector: 'tb-iot-hub-browse', @@ -34,7 +40,6 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy private static typeTabLabel(t: ItemType): string { switch (t) { case ItemType.WIDGET: return 'item.type-widget-plural'; - case ItemType.DASHBOARD: return 'item.type-dashboard-plural'; case ItemType.SOLUTION_TEMPLATE: return 'item.type-solution-template-plural'; case ItemType.CALCULATED_FIELD: return 'item.type-calculated-field-plural'; case ItemType.ALARM_RULE: return 'item.type-alarm-rule-plural'; @@ -44,6 +49,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy } readonly ItemType = ItemType; + readonly scrollThreshold = IOT_HUB_FILTER_SCROLL_THRESHOLD; @Input() creatorId: string; @Input() embedded = false; @@ -51,6 +57,11 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy @Input() mode: 'default' | 'add' = 'default'; @Input() fixedSubType: string; @Output() addItem = new EventEmitter(); + /** + * Fired whenever an install, update or delete changed what this tenant has installed, so a host + * page showing its own installed-items counter can refresh it instead of waiting for a reload. + */ + @Output() installedItemsChanged = new EventEmitter(); @Input() set activeType(value: ItemType) { if (value && value !== this._activeType) { const wasInit = !!this._activeType; @@ -74,15 +85,12 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy } get isCompactType(): boolean { - return this._activeType === ItemType.CALCULATED_FIELD - || this._activeType === ItemType.ALARM_RULE - || this._activeType === ItemType.RULE_CHAIN; + return isCompactItemType(this._activeType); } get searchPlaceholderKey(): string { switch (this._activeType) { case ItemType.WIDGET: return 'iot-hub.search-widgets'; - case ItemType.DASHBOARD: return 'iot-hub.search-dashboards'; case ItemType.SOLUTION_TEMPLATE: return 'iot-hub.search-solution-templates'; case ItemType.CALCULATED_FIELD: return 'iot-hub.search-calculated-fields'; case ItemType.ALARM_RULE: return 'iot-hub.search-alarm-rules'; @@ -125,12 +133,9 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy activeConnectivity = new Set(); activeHardwareTypes = new Set(); activeVendors = new Set(); + verifiedCreatorsOnly = false; - sortOptions: SortOption[] = [ - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; + readonly sortOptions = IOT_HUB_SORT_OPTIONS; typeTabs: { type: ItemType; label: string }[] = CREATOR_VISIBLE_ITEM_TYPES.map(t => ({ type: t, @@ -217,17 +222,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy if (!el) { return this.probeCols; } - // Force layout so `grid-template-columns` resolves to pixel tracks, not `repeat(...)`. - void el.offsetWidth; - const tracks = getComputedStyle(el).gridTemplateColumns; - if (!tracks || tracks === 'none') { - return 1; - } - if (tracks.startsWith('repeat(')) { - const match = tracks.match(/^repeat\(\s*(\d+)\s*,/); - return match ? parseInt(match[1], 10) : 1; - } - return Math.max(1, tracks.trim().split(/\s+/).filter(t => t.length > 0).length); + return measureGridColumns(el); } private adjustPageSize(): void { @@ -393,6 +388,12 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy this.loadItems(); } + onVerifiedCreatorsToggle(): void { + this.verifiedCreatorsOnly = !this.verifiedCreatorsOnly; + this.pageIndex = 0; + this.loadItems(); + } + isVendorActive(vendor: string): boolean { return this.activeVendors.has(vendor); } @@ -496,12 +497,14 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy this.activeConnectivity.clear(); this.activeHardwareTypes.clear(); this.activeVendors.clear(); + this.verifiedCreatorsOnly = false; } get activeFilterCount(): number { const subtypeCount = this.fixedSubType ? this.getActiveSubtypesArray().length : (this.getActiveSubtypes()?.size || 0); return subtypeCount + this.activeCategories.size + this.activeUseCases.size + - this.activeConnectivity.size + this.activeHardwareTypes.size + this.activeVendors.size; + this.activeConnectivity.size + this.activeHardwareTypes.size + this.activeVendors.size + + (this.verifiedCreatorsOnly ? 1 : 0); } hasActiveDropdownFilters(): boolean { @@ -509,7 +512,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy return this.activeCategories.size > 0 || this.activeUseCases.size > 0 || subtypeCount > 0 || this.activeConnectivity.size > 0 || this.activeHardwareTypes.size > 0 || - this.activeVendors.size > 0; + this.activeVendors.size > 0 || this.verifiedCreatorsOnly; } hasActiveFilters(): boolean { @@ -519,7 +522,6 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy getTitle(): string { switch (this.activeType) { case ItemType.WIDGET: return 'iot-hub.title-widgets'; - case ItemType.DASHBOARD: return 'iot-hub.title-dashboards'; case ItemType.SOLUTION_TEMPLATE: return 'iot-hub.title-solution-templates'; case ItemType.CALCULATED_FIELD: return 'iot-hub.title-calculated-fields'; case ItemType.ALARM_RULE: return 'iot-hub.title-alarm-rules'; @@ -627,7 +629,11 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy }); } - private reloadInstalledItems(): void { + /** + * Re-reads what is installed for the active type and announces the change. Public so a host page + * that opens the item detail dialog itself can refresh this grid through the same path. + */ + reloadInstalledItems(): void { const config = {ignoreLoading: true}; const pageLink = new PageLink(10000, 0); if (this.activeType === ItemType.WIDGET) { @@ -643,6 +649,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy this.installedItemCounts = counts; }); } + this.installedItemsChanged.emit(); } private loadFilterInfo(): void { @@ -693,7 +700,8 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy ruleChainTypes: this.activeRuleChainTypes.size > 0 ? Array.from(this.activeRuleChainTypes) : undefined, hardwareTypes: this.activeHardwareTypes.size > 0 ? Array.from(this.activeHardwareTypes) : undefined, connectivity: this.activeConnectivity.size > 0 ? Array.from(this.activeConnectivity) : undefined, - vendors: this.activeVendors.size > 0 ? Array.from(this.activeVendors) : undefined + vendors: this.activeVendors.size > 0 ? Array.from(this.activeVendors) : undefined, + creatorVerified: this.verifiedCreatorsOnly }); this.iotHubApiService.getPublishedVersions( query, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts index f2327c253b..f6591ac8f8 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts @@ -14,6 +14,7 @@ import { TbIotHubUnpublishedWarningDialogComponent } from './iot-hub-unpublished import { TbDeviceInstallDialogComponent } from './device-install-dialog/device-install-dialog.component'; import { InstallFormRendererComponent } from './device-install-dialog/install-form-renderer/install-form-renderer.component'; import { TbIotHubSearchComponent } from './iot-hub-search.component'; +import { TbIotHubFacetListComponent } from './iot-hub-facet-list.component'; import { TbIotHubInstalledItemsTableComponent } from './iot-hub-installed-items-table.component'; import { TbIotHubInstalledItemsDialogComponent } from './iot-hub-installed-items-dialog.component'; import { TbIotHubSelectCfEntityDialogComponent } from './iot-hub-select-cf-entity-dialog.component'; @@ -37,6 +38,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link TbIotHubUnpublishedWarningDialogComponent, TbDeviceInstallDialogComponent, TbIotHubSearchComponent, + TbIotHubFacetListComponent, TbIotHubInstalledItemsTableComponent, TbIotHubInstalledItemsDialogComponent, TbIotHubSelectCfEntityDialogComponent, @@ -66,6 +68,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link TbIotHubUnpublishedWarningDialogComponent, TbDeviceInstallDialogComponent, TbIotHubSearchComponent, + TbIotHubFacetListComponent, TbIotHubInstalledItemsTableComponent, TbIotHubInstalledItemsDialogComponent, TbIotHubSelectCfEntityDialogComponent, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html new file mode 100644 index 0000000000..658ed108df --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html @@ -0,0 +1,31 @@ + + + + {{ label | translate }} + + + @if (searchable) { + + } + +
    + @for (key of visibleOptions; track key) { + + {{ labelFor(key) }} + + } +
    +
    diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss new file mode 100644 index 0000000000..494b251eb2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +@import "./iot-hub-common"; + +// Matches the type pages' filter panel, minus its rail indent. +.tb-iot-hub-facet-panel.mat-expansion-panel { + box-shadow: none; + border-radius: 0; + background: transparent; + + // Text is indented by --tb-facet-indent (set by the host); the rules between facets are not. + .mat-expansion-panel-header { + padding: 8px 16px 8px var(--tb-facet-indent, 16px); + height: 48px; + min-height: 48px; + } + + ::ng-deep .mat-expansion-panel-header-title { + font-size: 14px; + font-weight: 500; + color: rgba(0, 0, 0, 0.87); + } + + ::ng-deep .mat-expansion-panel-body { + padding: 0 8px 8px var(--tb-facet-indent, 16px); + } + + mat-checkbox { + display: block; + overflow: hidden; + + &:hover { + background: rgba(0, 0, 0, 0.04); + } + } + + .tb-iot-hub-facet-items { + // Capped only when long enough to scroll. + &.scrollable { + max-height: 280px; + overflow-y: auto; + } + + @include tb-iot-hub-hover-scrollbar; + } + + .tb-iot-hub-facet-search { + @include tb-iot-hub-search-container; + margin: 4px 8px 8px 0; + + mat-icon { + @include tb-iot-hub-search-icon(rgba(0, 0, 0, 0.54)); + } + + input { + @include tb-iot-hub-search-input-text(0.2px); + } + + .tb-iot-hub-facet-search-clear.mat-mdc-icon-button { + @include tb-iot-hub-search-clear; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts new file mode 100644 index 0000000000..fb62675145 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { Component, EventEmitter, Input, OnChanges, Output } from '@angular/core'; +import { filterByLabel, IOT_HUB_FILTER_SCROLL_THRESHOLD } from '@home/components/iot-hub/iot-hub-utils'; + +/** + * One checkbox facet of a filter panel: a title, the option keys, and the set of keys currently + * selected. Presentational only - the host decides what a toggle means. + */ +@Component({ + selector: 'tb-iot-hub-facet-list', + standalone: false, + templateUrl: './iot-hub-facet-list.component.html', + styleUrls: ['./iot-hub-facet-list.component.scss'] +}) +export class TbIotHubFacetListComponent implements OnChanges { + + /** Translation key for the facet's heading. */ + @Input() label: string; + + @Input() options: string[] = []; + + /** Keys the host has selected. The host hands over a new Set on every toggle. */ + @Input() selected = new Set(); + + /** Turns an option key into what the user reads. */ + @Input() labelFor: (key: string) => string = (key) => key; + + @Input() expanded = true; + + @Output() toggled = new EventEmitter(); + + search = ''; + searchable = false; + visibleOptions: string[] = []; + scrollable = false; + + ngOnChanges(): void { + this.searchable = this.options.length > IOT_HUB_FILTER_SCROLL_THRESHOLD; + this.applySearch(); + } + + onSearchChange(search: string): void { + this.search = search; + this.applySearch(); + } + + isSelected(key: string): boolean { + return this.selected.has(key); + } + + onToggle(key: string): void { + this.toggled.emit(key); + } + + private applySearch(): void { + this.visibleOptions = filterByLabel(this.options, this.search, this.labelFor); + this.scrollable = this.visibleOptions.length > IOT_HUB_FILTER_SCROLL_THRESHOLD; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html index e0745f549c..ca5f373996 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html @@ -130,12 +130,14 @@ @case ('error') {

    {{ 'iot-hub.install-error-title' | translate }}

    {{ 'iot-hub.install-error-message' | translate:{ name: item.name } }}

    - @if (item.type === ItemType.SOLUTION_TEMPLATE) { - - } @else { -
    - {{ errorMessage }} -
    + @if (errorMessage) { + @if (item.type === ItemType.SOLUTION_TEMPLATE) { + + } @else { +
    + {{ errorMessage }} +
    + } } } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 89214d628c..4c2fd30ab3 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -300,7 +300,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + this.errorMessage = result.errorMessage || ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -323,20 +323,31 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; + if (failedDependency) { + message = this.translate.instant('iot-hub.install-dependency-error', + { name: failedDependency.name, error: message }); + } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard // avoids the misleading warning on the "empty plan" failure, where nothing was installed. if (!result.rolledBack && this.planSummary.willInstall > 0) { - message += ' ' + this.translate.instant('iot-hub.install-rollback-partial'); + message = [message, this.translate.instant('iot-hub.install-rollback-partial')] + .filter(Boolean).join('\n\n'); } this.errorMessage = message; return; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss index 32e91f43c7..9c90354d0d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss @@ -116,7 +116,6 @@ .tb-type-calc-field { color: #3db5e0; background: rgba(61, 181, 224, 0.06); } .tb-type-alarm-rule { color: #d7702f; background: rgba(215, 112, 47, 0.06); } .tb-type-rule-chain { color: #aa5be3; background: rgba(170, 91, 227, 0.06); } -.tb-type-dashboard { color: #607d8b; background: rgba(96, 125, 139, 0.06); } // "vX.X.X Available" button — Design: border rgba(0,0,0,0.12), rounded-4, px-12 py-6, gap-8 .tb-installed-version-btn { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index c441060f5a..63c88b4cce 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -157,7 +157,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, getItemTypeChipClass(itemType: string): string { switch (itemType) { case 'WIDGET': return 'tb-type-widget'; - case 'DASHBOARD': return 'tb-type-dashboard'; case 'CALCULATED_FIELD': return 'tb-type-calc-field'; case 'ALARM_RULE': return 'tb-type-alarm-rule'; case 'RULE_CHAIN': return 'tb-type-rule-chain'; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html index cbde4bbf83..fee3e1a296 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html @@ -71,14 +71,15 @@ }
    } @else { - +
    @if (getPreviewUrl(); as previewUrl) { } @else {
    - {{ getPlaceholderIcon() }} + + {{ getPlaceholderIcon() }}
    }
    diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts index 22a4eaf323..123de28c3f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Component, EventEmitter, Input, Output } from '@angular/core'; import { MpItemVersionView, cfTypeTranslations, cfTypeIcons, ruleChainTypeTranslations, widgetTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; -import { getItemTypeIcon, ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; +import { getItemTypeIcon, isCompactItemType, ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { TranslateService } from '@ngx-translate/core'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -23,6 +23,11 @@ export class TbIotHubItemCardComponent { @Input() showTypeChip = true; @Input() showSubtype = false; @Input() mode: 'default' | 'add' = 'default'; + /** + * `auto`: compact row for the types with nothing to preview (single-type grids widen their + * cells for it). `preview`: the tall card for every type, for grids that mix types. + */ + @Input() layout: 'auto' | 'preview' = 'auto'; @Output() cardClick = new EventEmitter(); @Output() creatorClick = new EventEmitter(); @Output() installClick = new EventEmitter(); @@ -47,9 +52,10 @@ export class TbIotHubItemCardComponent { } isCompactLayout(): boolean { - return this.item.type === ItemType.CALCULATED_FIELD - || this.item.type === ItemType.ALARM_RULE - || this.item.type === ItemType.RULE_CHAIN; + if (this.layout === 'preview') { + return false; + } + return isCompactItemType(this.item.type); } getPreviewUrl(): string | null { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html index 28e7e74e6d..cdcaf1360b 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html @@ -13,7 +13,7 @@
    }
    - {{ item.name }} + {{ itemTitle }}
    {{ getTypeIcon() }} @@ -75,7 +75,7 @@
    @if (isCompactLayout()) { - +
    @if (item.description) { @@ -86,11 +86,15 @@
    } @else { - +
    - @if (item.type === ItemType.SOLUTION_TEMPLATE && carouselImages.length > 1) { + [class.dlg-preview-carousel]="carouselImages.length > 1" + tbPhotoSwipeGallery galleryChildrenSelector=".dlg-carousel-item, .dlg-preview-img" + (lightboxOpened)="lightboxOpen = true" + (slideChanged)="carouselIndex = $event" + (lightboxClosed)="lightboxOpen = false"> + @if (carouselImages.length > 1) {
    } @else { - @if (getPreviewUrl(); as url) { + @if (carouselImages[0]; as url) { } @else {
    @@ -156,7 +160,7 @@
    -
    +
    @if (showCreator) {
    {{ 'iot-hub.creator' | translate }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.scss index facb441ade..75db00eec7 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.scss @@ -144,6 +144,10 @@ &.dlg-preview-carousel { aspect-ratio: 1.5; } + + img { + cursor: zoom-in; + } } .dlg-preview-img { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts index d1c6f4f194..60ed0022bc 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts @@ -7,7 +7,7 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; import { MpItemVersionView, cfTypeTranslations, cfTypeIcons, ruleChainTypeTranslations, widgetTypeTranslations, NodeInfo } from '@shared/models/iot-hub/iot-hub-version.models'; -import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { getItemTypeIcon, isCompactItemType, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { getInstalledItemUrl, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; @@ -49,6 +49,8 @@ export class TbIotHubItemDetailDialogComponent extends DialogComponent r.type === 'SCREENSHOT'); - const allResources = screenshotResources.length > 0 - ? screenshotResources - : this.item.resources.filter(r => r.type === 'ICON'); - this.carouselImages = allResources.map(r => - this.iotHubApiService.resolveResourceUrl(`/api/resources/${r.id}`) - ); + const urls: string[] = []; + const previewUrl = this.getPreviewUrl(); + if (previewUrl) { + urls.push(previewUrl); + } + // Skip the screenshot the preview already shows; by id, since item.image may carry a suffix + const previewResourceId = this.item.image?.match(/\/api\/resources\/([^/?#]+)/)?.[1]; + for (const resource of this.item.resources || []) { + if (resource.type === 'SCREENSHOT' && resource.id !== previewResourceId) { + urls.push(this.resourceUrl(resource.id)); + } + } + if (!urls.length) { + // Same order as resolveIotHubItemImageUrl: image, screenshot, then a single icon stand-in + const icon = this.item.resources?.find(resource => resource.type === 'ICON'); + if (icon) { + urls.push(this.resourceUrl(icon.id)); + } + } + this.carouselImages = urls; + } + + private resourceUrl(id: string): string { + return this.iotHubApiService.resolveResourceUrl(`/api/resources/${id}`); } private loadReadme(): void { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.html index 7e7a0edd23..5d7dc04f30 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.html @@ -4,7 +4,9 @@ SPDX-License-Identifier: Apache-2.0 --> - code { + white-space: pre-wrap; + } + div.code-wrapper { display: inline-block; width: 100%; + // Reserve room for the absolutely positioned copy icon, plus the same gap on its + // far side, so the cell text does not run underneath it and the reservation + // follows the chip if its geometry ever changes. + padding-right: $copy-icon-width + 2 * $copy-icon-offset; button.clipboard-btn { top: -6px; @@ -275,11 +304,10 @@ $gallery-border-hover-color: #2a7dec; margin-top: 20px; margin-bottom: 20px; overflow: hidden; - table-layout: fixed; - - &.auto { - table-layout: auto; - } + // Columns are sized to their content: with fixed layout every column got the + // same width, so cells with long values (e-mails, logins, tokens) had to wrap + // mid-word while short columns kept a lot of unused space. + table-layout: auto; > thead { background-color: $table-header-background-color; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts index f2ca8d8251..a733041f24 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts @@ -24,6 +24,14 @@ import { import { DevicePackageInfo } from '@shared/models/iot-hub/device-package.models'; import { isNotEmptyStr } from '@core/utils'; +// Every image the readme itself renders opens in the lightbox. Excluded is the chrome that happens +// to be an : the ${images.gallery(...)} block (it runs its own gallery), the code block +// clipboard icon and an item link card's thumbnail. Images inside a link are excluded too: the +// lightbox preventDefaults the click, which would swallow the navigation. +const README_GALLERY_SELECTOR = + 'img:not(.tb-gallery-images img):not(.clipboard-btn img):not(tb-iot-hub-item-link-card img):not(a img)'; +const README_GALLERY_IMAGE_CLASS = 'tb-readme-gallery-image'; + @Component({ selector: 'tb-iot-hub-markdown', standalone: false, @@ -61,6 +69,8 @@ export class TbIotHubMarkdownComponent implements OnInit, OnChanges { readonly itemLinkCompileModules: Type[] = [IotHubItemLinkModule]; + readonly readmeGallerySelector = README_GALLERY_SELECTOR; + constructor( private iotHubApiService: IotHubApiService, private elementRef: ElementRef @@ -86,6 +96,8 @@ export class TbIotHubMarkdownComponent implements OnInit, OnChanges { onReady() { const container = this.elementRef.nativeElement; + container.querySelectorAll(README_GALLERY_SELECTOR) + .forEach(image => image.classList.add(README_GALLERY_IMAGE_CLASS)); this.ready.emit(container); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-pe-required-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-pe-required-dialog.component.html index 5e1adf0ef9..bb79075f15 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-pe-required-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-pe-required-dialog.component.html @@ -23,7 +23,7 @@ {{ 'action.close' | translate }}
    diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-pe-required-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-pe-required-dialog.component.ts index 73fb98b503..67a6a78116 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-pe-required-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-pe-required-dialog.component.ts @@ -28,6 +28,6 @@ export class TbIotHubPeRequiredDialogComponent extends DialogComponent -
    +
    {{ 'iot-hub.results-count' | translate:{ count: totalElements } }}
    - -
    + + + + +
    + @if (showFilters) { + + }
    -
    +
    {{ 'iot-hub.results-count' | translate:{ count: totalElements } }} @@ -76,62 +88,98 @@
    -
    - -
    - - @if (hasError) { -
    -
    -

    {{ 'iot-hub.network-server-unavailable' | translate }}

    -

    {{ 'iot-hub.network-server-unavailable-text' | translate }}

    - -
    + + +
    + @if (activeFilterCount > 0) { + } - - - @if (!hasError && totalElements === 0 && searchText?.trim()) { -
    -
    -

    {{ 'iot-hub.no-items-found' | translate }}

    -

    {{ 'iot-hub.try-adjusting-search' | translate }}

    -
    + + + @if (categoryOptions.length > 0) { + + + } + @if (useCaseOptions.length > 0) { + + + } +
    +
    - - @if (resultGroups.length > 0) { -
    - @for (group of resultGroups; track group.type) { -
    - - - -
    - @for (item of group.items; track item.id) { - - - } -
    -
    - } -
    +
    + + +
    + @if (showFilters) { + } + +
    + + @if (hasError) { +
    +
    +

    {{ 'iot-hub.network-server-unavailable' | translate }}

    +

    {{ 'iot-hub.network-server-unavailable-text' | translate }}

    + +
    + } + + + @if (!hasError && totalElements === 0 && searchText?.trim()) { +
    +
    +

    {{ 'iot-hub.no-items-found' | translate }}

    +

    {{ 'iot-hub.try-adjusting-search' | translate }}

    +
    + } + + + @if (results.length > 0) { +
    + @for (item of results; track item.id) { + + + } +
    + } +
    diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss index 4b43ad5b3c..ff79875722 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss @@ -8,6 +8,13 @@ flex-direction: column; } +// Full bleed: content rows pad themselves in by --tb-search-side-pad; the divider and the filter +// rail reach the edge. +.tb-search-pad { + padding-left: var(--tb-search-side-pad, 0px); + padding-right: var(--tb-search-side-pad, 0px); +} + .tb-search-results-count-mobile { display: none; margin-left: auto; @@ -143,69 +150,113 @@ overflow: auto; } -// Categories / sections -.tb-search-categories { - display: flex; - flex-direction: column; - gap: 48px; +// Card grid +.tb-search-card-grid { + display: grid; + grid-template-columns: repeat(5, 1fr); + gap: 20px; + + // Zero-height probe for the column count; needs display: grid and a width to resolve tracks. + &.tb-search-card-grid-probe { + width: 100%; + height: 0; + gap: 0; + overflow: hidden; + visibility: hidden; + pointer-events: none; + } } -// Section header -.tb-search-section-header { - font-size: 18px; - font-weight: 500; - line-height: 24px; - color: rgba(0, 0, 0, 0.87); - padding: 0; - margin-bottom: 12px; +// Filter button, with the active count +.tb-search-filter-btn { + flex-shrink: 0; +} + +.tb-search-filter-count { + margin-left: 6px; + min-width: 18px; + height: 18px; + padding: 0 5px; + border-radius: 9px; + background: rgba(0, 0, 0, 0.08); + font-size: 12px; + line-height: 18px; + font-variant-numeric: tabular-nums; +} - mat-icon { - font-size: 24px; - width: 24px; - height: 24px; +// Facet sidebar beside the grid. Both columns scroll inside the given height, so neither grows +// past the card. +.tb-search-layout { + display: flex; + gap: 24px; + height: 100%; + min-height: 0; + + .tb-results-container { + flex: 1; + min-width: 0; + // Only on the right: the gap to the rail already separates it on the left. + padding-right: var(--tb-search-side-pad, 0px); } } -// Card grid -.tb-search-card-grid { - display: grid; - grid-template-columns: repeat(5, 1fr); - gap: 20px; +.tb-search-facets-desktop { + width: 232px; + flex-shrink: 0; + border-right: 1px solid rgba(0, 0, 0, 0.12); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(3, 1fr); + // Starts at the card's edge so the rules across it reach it; each facet indents its own text. + --tb-facet-indent: var(--tb-search-side-pad, 16px); + + align-self: stretch; + height: 100%; + overflow-y: auto; + padding-top: 20px; + + @include tb-iot-hub-hover-scrollbar; +} + +// The close button and heading belong to the narrow layout only. +.tb-search-facets-header { + display: none; + height: 48px; + font-size: 16px; + font-weight: 500; +} + +.tb-search-facets { + display: flex; + flex-direction: column; + padding-bottom: 24px; + + // A flush rule between filter sections, as on the type pages. + tb-iot-hub-facet-list + tb-iot-hub-facet-list { + border-top: 1px solid rgba(0, 0, 0, 0.12); } } +.tb-search-facets-clear { + align-self: flex-start; + margin-left: calc(var(--tb-facet-indent, 16px) - 16px); +} + // Responsive @media #{$mat-gt-xxl} { .tb-search-card-grid { grid-template-columns: repeat(6, 1fr); - - &.tb-search-card-grid-compact { - grid-template-columns: repeat(4, 1fr); - } } } @media #{$mat-lt-xl} { .tb-search-card-grid { grid-template-columns: repeat(4, 1fr); - - &.tb-search-card-grid-compact { - grid-template-columns: repeat(3, 1fr); - } } } @media #{$mat-lt-xmd} { .tb-search-card-grid { grid-template-columns: repeat(3, 1fr); - - &.tb-search-card-grid-compact { - grid-template-columns: repeat(2, 1fr); - } } } @@ -228,10 +279,6 @@ .tb-search-card-grid { grid-template-columns: repeat(2, 1fr); - - &.tb-search-card-grid-compact { - grid-template-columns: repeat(1, 1fr); - } } } @@ -268,3 +315,36 @@ margin-left: 0; } } + +// Below this width the sidebar collapses and the Filter button opens it above the results. +@media #{$mat-lt-lg} { + .tb-search-layout { + flex-direction: column; + } + + .tb-search-facets-desktop { + display: none; + // Above the results it is content, not a rail, so it is padded in like the rows above. + width: 100%; + height: auto; + max-height: 60vh; + border-right: none; + border-bottom: 1px solid rgba(0, 0, 0, 0.12); + padding-right: 0; + + &.opened { + display: block; + } + } + + .tb-search-facets-header { + display: flex; + } +} + +// The sidebar is shown, so there is nothing for the button to open. +@media #{$mat-gt-md} { + .tb-search-filter-btn { + display: none; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts index f915be77e1..2ce6a552c7 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts @@ -1,33 +1,29 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; +import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, ViewChild, ElementRef, NgZone } from '@angular/core'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; -import { forkJoin, Subject, Subscription } from 'rxjs'; -import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; +import { forkJoin, of, Subject, Subscription } from 'rxjs'; +import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { SortOrder } from '@shared/models/page/sort-order'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { PageData } from '@shared/models/page/page-data'; +import { + CROSS_TYPE_ITEM_TYPES, + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + ItemType, + itemTypeTranslations +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from './iot-hub-actions.service'; +import { measureGridColumns } from './iot-hub-utils'; -interface SearchResultGroup { - type: ItemType; - items: MpItemVersionView[]; -} - -interface SortOption { - value: string; - label: string; - direction: Direction; -} - -const TYPE_ORDER: ItemType[] = [ - ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, - ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN -]; +/** A page is whole rows of the grid, and never fewer than MIN_PAGE_SIZE cards. */ +const ROWS_PER_PAGE = 3; +const MIN_PAGE_SIZE = 12; @Component({ selector: 'tb-iot-hub-search', @@ -37,32 +33,50 @@ const TYPE_ORDER: ItemType[] = [ }) export class TbIotHubSearchComponent implements OnInit, OnDestroy { - readonly ItemType = ItemType; - @Input() searchText = ''; @Input() creatorId: string; @Input() showCreator = true; + /** Off on the creator profile, which is already scoped to one creator. */ + @Input() showFilters = true; @Output() searchTextChange = new EventEmitter(); get searchPlaceholderKey(): string { return this.creatorId ? 'iot-hub.search-published-items' : 'iot-hub.search'; } - resultGroups: SearchResultGroup[] = []; + results: MpItemVersionView[] = []; totalElements = 0; isLoading = false; hasError = false; private retryTimer: any = null; - pageSize = 15; pageIndex = 0; - pageSizeOptions = [15, 30, 60]; - sortOptions: SortOption[] = [ - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; + /** A hidden element carrying the real grid's classes, so the column count comes from the CSS. */ + @ViewChild('cardGridProbe', { static: true }) cardGridProbe!: ElementRef; + cols = 5; + pageSize = MIN_PAGE_SIZE; + private resizeObserver?: ResizeObserver; + private resizeSubject = new Subject(); + private resizeSubscription?: Subscription; + + get pageSizeOptions(): number[] { + const base = Math.max(MIN_PAGE_SIZE, this.cols * ROWS_PER_PAGE); + return [base, base * 2, base * 4]; + } + + // Filter panel state. An empty set means "no filter". + + /** Narrow widths only: the facet panel is a block above the results, not a sidebar. */ + filtersOpen = false; + readonly typeOptions: string[] = CROSS_TYPE_ITEM_TYPES; + categoryOptions: string[] = []; + useCaseOptions: string[] = []; + activeTypes = new Set(); + activeCategories = new Set(); + activeUseCases = new Set(); + + readonly sortOptions = IOT_HUB_SORT_OPTIONS; selectedSortIndex = 0; installedWidgets: IotHubInstalledItem[] = []; @@ -74,16 +88,30 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { private searchSubject = new Subject(); private searchSubscription: Subscription; + /** Every reload goes through here, so a newer request cancels an older one still in flight. */ + private loadSubject = new Subject(); + private loadSubscription: Subscription; constructor( private router: Router, private translate: TranslateService, private iotHubApiService: IotHubApiService, - private iotHubActions: IotHubActionsService + private iotHubActions: IotHubActionsService, + private zone: NgZone ) {} ngOnInit(): void { + this.measureCols(); + this.observeGridWidth(); + if (this.showFilters) { + this.loadFilterInfo(); + } this.loadInstalledItems(); + this.loadSubscription = this.loadSubject.pipe( + switchMap(() => this.fetchResults(this.searchText || '').pipe( + catchError(() => of(null)) + )) + ).subscribe(result => this.applyResult(result)); this.searchSubscription = this.searchSubject.pipe( debounceTime(300), distinctUntilChanged() @@ -96,6 +124,125 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.searchSubscription?.unsubscribe(); + this.loadSubscription?.unsubscribe(); + this.resizeSubscription?.unsubscribe(); + this.resizeObserver?.disconnect(); + } + + // Filters + + getTypeLabel = (key: string): string => { + const translationKey = itemTypeTranslations.get(key as ItemType); + return translationKey ? this.translate.instant(translationKey + '-plural') : key; + }; + + onTypeToggle(key: string): void { + this.activeTypes = this.toggled(this.activeTypes, key); + this.reloadFromFirstPage(); + } + + onCategoryToggle(key: string): void { + this.activeCategories = this.toggled(this.activeCategories, key); + this.reloadFromFirstPage(); + } + + onUseCaseToggle(key: string): void { + this.activeUseCases = this.toggled(this.activeUseCases, key); + this.reloadFromFirstPage(); + } + + get activeFilterCount(): number { + return this.activeTypes.size + this.activeCategories.size + this.activeUseCases.size; + } + + clearFilters(): void { + if (this.activeFilterCount === 0) { + return; + } + this.activeTypes = new Set(); + this.activeCategories = new Set(); + this.activeUseCases = new Set(); + this.reloadFromFirstPage(); + } + + /** A new Set rather than a mutation, so the facet list's @Input sees the change. */ + private toggled(set: Set, key: string): Set { + const next = new Set(set); + if (!next.delete(key)) { + next.add(key); + } + return next; + } + + private reloadFromFirstPage(): void { + this.pageIndex = 0; + this.loadResults(); + } + + /** + * filterInfo answers per item type, so the six answers are merged. Each request has its own + * catchError: one type failing costs that type's options, not the panel. + */ + private loadFilterInfo(): void { + const config = { ignoreLoading: true, ignoreErrors: true }; + forkJoin( + CROSS_TYPE_ITEM_TYPES.map(type => + this.iotHubApiService.getFilterInfo(type, config).pipe(catchError(() => of(null))) + ) + ).subscribe({ + next: infos => { + this.categoryOptions = this.mergeFacet(infos.map(i => i?.categories)); + this.useCaseOptions = this.mergeFacet(infos.map(i => i?.useCases)); + } + }); + } + + /** Keys that have items in any of the per-type answers, sorted. */ + private mergeFacet(lists: (FilterParamInfo[] | undefined)[]): string[] { + const keys = new Set(); + for (const list of lists) { + for (const option of list || []) { + if (option.totalItems > 0) { + keys.add(option.key); + } + } + } + return [...keys].sort((a, b) => a.localeCompare(b)); + } + + // Column count -> page size + + private observeGridWidth(): void { + const el = this.cardGridProbe?.nativeElement; + if (!el || typeof ResizeObserver === 'undefined') { + return; + } + this.resizeSubscription = this.resizeSubject.pipe(debounceTime(150)).subscribe(() => { + const before = this.pageSizeOptions[0]; + // Keep the same first item in view, not the same page number. + const firstItem = this.pageIndex * this.pageSize; + this.measureCols(); + if (this.pageSizeOptions[0] === before) { + return; + } + this.pageSize = this.pageSizeOptions[0]; + this.pageIndex = Math.floor(firstItem / this.pageSize); + this.loadResults(); + }); + // zone.js does not patch ResizeObserver; without zone.run the reload would not render. + this.resizeObserver = new ResizeObserver(() => this.zone.run(() => this.resizeSubject.next())); + this.resizeObserver.observe(el); + } + + private measureCols(): void { + const el = this.cardGridProbe?.nativeElement; + if (!el) { + return; + } + this.cols = measureGridColumns(el); + if (!this.pageSizeOptions.includes(this.pageSize)) { + this.pageSize = this.pageSizeOptions[0]; + } } onSearchInput(): void { @@ -158,35 +305,6 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { this.loadResults(); } - // Type helpers - isCompactType(type: ItemType): boolean { - return type === ItemType.CALCULATED_FIELD - || type === ItemType.ALARM_RULE - || type === ItemType.RULE_CHAIN; - } - - getTypeLabel(type: ItemType): string { - const key = itemTypeTranslations.get(type); - return key ? this.translate.instant(key + '-plural') : type; - } - - getTypeRoute(type: ItemType): string { - switch (type) { - case ItemType.WIDGET: return 'widgets'; - case ItemType.SOLUTION_TEMPLATE: return 'solution-templates'; - case ItemType.CALCULATED_FIELD: return 'calculated-fields'; - case ItemType.ALARM_RULE: return 'alarm-rules'; - case ItemType.RULE_CHAIN: return 'rule-chains'; - case ItemType.DEVICE: return 'devices'; - default: return 'widgets'; - } - } - - navigateToType(type: ItemType): void { - const search = this.searchText?.trim() || undefined; - void this.router.navigate(['/iot-hub', this.getTypeRoute(type)], { queryParams: { search } }); - } - // Installed items getInstalledItem(item: MpItemVersionView): IotHubInstalledItem | undefined { switch (item.type) { @@ -270,52 +388,39 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { clearTimeout(this.retryTimer); this.retryTimer = null; } + // hasError stays as-is until a request succeeds. this.isLoading = true; - // hasError stays as-is until the request actually succeeds - // (cleared in the `next` callback below). - this.fetchResults(this.searchText || '').subscribe({ - next: result => { - this.applyResults(result.data, result.totalElements); - this.hasError = false; - }, - error: () => { - this.isLoading = false; - this.hasError = true; - this.resultGroups = []; - this.totalElements = 0; - } - }); + this.loadSubject.next(); + } + + /** A null result is a failed request. */ + private applyResult(result: PageData | null): void { + this.isLoading = false; + if (result) { + this.totalElements = result.totalElements; + this.results = result.data; + this.hasError = false; + } else { + this.hasError = true; + this.results = []; + this.totalElements = 0; + } } private fetchResults(text: string) { const sort = this.sortOptions[this.selectedSortIndex]; const sortOrder: SortOrder = { property: sort.value, direction: sort.direction }; const pageLink = new PageLink(this.pageSize, this.pageIndex, text.trim() || null, sortOrder); - const query = new MpItemVersionQuery(pageLink, { creatorId: this.creatorId || undefined }); + const query = new MpItemVersionQuery(pageLink, { + creatorId: this.creatorId || undefined, + // No type selected means every type the platform surfaces (the Hub also holds dashboards). + types: this.activeTypes.size ? [...this.activeTypes] : CROSS_TYPE_ITEM_TYPES, + categories: this.activeCategories.size ? [...this.activeCategories] : undefined, + useCases: this.activeUseCases.size ? [...this.activeUseCases] : undefined + }); return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true, ignoreErrors: true }); } - private applyResults(data: MpItemVersionView[], totalElements: number): void { - this.totalElements = totalElements; - this.resultGroups = this.groupResults(data); - this.isLoading = false; - } - - private groupResults(items: MpItemVersionView[]): SearchResultGroup[] { - const groupMap = new Map(); - for (const item of items) { - let list = groupMap.get(item.type); - if (!list) { - list = []; - groupMap.set(item.type, list); - } - list.push(item); - } - return TYPE_ORDER - .filter(type => groupMap.has(type)) - .map(type => ({ type, items: groupMap.get(type) })); - } - private loadInstalledItems(): void { const config = { ignoreLoading: true }; const pageLink = new PageLink(10000, 0); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html index 70efb190c3..a1fffb0a9d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html @@ -8,11 +8,11 @@ @switch (state) { @case ('confirm') {

    {{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }}

    -

    {{ 'iot-hub.update-desc' | translate }}

    +

    {{ updateDescKey | translate }}

    } @case ('updating') {

    {{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }}

    -

    {{ 'iot-hub.update-desc' | translate }}

    +

    {{ updateDescKey | translate }}

    } @case ('success') {

    {{ 'iot-hub.update-success-title' | translate }}

    diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts index ec4a48cd2d..e5472c45a1 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts @@ -59,6 +59,17 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent(items: T[], search: string, labelOf: (item: T) => string): T[] { + const normalized = (search || '').trim().toLowerCase(); if (!normalized) { return items; } - return items.filter(item => item.key.toLowerCase().includes(normalized)); + return items.filter(item => labelOf(item).toLowerCase().includes(normalized)); +} + +export function filterIotHubItemsBySearch(items: FilterParamInfo[], search: string): FilterParamInfo[] { + return filterByLabel(items, search, item => item.key); +} + +/** Column count of a CSS grid, from its computed tracks (`repeat(...)` before first layout). */ +export function measureGridColumns(el: HTMLElement): number { + void el.offsetWidth; + const tracks = getComputedStyle(el).gridTemplateColumns; + if (!tracks || tracks === 'none') { + return 1; + } + if (tracks.startsWith('repeat(')) { + const match = tracks.match(/^repeat\(\s*(\d+)\s*,/); + return match ? parseInt(match[1], 10) : 1; + } + return Math.max(1, tracks.trim().split(/\s+/).filter(t => t.length > 0).length); } export function groupIotHubFilterItems(items: FilterParamInfo[], search: string): IotHubFilterGroup[] { diff --git a/ui-ngx/src/app/modules/home/components/widget/config/basic/gauge/digital-simple-gauge-basic-config.component.ts b/ui-ngx/src/app/modules/home/components/widget/config/basic/gauge/digital-simple-gauge-basic-config.component.ts index 5e2c51f1a4..1eb2d860cb 100644 --- a/ui-ngx/src/app/modules/home/components/widget/config/basic/gauge/digital-simple-gauge-basic-config.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/config/basic/gauge/digital-simple-gauge-basic-config.component.ts @@ -27,7 +27,7 @@ import { DigitalGaugeSettings, DigitalGaugeType } from '@home/components/widget/lib/digital-gauge.models'; -import { ColorSettings, ColorType } from '@shared/models/widget-settings.models'; +import { ColorSettings, ColorType, normalizeColorRangeSettings } from '@shared/models/widget-settings.models'; import { getSourceTbUnitSymbol } from '@shared/models/unit.models'; @Component({ @@ -161,8 +161,8 @@ export class DigitalSimpleGaugeBasicConfigComponent extends BasicWidgetConfigCom if (barColor.type === ColorType.range) { this.widgetConfig.config.settings.useFixedLevelColor = true; - this.widgetConfig.config.settings.fixedLevelColors = - barColor.rangeList.advancedMode ? barColor.rangeList.rangeAdvanced : barColor.rangeList.range; + const rangeList = normalizeColorRangeSettings(barColor.rangeList); + this.widgetConfig.config.settings.fixedLevelColors = rangeList?.advancedMode ? rangeList.rangeAdvanced : rangeList?.range; } else { this.widgetConfig.config.settings.useFixedLevelColor = false; } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/ce-grant-tokens.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/ce-grant-tokens.scss new file mode 100644 index 0000000000..3df82ec15e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/ce-grant-tokens.scss @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +/* `:host` serves the encapsulated widget; `.tb-ce-grant-dialog-panel` the un-encapsulated dialog's overlay. */ +@mixin tb-ce-grant-tokens { + --tb-brand: #17685a; + --tb-brand-tint: #e2f1ec; + --tb-brand-ink: #0e5a4e; + + --tb-ink: rgba(0, 0, 0, 0.87); + --tb-ink-2: rgba(0, 0, 0, 0.6); + --tb-ink-3: rgba(0, 0, 0, 0.38); + --tb-line: rgba(0, 0, 0, 0.12); + + --tb-warn: #f44336; + + --tb-caution: #b26500; + --tb-caution-tint: rgb(255 167 38 / 0.14); + + --tb-radius-card: 8px; + + --tb-font-mono: "Roboto Mono", ui-monospace, monospace; + + --tb-detail-bg: #f6f8f9; + --tb-note-bg: rgba(0, 0, 0, 0.03); + --tb-code-bg: rgba(0, 0, 0, 0.03); +} + +:host { + @include tb-ce-grant-tokens; +} + +.tb-ce-grant-dialog-panel { + @include tb-ce-grant-tokens; +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.html new file mode 100644 index 0000000000..343656a496 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.html @@ -0,0 +1,555 @@ + + +
    + {{ value }} +
    + +
    + + +
    + security +

    {{ textKey | translate }}

    +
    +
    + + +
    + {{ 'ce-grant.safe-to-close' | translate }} + +
    +
    + + +
    + @if (reportPending) { +
    + +
    + } @else if (reportLoadError) { +

    {{ reportLoadError }}

    + } @else { +

    {{ 'ce-grant.result-lede' | translate }}

    + + } +
    +
    + @if (reportLoadError) { + + + } @else { + {{ 'ce-grant.result-safe-to-close' | translate }} + + @if (showHandedOver) { + + } + } +
    +
    + +
    + + +

    {{ 'ce-grant.title' | translate }}

    + + +
    + @if (isLoading$ | async) { + + } + + @if (!config.hero) { + @if (config.rail) { + + } + + @if (config.topBanner) { +
    + @switch (config.topBanner) { + @case ('offlineBanner') { +
    + cloud_off +

    {{ 'ce-grant.offline-caution' | translate }}

    + +
    + @if (registerErrorMessage) { +

    {{ registerErrorMessage }}

    + } + } + } +
    + } + +
    + @if (config.spinner) { + + } @else { +
    + {{ config.icon }} +
    + } +

    {{ title | translate }}

    +
    + } + + @if (!stateKnown) { +
    + @if (initialLoadFailed) { +

    {{ 'ce-grant.load-error-lede' | translate }}

    + } @else { + + } +
    +
    + + @if (initialLoadFailed) { + + } +
    + } @else { + @switch (state) { + + @case (communityGrantState.intro) { +
    + +
    +
    + +
    +
    +
    +

    {{ 'ce-grant.intro-heading' | translate }}

    +
    +

    {{ 'ce-grant.intro-lede' | translate }}

    +

    + + {{ 'ce-grant.intro-read-announcement' | translate }} + mdi:arrow-top-right + +

    + @if (registerErrorMessage) { +

    {{ registerErrorMessage }}

    + } +
    +
    + +
    +

    {{ 'ce-grant.intro-included-title' | translate }}

    +
      +
    • + check + + {{ 'ce-grant.intro-included-devices-and-servers-lead' | translate }} + {{ 'ce-grant.intro-included-devices-and-servers-text' | translate }} + +
    • +
    • + check + + {{ 'ce-grant.intro-included-permanent-lead' | translate }} + {{ 'ce-grant.intro-included-permanent-text' | translate }} + +
    • +
    • + check + + {{ 'ce-grant.intro-included-security-lead' | translate }} + {{ 'ce-grant.intro-included-security-text' | translate }} + +
    • +
    • + check + + {{ 'ce-grant.intro-included-register-lead' | translate }} + {{ 'ce-grant.intro-included-register-text' | translate }} + +
    • +
    + +

    {{ 'ce-grant.intro-assurance' | translate }}

    +
    + +
    + + +
    +
    + } + + @case (communityGrantState.awaiting) { +
    +

    {{ 'ce-grant.awaiting-lede' | translate }}

    +
    +

    + {{ 'ce-grant.need-link' | translate }} +

    +

    + {{ (stalled ? 'ce-grant.stall-note': 'ce-grant.link-use-note') | translate }} +

    + +

    + + {{ 'ce-grant.link-share-caution' | translate }} +

    +
    +
    + + } + + @case (communityGrantState.verifying) { +
    +

    {{ 'ce-grant.verifying-lede' | translate }}

    + + @if (stalled) { +
    +

    + {{ 'ce-grant.no-report-yet' | translate }} +

    +

    + {{ 'ce-grant.verifying-stall-note' | translate }} +

    + +
    + } +
    + + } + + @case (communityGrantState.registered) { +
    +
    + + + + + {{ 'ce-grant.ce-grant' | translate }} + {{ 'ce-grant.ce-grant-note' | translate }} + +
    +

    {{ 'ce-grant.registered-lede' | translate }}

    +
    +
    + + + {{ 'ce-grant.card-registered-link' | translate }} + mdi:arrow-top-right + +
    + } + + @case (communityGrantState.review) { +
    +

    {{ 'ce-grant.review-lede' | translate }}

    +
    +
    + +
    + } + + @case (communityGrantState.offline) { +
    +

    {{ 'ce-grant.offline-lede' | translate }}

    + +

    + + {{ 'ce-grant.link-share-caution' | translate }} +

    +
    +
    + + +
    + } + + @case (communityGrantState.verify) { +
    +

    {{ 'ce-grant.verify-lede' | translate }}

    +

    {{ 'ce-grant.verify-upload-tool' | translate }}

    +
    + + + @if (bundleFile) { + + insert_drive_file + {{ bundleFile.name }} + + + } +
    + @if (!noBundleSelected && !bundleError) { +

    {{ 'ce-grant.verify-upload-hint' | translate }}

    + } + @if (noBundleSelected) { +

    {{ 'ce-grant.verify-error-no-file' | translate }}

    + } + @if (bundleError === communityGrantBundleErrorCode.NOT_A_BUNDLE) { +

    {{ 'ce-grant.verify-error-not-a-bundle' | translate }}

    + } + @if (bundleError === communityGrantBundleErrorCode.MALFORMED) { +

    {{ 'ce-grant.verify-error-malformed' | translate }}

    + } + @if (bundleExpiredAt) { +
    + warning +

    {{ 'ce-grant.bundle-expired-warning' | translate: {date: bundleExpiredAt | date: 'medium'} }}

    +
    + } + + @if (checkFailed) { + @if (checkFailedMessage) { + +

    {{ checkFailedMessage }}

    + } @else { +

    + } + } +
    +
    + + @if (bundleFile || runCheckPending) { + + } @else { + + } +
    + } + + @case (communityGrantState.result) { + + } + @case (communityGrantState.handedOver) { + + } + @case (communityGrantState.expired) { +
    + @if (checkFailedPark) { +

    {{ 'ce-grant.check-failed-lede' | translate }}

    +

    + } @else if (portalUnreachablePark) { +

    {{ 'ce-grant.portal-unreachable-lede' | translate }}

    +

    {{ 'ce-grant.portal-unreachable-text' | translate }}

    + } @else { +

    {{ 'ce-grant.expired-lede' | translate }}

    +

    {{ 'ce-grant.expired-text' | translate }}

    + } + @if (registerErrorMessage) { +

    {{ registerErrorMessage }}

    + } +
    +
    + + +
    + } + + @case (communityGrantState.already) { +
    +

    {{ 'ce-grant.already-lede-no-mask' | translate }}

    +

    +

    {{ 'ce-grant.already-someone-else-registered' | translate }}

    + @if (accessRequested) { +

    {{ 'ce-grant.already-request-sent' | translate }}

    + } + @if (requestAccessErrorMessage) { +

    {{ requestAccessErrorMessage }}

    + } +
    +
    + + +
    + } + + @case (communityGrantState.wrongInstallation) { +
    +

    {{ 'ce-grant.wrong-installation-lede' | translate }}

    +

    +
    +
    + +
    + } + } + } +
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.scss new file mode 100644 index 0000000000..fbf6cf5d75 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.scss @@ -0,0 +1,709 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 + +/* ViewEncapsulation.None: every rule stays nested under .tb-ce-grant-dialog-panel or .tb-ce-grant-dialog. */ +@import "constants"; +@import "mixins"; + +.tb-ce-grant-dialog-panel { + width: min(600px, 100%); + + .mdc-dialog__surface { + border-radius: var(--tb-radius-card); + } + + &.tb-ce-grant-dialog-panel-wide { + width: min(860px, 100%); + + /* The intro's actions live inside the grid, so the whole sheet scrolls rather than its content. */ + .mdc-dialog__surface { + overflow-y: auto; + } + + .mat-mdc-dialog-content { + max-height: none; + } + } + + @media screen and (max-width: 900px) { + &.tb-ce-grant-dialog-panel-wide { + width: min(600px, 100%); + } + } + + @media #{$mat-lt-sm} { + .mdc-dialog__surface { + border-radius: 0; + } + } +} + +.tb-dialog .mat-mdc-dialog-container .tb-ce-grant-dialog { + display: flex; + flex-direction: column; + + --mat-progress-spinner-active-indicator-color: var(--tb-brand); + + mat-toolbar.mat-toolbar { + --mat-toolbar-container-background-color: var(--tb-brand); + --mat-toolbar-container-text-color: #fff; + --mat-toolbar-standard-height: 52px; + --mat-toolbar-mobile-height: 52px; + + flex: none; + /* Keeps the only close control in reach while the intro's sheet scrolls. */ + position: sticky; + top: 0; + z-index: 2; + gap: 12px; + padding: 0 8px 0 20px; + + /* mat-dialog-title here only labels the dialog; drop its dialog layout */ + h2.mat-mdc-dialog-title { + display: block; + padding: 0; + margin: 0; + font-size: 16px; + font-weight: 500; + line-height: normal; + letter-spacing: 0.005em; + color: inherit; + + &::before { + display: none; + } + } + } + + .tb-ce-grant-banner-container { + margin: 16px 24px 0; + } + + .tb-ce-grant-condition { + display: flex; + align-items: center; + gap: 10px; + padding: 5px 6px 5px 14px; + border-radius: 8px; + background: var(--tb-caution-tint); + .mat-icon { + @include tb-mat-icon-size(20); + flex: none; + color: var(--tb-caution); + } + svg { + flex: none; + color: var(--tb-caution); + } + p { + flex: 1; + min-width: 0; + margin: 0; + font-size: 13px; + line-height: 1.5; + color: var(--tb-ink); + } + } + + .tb-ce-grant-status { + flex: none; + padding: 24px 24px 0; + + h2 { + margin: 0; + font-size: 20px; + font-weight: 500; + line-height: 1.3; + letter-spacing: 0.005em; + color: var(--tb-ink); + } + } + + .tb-ce-grant-mark { + position: relative; + display: flex; + align-items: center; + justify-content: center; + width: 44px; + height: 44px; + margin: 0 0 14px; + border-radius: 50%; + background: var(--tb-brand); + color: #fff; + + &.tb-ce-grant-mark-live { + &::after { + content: ''; + position: absolute; + inset: 0; + border-radius: 50%; + animation: tb-ce-grant-mark-listen 2.4s cubic-bezier(0.25, 0, 0.35, 1) infinite; + } + @keyframes tb-ce-grant-mark-listen { + 0% { box-shadow: 0 0 0 0 rgb(23 104 90 / 0.30); } + 70% { box-shadow: 0 0 0 13px rgb(23 104 90 / 0); } + 100% { box-shadow: 0 0 0 0 rgb(23 104 90 / 0); } + } + } + + &.tb-ce-grant-mark-info { + background: rgba(0, 0, 0, 0.55); + color: #fff; + } + + .mat-icon { + @include tb-mat-icon-size(22); + + color: inherit; + } + } + + /* Display-only: no navigation, no content pane. */ + mat-stepper.tb-ce-grant-rail { + --mat-stepper-container-color: transparent; + --mat-stepper-header-height: auto; + --mat-stepper-line-color: var(--tb-line); + --mat-stepper-header-icon-background-color: transparent; + --mat-stepper-header-icon-foreground-color: #fff; + --mat-stepper-header-selected-state-icon-background-color: transparent; + --mat-stepper-header-selected-state-icon-foreground-color: #fff; + --mat-stepper-header-done-state-icon-background-color: var(--tb-brand); + --mat-stepper-header-done-state-icon-foreground-color: #fff; + --mat-stepper-header-label-text-size: 13px; + --mat-stepper-header-label-text-color: var(--tb-ink-3); + --mat-stepper-header-selected-state-label-text-size: 13px; + --mat-stepper-header-selected-state-label-text-color: var(--tb-ink-3); + --mat-stepper-header-selected-state-label-text-weight: 500; + --mat-stepper-header-hover-state-layer-color: transparent; + --mat-stepper-header-focus-state-layer-color: transparent; + + flex: none; + padding: 17px 24px; + border-bottom: 1px solid var(--tb-line); + pointer-events: none; + + .mat-horizontal-stepper-header-container { + align-items: center; + .mat-stepper-horizontal-line { + min-width: 16px; + margin: 0 10px; + border-top-width: 2px; + border-top-color: var(--tb-brand); + } + .mat-horizontal-stepper-header[aria-selected="true"] ~ .mat-stepper-horizontal-line { + border-top-color: var(--tb-line); + } + .mat-step-label { + line-height: 1.55; + &.mat-step-label-selected { + color: var(--tb-ink); + } + .tb-ce-grant-rail-completed { + color: var(--tb-ink-2); + } + } + } + + .mat-horizontal-content-container { + display: none; + } + + .mat-horizontal-stepper-header { + padding: 0; + overflow: visible; + } + + .mat-step-icon { + width: 20px; + height: 20px; + margin: 0 7px 0 0; + + .mat-icon { + font-weight: 600; + @include tb-mat-icon-size(14); + } + } + + .mat-step-icon-state-done { + border: 2px solid var(--tb-brand); + } + + .mat-step-icon-state-number { + border: 2px solid var(--tb-ink-3); + + &.mat-step-icon-selected { + border-color: var(--tb-brand); + + .tb-ce-grant-rail-dot { + background: var(--tb-brand); + } + } + } + + .mat-step-icon-state-edit { + background: none; + } + + .tb-ce-grant-rail-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: transparent; + } + + .tb-ce-grant-rail-active { + flex: none; + width: 20px; + height: 20px; + border-radius: 50%; + border: 2px solid var(--tb-brand); + display: flex; + align-items: center; + justify-content: center; + color: #fff; + .tb-ce-grant-rail-dot { + background: var(--tb-brand); + } + } + } + + .mat-mdc-dialog-content { + padding: 18px 24px 4px; + color: var(--tb-ink-2); + + > p { + margin: 0 0 14px; + font-size: 14px; + line-height: 1.6; + color: var(--tb-ink-2); + } + + > p.tb-ce-grant-body-lede { + font-size: 15px; + color: var(--tb-ink); + } + .tb-ce-grant-section { + margin-top: 24px; + padding-top: 16px; + border-top: 1px solid var(--tb-line); + overflow: hidden; + .tb-ce-grant-section-header { + margin: 0 0 6px; + font-size: 14px; + font-weight: 500; + color: var(--tb-ink); + } + .tb-ce-grant-section-note { + margin: 0 0 12px; + font-size: 13px; + line-height: 1.55; + color: var(--tb-ink-2); + } + } + } + + .mat-mdc-dialog-actions { + flex-wrap: wrap; + gap: 8px; + min-height: 0; + padding: 26px 24px 20px; + + > :not(:first-child) { + margin-left: 0; + } + } + + .tb-ce-grant-safe { + margin-right: auto; + font-size: 12.5px; + color: var(--tb-ink-3); + } + + .mat-mdc-unelevated-button.mat-primary { + --mat-button-filled-container-color: var(--tb-brand); + --mat-button-filled-label-text-color: #fff; + --mat-button-filled-icon-color: #fff; + } + + .mat-mdc-outlined-button.mat-primary:not(:disabled) { + --mat-button-outlined-label-text-color: var(--tb-brand-ink); + --mat-button-outlined-icon-color: var(--tb-brand-ink); + border-color: var(--tb-line); + } + + .mat-mdc-button:not(.mat-primary):not(.mat-accent):not(.mat-warn) { + --mat-button-text-label-text-color: var(--tb-ink-2); + } + + .mat-mdc-button.mat-primary { + --mat-button-text-label-text-color: var(--tb-brand-ink); + --mat-button-text-icon-color: var(--tb-brand-ink); + --mat-button-text-state-layer-color: var(--tb-brand); + } + + .mat-mdc-dialog-content.tb-ce-grant-cols { + display: grid; + grid-template-columns: 1.02fr 1fr; + grid-template-rows: 1fr auto; + padding: 0; + } + + .tb-ce-grant-pitch-col { + grid-column: 1; + grid-row: 1 / span 2; + } + + .tb-ce-grant-detail-col { + grid-column: 2; + grid-row: 1; + padding: 40px 24px 4px; + background: var(--tb-detail-bg); + } + + .tb-ce-grant-cols .mat-mdc-dialog-actions { + grid-column: 2; + grid-row: 2; + padding: 26px 24px 26px; + background: var(--tb-detail-bg); + justify-content: end; + } + + .tb-ce-grant-hero { + display: flex; + align-items: center; + justify-content: center; + padding: 18px 14px 2px; + + img { + display: block; + width: 360px; + max-width: 100%; + height: auto; + } + } + + .tb-ce-grant-pad { + padding: 14px 22px 4px; + } + + .tb-ce-grant-pitch { + padding: 8px 0 14px; + text-align: left; + + h2 { + max-width: none; + margin: 0; + font-size: 26px; + font-weight: 500; + line-height: 1.25; + letter-spacing: -0.01em; + color: var(--tb-ink); + } + } + + .tb-ce-grant-lede { + letter-spacing: normal; + margin: 0 0 12px; + font-size: 14px; + line-height: 1.6; + color: var(--tb-ink-2); + } + + .tb-ce-grant-readmore { + margin: 0 0 20px; + font-size: 13px; + line-height: 1.55; + letter-spacing: normal; + + a { + display: inline-flex; + align-items: center; + gap: 0; + color: var(--tb-brand-ink); + text-decoration: none; + white-space: nowrap; + border-bottom: none; + + &:hover { + text-decoration: underline; + text-underline-offset: 3px; + } + + tb-icon { + @include tb-mat-icon-size(14); + + color: inherit; + } + } + } + + /* The global button-icon rule spaces the wrong side of a trailing icon. */ + .mat-mdc-button-base tb-icon[iconPositionEnd] { + @include tb-mat-icon-size(16); + + margin: 0 0 0 6px; + } + + .tb-ce-grant-label { + margin: 0 0 10px; + font-size: 15px; + font-weight: 500; + color: var(--tb-ink); + } + + .tb-ce-grant-list { + margin: 0; + padding: 0; + list-style: none; + + li { + display: flex; + gap: 10px; + padding: 6px 0; + font-size: 14px; + line-height: 1.55; + color: var(--tb-ink-2); + letter-spacing: normal; + } + + b { + font-weight: 500; + color: var(--tb-ink); + } + + .mat-icon { + @include tb-mat-icon-size(15); + transform: scale(1.5); + margin: 4px 0 0; + color: var(--tb-brand-ink); + } + } + + mat-divider { + margin: 20px 0 0; + border-top-color: var(--tb-line); + } + + .tb-ce-grant-assurance { + margin: 16px 0 0; + font-size: 12.5px; + line-height: 1.6; + letter-spacing: normal; + color: var(--tb-ink-2); + } + + .tb-ce-grant-code { + max-height: calc(4.5em + 24px); + overflow-y: auto; + overscroll-behavior: contain; + padding: 12px 14px; + border-radius: 6px; + background: var(--tb-code-bg); + + code { + display: block; + font-family: var(--tb-font-mono); + font-size: 13px; + line-height: 1.5; + color: var(--tb-ink); + word-break: break-all; + } + } + .tb-ce-grant-link-acts { + display: flex; + align-items: center; + justify-content: flex-end; + flex-wrap: wrap; + gap: 4px; + margin-top: 12px; + overflow: hidden; + } + + /* "Copied" is inert but not disabled, so it keeps its color */ + .mat-mdc-button, .mat-mdc-unelevated-button { + &.tb-ce-grant-copy { + flex: none; + min-width: 0; + --mat-button-text-with-icon-horizontal-padding: 24px; + --mat-button-filled-horizontal-padding: 24px; + + &.tb-ce-grant-copied { + pointer-events: none; + --mat-button-text-state-layer-color: transparent; + } + } + } + + .tb-ce-grant-infobar { + display: flex; + gap: 12px; + margin: 16px 0 4px; + padding: 13px 15px; + border-radius: 8px; + background: var(--tb-note-bg); + + .mat-icon { + @include tb-mat-icon-size(16); + + margin-top: 1px; + color: var(--tb-ink-3); + } + + p { + margin: 0; + font-size: 13px; + line-height: 1.6; + letter-spacing: normal; + color: var(--tb-ink-2); + } + } + + .tb-ce-grant-warnbar { + display: flex; + gap: 12px; + margin: 16px 0 4px; + padding: 13px 15px; + border-radius: 8px; + border: 1px solid color-mix(in srgb, var(--tb-warn) 40%, transparent); + background: color-mix(in srgb, var(--tb-warn) 8%, transparent); + + .mat-icon { + @include tb-mat-icon-size(16); + + margin-top: 1px; + color: var(--tb-warn); + } + + p { + margin: 0; + font-size: 13px; + line-height: 1.6; + color: var(--tb-ink); + } + } + + .tb-ce-grant-lic { + display: flex; + align-items: center; + gap: 12px; + margin: 0 0 16px; + padding: 12px 14px; + border: 1px solid var(--tb-line); + border-radius: 8px; + .tb-ce-grant-lic-mark { + flex: none; + width: 34px; + height: 34px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 50%; + background: rgb(0 105 92 / 0.1); + color: rgb(0 105 92); + } + .tb-ce-grant-lic-text { + display: flex; + flex-direction: column; + gap: 1px; + min-width: 0; + b { + font-size: 15px; + font-weight: 500; + color: var(--tb-ink); + } + span { + font-size: 13px; + color: var(--tb-ink-2); + } + } + } + + .tb-ce-grant-caution { + display: flex; + gap: 8px; + align-items: flex-start; + svg { + flex: none; + margin-top: 3px; + color: var(--tb-caution); + } + } + + p.tb-ce-grant-hint { + text-wrap: pretty; + margin: 14px 0 0; + font-size: 14px; + line-height: 1.55; + color: var(--tb-ink-2); + max-width: 56ch; + } + + p.tb-ce-grant-error { + margin: 10px 0 0; + font-size: 12.5px; + line-height: 1.5; + color: var(--tb-warn); + + a { + color: inherit; + font-weight: 500; + text-decoration: underline; + text-underline-offset: 2px; + } + } + + p.tb-ce-grant-file-title { + margin: 20px 0 10px; + font-size: 16px; + font-weight: 500; + color: var(--tb-ink); + } + .tb-ce-grant-file { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; + } + + .tb-ce-grant-file-name { + display: inline-flex; + align-items: center; + gap: 7px; + min-width: 0; + overflow-wrap: anywhere; + font-family: var(--tb-font-mono); + font-size: 12.5px; + color: var(--tb-ink-2); + .mat-icon { + flex: none; + color: var(--tb-ink-3); + } + } + + .tb-ce-grant-loading, + .tb-ce-grant-report-loading { + display: flex; + align-items: center; + justify-content: center; + padding: 40px 0; + } + + @media screen and (max-width: 900px) { + .mat-mdc-dialog-content.tb-ce-grant-cols { + display: block; + } + + .tb-ce-grant-pitch { + text-align: center; + + h2 { + max-width: 420px; + margin: 0 auto; + } + } + + .tb-ce-grant-detail-col { + padding-top: 24px; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.ts new file mode 100644 index 0000000000..33a6f79d58 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.ts @@ -0,0 +1,492 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { ChangeDetectorRef, Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { MatDialogRef } from '@angular/material/dialog'; +import { STEPPER_GLOBAL_OPTIONS } from '@angular/cdk/stepper'; +import { Router } from '@angular/router'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { DialogService } from '@core/services/dialog.service'; +import { ClipboardService } from 'ngx-clipboard'; +import { TranslateService } from '@ngx-translate/core'; +import { Subscription, interval, timer } from 'rxjs'; +import { switchMap } from 'rxjs/operators'; +import { CommunityGrantService } from '@core/http/community-grant.service'; +import { RequestConfig } from '@core/http/http-utils'; +import { + CommunityGrantBackendMode, + CommunityGrantBackendState, + CommunityGrantBundleErrorCode, + CommunityGrantBundleParseError, + CommunityGrantParkReason, + CommunityGrantRegistration, + CommunityGrantState, + CommunityGrantStateConfig, + communityGrantOnlinePollableStates, + communityGrantPollInterval, + communityGrantPortalUrl, + communityGrantRailLabels, + communityGrantStallTimeout, + communityGrantStateConfigs, + communityGrantStateTitles, + peekCommunityGrantBundle, + resolveCommunityGrantErrorMessage +} from '@shared/models/ce-grant/community-grant.models'; + +// The calling button shows both the error and the wait, so no toast and no global loading bar. +const startRequestConfig: RequestConfig = {ignoreErrors: true, ignoreLoading: true}; + +@Component({ + selector: 'tb-community-grant-dialog', + templateUrl: './community-grant-dialog.component.html', + styleUrls: ['./ce-grant-tokens.scss', './community-grant-dialog.component.scss'], + encapsulation: ViewEncapsulation.None, + // Lets `[state]` pick the node icons instead of Material's default indicator logic. + providers: [{provide: STEPPER_GLOBAL_OPTIONS, useValue: {displayDefaultIndicatorType: false}}], + standalone: false +}) +export class CommunityGrantDialogComponent extends DialogComponent + implements OnInit, OnDestroy { + + communityGrantState = CommunityGrantState; + communityGrantBundleErrorCode = CommunityGrantBundleErrorCode; + + get portalUrl(): string { + return this.registration.portalUrl ?? communityGrantPortalUrl; + } + + /** `intro` is only the default, so no state screen renders until the first `GET /state` answers. */ + stateKnown = false; + + initialLoadFailed = false; + + state = CommunityGrantState.intro; + + registration: CommunityGrantRegistration = {state: CommunityGrantState.intro}; + + registerPending = false; + retryPending = false; + runCheckPending = false; + startAgainPending = false; + requestAccessPending = false; + + registerErrorMessage: string = null; + + stalled = false; + + accessRequested = false; + requestAccessErrorMessage: string = null; + + bundleFile: File = null; + noBundleSelected = false; + bundleError: CommunityGrantBundleErrorCode = null; + bundleExpiredAt: number = null; + checkFailed = false; + checkFailedMessage: string = null; + + copiedValue: string = null; + + reportPending = false; + reportLoadError: string = null; + + private verifyEntryState = CommunityGrantState.offline; + + private pollSubscription: Subscription; + private stallSubscription: Subscription; + private initialLoadSubscription: Subscription; + private handoffSubscription: Subscription; + private copiedTimer: Subscription; + + constructor(protected store: Store, + protected router: Router, + public dialogRef: MatDialogRef, + private communityGrantService: CommunityGrantService, + private dialogService: DialogService, + private clipboardService: ClipboardService, + private translate: TranslateService, + private cd: ChangeDetectorRef) { + super(store, router, dialogRef); + dialogRef.addPanelClass('tb-ce-grant-dialog-panel'); + this.updatePanelWidth(); + } + + ngOnInit(): void { + this.loadInitialState(); + } + + private loadInitialState(): void { + this.initialLoadFailed = false; + this.initialLoadSubscription?.unsubscribe(); + this.initialLoadSubscription = this.communityGrantService.pollRegistration().subscribe({ + next: (registration) => { + this.stateKnown = true; + this.applyRegistration(registration); + }, + error: () => { + this.initialLoadFailed = true; + this.cd.markForCheck(); + } + }); + } + + retryInitialLoad(): void { + this.loadInitialState(); + } + + ngOnDestroy(): void { + this.stopPolling(); + this.initialLoadSubscription?.unsubscribe(); + this.handoffSubscription?.unsubscribe(); + this.copiedTimer?.unsubscribe(); + super.ngOnDestroy(); + } + + get config(): CommunityGrantStateConfig { + return communityGrantStateConfigs.get(this.state); + } + + get checkFailedPark(): boolean { + return this.isPark(CommunityGrantParkReason.CHECK_FAILED); + } + + get portalUnreachablePark(): boolean { + return this.isPark(CommunityGrantParkReason.PORTAL_UNREACHABLE); + } + + private isPark(reason: CommunityGrantParkReason): boolean { + return this.state === CommunityGrantState.expired && this.registration.parkReason === reason; + } + + get title(): string { + if (this.checkFailedPark) { + return 'ce-grant.check-failed-title'; + } + if (this.portalUnreachablePark) { + return 'ce-grant.portal-unreachable-title'; + } + return communityGrantStateTitles.get(this.state); + } + + get railLabels(): string[] { + return communityGrantRailLabels.get(this.config.rail) ?? []; + } + + get railSelectedIndex(): number { + return Math.min(this.config.railStep, this.railLabels.length - 1); + } + + railStepState(index: number): string { + return index < this.config.railStep ? 'done' : 'number'; + } + + get registrationLink(): string { + return this.registration.registrationLink; + } + + isCopied(value: string): boolean { + return this.copiedValue === value; + } + + copy(value: string): void { + this.clipboardService.copy(value); + this.copiedValue = value; + this.copiedTimer?.unsubscribe(); + this.copiedTimer = timer(1600).subscribe(() => { + this.copiedValue = null; + this.cd.markForCheck(); + }); + } + + private openLink(url: string): void { + window.open(url, '_blank'); + } + + loadReport(): void { + this.reportPending = true; + this.reportLoadError = null; + this.communityGrantService.downloadOfflineReport({ignoreErrors: true}).subscribe({ + next: (report) => { + this.reportPending = false; + if (!report) { + this.reportLoadError = this.translate.instant('ce-grant.result-error-empty'); + this.cd.markForCheck(); + return; + } + this.registration = {...this.registration, report}; + this.cd.markForCheck(); + }, + error: (err: HttpErrorResponse) => { + this.reportPending = false; + this.reportLoadError = this.extractErrorMessage(err, 'text'); + this.cd.markForCheck(); + } + }); + } + + register(open = true): void { + this.registerPending = true; + this.registerErrorMessage = null; + this.communityGrantService.register(startRequestConfig).subscribe({ + next: (registration) => { + this.registerPending = false; + this.applyRegistration(registration); + if (open && this.registrationLink && this.state === CommunityGrantState.awaiting) { + this.openLink(this.registrationLink); + } + }, + error: (err: HttpErrorResponse) => { + this.registerPending = false; + this.registerErrorMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + /** Re-mints over the live link this screen shows, which stops working. */ + retry(): void { + this.retryPending = true; + this.registerErrorMessage = null; + this.communityGrantService.register(startRequestConfig).subscribe({ + next: (registration) => { + this.retryPending = false; + this.applyRegistration(registration); + }, + error: (err: HttpErrorResponse) => { + this.retryPending = false; + this.registerErrorMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + startAgain(): void { + this.startAgainPending = true; + this.registerErrorMessage = null; + this.communityGrantService.register(startRequestConfig).subscribe({ + next: (registration) => { + this.startAgainPending = false; + this.applyRegistration(registration); + }, + error: (err: HttpErrorResponse) => { + this.startAgainPending = false; + this.registerErrorMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + requestAccess(): void { + this.requestAccessPending = true; + this.requestAccessErrorMessage = null; + this.communityGrantService.requestAccess({ignoreErrors: true}).subscribe({ + next: () => { + this.requestAccessPending = false; + this.accessRequested = true; + this.cd.markForCheck(); + }, + error: (err: HttpErrorResponse) => { + this.requestAccessPending = false; + this.requestAccessErrorMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + continueToCheck(): void { + this.verifyEntryState = CommunityGrantState.offline; + this.goToState(CommunityGrantState.verify); + } + + runCheckByHand(): void { + this.verifyEntryState = CommunityGrantState.verifying; + this.goToState(CommunityGrantState.verify); + } + + backFromVerify(): void { + this.goToState(this.verifyEntryState); + } + + bundleFileSelected(event: Event): void { + const input = event.target as HTMLInputElement; + this.bundleFile = input.files?.length ? input.files[0] : null; + this.noBundleSelected = false; + this.bundleError = null; + this.bundleExpiredAt = null; + this.checkFailed = false; + this.checkFailedMessage = null; + const chosen = this.bundleFile; + if (!chosen) { + this.cd.markForCheck(); + return; + } + peekCommunityGrantBundle(chosen).then(preflight => { + if (this.bundleFile !== chosen) { + return; + } + this.bundleExpiredAt = preflight.challengeExpired ? preflight.manifest.challengeExpiresAt : null; + this.cd.markForCheck(); + }).catch((e: unknown) => { + if (this.bundleFile !== chosen) { + return; + } + this.bundleError = e instanceof CommunityGrantBundleParseError + ? e.code : CommunityGrantBundleErrorCode.MALFORMED; + this.cd.markForCheck(); + }); + this.cd.markForCheck(); + } + + clearBundleFile(bundleInput: HTMLInputElement): void { + bundleInput.value = ''; + this.bundleFile = null; + this.noBundleSelected = false; + this.bundleError = null; + this.bundleExpiredAt = null; + this.checkFailed = false; + this.checkFailedMessage = null; + this.cd.markForCheck(); + } + + runCheck(): void { + this.noBundleSelected = !this.bundleFile; + this.checkFailed = false; + this.checkFailedMessage = null; + if (this.noBundleSelected || this.bundleError) { + this.cd.markForCheck(); + return; + } + this.runCheckPending = true; + this.communityGrantService.runOfflineScaleCheck(this.bundleFile).subscribe({ + next: (registration) => this.applyRegistration(registration), + error: (err: HttpErrorResponse) => { + this.runCheckPending = false; + this.checkFailed = true; + this.checkFailedMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + private extractErrorMessage(error: HttpErrorResponse, responseType?: string): string { + return resolveCommunityGrantErrorMessage(error, this.translate, responseType); + } + + /** A refusal usually means the poller moved the state on first, so the state is re-read instead. */ + confirmHandoff(): void { + this.handoffSubscription?.unsubscribe(); + this.handoffSubscription = this.communityGrantService.confirmOfflineHandoff({ignoreErrors: true}).subscribe({ + next: () => this.close(), + error: () => { + this.handoffSubscription = this.communityGrantService.pollRegistration({ignoreErrors: true}) + .subscribe(registration => this.applyRegistration(registration)); + } + }); + } + + close(): void { + this.dialogRef.close(); + } + + /** A by-hand run in progress holds the `verify` screen, whatever state the flow is in. */ + private applyRegistration(registration: CommunityGrantRegistration): void { + const awaitedRun = this.runCheckPending; + this.registration = registration; + this.runCheckPending = !!registration.offlineRunInProgress; + const failed = awaitedRun && !this.runCheckPending && !!registration.offlineRunError; + if (!this.runCheckPending && !failed) { + this.goToState(registration.state); + return; + } + this.showVerify(); + if (failed) { + this.checkFailed = true; + this.checkFailedMessage = registration.offlineRunError; + } + this.cd.markForCheck(); + } + + /** Stays on `verify` without {@link goToState}, which would clear the bundle's pre-flight warning. */ + private showVerify(): void { + if (this.state !== CommunityGrantState.verify) { + this.verifyEntryState = this.registration.state; + this.goToState(CommunityGrantState.verify); + return; + } + if (this.runCheckPending && !this.pollSubscription) { + this.startPolling(); + } else if (!this.runCheckPending) { + this.stopPolling(); + } + } + + private goToState(state: CommunityGrantState): void { + // `VALIDATING` + `ONLINE` with a report is a by-hand run's result, not the automatic wait. + if (state === CommunityGrantState.verifying && this.registration.report + && this.registration.backendState === CommunityGrantBackendState.VALIDATING + && this.registration.mode === CommunityGrantBackendMode.ONLINE) { + state = CommunityGrantState.result; + } + this.state = state; + this.stalled = false; + this.registerErrorMessage = null; + this.noBundleSelected = false; + this.bundleError = null; + this.bundleExpiredAt = null; + this.checkFailed = false; + this.checkFailedMessage = null; + this.reportPending = false; + this.reportLoadError = null; + this.requestAccessErrorMessage = null; + this.stopPolling(); + if (communityGrantOnlinePollableStates.has(state) || this.runCheckPending) { + this.startPolling(); + } + if ((state === CommunityGrantState.result || state === CommunityGrantState.handedOver) + && !this.registration.report) { + // The state omits the report when the server could not read it, so it is fetched on its own. + this.loadReport(); + } + this.updatePanelWidth(); + this.cd.markForCheck(); + } + + private updatePanelWidth(): void { + if (this.stateKnown && this.config.hero) { + this.dialogRef.addPanelClass('tb-ce-grant-dialog-panel-wide'); + } else { + this.dialogRef.removePanelClass('tb-ce-grant-dialog-panel-wide'); + } + } + + /** Compares more than the UI state: the mapping is many-to-one, and a re-mint changes only the link. */ + private startPolling(): void { + this.pollSubscription = interval(communityGrantPollInterval).pipe( + switchMap(() => this.communityGrantService.pollRegistration({ignoreLoading: true, ignoreErrors: true})) + ).subscribe((registration) => { + // A run in progress holds `verify`, so a differing mapped state alone is not a change. + const holdsVerify = this.runCheckPending && registration.offlineRunInProgress; + if ((!holdsVerify && registration.state !== this.state) + || registration.backendState !== this.registration.backendState + || registration.mode !== this.registration.mode + || registration.report !== this.registration.report + || registration.registrationLink !== this.registration.registrationLink + || registration.offlineRunInProgress !== this.registration.offlineRunInProgress + || registration.offlineRunError !== this.registration.offlineRunError) { + this.applyRegistration(registration); + } + }); + this.stallSubscription = timer(communityGrantStallTimeout).subscribe(() => { + this.stalled = true; + this.cd.markForCheck(); + }); + } + + private stopPolling(): void { + this.pollSubscription?.unsubscribe(); + this.pollSubscription = null; + this.stallSubscription?.unsubscribe(); + this.stallSubscription = null; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts index fa07dcc4e2..f3dcf6b1ad 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts @@ -23,6 +23,9 @@ import { } from '@home/components/widget/lib/home-page/recent-dashboards-widget.component'; import { IotHubWidgetComponent } from '@home/components/widget/lib/home-page/iot-hub-widget.component'; import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-components.module'; +import { + CommunityGrantDialogComponent +} from '@home/components/widget/lib/home-page/community-grant-dialog.component'; @NgModule({ declarations: @@ -41,7 +44,8 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone QuickLinkComponent, AddQuickLinkDialogComponent, RecentDashboardsWidgetComponent, - IotHubWidgetComponent + IotHubWidgetComponent, + CommunityGrantDialogComponent ], imports: [ CommonModule, @@ -63,7 +67,8 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone QuickLinkComponent, AddQuickLinkDialogComponent, RecentDashboardsWidgetComponent, - IotHubWidgetComponent + IotHubWidgetComponent, + CommunityGrantDialogComponent ] }) export class HomePageWidgetsModule { } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html index 7b0807a587..f332a8e86f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html @@ -4,49 +4,107 @@ SPDX-License-Identifier: Apache-2.0 --> -
    +
    -
    -
    -
    - -
    {{ updateMessage?.currentVersion }}
    -
    + + @switch (cardState()) { + + @case (communityGrantCardState.progress) { +
    +
    +

    + {{ grantCard().title | translate }} +

    +

    {{ grantCard().text | translate }}

    + @if (grantCard().waiting) { + + } @else { + + }
    -
    -
    -
    -
    - - widgets.version-info.available-version - widgets.version-info.available - + } + + @case (communityGrantCardState.status) { +
    +
    +

    + {{ grantCard().title | translate }} +

    +

    {{ grantCard().text | translate }}

    + @if (grantCardHasLinks()) { + + }
    -
    {{ updateMessage?.latestVersion }}
    -
    - {{ 'widgets.version-info.upgrade' | translate }} + @if (grantCard().action) { + + } +
    + } + + @case (communityGrantCardState.offer) { +
    +
    +

    {{'widgets.version-info.thingsboard-version-available' | translate: {version: offerVersion()} }}

    +

    {{ 'widgets.version-info.free-community-grant-text' | translate }}

    + @if (showExpiredNote()) { +

    {{ 'ce-grant.card-expired-note' | translate }}

    + } + @if (showCheckFailedNote()) { +

    {{ 'ce-grant.card-check-failed-note' | translate }}

    + } + @if (showPortalUnreachableNote()) { +

    {{ 'ce-grant.card-portal-unreachable-note' | translate }}

    + }
    + +

    {{ 'widgets.version-info.community-grant-registration-close' | translate }}

    -
    - {{ 'widgets.version-info.upgrade' | translate }} + } + + @case (communityGrantCardState.upToDate) { +
    +
    + +
    widgets.version-info.version-is-up-to-date
    +
    -
    -
    + } + + @default {} + }
    - -
    -
    check
    -
    widgets.version-info.version-is-up-to-date
    -
    -
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss index f6e77b092e..b64a74c258 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss @@ -3,61 +3,80 @@ @import "../../../../../../../scss/constants"; :host { + + .tb-card-content { + display: flex; + flex-direction: column; + gap: 14px; + @media #{$mat-md-lg} { + gap: 4px; + } + } .tb-card-header { display: flex; flex-direction: row; justify-content: space-between; align-items: center; - margin-bottom: 8px; @media #{$mat-md-lg} { margin-bottom: 4px; } + .tb-title { + font-size: 16px; + font-weight: 500; + color: rgba(0, 0, 0, 0.87); + @media #{$mat-md-lg} { + font-size: 12px; + } + } } - .tb-contact-us { + a.tb-contact-us { + font-size: 13.5px; + border-bottom-color: transparent; + &:hover, &:focus { + border-bottom-color: #4054b2; + } @media #{$mat-md-lg} { - height: 24px; font-size: 12px; } } .tb-version-info-container { - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - padding: 8px 16px 4px 16px; - overflow: hidden; + display: flex; + gap: 8px; + align-items: center; + border: 1px solid rgba(0, 0, 0, 0.12); + border-radius: 8px; + padding: 12px 14px; white-space: nowrap; - @media #{$mat-lt-md} { - padding: 16px; - } @media #{$mat-md-lg} { padding: 4px; } &.up-to-date { box-shadow: none; border: none; - background: #F3F6FA; white-space: initial; text-align: center; } } .tb-version-link { + display: flex; + align-items: center; + gap: 8px; font-weight: 400; font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); + line-height: 1.55; + letter-spacing: normal; + color: rgba(0, 0, 0, 0.6); position: relative; border-bottom: none; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } &:hover, &:focus { border-bottom: none; } + b { + color: rgba(0, 0, 0, 0.87); + } &::after { content: 'arrow_forward'; display: inline-block; @@ -68,36 +87,149 @@ font-size: 18px; color: rgba(0, 0, 0, 0.12); vertical-align: bottom; - margin-left: 6px; + margin-left: -4px; } &:hover::after { color: inherit; } } - .tb-version { + /* Shared geometry, so the widget keeps its height as the registration moves. */ + .tb-update-available-container, + .tb-grant-card { + display: flex; + flex-direction: column; + gap: 14px; + padding: 16px 18px; + border-radius: 8px; + background: var(--tb-brand-tint); + @media #{$mat-md-lg} { + gap: 4px; + padding: 8px 10px; + } + } + + .tb-update-available-container p, + .tb-grant-card-text { + letter-spacing: normal; + line-height: 1.55; + color: var(--tb-ink-2); + } + + .tb-update-available-container { + h3 { + letter-spacing: normal; + margin: 0 0 6px; + font-size: 15px; + font-weight: 500; + } + p { + margin: 0; + font-size: 13.5px; + } + .tb-grant-expired-note { + margin-top: 8px; + font-size: 12.5px; + @media #{$mat-md-lg} { + font-size: 11px; + } + } + } + + .tb-grant-card.held { + background: var(--tb-note-bg); + + .tb-grant-card-title, .tb-grant-card-icon { + color: var(--tb-ink-2); + } + } + + .tb-grant-card.done { + .tb-grant-card-title { + color: var(--tb-ink-2); + } + } + + .tb-grant-card-title { + display: flex; + align-items: center; + gap: 9px; + margin: 0; + letter-spacing: normal; + font-size: 14px; font-weight: 500; - font-size: 18px; - line-height: 24px; - letter-spacing: 0.15px; - color: rgba(0, 0, 0, 0.87); + color: var(--tb-ink); @media #{$mat-md-lg} { font-size: 12px; - line-height: 14px; } } - .tb-upgrade { + .tb-grant-card-icon { + flex: none; + font-size: 16px; + color: var(--tb-brand-ink); + } + + .tb-grant-live-dot { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--tb-brand); + animation: tbCeGrantPulse 1.6s ease-in-out infinite; + &.tb-waiting { + animation: none; + background: none; + box-shadow: inset 0 0 0 2px var(--tb-brand); + } + } + + .tb-grant-card-text { + margin: 8px 0 0; + font-size: 13px; @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - padding: 0; - overflow: hidden; + margin-top: 4px; + font-size: 11px; + } + } + + .tb-grant-card-link { + display: flex; + flex-wrap: wrap; + gap: 5px 18px; + margin: 12px 0 0; + letter-spacing: normal; + font-size: 12.5px; + + a { + display: inline-flex; + align-items: center; + gap: 4px; + color: var(--tb-brand-ink); + text-decoration: none; + border-bottom: none; + + &:hover, &:focus { + text-decoration: underline; + text-underline-offset: 3px; + border-bottom: none; + } + + tb-icon { + color: inherit; + } } } .check-icon { - color: #198038; + width: 34px; + height: 34px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + color: var(--tb-brand-ink); + background: var(--tb-brand-tint); font-weight: 600; @media #{$mat-md-lg} { font-size: 16px; @@ -107,12 +239,17 @@ .up-to-date-text { font-weight: 400; font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); + line-height: 1.55; + letter-spacing: normal; + color: rgba(0, 0, 0, 0.6); @media #{$mat-md-lg} { font-size: 11px; line-height: 16px; } } } + +@keyframes tbCeGrantPulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.3; } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts index d701f6f413..d4b25a1b0d 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; +import { ChangeDetectionStrategy, Component, computed, OnDestroy, OnInit, signal } from '@angular/core'; import { PageComponent } from '@shared/components/page.component'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; @@ -8,32 +8,152 @@ import { AdminService } from '@core/http/admin.service'; import { UpdateMessage } from '@shared/models/settings.models'; import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { Authority } from '@shared/models/authority.enum'; -import { of } from 'rxjs'; +import { of, Subscription } from 'rxjs'; +import { MatDialog } from '@angular/material/dialog'; +import { + CommunityGrantDialogComponent +} from '@home/components/widget/lib/home-page/community-grant-dialog.component'; +import { CommunityGrantService } from '@core/http/community-grant.service'; +import { + CommunityGrantCardState, + CommunityGrantParkReason, + CommunityGrantState, + communityGrantCardConfigs, + communityGrantPortalUrl, + communityGrantStateConfigs, + CommunityGrantCardConfig +} from '@shared/models/ce-grant/community-grant.models'; @Component({ selector: 'tb-version-info', templateUrl: './version-info.component.html', - styleUrls: ['./home-page-widget.scss', './version-info.component.scss'], + styleUrls: ['./home-page-widget.scss', './ce-grant-tokens.scss', './version-info.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, standalone: false }) -export class VersionInfoComponent extends PageComponent implements OnInit { +export class VersionInfoComponent extends PageComponent implements OnInit, OnDestroy { authUser = getCurrentAuthUser(this.store); - updateMessage: UpdateMessage; + + readonly updateMessage = signal(null); + + readonly registrationLink = signal(communityGrantPortalUrl); + + readonly communityGrantCardState = CommunityGrantCardState; + + /** Null is a real answer to the update check, so it cannot double as "not yet". */ + private readonly updateChecked = signal(false); + + private readonly grantState = signal(null); + + private readonly grantStateKnown = signal(false); + + readonly grantCard = computed(() => communityGrantCardConfigs.get(this.grantState()) ?? null); + + readonly grantIcon = computed(() => { + const state = communityGrantStateConfigs.get(this.grantState()); + return state?.cardIcon || state?.icon; + }); + + readonly grantCardHasLinks = computed(() => + this.hasLinks(communityGrantCardConfigs.get(this.grantState()) ?? null)); + + private readonly grantParkReason = signal(null); + + readonly showExpiredNote = computed(() => this.isPark(null)); + + readonly showCheckFailedNote = computed(() => this.isPark(CommunityGrantParkReason.CHECK_FAILED)); + + readonly showPortalUnreachableNote = + computed(() => this.isPark(CommunityGrantParkReason.PORTAL_UNREACHABLE)); + + /** A registration outranks the release offer; anything about the release waits for both reads. */ + readonly cardState = computed(() => { + const card = this.grantCard(); + if (card) { + return card.body; + } + if (!this.grantStateKnown() || !this.updateChecked()) { + return CommunityGrantCardState.pending; + } + return this.authUser.authority === Authority.SYS_ADMIN + ? CommunityGrantCardState.offer + : CommunityGrantCardState.upToDate; + }); + + readonly offerVersion = computed(() => + this.updateMessage()?.updateAvailable ? this.updateMessage().latestVersion : '4.4'); + + private communityGrantStateSubscription: Subscription; constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService) { + private adminService: AdminService, + private communityGrantService: CommunityGrantService, + private dialog: MatDialog) { super(store); } ngOnInit() { (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.checkUpdates() : of(null)).subscribe( - (updateMessage) => { - this.updateMessage = updateMessage; - this.cd.markForCheck(); - } - ); + this.adminService.checkUpdates() : of(null)).subscribe({ + next: (updateMessage) => { + this.updateMessage.set(updateMessage); + this.updateChecked.set(true); + }, + error: () => this.updateChecked.set(true) + }); + this.loadCommunityGrantState(); + } + + ngOnDestroy(): void { + this.communityGrantStateSubscription?.unsubscribe(); + super.ngOnDestroy(); + } + + private loadCommunityGrantState(): void { + if (this.authUser.authority !== Authority.SYS_ADMIN) { + this.grantStateKnown.set(true); + return; + } + this.communityGrantStateSubscription?.unsubscribe(); + this.communityGrantStateSubscription = this.communityGrantService.pollRegistration({ignoreErrors: true}) + .subscribe({ + next: (registration) => { + this.registrationLink.set(registration.registrationLink ?? communityGrantPortalUrl); + this.applyGrantState(registration.state, registration.parkReason); + }, + error: () => this.applyGrantState(null, null) + }); + } + + private applyGrantState(state: CommunityGrantState, parkReason: CommunityGrantParkReason): void { + this.grantState.set(state); + this.grantParkReason.set(parkReason); + this.grantStateKnown.set(true); + } + + /** `null` matches any park reason other than the two retryable ones. */ + private isPark(reason: CommunityGrantParkReason): boolean { + if (this.grantState() !== CommunityGrantState.expired) { + return false; + } + const parked = this.grantParkReason(); + return reason === null + ? parked !== CommunityGrantParkReason.CHECK_FAILED + && parked !== CommunityGrantParkReason.PORTAL_UNREACHABLE + : parked === reason; + } + + private hasLinks(config: CommunityGrantCardConfig): boolean { + return !!config?.registrationLink || !!config?.linkAction; + } + + getCommunityGrant(): void { + this.dialog.open(CommunityGrantDialogComponent, { + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + maxWidth: '100vw', + maxHeight: '92vh', + autoFocus: false + }).afterClosed().subscribe(() => this.loadCommunityGrantState()); } } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts index b918e859e6..a34f88e9b0 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts @@ -121,9 +121,6 @@ export const hereMapProviderTranslationMap = new Map( export interface HereMapProviderSettings { mapProviderHere: HereMapProvider; credentials: { - useV3: boolean; - app_id: string; - app_code: string; apiKey: string; }; } @@ -131,9 +128,6 @@ export interface HereMapProviderSettings { export const defaultHereMapProviderSettings: HereMapProviderSettings = { mapProviderHere: HereMapProvider.hereNormalDay, credentials: { - useV3: true, - app_id: 'AhM6TzD9ThyK78CT3ptx', - app_code: 'p6NPiITB3Vv0GMUFnkLOOg', apiKey: 'kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE' } }; diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts index 5afa3c4c6d..64f4f6752b 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts @@ -2,9 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import L from 'leaflet'; import LeafletMap from '../leaflet-map'; -import { DEFAULT_ZOOM_LEVEL, WidgetUnitedMapSettings } from '../map-models'; +import { DEFAULT_ZOOM_LEVEL, defaultHereMapProviderSettings, WidgetUnitedMapSettings } from '../map-models'; import { WidgetContext } from '@home/models/widget-component.models'; -import { isDefinedAndNotNull } from '@core/utils'; +import { hereV3Provider } from '@shared/models/widget/maps/map.models'; export class HEREMap extends LeafletMap { constructor(ctx: WidgetContext, $container: HTMLElement, options: WidgetUnitedMapSettings) { @@ -13,11 +13,8 @@ export class HEREMap extends LeafletMap { doubleClickZoom: !this.options.disableDoubleClickZooming, zoomControl: !this.options.disableZoomControl }).setView(options?.parsedDefaultCenterPosition, options?.defaultZoomLevel || DEFAULT_ZOOM_LEVEL); - let provider = options.mapProviderHere || 'HERE.normalDay'; - if (options.credentials.useV3 && isDefinedAndNotNull(options.credentials.apiKey)) { - provider = options.mapProviderHere?.replace('HERE', 'HEREv3') || 'HEREv3.normalDay'; - } - const tileLayer = (L.tileLayer as any).provider(provider, options.credentials); + const apiKey = options.credentials?.apiKey || defaultHereMapProviderSettings.credentials.apiKey; + const tileLayer = L.tileLayer.provider(hereV3Provider(options.mapProviderHere), {apiKey}); tileLayer.addTo(map); super.setMap(map); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts index 9ad91048d7..d092a0078f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts @@ -3,7 +3,7 @@ import L, { TB } from 'leaflet'; import { guid, isDefinedAndNotNull, isNotEmptyStr } from '@core/utils'; import 'leaflet-providers'; -import { Map as MapLibreGLMap, LngLat as MapLibreGLLngLat } from 'maplibre-gl'; +import { Map as MapLibreGLMap, setWorkerUrl } from 'maplibre-gl'; import '@geoman-io/leaflet-geoman-free'; import 'leaflet.markercluster'; import { MatIconRegistry } from '@angular/material/icon'; @@ -1070,6 +1070,9 @@ const chinaProvider = (type: string, options?: L.TileLayerOptions): L.TB.TileLay return new ChinaProvider(type, options); } +// The worker is copied to assets by angular.json, bundlers cannot resolve it from import.meta.url +setWorkerUrl(new URL('assets/maplibre-gl/maplibre-gl-worker.mjs', document.baseURI).href); + class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { options: TB.MapLibreGL.LeafletMapLibreGLMapOptions; @@ -1246,23 +1249,19 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { this._transformGL(gl); - if (gl.transform.width !== size.x || gl.transform.height !== size.y) { + if (container.clientWidth !== size.x || container.clientHeight !== size.y) { container.style.width = size.x + 'px'; container.style.height = size.y + 'px'; gl.resize(); - } else { - gl._update(); } } private _transformGL(gl: MapLibreGLMap) { const center = this._map.getCenter(); - const tr = gl._getTransformForUpdate(); - if (!tr) { return; } - tr.setCenter(MapLibreGLLngLat.convert([center.lng, center.lat])); - tr.setZoom(this._map.getZoom() - 1); - gl.transform.apply(tr); - gl._fireMoveEvents(); + gl.jumpTo({ + center: [center.lng, center.lat], + zoom: this._map.getZoom() - 1 + }); } private _pinchZoom() { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts index a79f290c9b..d61e81ca6e 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 import { + CartoMapLayerSettings, CustomMapLayerSettings, + defaultCartoMapLayerSettings, defaultCustomMapLayerSettings, defaultGoogleMapLayerSettings, defaultHereMapLayerSettings, @@ -10,8 +12,10 @@ import { defaultTencentMapLayerSettings, GoogleMapLayerSettings, HereMapLayerSettings, + hereV3Provider, MapLayerSettings, MapProvider, + normalizeMapLayerSettings, OpenStreetMapLayerSettings, ReferenceLayerType, TencentMapLayerSettings, WEBGL_ERROR_EVENT @@ -46,9 +50,12 @@ export abstract class TbMapLayer { static fromSettings(ctx: WidgetContext, inputSettings: DeepPartial) { + inputSettings = normalizeMapLayerSettings(inputSettings as MapLayerSettings); switch (inputSettings.provider) { case MapProvider.openstreet: return new TbOpenStreetMapLayer(ctx, inputSettings); + case MapProvider.carto: + return new TbCartoMapLayer(ctx, inputSettings); case MapProvider.google: return new TbGoogleMapLayer(ctx, inputSettings); case MapProvider.tencent: @@ -212,6 +219,24 @@ class TbOpenStreetMapLayer extends TbMapLayer { } +class TbCartoMapLayer extends TbMapLayer { + + constructor(protected ctx: WidgetContext, + protected inputSettings: DeepPartial) { + super(ctx, inputSettings); + } + + protected defaultSettings(): CartoMapLayerSettings { + return defaultCartoMapLayerSettings; + } + + protected createLayer(): Observable { + const layer = L.tileLayer.provider(this.settings.layerType, {apikey: this.settings.apiKey || ''}); + return of(layer); + } + +} + class TbGoogleMapLayer extends TbMapLayer { static loadedApiKeysGlobal: {[key: string]: boolean} = {}; @@ -293,7 +318,7 @@ class TbHereMapLayer extends TbMapLayer { protected createLayer(): Observable { const apiKey = this.settings.apiKey || defaultHereMapLayerSettings.apiKey; - const layer = L.tileLayer.provider(this.settings.layerType, {useV3: true, apiKey} as any); + const layer = L.tileLayer.provider(hereV3Provider(this.settings.layerType), {apiKey}); return of(layer); } @@ -311,7 +336,9 @@ class TbCustomMapLayer extends TbMapLayer { } protected createLayer(): Observable { - const layer = L.tileLayer(this.settings.tileUrl); + const layer = L.tileLayer(this.settings.tileUrl, this.settings.customAttribution ? { + attribution: this.settings.customAttribution + } : undefined); return of(layer); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/color-range-list.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/color-range-list.component.ts index 0256cc5248..84c574c559 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/color-range-list.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/color-range-list.component.ts @@ -16,12 +16,13 @@ import { AdvancedColorRange, ColorRange, ColorRangeSettings, + normalizeColorRangeSettings, ValueSourceType } from '@shared/models/widget-settings.models'; import { TbPopoverComponent } from '@shared/components/popover.component'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; -import { deepClone, isDefinedAndNotNull, isUndefined } from '@core/utils'; +import { isDefinedAndNotNull } from '@core/utils'; import { CdkDragDrop } from '@angular/cdk/drag-drop'; import { IAliasController } from '@core/api/widget-api.models'; import { coerceBoolean } from '@shared/decorators/coercion'; @@ -121,11 +122,11 @@ export class ColorRangeListComponent implements OnInit, ControlValueAccessor, On writeValue(value: any): void { if (value) { let rangeList: ColorRangeSettings = {}; - if (this.simpleRange || (isUndefined(value?.advancedMode) && value?.length)) { + if (this.simpleRange) { rangeList.advancedMode = false; - rangeList.range = value; + rangeList.range = normalizeColorRangeSettings(value).range; } else { - rangeList = deepClone(value); + rangeList = normalizeColorRangeSettings(value); } this.colorRangeListFormGroup.get('advancedMode').patchValue(rangeList.advancedMode || false, {emitEvent: false}); if (isDefinedAndNotNull(rangeList?.range)) { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/color-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/color-settings.component.ts index f03ed93246..41c781b893 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/color-settings.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/color-settings.component.ts @@ -11,14 +11,14 @@ import { ViewContainerRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; -import { ColorRange, ColorSettings, ColorType, ComponentStyle } from '@shared/models/widget-settings.models'; +import { ColorSettings, ColorType, ComponentStyle, normalizeColorRangeSettings } from '@shared/models/widget-settings.models'; import { MatButton } from '@angular/material/button'; import { TbPopoverService } from '@shared/components/popover.service'; import { ColorSettingsPanelComponent } from '@home/components/widget/lib/settings/common/color-settings-panel.component'; import { IAliasController } from '@core/api/widget-api.models'; -import { deepClone, isDefinedAndNotNull } from '@core/utils'; +import { isDefinedAndNotNull } from '@core/utils'; import { coerceBoolean } from '@shared/decorators/coercion'; import { DataKeysCallbacks } from '@home/components/widget/lib/settings/common/key/data-keys.component.models'; import { Datasource } from '@shared/models/widget.models'; @@ -129,11 +129,9 @@ export class ColorSettingsComponent implements OnInit, ControlValueAccessor, OnD writeValue(value: ColorSettings): void { if (value) { - this.modelValue = value; - if (isDefinedAndNotNull(this.modelValue.rangeList) && !isDefinedAndNotNull(this.modelValue.rangeList?.advancedMode)) { - const range = deepClone(this.modelValue.rangeList) as ColorRange[]; - this.modelValue.rangeList = deepClone({advancedMode: false, range}); - } + this.modelValue = isDefinedAndNotNull(value.rangeList) + ? {...value, rangeList: normalizeColorRangeSettings(value.rangeList)} + : value; this.updateColorStyle(); } } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/count-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/count-widget-settings.component.ts index eae553cec3..def1141af5 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/count-widget-settings.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/count-widget-settings.component.ts @@ -140,7 +140,7 @@ export class CountWidgetSettingsComponent extends PageComponent implements OnIni } private updateModel() { - const value: CountWidgetSettings = this.countWidgetConfigForm.value; + const value: CountWidgetSettings = this.countWidgetConfigForm.getRawValue(); this.propagateChange(value); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html index e19007a1e5..02ddc00901 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html @@ -23,6 +23,14 @@ + + + + {{ cartoLayerTranslationMap.get(layerType) | translate }} + + + diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts index 9680188046..93ed9be3f1 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts @@ -25,6 +25,8 @@ import { TbPopoverService } from '@shared/components/popover.service'; import { TranslateService } from '@ngx-translate/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { + cartoLayerTranslationMap, + cartoLayerTypes, defaultLayerTitle, defaultMapLayerSettings, googleMapLayerTranslationMap, @@ -35,6 +37,8 @@ import { MapProvider, mapProviders, mapProviderTranslationMap, + mapProviderHasApiKey, + mapProviderRequiresApiKey, openStreetLayerTypes, openStreetMapLayerTranslationMap, tencentLayerTranslationMap, @@ -71,6 +75,10 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { openStreetMapLayerTranslationMap = openStreetMapLayerTranslationMap; + cartoLayerTypes = cartoLayerTypes; + + cartoLayerTranslationMap = cartoLayerTranslationMap; + googleMapLayerTypes = googleMapLayerTypes; googleMapLayerTranslationMap = googleMapLayerTranslationMap; @@ -110,6 +118,7 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { provider: [null, [Validators.required]], layerType: [null, [Validators.required]], tileUrl: [null, [Validators.required]], + customAttribution: [null, []], apiKey: [null, [Validators.required]], referenceLayer: [null, []] }); @@ -202,12 +211,15 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { const provider: MapProvider = this.layerFormGroup.get('provider').value; if (provider === MapProvider.custom) { this.layerFormGroup.get('tileUrl').enable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').enable({emitEvent: false}); this.layerFormGroup.get('layerType').disable({emitEvent: false}); } else { this.layerFormGroup.get('tileUrl').disable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').disable({emitEvent: false}); this.layerFormGroup.get('layerType').enable({emitEvent: false}); } - if ([MapProvider.google, MapProvider.here].includes(provider)) { + if (mapProviderHasApiKey(provider)) { + this.layerFormGroup.get('apiKey').setValidators(mapProviderRequiresApiKey(provider) ? [Validators.required] : []); this.layerFormGroup.get('apiKey').enable({emitEvent: false}); } else { this.layerFormGroup.get('apiKey').disable({emitEvent: false}); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html index cdf24fd07c..a65dc5bf18 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html @@ -33,6 +33,14 @@ + + + + {{ cartoLayerTranslationMap.get(layerType) | translate }} + + + @@ -62,12 +70,18 @@
    -
    +
    +
    widgets.maps.layer.provider.custom.attribution
    + + + +
    +
    widgets.maps.layer.credentials.credentials
    widgets.maps.layer.credentials.api-key
    - +
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts index bddca3f360..5e4866df9c 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts @@ -5,6 +5,8 @@ import { TbPopoverComponent } from '@shared/components/popover.component'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { + cartoLayerTranslationMap, + cartoLayerTypes, defaultLayerTitle, defaultMapLayerSettings, googleMapLayerTranslationMap, @@ -15,6 +17,8 @@ import { MapProvider, mapProviders, mapProviderTranslationMap, + mapProviderHasApiKey, + mapProviderRequiresApiKey, openStreetLayerTypes, openStreetMapLayerTranslationMap, referenceLayerTypes, referenceLayerTypeTranslationMap, tencentLayerTranslationMap, @@ -42,6 +46,10 @@ export class MapLayerSettingsPanelComponent implements OnInit { openStreetMapLayerTranslationMap = openStreetMapLayerTranslationMap; + cartoLayerTypes = cartoLayerTypes; + + cartoLayerTranslationMap = cartoLayerTranslationMap; + googleMapLayerTypes = googleMapLayerTypes; googleMapLayerTranslationMap = googleMapLayerTranslationMap; @@ -81,6 +89,7 @@ export class MapLayerSettingsPanelComponent implements OnInit { provider: [null, [Validators.required]], layerType: [null, [Validators.required]], tileUrl: [null, [Validators.required]], + customAttribution: [null, []], apiKey: [null, [Validators.required]], referenceLayer: [null, []] } @@ -108,6 +117,10 @@ export class MapLayerSettingsPanelComponent implements OnInit { return this.translate.instant(translationKey); } + hasApiKey(): boolean { + return mapProviderHasApiKey(this.layerFormGroup.get('provider').value); + } + applyLayerSettings() { const layerSettings: MapLayerSettings = this.layerFormGroup.value; this.mapLayerSettingsApplied.emit(layerSettings); @@ -126,12 +139,15 @@ export class MapLayerSettingsPanelComponent implements OnInit { const provider: MapProvider = this.layerFormGroup.get('provider').value; if (provider === MapProvider.custom) { this.layerFormGroup.get('tileUrl').enable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').enable({emitEvent: false}); this.layerFormGroup.get('layerType').disable({emitEvent: false}); } else { this.layerFormGroup.get('tileUrl').disable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').disable({emitEvent: false}); this.layerFormGroup.get('layerType').enable({emitEvent: false}); } - if ([MapProvider.google, MapProvider.here].includes(provider)) { + if (mapProviderHasApiKey(provider)) { + this.layerFormGroup.get('apiKey').setValidators(mapProviderRequiresApiKey(provider) ? [Validators.required] : []); this.layerFormGroup.get('apiKey').enable({emitEvent: false}); } else { this.layerFormGroup.get('apiKey').disable({emitEvent: false}); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts index d6ac020c42..a73c9bfbb5 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts @@ -20,7 +20,8 @@ import { MapLayerSettings, mapLayerValid, mapLayerValidator, - MapProvider + MapProvider, + normalizeMapLayerSettings } from '@shared/models/widget/maps/map.models'; @Component({ @@ -93,7 +94,7 @@ export class MapLayersComponent implements ControlValueAccessor, OnInit, Validat } writeValue(value: MapLayerSettings[] | undefined): void { - const layers: MapLayerSettings[] = value || []; + const layers: MapLayerSettings[] = (value || []).map(layer => normalizeMapLayerSettings(layer)); this.layersFormGroup.setControl('layers', this.prepareLayersFormArray(layers), {emitEvent: false}); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.ts index 7fb20254a8..621c84a59a 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.ts @@ -28,6 +28,7 @@ import { ColorSettings, ColorType, constantColor, + normalizeColorRangeSettings, simpleDateFormat, ValueSourceConfig, ValueSourceType @@ -219,7 +220,8 @@ export class DigitalGaugeWidgetSettingsComponent extends WidgetSettingsComponent if (barColor.type === ColorType.range) { settings.useFixedLevelColor = true; - settings.fixedLevelColors = barColor.rangeList.advancedMode ? barColor.rangeList.rangeAdvanced : barColor.rangeList.range; + const rangeList = normalizeColorRangeSettings(barColor.rangeList); + settings.fixedLevelColors = rangeList?.advancedMode ? rangeList.rangeAdvanced : rangeList?.range; } else { settings.useFixedLevelColor = false; } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html index d95bb0daa3..2131e54bdf 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html @@ -16,25 +16,10 @@
    widgets.maps.credentials - - {{ 'widgets.maps.here-use-new-version-api-3' | translate }} - -
    - - widgets.maps.here-app-id - - - - widgets.maps.here-app-code - - -
    - - - widgets.maps.here-api-key - - - + + widgets.maps.here-api-key + +
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts index 823840b624..14d5236473 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts @@ -16,11 +16,11 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { TranslateService } from '@ngx-translate/core'; import { + defaultHereMapProviderSettings, HereMapProvider, HereMapProviderSettings, hereMapProviderTranslationMap } from '@home/components/widget/lib/maps-legacy/map-models'; -import { isDefinedAndNotNull } from '@core/utils'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @Component({ @@ -67,25 +67,9 @@ export class HereMapProviderSettingsComponent extends PageComponent implements O this.providerSettingsFormGroup = this.fb.group({ mapProviderHere: [null, [Validators.required]], credentials: this.fb.group({ - useV3: [true], - app_id: [null, [Validators.required]], - app_code: [null, [Validators.required]], apiKey: [null, [Validators.required]] }) }); - this.providerSettingsFormGroup.get('credentials.useV3').valueChanges.pipe( - takeUntilDestroyed(this.destroyRef) - ).subscribe(value => { - if (value) { - this.providerSettingsFormGroup.get('credentials.apiKey').enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_id').disable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_code').disable({emitEvent: false}); - } else { - this.providerSettingsFormGroup.get('credentials.apiKey').disable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_id').enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_code').enable({emitEvent: false}); - } - }); this.providerSettingsFormGroup.valueChanges.pipe( takeUntilDestroyed(this.destroyRef) ).subscribe(() => { @@ -106,21 +90,17 @@ export class HereMapProviderSettingsComponent extends PageComponent implements O this.providerSettingsFormGroup.disable({emitEvent: false}); } else { this.providerSettingsFormGroup.enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.useV3').updateValueAndValidity({onlySelf: true}); } } writeValue(value: HereMapProviderSettings): void { - if (!isDefinedAndNotNull(value.credentials.useV3)) { - if (isDefinedAndNotNull(value.credentials.app_id) && isDefinedAndNotNull(value.credentials.app_code)) { - value.credentials.useV3 = false; - } - } this.modelValue = value; - this.providerSettingsFormGroup.patchValue( - value, {emitEvent: false} - ); - this.providerSettingsFormGroup.get('credentials.useV3').updateValueAndValidity({onlySelf: true}); + this.providerSettingsFormGroup.patchValue({ + mapProviderHere: value?.mapProviderHere, + credentials: { + apiKey: value?.credentials?.apiKey || defaultHereMapProviderSettings.credentials.apiKey + } + }, {emitEvent: false}); } public validate(c: FormControl) { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html index d91164a6c3..42f92fc3d1 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html @@ -96,7 +96,8 @@
    - +

    {{ 'iot-hub.published-items' | translate }} ({{ creator.publishedCount }})

    diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-deep-link.utils.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-deep-link.utils.ts index 1bfed40ed3..6b417e3353 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-deep-link.utils.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-deep-link.utils.ts @@ -12,7 +12,6 @@ export function isUUID(s: string | null | undefined): s is string { export function typeSegment(t: ItemType): string | undefined { switch (t) { case ItemType.WIDGET: return 'widgets'; - case ItemType.DASHBOARD: return 'dashboards'; case ItemType.SOLUTION_TEMPLATE: return 'solution-templates'; case ItemType.CALCULATED_FIELD: return 'calculated-fields'; case ItemType.ALARM_RULE: return 'alarm-rules'; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index cf4007b511..b2b785ceae 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -54,13 +54,13 @@ [matAutocomplete]="searchAuto" (input)="onSearchInput()" (focus)="onSearchFocus()" - (keyup.enter)="onSearch()"> + (keydown.enter)="onSearchEnter($event)"> @if (searchText) { } - @@ -72,6 +72,13 @@ + } @else if (searchFailed) { + +
    + cloud_off + {{ 'iot-hub.network-server-unavailable' | translate }} +
    +
    } @else if (searchResults.length === 0 && searchLoaded) {
    @@ -84,39 +91,55 @@
    } @else { - @for (group of searchResultGroups; track group.type) { - - @for (item of group.items; track item.id) { - - @if (isCompactType(item.type)) { -
    - {{ getCompactIcon(item) }} -
    - } @else { -
    - @if (getItemImage(item); as imgUrl) { - + @for (item of searchResults; track item.id) { + + +
    + @if (isCompactType(item.type)) { +
    + {{ getCompactIcon(item) }} +
    + } @else if (getItemImage(item); as imgUrl) { + + } @else { + {{ getItemTypeIcon(item.type) }} + } +
    +
    + {{ item.name }} + + + {{ getItemTypeIcon(item.type) }} + {{ getItemTypeLabel(item.type) }} + + @if (item.creatorDisplayName) { + + @if (item.creatorVerified) { + verified } @else { - {{ getItemTypeIcon(item.type) }} + person } -
    - } -
    - {{ item.name }} - - person - {{ item.creatorDisplayName }} + {{ item.creatorDisplayName }} -
    -
    - } - + } + +
    +
    } } - + + @if (searchText?.trim(); as query) { + @if (searchTotal > searchResults.length) { + {{ 'iot-hub.see-all-results-for' | translate:{ count: searchTotal, search: query } }} + } @else { + {{ 'iot-hub.see-results-for' | translate:{ search: query } }} + } + } @else { + {{ 'iot-hub.see-all-results' | translate }} + } +
    diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index de032d8f1a..7440403390 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -220,36 +220,14 @@ 0 114px 46px 0 rgba(0, 0, 0, 0.01), 0 178px 50px 0 rgba(0, 0, 0, 0); - // Section group — 12px gap between groups - .mat-mdc-optgroup + .mat-mdc-optgroup .mat-mdc-optgroup-label { - margin-top: 12px; - } - - // Section title — Design: 14px Medium, 0.25 tracking, black-tertiary, 4px V / 16px H - .mat-mdc-optgroup .mat-mdc-optgroup-label { - padding: 4px 16px; - min-height: 28px; - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - white-space: nowrap; - + // Shared by every row; each row kind below is selected by its own class. + .mat-mdc-option { .mdc-list-item__primary-text { - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); + display: flex; + align-items: center; + gap: 16px; + width: 100%; } - } - - // Item row — Design: 8px V / 16px H, 16px gap, centered - .mat-mdc-optgroup .mat-mdc-option:not(.mat-mdc-option-multiple) { - padding: 8px 16px; - min-height: auto; - height: auto; &:hover:not(.mdc-list-item--disabled), &.mat-mdc-option-active:not(.mdc-list-item--disabled) { @@ -259,13 +237,13 @@ .mat-icon, tb-icon { margin-right: 0; } + } - .mdc-list-item__primary-text { - display: flex; - align-items: center; - gap: 16px; - width: 100%; - } + // Item row — Design: 8px V / 16px H, 16px gap, centered + .mat-mdc-option.tb-search-popup-item { + padding: 8px 16px; + min-height: auto; + height: auto; } // Thumbnail — Design: 99px x 56px, 4px radius, 1px border, 4% bg @@ -295,11 +273,11 @@ color: rgba(0, 0, 0, 0.38); } - // Icon square — Design: 56x56, 4.667px radius, colored bg + // Icon tile for an item with no screenshot, centred in the thumbnail frame: 36x36, colored bg .tb-search-popup-icon-square { - width: 56px; - height: 56px; - border-radius: 4.667px; + width: 36px; + height: 36px; + border-radius: 6px; flex-shrink: 0; display: flex; align-items: center; @@ -307,9 +285,9 @@ } .tb-search-popup-icon-inner { - font-size: 28px; - width: 28px; - height: 28px; + font-size: 22px; + width: 22px; + height: 22px; color: white !important; --tb-icon-color: white; } @@ -346,13 +324,63 @@ letter-spacing: 0.25px; color: rgba(0, 0, 0, 0.54); white-space: nowrap; + min-width: 0; mat-icon { + flex-shrink: 0; font-size: 16px; width: 16px; height: 16px; margin-right: 0; color: rgba(0, 0, 0, 0.54); + + // Same teal the IoT Hub item cards give a verified creator. + &.tb-search-popup-verified { + color: #00695c; + } + } + } + + // Shares the meta row with the item type, so a long name is cut rather than overflowing. + .tb-search-popup-author-name { + overflow: hidden; + text-overflow: ellipsis; + } + + // Meta row: the item type, a middle dot, then the author - "Widget · pinkevych.d". + .tb-search-popup-meta { + display: flex; + align-items: center; + gap: 4px; + min-width: 0; + } + + // Item type in its colour, darkened so the paler ones stay legible. + .tb-search-popup-type { + display: flex; + align-items: center; + gap: 4px; + flex-shrink: 0; + font-size: 12px; + font-weight: 500; + line-height: 16px; + letter-spacing: 0.25px; + color: color-mix(in srgb, var(--tb-search-popup-type-color) 75%, #000); + white-space: nowrap; + + tb-icon { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + color: inherit; + } + + // No author, nothing to separate from. + &:not(:last-child)::after { + content: '·'; + font-weight: 700; + color: rgba(0, 0, 0, 0.54); } } @@ -370,6 +398,7 @@ .tb-search-popup-no-results { pointer-events: none; opacity: 1 !important; + padding: 8px 16px; } .tb-search-popup-no-results-content { @@ -391,26 +420,31 @@ } // Footer — Design: 40px h, 8px V / 16px H, 1px top border, tb-primary text - .tb-search-popup-footer { + .mat-mdc-option.tb-search-popup-footer { position: sticky; bottom: 0; + z-index: 1; border-top: 1px solid rgba(0, 0, 0, 0.12); height: 40px; min-height: 40px; padding: 8px 16px; - display: flex; - align-items: center; - justify-content: flex-start; font-size: 14px; font-weight: 500; line-height: 20px; letter-spacing: 0.25px; color: $tb-primary-color; - cursor: pointer; background: white; white-space: nowrap; - &:hover { + .mdc-list-item__primary-text { + justify-content: flex-start; + font: inherit; + letter-spacing: inherit; + color: inherit; + } + + &:hover:not(.mdc-list-item--disabled), + &.mat-mdc-option-active:not(.mdc-list-item--disabled) { background: #f5f5f5; } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index fffd19c021..0d987e8a83 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -3,14 +3,25 @@ import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { Router } from '@angular/router'; import { MatAutocompleteTrigger } from '@angular/material/autocomplete'; +import { MatOptionSelectionChange } from '@angular/material/core'; import { BreakpointObserver } from '@angular/cdk/layout'; -import { forkJoin, Subject, Subscription } from 'rxjs'; -import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; +import { forkJoin, of, Subject, Subscription } from 'rxjs'; +import { catchError, debounceTime, switchMap } from 'rxjs/operators'; import { MediaBreakpoints } from '@shared/models/constants'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { PageData } from '@shared/models/page/page-data'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + CROSS_TYPE_ITEM_TYPES, + getItemTypeColor, + isCompactItemType, + getItemTypeIcon, + ItemType, + itemTypeColors, + itemTypeTranslations, + RELEVANCE_SORT_PROPERTY +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; @@ -32,15 +43,8 @@ interface HeroTypeConfig { icon: string; } -interface SearchResultGroup { - type: ItemType; - items: MpItemVersionView[]; -} - -const SEARCH_GROUP_ORDER: ItemType[] = [ - ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, - ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN -]; +/** Rows the search popup shows: page 0 of the search page's own request. */ +const SEARCH_POPUP_PAGE_SIZE = 10; @Component({ selector: 'tb-iot-hub-home', @@ -51,12 +55,15 @@ const SEARCH_GROUP_ORDER: ItemType[] = [ export class TbIotHubHomeComponent implements OnInit, OnDestroy { readonly ItemType = ItemType; + readonly isCompactType = isCompactItemType; searchText = ''; searchResults: MpItemVersionView[] = []; - searchResultGroups: SearchResultGroup[] = []; + /** Everything the search matched, for the footer's "See all N results". */ + searchTotal = 0; searchLoaded = false; searchLoading = false; + searchFailed = false; @ViewChild(MatAutocompleteTrigger) searchAutoTrigger: MatAutocompleteTrigger; @ViewChild('searchInput', {read: ElementRef}) searchInputRef: ElementRef; private searchSubject = new Subject(); @@ -65,27 +72,27 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { heroTypes: HeroTypeConfig[] = [ { - type: ItemType.DEVICE, labelKey: 'item.type-device-plural', color: '#4b63cc', + type: ItemType.DEVICE, labelKey: 'item.type-device-plural', color: itemTypeColors[ItemType.DEVICE], icon: 'assets/iot-hub/hero-device-cluster.svg' }, { - type: ItemType.SOLUTION_TEMPLATE, labelKey: 'item.type-solution-template-plural', color: '#2b6bb4', + type: ItemType.SOLUTION_TEMPLATE, labelKey: 'item.type-solution-template-plural', color: itemTypeColors[ItemType.SOLUTION_TEMPLATE], icon: 'assets/iot-hub/hero-solution-template-cluster.svg' }, { - type: ItemType.WIDGET, labelKey: 'item.type-widget-plural', color: '#2c9755', + type: ItemType.WIDGET, labelKey: 'item.type-widget-plural', color: itemTypeColors[ItemType.WIDGET], icon: 'assets/iot-hub/hero-widget-cluster.svg' }, { - type: ItemType.CALCULATED_FIELD, labelKey: 'item.type-calculated-field-plural', color: '#3cb4e0', + type: ItemType.CALCULATED_FIELD, labelKey: 'item.type-calculated-field-plural', color: itemTypeColors[ItemType.CALCULATED_FIELD], icon: 'assets/iot-hub/hero-calculated-field-cluster.svg' }, { - type: ItemType.ALARM_RULE, labelKey: 'item.type-alarm-rule-plural', color: '#d66f2e', + type: ItemType.ALARM_RULE, labelKey: 'item.type-alarm-rule-plural', color: itemTypeColors[ItemType.ALARM_RULE], icon: 'assets/iot-hub/hero-alarm-rule-cluster.svg' }, { - type: ItemType.RULE_CHAIN, labelKey: 'item.type-rule-chain-plural', color: '#a95ae2', + type: ItemType.RULE_CHAIN, labelKey: 'item.type-rule-chain-plural', color: itemTypeColors[ItemType.RULE_CHAIN], icon: 'assets/iot-hub/hero-rule-chain-cluster.svg' } ]; @@ -153,17 +160,23 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }); this.searchSubscription = this.searchSubject.pipe( debounceTime(300), - distinctUntilChanged(), switchMap(text => { this.searchLoading = true; - const sortOrder: SortOrder = { property: 'totalInstallCount', direction: Direction.DESC }; - const pageLink = new PageLink(10, 0, text.trim() || null, sortOrder); - const query = new MpItemVersionQuery(pageLink); - return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }); + const trimmed = text.trim(); + // One list ranked across every type the platform surfaces. With an empty field relevance + // is served as the install count. + const sortOrder: SortOrder = { property: RELEVANCE_SORT_PROPERTY, direction: Direction.DESC }; + const pageLink = new PageLink(SEARCH_POPUP_PAGE_SIZE, 0, trimmed || null, sortOrder); + const query = new MpItemVersionQuery(pageLink, { types: CROSS_TYPE_ITEM_TYPES }); + // A failure must not end the subscription. + return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }).pipe( + catchError(() => of(null as PageData)) + ); }) - ).subscribe(result => { - this.searchResults = result.data; - this.searchResultGroups = this.groupSearchResults(result.data); + ).subscribe(page => { + this.searchFailed = !page; + this.searchResults = page?.data ?? []; + this.searchTotal = page?.totalElements ?? 0; this.searchLoaded = true; this.searchLoading = false; }); @@ -227,7 +240,26 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { setTimeout(() => this.searchAutoTrigger?.openPanel()); } - onSearch(): void { + onRowSelected(event: MatOptionSelectionChange, item: MpItemVersionView): void { + if (event.isUserInput) { + this.openItemDetail(item); + } + } + + onFooterSelected(event: MatOptionSelectionChange): void { + if (event.isUserInput) { + this.seeAllResults(); + } + } + + /** + * Enter in the field opens the search page - unless the autocomplete has just used this press + * to select a highlighted row, which it marks with preventDefault before this handler runs. + */ + onSearchEnter(event: KeyboardEvent): void { + if (event.defaultPrevented || event.isComposing) { + return; + } this.seeAllResults(); } @@ -237,12 +269,6 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { void this.router.navigate(['/iot-hub/search'], { queryParams: { search } }); } - isCompactType(type: ItemType): boolean { - return type === ItemType.CALCULATED_FIELD - || type === ItemType.ALARM_RULE - || type === ItemType.RULE_CHAIN; - } - getCompactIcon(item: MpItemVersionView): string { return item.icon || getItemTypeIcon(item.type); } @@ -255,9 +281,13 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { return getItemTypeIcon(type); } - getSearchGroupLabel(type: ItemType): string { + getItemTypeColor(type: ItemType): string { + return getItemTypeColor(type); + } + + getItemTypeLabel(type: ItemType): string { const key = itemTypeTranslations.get(type); - return key ? this.translate.instant(key + '-plural') : type; + return key ? this.translate.instant(key) : type; } navigateToBrowse(type: ItemType): void { @@ -276,7 +306,6 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { private getTypeRoute(type: ItemType): string { switch (type) { case ItemType.WIDGET: return 'widgets'; - case ItemType.DASHBOARD: return 'dashboards'; case ItemType.SOLUTION_TEMPLATE: return 'solution-templates'; case ItemType.CALCULATED_FIELD: return 'calculated-fields'; case ItemType.ALARM_RULE: return 'alarm-rules'; @@ -523,21 +552,4 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }); } - private groupSearchResults(items: MpItemVersionView[]): SearchResultGroup[] { - const groupMap = new Map(); - for (const item of items) { - if (!SEARCH_GROUP_ORDER.includes(item.type)) { - continue; - } - let list = groupMap.get(item.type); - if (!list) { - list = []; - groupMap.set(item.type, list); - } - list.push(item); - } - return SEARCH_GROUP_ORDER - .filter(type => groupMap.has(type)) - .map(type => ({ type, items: groupMap.get(type) })); - } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html index 59a42eab29..5787b5ecf0 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html @@ -35,7 +35,8 @@ + [hideTabs]="true" + (installedItemsChanged)="loadInstalledCount()"> diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts index b89448be3c..cc54a57641 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { Component, OnInit } from '@angular/core'; +import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { TbIotHubBrowseComponent } from '@home/components/iot-hub/iot-hub-browse.component'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { PageLink } from '@shared/models/page/page-link'; @@ -28,13 +29,6 @@ const PAGE_CONFIGS: Record = { image: 'assets/iot-hub/items-page-widgets-hero.svg', routeSegment: 'widgets' }, - DASHBOARD: { - type: ItemType.DASHBOARD, - titleKey: 'item.type-dashboard-plural', - descriptionKey: 'iot-hub.items-page-desc-dashboards', - image: 'assets/iot-hub/items-page-dashboards-hero.svg', - routeSegment: 'dashboards' - }, SOLUTION_TEMPLATE: { type: ItemType.SOLUTION_TEMPLATE, titleKey: 'item.type-solution-template-plural', @@ -83,6 +77,8 @@ export class TbIotHubItemsPageComponent implements OnInit { config: ItemTypePageConfig; installedItemsCount = 0; + @ViewChild(TbIotHubBrowseComponent) private browse: TbIotHubBrowseComponent; + constructor( private route: ActivatedRoute, private router: Router, @@ -109,7 +105,7 @@ export class TbIotHubItemsPageComponent implements OnInit { window.open(this.iotHubApiService.baseUrl + '/signup', '_blank'); } - private loadInstalledCount(): void { + loadInstalledCount(): void { this.iotHubApiService.getInstalledItemsCount(this.config.type, { ignoreLoading: true }).subscribe(count => { this.installedItemsCount = count; }); @@ -147,7 +143,13 @@ export class TbIotHubItemsPageComponent implements OnInit { 'default', true, openItem.preview - ).subscribe(); + ).subscribe(result => { + // The deep-linked dialog is opened by this page rather than by the grid, so its outcome + // has to be fed back in by hand — the grid then refreshes and announces the new count. + if (result === 'installed' || result === 'updated' || result === 'deleted') { + this.browse?.reloadInstalledItems(); + } + }); }); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-routing.module.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-routing.module.ts index 2128d6d6b7..32f562e150 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-routing.module.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-routing.module.ts @@ -40,16 +40,6 @@ const routes: Routes = [ breadcrumb: { label: 'item.type-widget-plural', icon: 'widgets' } } }, - { - path: 'dashboards', - component: TbIotHubItemsPageComponent, - data: { - auth: [Authority.TENANT_ADMIN], - title: 'item.type-dashboard-plural', - itemType: 'DASHBOARD', - breadcrumb: { label: 'item.type-dashboard-plural', icon: 'dashboard' } - } - }, { path: 'solution-templates', component: TbIotHubItemsPageComponent, diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss index 1e617fb1f3..5766a46a4c 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss @@ -8,12 +8,17 @@ height: 100%; } +// Same frame as the type pages: one even padding on the card, and the search component pulled +// out to the card's edges by the same amount, so the rail, heading and grid line up. +.tb-search-page { + --tb-search-page-pad: 40px; + padding: var(--tb-search-page-pad) var(--tb-search-page-pad) calc(var(--tb-search-page-pad) + 8px); +} // Back button .tb-search-back-btn { align-self: flex-start; - margin-top: 40px; - margin-left: 123px; + margin-left: -8px; } // Title @@ -30,100 +35,24 @@ color: rgba(0, 0, 0, 0.54); } +// Full bleed; it pads its own rows back in through --tb-search-side-pad. tb-iot-hub-search { flex: 1; min-height: 0; - padding-left: 123px; - padding-right: 123px; - - ::ng-deep { - .tb-search-divider { - margin-left: -123px; - margin-right: -123px; - } - - .tb-results-container { - padding-right: 123px; - padding-bottom: 40px; - margin-right: -123px; - } - } -} - -// Responsive -@media #{$mat-lt-xxl} { - .tb-search-back-btn { - margin-left: 40px; - } - - tb-iot-hub-search { - padding-left: 40px; - padding-right: 40px; - - ::ng-deep { - .tb-search-divider { - margin-left: -40px; - margin-right: -40px; - } - - .tb-results-container { - padding-right: 40px; - margin-right: -40px; - } - } - } + --tb-search-side-pad: var(--tb-search-page-pad); + margin-left: calc(-1 * var(--tb-search-page-pad)); + margin-right: calc(-1 * var(--tb-search-page-pad)); } @media #{$mat-lt-lg} { - .tb-search-back-btn { - margin-top: 24px; - margin-left: 24px; - } - - tb-iot-hub-search { - padding-left: 24px; - padding-right: 24px; - - ::ng-deep { - .tb-search-divider { - margin-left: -24px; - margin-right: -24px; - } - - .tb-results-container { - padding-right: 24px; - padding-bottom: 24px; - margin-right: -24px; - } - } + .tb-search-page { + --tb-search-page-pad: 24px; } } @media #{$mat-lt-sm} { .tb-search-page { + --tb-search-page-pad: 16px; gap: 16px; } - - .tb-search-back-btn { - margin-top: 16px; - margin-left: 16px; - } - - tb-iot-hub-search { - padding-left: 16px; - padding-right: 16px; - - ::ng-deep { - .tb-search-divider { - margin-left: -16px; - margin-right: -16px; - } - - .tb-results-container { - padding-right: 16px; - padding-bottom: 16px; - margin-right: -16px; - } - } - } } diff --git a/ui-ngx/src/app/shared/directives/photoswipe-gallery.directive.ts b/ui-ngx/src/app/shared/directives/photoswipe-gallery.directive.ts index 3619c383ac..1978ce2f10 100644 --- a/ui-ngx/src/app/shared/directives/photoswipe-gallery.directive.ts +++ b/ui-ngx/src/app/shared/directives/photoswipe-gallery.directive.ts @@ -1,17 +1,35 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { Directive, ElementRef, Input, OnDestroy, OnInit } from '@angular/core'; +import { Directive, ElementRef, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output } from '@angular/core'; import PhotoSwipeLightbox from 'photoswipe/lightbox'; import PhotoSwipe from 'photoswipe'; import cssjs from '@core/css/css'; const PHOTO_GALLERY_STYLE_ID = 'photoswipe-gallery-style'; +// Share of the available area an opened image takes, leaving backdrop to click and room for close +const SHRINK_FILL = 0.86; +const GROW_FILL = 0.95; +/** Upper bound for enlarging a small image, relative to its own size. */ +const MAX_UPSCALE = 2; +/** How far a click-to-zoom steps past the level the image opened at. */ +const ZOOM_STEP = 2; +// Symmetric, so the image stays centred; the caption floats over the bottom padding +const VIEWPORT_PADDING = { top: 64, bottom: 64, left: 24, right: 24 }; const PHOTO_GALLERY_CLASS = 'tb-photoswipe-gallery'; const PHOTO_GALLERY_STYLE = - '{\n'+ - ' background: rgba(10, 10, 20, 0.55);\n' + + // PhotoSwipe's own transform/will-change create a layer backdrop-filter cannot see through + '{\n' + + ' transform: none;\n' + + ' will-change: auto;\n' + + '}\n' + + '\n' + + // On .pswp__bg, the layer PhotoSwipe fades in with the zoom + '.pswp__bg {\n' + + ' background: rgba(10, 10, 20, 0.55);\n' + ' backdrop-filter: blur(18px);\n' + - ' opacity: 1;\n' + + ' -webkit-backdrop-filter: blur(18px);\n' + + ' transform: none;\n' + + ' will-change: backdrop-filter;\n' + '}\n' + '\n' + '.pswp__tb-photoswipe-caption {\n' + @@ -49,12 +67,18 @@ const PHOTO_GALLERY_STYLE = '.pswp__item img.pswp__img {\n' + ' display: block;\n' + ' object-fit: contain;\n' + - ' border-radius: 4px; \n' + - ' box-shadow: 0 20px 60px #00000080;\n' + + ' border-radius: 4px;\n' + '}\n' + '\n' + + // drop-shadow follows transparency; on the wrap so it survives the placeholder swap + '.pswp__zoom-wrap {\n' + + ' filter: drop-shadow(0 20px 30px rgba(0, 0, 0, 0.5));\n' + + '}\n' + + '\n' + + // PhotoSwipe's #222 placeholder background flashes against the translucent backdrop '.pswp__item .pswp__img--placeholder {\n' + - ' border-radius: 4px; \n' + + ' background: transparent;\n' + + ' border-radius: 4px;\n' + '}\n' + '\n' + '.pswp__button {\n' + @@ -117,6 +141,49 @@ const PHOTO_GALLERY_STYLE = ' right: 12px;\n' + '}'; +/** The parts of PhotoSwipe's ZoomLevel this directive needs; `panAreaSize` already excludes padding. */ +interface ZoomLevelSizes { + fit: number; + panAreaSize: { x: number; y: number } | null; + elementSize: { x: number; y: number } | null; +} + +/** PhotoSwipe's `fit` is capped at 1; use the raw ratio so a small image grows, up to MAX_UPSCALE. */ +function initialZoom(zoomLevel: ZoomLevelSizes): number { + const { panAreaSize, elementSize } = zoomLevel; + if (!panAreaSize || !elementSize?.x || !elementSize?.y) { + return zoomLevel.fit; + } + const fitRatio = Math.min(panAreaSize.x / elementSize.x, panAreaSize.y / elementSize.y); + if (fitRatio <= 1) { + return fitRatio * SHRINK_FILL; + } + return Math.min(fitRatio * GROW_FILL, MAX_UPSCALE); +} + +/** Click-to-zoom level; always above the opening level, so the click visibly zooms. */ +function secondaryZoom(zoomLevel: ZoomLevelSizes): number { + return Math.max(initialZoom(zoomLevel) * ZOOM_STEP, Math.min(1, zoomLevel.fit * 3)); +} + +// A gallery child may be a container with no image in it +function thumbnailImage(element: Element): HTMLImageElement | null { + return element instanceof HTMLImageElement ? element : element.querySelector('img'); +} + +/** Bounds of the pixels an `object-fit: contain` image paints, centred inside its box. */ +function containedImageBounds(image: HTMLImageElement): { x: number; y: number; w: number } { + const rect = image.getBoundingClientRect(); + const scale = Math.min(rect.width / image.naturalWidth, rect.height / image.naturalHeight); + const width = image.naturalWidth * scale; + const height = image.naturalHeight * scale; + return { + x: rect.left + (rect.width - width) / 2, + y: rect.top + (rect.height - height) / 2, + w: width + }; +} + @Directive({ selector: '[tbPhotoSwipeGallery]', standalone: false @@ -126,10 +193,17 @@ export class PhotoSwipeGalleryDirective implements OnInit, OnDestroy { @Input() galleryChildrenSelector = '.tb-image'; @Input() imageCaptionSelector = '.tb-image-tooltip'; + @Output() readonly lightboxOpened = new EventEmitter(); + @Output() readonly lightboxClosed = new EventEmitter(); + /** The slide the lightbox moved to, emitted while it is still open. */ + @Output() readonly slideChanged = new EventEmitter(); + private lightbox: PhotoSwipeLightbox; + private closeOnOpened = false; constructor( - private elementRef: ElementRef + private elementRef: ElementRef, + private ngZone: NgZone ) {} ngOnInit(): void { @@ -139,22 +213,38 @@ export class PhotoSwipeGalleryDirective implements OnInit, OnDestroy { children: this.galleryChildrenSelector, pswpModule: PhotoSwipe, counter: false, - bgOpacity: 0, - mainClass: PHOTO_GALLERY_CLASS + // No toolbar magnifier: zoom stays on scroll and click + zoom: false, + // The backdrop look lives in PHOTO_GALLERY_STYLE; PhotoSwipe fades it in up to this opacity + bgOpacity: 1, + mainClass: PHOTO_GALLERY_CLASS, + padding: VIEWPORT_PADDING, + // The scroll lock only preventDefaults wheel, so PhotoSwipe still receives it + wheelToZoom: true, + initialZoomLevel: zoomLevel => initialZoom(zoomLevel), + secondaryZoomLevel: zoomLevel => secondaryZoom(zoomLevel) }); this.lightbox.addFilter('domItemData', (itemData, element) => { - let image: HTMLImageElement; - if (element instanceof HTMLImageElement) { - image = element; - } else { - image = element.querySelector('img'); + const image = thumbnailImage(element); + if (!image) { + return itemData; } itemData.src = image.src; itemData.width = image.naturalWidth; itemData.height = image.naturalHeight; - itemData.thumbCropped = true; + // Only a cover-fitted thumbnail is cropped; otherwise the zoom starts from a clipped frame + itemData.thumbCropped = getComputedStyle(image).objectFit === 'cover'; return itemData; }); + // PhotoSwipe measures the thumbnail's box, but `contain` paints a smaller image inside it, + // so the zoom would start off the visible pixels + this.lightbox.addFilter('thumbBounds', (thumbBounds, itemData) => { + const image = itemData.element ? thumbnailImage(itemData.element) : null; + if (!image?.naturalWidth || getComputedStyle(image).objectFit !== 'contain') { + return thumbBounds; + } + return containedImageBounds(image); + }); this.lightbox.on('uiRegister', () => { this.lightbox.pswp.ui.registerElement({ name: 'tb-photoswipe-caption', @@ -182,15 +272,81 @@ export class PhotoSwipeGalleryDirective implements OnInit, OnDestroy { } }); }); + // Emitted while still open: PhotoSwipe reads the thumbnail position when closing starts, so a + // host carousel must already show the matching slide by then + this.lightbox.on('change', () => { + this.ngZone.run(() => this.slideChanged.emit(this.lightbox.pswp.currIndex)); + }); + this.lightbox.on('beforeOpen', () => { + this.attachDocumentListeners(); + this.ngZone.run(() => this.lightboxOpened.emit()); + }); + this.lightbox.on('destroy', () => { + this.detachDocumentListeners(); + this.ngZone.run(() => this.lightboxClosed.emit()); + }); this.lightbox.init(); } ngOnDestroy(): void { + this.detachDocumentListeners(); if (this.lightbox) { this.lightbox.destroy(); } } + /** + * Escape closes the image only, not a mat-dialog behind it. Runs in the capture phase, ahead of + * the CDK overlay, and closes PhotoSwipe itself: stopping propagation also keeps the key from + * PhotoSwipe's own bubble-phase handler on document. + */ + private readonly onKeydownCapture = (e: KeyboardEvent): void => { + const pswp = this.lightbox?.pswp; + if (e.key !== 'Escape' || !pswp) { + return; + } + e.stopPropagation(); + e.preventDefault(); + if (pswp.opener?.isOpen) { + pswp.close(); + return; + } + // During the opening zoom close() is a no-op, so close once it ends (only once) + if (this.closeOnOpened) { + return; + } + this.closeOnOpened = true; + pswp.on('openingAnimationEnd', () => pswp.close()); + }; + + private readonly onScrollEvent = (e: Event): void => { + // Touch gestures inside the lightbox belong to PhotoSwipe (pan, pinch, swipe) + if (e.type === 'touchmove' && this.lightbox?.pswp?.element?.contains(e.target as Node)) { + return; + } + e.preventDefault(); + }; + + /** + * Escape interception plus the page scroll lock. PhotoSwipe does not lock page scroll, and the + * scroller may be the page or a dialog pane, so the wheel and touch events are blocked instead. + * Outside the zone, since touchmove fires at ~60 Hz during a pinch or pan. + */ + private attachDocumentListeners(): void { + this.ngZone.runOutsideAngular(() => { + document.addEventListener('keydown', this.onKeydownCapture, true); + document.addEventListener('wheel', this.onScrollEvent, { passive: false, capture: true }); + document.addEventListener('touchmove', this.onScrollEvent, { passive: false, capture: true }); + }); + } + + private detachDocumentListeners(): void { + this.closeOnOpened = false; + document.removeEventListener('keydown', this.onKeydownCapture, true); + document.removeEventListener('wheel', this.onScrollEvent, true); + document.removeEventListener('touchmove', this.onScrollEvent, true); + } + private initPhotoSwipeGalleryStyle(): void { const existingElement = document.getElementById(PHOTO_GALLERY_STYLE_ID); if (!existingElement) { diff --git a/ui-ngx/src/app/shared/models/ace/tbel/worker-tbel.js b/ui-ngx/src/app/shared/models/ace/tbel/worker-tbel.js index c15527f4da..323b8ef874 100644 --- a/ui-ngx/src/app/shared/models/ace/tbel/worker-tbel.js +++ b/ui-ngx/src/app/shared/models/ace/tbel/worker-tbel.js @@ -2410,20 +2410,20 @@ function toNumber(value) { module.exports = slice; -},{}],"/../../jshint/node_modules/underscore/underscore.js":[function(_dereq_,module,exports){ +},{}],"/../../jshint/node_modules/underscore/underscore-umd.js":[function(_dereq_,module,exports){ (function (global){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define('underscore', factory) : - (function() { - var current = global._; - var exports = factory(); - global._ = exports; - exports.noConflict = function() { global._ = current; return exports; }; - })(); + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, (function () { + var current = global._; + var exports = global._ = factory(); + exports.noConflict = function () { global._ = current; return exports; }; + }())); }(this, (function () { - var root = typeof self == 'object' && self.self === self && self || - typeof global == 'object' && global.global === global && global || + var VERSION = '1.13.8'; + var root = (typeof self == 'object' && self.self === self && self) || + (typeof global == 'object' && global.global === global && global) || Function('return this')() || {}; var ArrayProto = Array.prototype, ObjProto = Object.prototype; @@ -2432,49 +2432,18 @@ module.exports = slice; slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; + var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined', + supportsDataView = typeof DataView !== 'undefined'; var nativeIsArray = Array.isArray, nativeKeys = Object.keys, - nativeCreate = Object.create; - var _isNaN = root.isNaN, - _isFinite = root.isFinite; - var Ctor = function(){}; - function _(obj) { - if (obj instanceof _) return obj; - if (!(this instanceof _)) return new _(obj); - this._wrapped = obj; - } - var VERSION = _.VERSION = '1.10.2'; - function optimizeCb(func, context, argCount) { - if (context === void 0) return func; - switch (argCount == null ? 3 : argCount) { - case 1: return function(value) { - return func.call(context, value); - }; - case 3: return function(value, index, collection) { - return func.call(context, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(context, accumulator, value, index, collection); - }; - } - return function() { - return func.apply(context, arguments); - }; - } - function baseIteratee(value, context, argCount) { - if (value == null) return identity; - if (isFunction(value)) return optimizeCb(value, context, argCount); - if (isObject(value) && !isArray(value)) return matcher(value); - return property(value); - } - _.iteratee = iteratee; - function iteratee(value, context) { - return baseIteratee(value, context, Infinity); - } - function cb(value, context, argCount) { - if (_.iteratee !== iteratee) return _.iteratee(value, context); - return baseIteratee(value, context, argCount); - } + nativeCreate = Object.create, + nativeIsView = supportsArrayBuffer && ArrayBuffer.isView; + var _isNaN = isNaN, + _isFinite = isFinite; + var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); + var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', + 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; function restArguments(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { @@ -2497,469 +2466,598 @@ module.exports = slice; return func.apply(this, args); }; } - function baseCreate(prototype) { - if (!isObject(prototype)) return {}; - if (nativeCreate) return nativeCreate(prototype); - Ctor.prototype = prototype; - var result = new Ctor; - Ctor.prototype = null; - return result; - } - - function shallowProperty(key) { - return function(obj) { - return obj == null ? void 0 : obj[key]; - }; - } - - function _has(obj, path) { - return obj != null && hasOwnProperty.call(obj, path); + function isObject(obj) { + var type = typeof obj; + return type === 'function' || (type === 'object' && !!obj); } - - function deepGet(obj, path) { - var length = path.length; - for (var i = 0; i < length; i++) { - if (obj == null) return void 0; - obj = obj[path[i]]; - } - return length ? obj : void 0; + function isNull(obj) { + return obj === null; } - var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; - var getLength = shallowProperty('length'); - function isArrayLike(collection) { - var length = getLength(collection); - return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; + function isUndefined(obj) { + return obj === void 0; } - function each(obj, iteratee, context) { - iteratee = optimizeCb(iteratee, context); - var i, length; - if (isArrayLike(obj)) { - for (i = 0, length = obj.length; i < length; i++) { - iteratee(obj[i], i, obj); - } - } else { - var _keys = keys(obj); - for (i = 0, length = _keys.length; i < length; i++) { - iteratee(obj[_keys[i]], _keys[i], obj); - } - } - return obj; + function isBoolean(obj) { + return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; } - function map(obj, iteratee, context) { - iteratee = cb(iteratee, context); - var _keys = !isArrayLike(obj) && keys(obj), - length = (_keys || obj).length, - results = Array(length); - for (var index = 0; index < length; index++) { - var currentKey = _keys ? _keys[index] : index; - results[index] = iteratee(obj[currentKey], currentKey, obj); - } - return results; + function isElement(obj) { + return !!(obj && obj.nodeType === 1); } - function createReduce(dir) { - var reducer = function(obj, iteratee, memo, initial) { - var _keys = !isArrayLike(obj) && keys(obj), - length = (_keys || obj).length, - index = dir > 0 ? 0 : length - 1; - if (!initial) { - memo = obj[_keys ? _keys[index] : index]; - index += dir; - } - for (; index >= 0 && index < length; index += dir) { - var currentKey = _keys ? _keys[index] : index; - memo = iteratee(memo, obj[currentKey], currentKey, obj); - } - return memo; - }; - - return function(obj, iteratee, memo, context) { - var initial = arguments.length >= 3; - return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); + function tagTester(name) { + var tag = '[object ' + name + ']'; + return function(obj) { + return toString.call(obj) === tag; }; } - var reduce = createReduce(1); - var reduceRight = createReduce(-1); - function find(obj, predicate, context) { - var keyFinder = isArrayLike(obj) ? findIndex : findKey; - var key = keyFinder(obj, predicate, context); - if (key !== void 0 && key !== -1) return obj[key]; + var isString = tagTester('String'); + var isNumber = tagTester('Number'); + var isDate = tagTester('Date'); + var isRegExp = tagTester('RegExp'); + var isError = tagTester('Error'); + var isSymbol = tagTester('Symbol'); + var isArrayBuffer = tagTester('ArrayBuffer'); + var isFunction = tagTester('Function'); + var nodelist = root.document && root.document.childNodes; + if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { + isFunction = function(obj) { + return typeof obj == 'function' || false; + }; } - function filter(obj, predicate, context) { - var results = []; - predicate = cb(predicate, context); - each(obj, function(value, index, list) { - if (predicate(value, index, list)) results.push(value); - }); - return results; + var isFunction$1 = isFunction; + var hasObjectTag = tagTester('Object'); + var hasDataViewBug = ( + supportsDataView && (!/\[native code\]/.test(String(DataView)) || hasObjectTag(new DataView(new ArrayBuffer(8)))) + ), + isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map)); + var isDataView = tagTester('DataView'); + function alternateIsDataView(obj) { + return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer); } - function reject(obj, predicate, context) { - return filter(obj, negate(cb(predicate)), context); + var isDataView$1 = (hasDataViewBug ? alternateIsDataView : isDataView); + var isArray = nativeIsArray || tagTester('Array'); + function has$1(obj, key) { + return obj != null && hasOwnProperty.call(obj, key); } - function every(obj, predicate, context) { - predicate = cb(predicate, context); - var _keys = !isArrayLike(obj) && keys(obj), - length = (_keys || obj).length; - for (var index = 0; index < length; index++) { - var currentKey = _keys ? _keys[index] : index; - if (!predicate(obj[currentKey], currentKey, obj)) return false; + var isArguments = tagTester('Arguments'); + (function() { + if (!isArguments(arguments)) { + isArguments = function(obj) { + return has$1(obj, 'callee'); + }; } - return true; + }()); + var isArguments$1 = isArguments; + function isFinite$1(obj) { + return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj)); } - function some(obj, predicate, context) { - predicate = cb(predicate, context); - var _keys = !isArrayLike(obj) && keys(obj), - length = (_keys || obj).length; - for (var index = 0; index < length; index++) { - var currentKey = _keys ? _keys[index] : index; - if (predicate(obj[currentKey], currentKey, obj)) return true; - } - return false; + function isNaN$1(obj) { + return isNumber(obj) && _isNaN(obj); } - function contains(obj, item, fromIndex, guard) { - if (!isArrayLike(obj)) obj = values(obj); - if (typeof fromIndex != 'number' || guard) fromIndex = 0; - return indexOf(obj, item, fromIndex) >= 0; + function constant(value) { + return function() { + return value; + }; } - var invoke = restArguments(function(obj, path, args) { - var contextPath, func; - if (isFunction(path)) { - func = path; - } else if (isArray(path)) { - contextPath = path.slice(0, -1); - path = path[path.length - 1]; + function createSizePropertyCheck(getSizeProperty) { + return function(collection) { + var sizeProperty = getSizeProperty(collection); + return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX; } - return map(obj, function(context) { - var method = func; - if (!method) { - if (contextPath && contextPath.length) { - context = deepGet(context, contextPath); - } - if (context == null) return void 0; - method = context[path]; - } - return method == null ? method : method.apply(context, args); - }); - }); - function pluck(obj, key) { - return map(obj, property(key)); } - function where(obj, attrs) { - return filter(obj, matcher(attrs)); + function shallowProperty(key) { + return function(obj) { + return obj == null ? void 0 : obj[key]; + }; } - function findWhere(obj, attrs) { - return find(obj, matcher(attrs)); + var getByteLength = shallowProperty('byteLength'); + var isBufferLike = createSizePropertyCheck(getByteLength); + var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/; + function isTypedArray(obj) { + return nativeIsView ? (nativeIsView(obj) && !isDataView$1(obj)) : + isBufferLike(obj) && typedArrayPattern.test(toString.call(obj)); } - function max(obj, iteratee, context) { - var result = -Infinity, lastComputed = -Infinity, - value, computed; - if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) { - obj = isArrayLike(obj) ? obj : values(obj); - for (var i = 0, length = obj.length; i < length; i++) { - value = obj[i]; - if (value != null && value > result) { - result = value; - } + var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false); + var getLength = shallowProperty('length'); + function emulatedSet(keys) { + var hash = {}; + for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true; + return { + contains: function(key) { return hash[key] === true; }, + push: function(key) { + hash[key] = true; + return keys.push(key); } - } else { - iteratee = cb(iteratee, context); - each(obj, function(v, index, list) { - computed = iteratee(v, index, list); - if (computed > lastComputed || computed === -Infinity && result === -Infinity) { - result = v; - lastComputed = computed; - } - }); - } - return result; + }; } - function min(obj, iteratee, context) { - var result = Infinity, lastComputed = Infinity, - value, computed; - if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) { - obj = isArrayLike(obj) ? obj : values(obj); - for (var i = 0, length = obj.length; i < length; i++) { - value = obj[i]; - if (value != null && value < result) { - result = value; - } + function collectNonEnumProps(obj, keys) { + keys = emulatedSet(keys); + var nonEnumIdx = nonEnumerableProps.length; + var constructor = obj.constructor; + var proto = (isFunction$1(constructor) && constructor.prototype) || ObjProto; + var prop = 'constructor'; + if (has$1(obj, prop) && !keys.contains(prop)) keys.push(prop); + while (nonEnumIdx--) { + prop = nonEnumerableProps[nonEnumIdx]; + if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) { + keys.push(prop); } - } else { - iteratee = cb(iteratee, context); - each(obj, function(v, index, list) { - computed = iteratee(v, index, list); - if (computed < lastComputed || computed === Infinity && result === Infinity) { - result = v; - lastComputed = computed; - } - }); } - return result; } - function shuffle(obj) { - return sample(obj, Infinity); + function keys(obj) { + if (!isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (has$1(obj, key)) keys.push(key); + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; } - function sample(obj, n, guard) { - if (n == null || guard) { - if (!isArrayLike(obj)) obj = values(obj); - return obj[random(obj.length - 1)]; - } - var sample = isArrayLike(obj) ? clone(obj) : values(obj); - var length = getLength(sample); - n = Math.max(Math.min(n, length), 0); - var last = length - 1; - for (var index = 0; index < n; index++) { - var rand = random(index, last); - var temp = sample[index]; - sample[index] = sample[rand]; - sample[rand] = temp; - } - return sample.slice(0, n); - } - function sortBy(obj, iteratee, context) { - var index = 0; - iteratee = cb(iteratee, context); - return pluck(map(obj, function(value, key, list) { - return { - value: value, - index: index++, - criteria: iteratee(value, key, list) - }; - }).sort(function(left, right) { - var a = left.criteria; - var b = right.criteria; - if (a !== b) { - if (a > b || a === void 0) return 1; - if (a < b || b === void 0) return -1; - } - return left.index - right.index; - }), 'value'); - } - function group(behavior, partition) { - return function(obj, iteratee, context) { - var result = partition ? [[], []] : {}; - iteratee = cb(iteratee, context); - each(obj, function(value, index) { - var key = iteratee(value, index, obj); - behavior(result, value, key); - }); - return result; - }; + function isEmpty(obj) { + if (obj == null) return true; + var length = getLength(obj); + if (typeof length == 'number' && ( + isArray(obj) || isString(obj) || isArguments$1(obj) + )) return length === 0; + return getLength(keys(obj)) === 0; } - var groupBy = group(function(result, value, key) { - if (_has(result, key)) result[key].push(value); else result[key] = [value]; - }); - var indexBy = group(function(result, value, key) { - result[key] = value; - }); - var countBy = group(function(result, value, key) { - if (_has(result, key)) result[key]++; else result[key] = 1; - }); - - var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; - function toArray(obj) { - if (!obj) return []; - if (isArray(obj)) return slice.call(obj); - if (isString(obj)) { - return obj.match(reStrSymbol); + function isMatch(object, attrs) { + var _keys = keys(attrs), length = _keys.length; + if (object == null) return !length; + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = _keys[i]; + if (attrs[key] !== obj[key] || !(key in obj)) return false; } - if (isArrayLike(obj)) return map(obj, identity); - return values(obj); - } - function size(obj) { - if (obj == null) return 0; - return isArrayLike(obj) ? obj.length : keys(obj).length; - } - var partition = group(function(result, value, pass) { - result[pass ? 0 : 1].push(value); - }, true); - function first(array, n, guard) { - if (array == null || array.length < 1) return n == null ? void 0 : []; - if (n == null || guard) return array[0]; - return initial(array, array.length - n); - } - function initial(array, n, guard) { - return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); - } - function last(array, n, guard) { - if (array == null || array.length < 1) return n == null ? void 0 : []; - if (n == null || guard) return array[array.length - 1]; - return rest(array, Math.max(0, array.length - n)); - } - function rest(array, n, guard) { - return slice.call(array, n == null || guard ? 1 : n); + return true; } - function compact(array) { - return filter(array, Boolean); + function _$1(obj) { + if (obj instanceof _$1) return obj; + if (!(this instanceof _$1)) return new _$1(obj); + this._wrapped = obj; } - function _flatten(input, shallow, strict, output) { - output = output || []; - var idx = output.length; - for (var i = 0, length = getLength(input); i < length; i++) { - var value = input[i]; - if (isArrayLike(value) && (isArray(value) || isArguments(value))) { - if (shallow) { - var j = 0, len = value.length; - while (j < len) output[idx++] = value[j++]; - } else { - _flatten(value, shallow, strict, output); - idx = output.length; + _$1.VERSION = VERSION; + _$1.prototype.value = function() { + return this._wrapped; + }; + _$1.prototype.valueOf = _$1.prototype.toJSON = _$1.prototype.value; + _$1.prototype.toString = function() { + return String(this._wrapped); + }; + function toBufferView(bufferSource) { + return new Uint8Array( + bufferSource.buffer || bufferSource, + bufferSource.byteOffset || 0, + getByteLength(bufferSource) + ); + } + var tagDataView = '[object DataView]'; + function isEqual(a, b) { + var todo = [{a: a, b: b}]; + var aStack = [], bStack = []; + while (todo.length) { + var frame = todo.pop(); + if (frame === true) { + aStack.pop(); + bStack.pop(); + continue; + } + a = frame.a; + b = frame.b; + if (a === b) { + if (a !== 0 || 1 / a === 1 / b) continue; + return false; + } + if (a == null || b == null) return false; + if (a !== a) { + if (b !== b) continue; + return false; + } + var type = typeof a; + if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; + if (a instanceof _$1) a = a._wrapped; + if (b instanceof _$1) b = b._wrapped; + var className = toString.call(a); + if (className !== toString.call(b)) return false; + if (hasDataViewBug && className == '[object Object]' && isDataView$1(a)) { + if (!isDataView$1(b)) return false; + className = tagDataView; + } + switch (className) { + case '[object RegExp]': + case '[object String]': + if ('' + a === '' + b) continue; + return false; + case '[object Number]': + todo.push({a: +a, b: +b}); + continue; + case '[object Date]': + case '[object Boolean]': + if (+a === +b) continue; + return false; + case '[object Symbol]': + if (SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b)) continue; + return false; + case '[object ArrayBuffer]': + case tagDataView: + todo.push({a: toBufferView(a), b: toBufferView(b)}); + continue; + } + var areArrays = className === '[object Array]'; + if (!areArrays && isTypedArray$1(a)) { + var byteLength = getByteLength(a); + if (byteLength !== getByteLength(b)) return false; + if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) continue; + areArrays = true; + } + if (!areArrays) { + if (typeof a != 'object' || typeof b != 'object') return false; + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(isFunction$1(aCtor) && aCtor instanceof aCtor && + isFunction$1(bCtor) && bCtor instanceof bCtor) + && ('constructor' in a && 'constructor' in b)) { + return false; } - } else if (!strict) { - output[idx++] = value; } - } - return output; - } - function flatten(array, shallow) { - return _flatten(array, shallow, false); - } - var without = restArguments(function(array, otherArrays) { - return difference(array, otherArrays); - }); - function uniq(array, isSorted, iteratee, context) { - if (!isBoolean(isSorted)) { - context = iteratee; - iteratee = isSorted; - isSorted = false; - } - if (iteratee != null) iteratee = cb(iteratee, context); - var result = []; - var seen = []; - for (var i = 0, length = getLength(array); i < length; i++) { - var value = array[i], - computed = iteratee ? iteratee(value, i, array) : value; - if (isSorted && !iteratee) { - if (!i || seen !== computed) result.push(value); - seen = computed; - } else if (iteratee) { - if (!contains(seen, computed)) { - seen.push(computed); - result.push(value); + var length = aStack.length; + while (length--) { + if (aStack[length] === a) { + if (bStack[length] === b) break; + return false; + } + } + if (length >= 0) continue; + aStack.push(a); + bStack.push(b); + todo.push(true); + if (areArrays) { + length = a.length; + if (length !== b.length) return false; + while (length--) { + todo.push({a: a[length], b: b[length]}); + } + } else { + var _keys = keys(a), key; + length = _keys.length; + if (keys(b).length !== length) return false; + while (length--) { + key = _keys[length]; + if (!has$1(b, key)) return false; + todo.push({a: a[key], b: b[key]}); } - } else if (!contains(result, value)) { - result.push(value); } } - return result; + return true; } - var union = restArguments(function(arrays) { - return uniq(_flatten(arrays, true, true)); - }); - function intersection(array) { - var result = []; - var argsLength = arguments.length; - for (var i = 0, length = getLength(array); i < length; i++) { - var item = array[i]; - if (contains(result, item)) continue; - var j; - for (j = 1; j < argsLength; j++) { - if (!contains(arguments[j], item)) break; + function allKeys(obj) { + if (!isObject(obj)) return []; + var keys = []; + for (var key in obj) keys.push(key); + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + } + function ie11fingerprint(methods) { + var length = getLength(methods); + return function(obj) { + if (obj == null) return false; + var keys = allKeys(obj); + if (getLength(keys)) return false; + for (var i = 0; i < length; i++) { + if (!isFunction$1(obj[methods[i]])) return false; } - if (j === argsLength) result.push(item); + return methods !== weakMapMethods || !isFunction$1(obj[forEachName]); + }; + } + var forEachName = 'forEach', + hasName = 'has', + commonInit = ['clear', 'delete'], + mapTail = ['get', hasName, 'set']; + var mapMethods = commonInit.concat(forEachName, mapTail), + weakMapMethods = commonInit.concat(mapTail), + setMethods = ['add'].concat(commonInit, forEachName, hasName); + var isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map'); + var isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap'); + var isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set'); + var isWeakSet = tagTester('WeakSet'); + function values(obj) { + var _keys = keys(obj); + var length = _keys.length; + var values = Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[_keys[i]]; } - return result; + return values; } - var difference = restArguments(function(array, rest) { - rest = _flatten(rest, true, true); - return filter(array, function(value){ - return !contains(rest, value); - }); - }); - function unzip(array) { - var length = array && max(array, getLength).length || 0; - var result = Array(length); - - for (var index = 0; index < length; index++) { - result[index] = pluck(array, index); + function pairs(obj) { + var _keys = keys(obj); + var length = _keys.length; + var pairs = Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [_keys[i], obj[_keys[i]]]; } - return result; + return pairs; } - var zip = restArguments(unzip); - function object(list, values) { + function invert(obj) { var result = {}; - for (var i = 0, length = getLength(list); i < length; i++) { - if (values) { - result[list[i]] = values[i]; - } else { - result[list[i][0]] = list[i][1]; - } + var _keys = keys(obj); + for (var i = 0, length = _keys.length; i < length; i++) { + result[obj[_keys[i]]] = _keys[i]; } return result; } - function createPredicateIndexFinder(dir) { - return function(array, predicate, context) { - predicate = cb(predicate, context); - var length = getLength(array); - var index = dir > 0 ? 0 : length - 1; - for (; index >= 0 && index < length; index += dir) { - if (predicate(array[index], index, array)) return index; + function functions(obj) { + var names = []; + for (var key in obj) { + if (isFunction$1(obj[key])) names.push(key); + } + return names.sort(); + } + function createAssigner(keysFunc, defaults) { + return function(obj) { + var length = arguments.length; + if (defaults) obj = Object(obj); + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!defaults || obj[key] === void 0) obj[key] = source[key]; + } } - return -1; + return obj; }; } - var findIndex = createPredicateIndexFinder(1); - var findLastIndex = createPredicateIndexFinder(-1); - function sortedIndex(array, obj, iteratee, context) { - iteratee = cb(iteratee, context, 1); - var value = iteratee(obj); - var low = 0, high = getLength(array); - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; - } - return low; + var extend = createAssigner(allKeys); + var extendOwn = createAssigner(keys); + var defaults = createAssigner(allKeys, true); + function ctor() { + return function(){}; } - function createIndexFinder(dir, predicateFind, sortedIndex) { - return function(array, item, idx) { - var i = 0, length = getLength(array); - if (typeof idx == 'number') { - if (dir > 0) { - i = idx >= 0 ? idx : Math.max(idx + length, i); - } else { - length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; - } - } else if (sortedIndex && idx && length) { - idx = sortedIndex(array, item); - return array[idx] === item ? idx : -1; - } - if (item !== item) { - idx = predicateFind(slice.call(array, i, length), isNaN); - return idx >= 0 ? idx + i : -1; - } - for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { - if (array[idx] === item) return idx; - } - return -1; + function baseCreate(prototype) { + if (!isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + var Ctor = ctor(); + Ctor.prototype = prototype; + var result = new Ctor; + Ctor.prototype = null; + return result; + } + function create(prototype, props) { + var result = baseCreate(prototype); + if (props) extendOwn(result, props); + return result; + } + function clone(obj) { + if (!isObject(obj)) return obj; + return isArray(obj) ? obj.slice() : extend({}, obj); + } + function tap(obj, interceptor) { + interceptor(obj); + return obj; + } + function toPath$1(path) { + return isArray(path) ? path : [path]; + } + _$1.toPath = toPath$1; + function toPath(path) { + return _$1.toPath(path); + } + function deepGet(obj, path) { + var length = path.length; + for (var i = 0; i < length; i++) { + if (obj == null) return void 0; + obj = obj[path[i]]; + } + return length ? obj : void 0; + } + function get(object, path, defaultValue) { + var value = deepGet(object, toPath(path)); + return isUndefined(value) ? defaultValue : value; + } + function has(obj, path) { + path = toPath(path); + var length = path.length; + for (var i = 0; i < length; i++) { + var key = path[i]; + if (!has$1(obj, key)) return false; + obj = obj[key]; + } + return !!length; + } + function identity(value) { + return value; + } + function matcher(attrs) { + attrs = extendOwn({}, attrs); + return function(obj) { + return isMatch(obj, attrs); }; } - var indexOf = createIndexFinder(1, findIndex, sortedIndex); - var lastIndexOf = createIndexFinder(-1, findLastIndex); - function range(start, stop, step) { - if (stop == null) { - stop = start || 0; - start = 0; + function property(path) { + path = toPath(path); + return function(obj) { + return deepGet(obj, path); + }; + } + function optimizeCb(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; } - if (!step) { - step = stop < start ? -1 : 1; + return function() { + return func.apply(context, arguments); + }; + } + function baseIteratee(value, context, argCount) { + if (value == null) return identity; + if (isFunction$1(value)) return optimizeCb(value, context, argCount); + if (isObject(value) && !isArray(value)) return matcher(value); + return property(value); + } + function iteratee(value, context) { + return baseIteratee(value, context, Infinity); + } + _$1.iteratee = iteratee; + function cb(value, context, argCount) { + if (_$1.iteratee !== iteratee) return _$1.iteratee(value, context); + return baseIteratee(value, context, argCount); + } + function mapObject(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var _keys = keys(obj), + length = _keys.length, + results = {}; + for (var index = 0; index < length; index++) { + var currentKey = _keys[index]; + results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } - - var length = Math.max(Math.ceil((stop - start) / step), 0); - var range = Array(length); - - for (var idx = 0; idx < length; idx++, start += step) { - range[idx] = start; + return results; + } + function noop(){} + function propertyOf(obj) { + if (obj == null) return noop; + return function(path) { + return get(obj, path); + }; + } + function times(n, iteratee, context) { + var accum = Array(Math.max(0, n)); + iteratee = optimizeCb(iteratee, context, 1); + for (var i = 0; i < n; i++) accum[i] = iteratee(i); + return accum; + } + function random(min, max) { + if (max == null) { + max = min; + min = 0; } - - return range; + return min + Math.floor(Math.random() * (max - min + 1)); } - function chunk(array, count) { - if (count == null || count < 1) return []; - var result = []; - var i = 0, length = array.length; - while (i < length) { - result.push(slice.call(array, i, i += count)); + var now = Date.now || function() { + return new Date().getTime(); + }; + function createEscaper(map) { + var escaper = function(match) { + return map[match]; + }; + var source = '(?:' + keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function(string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + } + var escapeMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + var _escape = createEscaper(escapeMap); + var unescapeMap = invert(escapeMap); + var _unescape = createEscaper(unescapeMap); + var templateSettings = _$1.templateSettings = { + evaluate: /<%([\s\S]+?)%>/g, + interpolate: /<%=([\s\S]+?)%>/g, + escape: /<%-([\s\S]+?)%>/g + }; + var noMatch = /(.)^/; + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; + function escapeChar(match) { + return '\\' + escapes[match]; + } + var bareIdentifier = /^\s*(\w|\$)+\s*$/; + function template(text, settings, oldSettings) { + if (!settings && oldSettings) settings = oldSettings; + settings = defaults({}, settings, _$1.templateSettings); + var matcher = RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset).replace(escapeRegExp, escapeChar); + index = offset + match.length; + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } else if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } else if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + return match; + }); + source += "';\n"; + var argument = settings.variable; + if (argument) { + if (!bareIdentifier.test(argument)) throw new Error( + 'variable is not a bare identifier: ' + argument + ); + } else { + source = 'with(obj||{}){\n' + source + '}\n'; + argument = 'obj'; } - return result; + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + 'return __p;\n'; + var render; + try { + render = new Function(argument, '_', source); + } catch (e) { + e.source = source; + throw e; + } + var template = function(data) { + return render.call(this, data, _$1); + }; + template.source = 'function(' + argument + '){\n' + source + '}'; + return template; + } + function result(obj, path, fallback) { + path = toPath(path); + var length = path.length; + if (!length) { + return isFunction$1(fallback) ? fallback.call(obj) : fallback; + } + for (var i = 0; i < length; i++) { + var prop = obj == null ? void 0 : obj[path[i]]; + if (prop === void 0) { + prop = fallback; + i = length; + } + obj = isFunction$1(prop) ? prop.call(obj) : prop; + } + return obj; + } + var idCounter = 0; + function uniqueId(prefix) { + var id = ++idCounter + ''; + return prefix ? prefix + id : id; + } + function chain(obj) { + var instance = _$1(obj); + instance._chain = true; + return instance; } function executeBound(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); @@ -2968,13 +3066,6 @@ module.exports = slice; if (isObject(result)) return result; return self; } - var bind = restArguments(function(func, context, args) { - if (!isFunction(func)) throw new TypeError('Bind must be called on a function'); - var bound = restArguments(function(callArgs) { - return executeBound(func, bound, context, this, args.concat(callArgs)); - }); - return bound; - }); var partial = restArguments(function(func, boundArgs) { var placeholder = partial.placeholder; var bound = function() { @@ -2988,22 +3079,56 @@ module.exports = slice; }; return bound; }); - - partial.placeholder = _; - var bindAll = restArguments(function(obj, _keys) { - _keys = _flatten(_keys, false, false); - var index = _keys.length; - if (index < 1) throw new Error('bindAll must be passed function names'); - while (index--) { - var key = _keys[index]; - obj[key] = bind(obj[key], obj); - } - }); - function memoize(func, hasher) { - var memoize = function(key) { - var cache = memoize.cache; + partial.placeholder = _$1; + var bind = restArguments(function(func, context, args) { + if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function'); + var bound = restArguments(function(callArgs) { + return executeBound(func, bound, context, this, args.concat(callArgs)); + }); + return bound; + }); + var isArrayLike = createSizePropertyCheck(getLength); + function flatten$1(input, depth, strict) { + if (!depth && depth !== 0) depth = Infinity; + var output = [], idx = 0, i = 0, length = getLength(input) || 0, stack = []; + while (true) { + if (i >= length) { + if (!stack.length) break; + var frame = stack.pop(); + i = frame.i; + input = frame.v; + length = getLength(input); + continue; + } + var value = input[i++]; + if (stack.length >= depth) { + output[idx++] = value; + } else if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) { + stack.push({i: i, v: input}); + i = 0; + input = value; + length = getLength(input); + } else if (!strict) { + output[idx++] = value; + } + } + return output; + } + var bindAll = restArguments(function(obj, keys) { + keys = flatten$1(keys, false, false); + var index = keys.length; + if (index < 1) throw new Error('bindAll must be passed function names'); + while (index--) { + var key = keys[index]; + obj[key] = bind(obj[key], obj); + } + return obj; + }); + function memoize(func, hasher) { + var memoize = function(key) { + var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); - if (!_has(cache, address)) cache[address] = func.apply(this, arguments); + if (!has$1(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; @@ -3014,19 +3139,17 @@ module.exports = slice; return func.apply(null, args); }, wait); }); - var defer = partial(delay, _, 1); + var defer = partial(delay, _$1, 1); function throttle(func, wait, options) { var timeout, context, args, result; var previous = 0; if (!options) options = {}; - var later = function() { previous = options.leading === false ? 0 : now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; - var throttled = function() { var _now = now(); if (!previous && options.leading === false) previous = _now; @@ -3046,41 +3169,39 @@ module.exports = slice; } return result; }; - throttled.cancel = function() { clearTimeout(timeout); previous = 0; timeout = context = args = null; }; - return throttled; } function debounce(func, wait, immediate) { - var timeout, result; - - var later = function(context, args) { - timeout = null; - if (args) result = func.apply(context, args); + var timeout, previous, args, result, context; + var later = function() { + var passed = now() - previous; + if (wait > passed) { + timeout = setTimeout(later, wait - passed); + } else { + timeout = null; + if (!immediate) result = func.apply(context, args); + if (!timeout) args = context = null; + } }; - - var debounced = restArguments(function(args) { - if (timeout) clearTimeout(timeout); - if (immediate) { - var callNow = !timeout; + var debounced = restArguments(function(_args) { + context = this; + args = _args; + previous = now(); + if (!timeout) { timeout = setTimeout(later, wait); - if (callNow) result = func.apply(this, args); - } else { - timeout = delay(later, wait, this, args); + if (immediate) result = func.apply(context, args); } - return result; }); - debounced.cancel = function() { clearTimeout(timeout); - timeout = null; + timeout = args = context = null; }; - return debounced; } function wrap(func, wrapper) { @@ -3119,513 +3240,579 @@ module.exports = slice; }; } var once = partial(before, 2); - var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); - var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', - 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; - - function collectNonEnumProps(obj, _keys) { - var nonEnumIdx = nonEnumerableProps.length; - var constructor = obj.constructor; - var proto = isFunction(constructor) && constructor.prototype || ObjProto; - var prop = 'constructor'; - if (_has(obj, prop) && !contains(_keys, prop)) _keys.push(prop); - - while (nonEnumIdx--) { - prop = nonEnumerableProps[nonEnumIdx]; - if (prop in obj && obj[prop] !== proto[prop] && !contains(_keys, prop)) { - _keys.push(prop); + function findKey(obj, predicate, context) { + predicate = cb(predicate, context); + var _keys = keys(obj), key; + for (var i = 0, length = _keys.length; i < length; i++) { + key = _keys[i]; + if (predicate(obj[key], key, obj)) return key; + } + } + function createPredicateIndexFinder(dir) { + return function(array, predicate, context) { + predicate = cb(predicate, context); + var length = getLength(array); + var index = dir > 0 ? 0 : length - 1; + for (; index >= 0 && index < length; index += dir) { + if (predicate(array[index], index, array)) return index; } + return -1; + }; + } + var findIndex = createPredicateIndexFinder(1); + var findLastIndex = createPredicateIndexFinder(-1); + function sortedIndex(array, obj, iteratee, context) { + iteratee = cb(iteratee, context, 1); + var value = iteratee(obj); + var low = 0, high = getLength(array); + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } + return low; } - function keys(obj) { - if (!isObject(obj)) return []; - if (nativeKeys) return nativeKeys(obj); - var _keys = []; - for (var key in obj) if (_has(obj, key)) _keys.push(key); - if (hasEnumBug) collectNonEnumProps(obj, _keys); - return _keys; + function createIndexFinder(dir, predicateFind, sortedIndex) { + return function(array, item, idx) { + var i = 0, length = getLength(array); + if (typeof idx == 'number') { + if (dir > 0) { + i = idx >= 0 ? idx : Math.max(idx + length, i); + } else { + length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; + } + } else if (sortedIndex && idx && length) { + idx = sortedIndex(array, item); + return array[idx] === item ? idx : -1; + } + if (item !== item) { + idx = predicateFind(slice.call(array, i, length), isNaN$1); + return idx >= 0 ? idx + i : -1; + } + for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { + if (array[idx] === item) return idx; + } + return -1; + }; } - function allKeys(obj) { - if (!isObject(obj)) return []; - var _keys = []; - for (var key in obj) _keys.push(key); - if (hasEnumBug) collectNonEnumProps(obj, _keys); - return _keys; + var indexOf = createIndexFinder(1, findIndex, sortedIndex); + var lastIndexOf = createIndexFinder(-1, findLastIndex); + function find(obj, predicate, context) { + var keyFinder = isArrayLike(obj) ? findIndex : findKey; + var key = keyFinder(obj, predicate, context); + if (key !== void 0 && key !== -1) return obj[key]; } - function values(obj) { - var _keys = keys(obj); - var length = _keys.length; - var values = Array(length); - for (var i = 0; i < length; i++) { - values[i] = obj[_keys[i]]; + function findWhere(obj, attrs) { + return find(obj, matcher(attrs)); + } + function each(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var _keys = keys(obj); + for (i = 0, length = _keys.length; i < length; i++) { + iteratee(obj[_keys[i]], _keys[i], obj); + } } - return values; + return obj; } - function mapObject(obj, iteratee, context) { + function map(obj, iteratee, context) { iteratee = cb(iteratee, context); - var _keys = keys(obj), - length = _keys.length, - results = {}; + var _keys = !isArrayLike(obj) && keys(obj), + length = (_keys || obj).length, + results = Array(length); for (var index = 0; index < length; index++) { - var currentKey = _keys[index]; - results[currentKey] = iteratee(obj[currentKey], currentKey, obj); + var currentKey = _keys ? _keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; } - function pairs(obj) { - var _keys = keys(obj); - var length = _keys.length; - var pairs = Array(length); - for (var i = 0; i < length; i++) { - pairs[i] = [_keys[i], obj[_keys[i]]]; + function createReduce(dir) { + var reducer = function(obj, iteratee, memo, initial) { + var _keys = !isArrayLike(obj) && keys(obj), + length = (_keys || obj).length, + index = dir > 0 ? 0 : length - 1; + if (!initial) { + memo = obj[_keys ? _keys[index] : index]; + index += dir; + } + for (; index >= 0 && index < length; index += dir) { + var currentKey = _keys ? _keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + }; + return function(obj, iteratee, memo, context) { + var initial = arguments.length >= 3; + return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); + }; + } + var reduce = createReduce(1); + var reduceRight = createReduce(-1); + function filter(obj, predicate, context) { + var results = []; + predicate = cb(predicate, context); + each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + return results; + } + function reject(obj, predicate, context) { + return filter(obj, negate(cb(predicate)), context); + } + function every(obj, predicate, context) { + predicate = cb(predicate, context); + var _keys = !isArrayLike(obj) && keys(obj), + length = (_keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = _keys ? _keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; } - return pairs; + return true; } - function invert(obj) { - var result = {}; - var _keys = keys(obj); - for (var i = 0, length = _keys.length; i < length; i++) { - result[obj[_keys[i]]] = _keys[i]; + function some(obj, predicate, context) { + predicate = cb(predicate, context); + var _keys = !isArrayLike(obj) && keys(obj), + length = (_keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = _keys ? _keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; } - return result; + return false; } - function functions(obj) { - var names = []; - for (var key in obj) { - if (isFunction(obj[key])) names.push(key); + function contains(obj, item, fromIndex, guard) { + if (!isArrayLike(obj)) obj = values(obj); + if (typeof fromIndex != 'number' || guard) fromIndex = 0; + return indexOf(obj, item, fromIndex) >= 0; + } + var invoke = restArguments(function(obj, path, args) { + var contextPath, func; + if (isFunction$1(path)) { + func = path; + } else { + path = toPath(path); + contextPath = path.slice(0, -1); + path = path[path.length - 1]; } - return names.sort(); + return map(obj, function(context) { + var method = func; + if (!method) { + if (contextPath && contextPath.length) { + context = deepGet(context, contextPath); + } + if (context == null) return void 0; + method = context[path]; + } + return method == null ? method : method.apply(context, args); + }); + }); + function pluck(obj, key) { + return map(obj, property(key)); } - function createAssigner(keysFunc, defaults) { - return function(obj) { - var length = arguments.length; - if (defaults) obj = Object(obj); - if (length < 2 || obj == null) return obj; - for (var index = 1; index < length; index++) { - var source = arguments[index], - _keys = keysFunc(source), - l = _keys.length; - for (var i = 0; i < l; i++) { - var key = _keys[i]; - if (!defaults || obj[key] === void 0) obj[key] = source[key]; + function where(obj, attrs) { + return filter(obj, matcher(attrs)); + } + function max(obj, iteratee, context) { + var result = -Infinity, lastComputed = -Infinity, + value, computed; + if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) { + obj = isArrayLike(obj) ? obj : values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value != null && value > result) { + result = value; } } - return obj; + } else { + iteratee = cb(iteratee, context); + each(obj, function(v, index, list) { + computed = iteratee(v, index, list); + if (computed > lastComputed || (computed === -Infinity && result === -Infinity)) { + result = v; + lastComputed = computed; + } + }); + } + return result; + } + function min(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) { + obj = isArrayLike(obj) ? obj : values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value != null && value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + each(obj, function(v, index, list) { + computed = iteratee(v, index, list); + if (computed < lastComputed || (computed === Infinity && result === Infinity)) { + result = v; + lastComputed = computed; + } + }); + } + return result; + } + var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; + function toArray(obj) { + if (!obj) return []; + if (isArray(obj)) return slice.call(obj); + if (isString(obj)) { + return obj.match(reStrSymbol); + } + if (isArrayLike(obj)) return map(obj, identity); + return values(obj); + } + function sample(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = values(obj); + return obj[random(obj.length - 1)]; + } + var sample = toArray(obj); + var length = getLength(sample); + n = Math.max(Math.min(n, length), 0); + var last = length - 1; + for (var index = 0; index < n; index++) { + var rand = random(index, last); + var temp = sample[index]; + sample[index] = sample[rand]; + sample[rand] = temp; + } + return sample.slice(0, n); + } + function shuffle(obj) { + return sample(obj, Infinity); + } + function sortBy(obj, iteratee, context) { + var index = 0; + iteratee = cb(iteratee, context); + return pluck(map(obj, function(value, key, list) { + return { + value: value, + index: index++, + criteria: iteratee(value, key, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + } + function group(behavior, partition) { + return function(obj, iteratee, context) { + var result = partition ? [[], []] : {}; + iteratee = cb(iteratee, context); + each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + return result; }; } - var extend = createAssigner(allKeys); - var extendOwn = createAssigner(keys); - function findKey(obj, predicate, context) { - predicate = cb(predicate, context); - var _keys = keys(obj), key; - for (var i = 0, length = _keys.length; i < length; i++) { - key = _keys[i]; - if (predicate(obj[key], key, obj)) return key; - } + var groupBy = group(function(result, value, key) { + if (has$1(result, key)) result[key].push(value); else result[key] = [value]; + }); + var indexBy = group(function(result, value, key) { + result[key] = value; + }); + var countBy = group(function(result, value, key) { + if (has$1(result, key)) result[key]++; else result[key] = 1; + }); + var partition = group(function(result, value, pass) { + result[pass ? 0 : 1].push(value); + }, true); + function size(obj) { + if (obj == null) return 0; + return isArrayLike(obj) ? obj.length : keys(obj).length; } function keyInObj(value, key, obj) { return key in obj; } - var pick = restArguments(function(obj, _keys) { - var result = {}, iteratee = _keys[0]; + var pick = restArguments(function(obj, keys) { + var result = {}, iteratee = keys[0]; if (obj == null) return result; - if (isFunction(iteratee)) { - if (_keys.length > 1) iteratee = optimizeCb(iteratee, _keys[1]); - _keys = allKeys(obj); + if (isFunction$1(iteratee)) { + if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); + keys = allKeys(obj); } else { iteratee = keyInObj; - _keys = _flatten(_keys, false, false); + keys = flatten$1(keys, false, false); obj = Object(obj); } - for (var i = 0, length = _keys.length; i < length; i++) { - var key = _keys[i]; + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }); - var omit = restArguments(function(obj, _keys) { - var iteratee = _keys[0], context; - if (isFunction(iteratee)) { + var omit = restArguments(function(obj, keys) { + var iteratee = keys[0], context; + if (isFunction$1(iteratee)) { iteratee = negate(iteratee); - if (_keys.length > 1) context = _keys[1]; + if (keys.length > 1) context = keys[1]; } else { - _keys = map(_flatten(_keys, false, false), String); + keys = map(flatten$1(keys, false, false), String); iteratee = function(value, key) { - return !contains(_keys, key); + return !contains(keys, key); }; } return pick(obj, iteratee, context); }); - var defaults = createAssigner(allKeys, true); - function create(prototype, props) { - var result = baseCreate(prototype); - if (props) extendOwn(result, props); - return result; - } - function clone(obj) { - if (!isObject(obj)) return obj; - return isArray(obj) ? obj.slice() : extend({}, obj); - } - function tap(obj, interceptor) { - interceptor(obj); - return obj; - } - function isMatch(object, attrs) { - var _keys = keys(attrs), length = _keys.length; - if (object == null) return !length; - var obj = Object(object); - for (var i = 0; i < length; i++) { - var key = _keys[i]; - if (attrs[key] !== obj[key] || !(key in obj)) return false; - } - return true; - } - function eq(a, b, aStack, bStack) { - if (a === b) return a !== 0 || 1 / a === 1 / b; - if (a == null || b == null) return false; - if (a !== a) return b !== b; - var type = typeof a; - if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; - return deepEq(a, b, aStack, bStack); - } - function deepEq(a, b, aStack, bStack) { - if (a instanceof _) a = a._wrapped; - if (b instanceof _) b = b._wrapped; - var className = toString.call(a); - if (className !== toString.call(b)) return false; - switch (className) { - case '[object RegExp]': - case '[object String]': - return '' + a === '' + b; - case '[object Number]': - if (+a !== +a) return +b !== +b; - return +a === 0 ? 1 / +a === 1 / b : +a === +b; - case '[object Date]': - case '[object Boolean]': - return +a === +b; - case '[object Symbol]': - return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b); - } - - var areArrays = className === '[object Array]'; - if (!areArrays) { - if (typeof a != 'object' || typeof b != 'object') return false; - var aCtor = a.constructor, bCtor = b.constructor; - if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && - isFunction(bCtor) && bCtor instanceof bCtor) - && ('constructor' in a && 'constructor' in b)) { - return false; - } - } - aStack = aStack || []; - bStack = bStack || []; - var length = aStack.length; - while (length--) { - if (aStack[length] === a) return bStack[length] === b; - } - aStack.push(a); - bStack.push(b); - if (areArrays) { - length = a.length; - if (length !== b.length) return false; - while (length--) { - if (!eq(a[length], b[length], aStack, bStack)) return false; - } - } else { - var _keys = keys(a), key; - length = _keys.length; - if (keys(b).length !== length) return false; - while (length--) { - key = _keys[length]; - if (!(_has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; - } - } - aStack.pop(); - bStack.pop(); - return true; - } - function isEqual(a, b) { - return eq(a, b); - } - function isEmpty(obj) { - if (obj == null) return true; - if (isArrayLike(obj) && (isArray(obj) || isString(obj) || isArguments(obj))) return obj.length === 0; - return keys(obj).length === 0; - } - function isElement(obj) { - return !!(obj && obj.nodeType === 1); - } - function tagTester(name) { - return function(obj) { - return toString.call(obj) === '[object ' + name + ']'; - }; - } - var isArray = nativeIsArray || tagTester('Array'); - function isObject(obj) { - var type = typeof obj; - return type === 'function' || type === 'object' && !!obj; - } - var isArguments = tagTester('Arguments'); - var isFunction = tagTester('Function'); - var isString = tagTester('String'); - var isNumber = tagTester('Number'); - var isDate = tagTester('Date'); - var isRegExp = tagTester('RegExp'); - var isError = tagTester('Error'); - var isSymbol = tagTester('Symbol'); - var isMap = tagTester('Map'); - var isWeakMap = tagTester('WeakMap'); - var isSet = tagTester('Set'); - var isWeakSet = tagTester('WeakSet'); - (function() { - if (!isArguments(arguments)) { - isArguments = function(obj) { - return _has(obj, 'callee'); - }; - } - }()); - var nodelist = root.document && root.document.childNodes; - if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { - isFunction = function(obj) { - return typeof obj == 'function' || false; - }; + function initial(array, n, guard) { + return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); } - function isFinite(obj) { - return !isSymbol(obj) && _isFinite(obj) && !_isNaN(parseFloat(obj)); + function first(array, n, guard) { + if (array == null || array.length < 1) return n == null || guard ? void 0 : []; + if (n == null || guard) return array[0]; + return initial(array, array.length - n); } - function isNaN(obj) { - return isNumber(obj) && _isNaN(obj); + function rest(array, n, guard) { + return slice.call(array, n == null || guard ? 1 : n); } - function isBoolean(obj) { - return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; + function last(array, n, guard) { + if (array == null || array.length < 1) return n == null || guard ? void 0 : []; + if (n == null || guard) return array[array.length - 1]; + return rest(array, Math.max(0, array.length - n)); } - function isNull(obj) { - return obj === null; + function compact(array) { + return filter(array, Boolean); } - function isUndefined(obj) { - return obj === void 0; + function flatten(array, depth) { + return flatten$1(array, depth, false); } - function has(obj, path) { - if (!isArray(path)) { - return _has(obj, path); + var difference = restArguments(function(array, rest) { + rest = flatten$1(rest, true, true); + return filter(array, function(value){ + return !contains(rest, value); + }); + }); + var without = restArguments(function(array, otherArrays) { + return difference(array, otherArrays); + }); + function uniq(array, isSorted, iteratee, context) { + if (!isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; } - var length = path.length; - for (var i = 0; i < length; i++) { - var key = path[i]; - if (obj == null || !hasOwnProperty.call(obj, key)) { - return false; + if (iteratee != null) iteratee = cb(iteratee, context); + var result = []; + var seen = []; + for (var i = 0, length = getLength(array); i < length; i++) { + var value = array[i], + computed = iteratee ? iteratee(value, i, array) : value; + if (isSorted && !iteratee) { + if (!i || seen !== computed) result.push(value); + seen = computed; + } else if (iteratee) { + if (!contains(seen, computed)) { + seen.push(computed); + result.push(value); + } + } else if (!contains(result, value)) { + result.push(value); } - obj = obj[key]; } - return !!length; - } - function identity(value) { - return value; - } - function constant(value) { - return function() { - return value; - }; + return result; } - - function noop(){} - function property(path) { - if (!isArray(path)) { - return shallowProperty(path); + var union = restArguments(function(arrays) { + return uniq(flatten$1(arrays, true, true)); + }); + function intersection(array) { + var result = []; + var argsLength = arguments.length; + for (var i = 0, length = getLength(array); i < length; i++) { + var item = array[i]; + if (contains(result, item)) continue; + var j; + for (j = 1; j < argsLength; j++) { + if (!contains(arguments[j], item)) break; + } + if (j === argsLength) result.push(item); } - return function(obj) { - return deepGet(obj, path); - }; + return result; } - function propertyOf(obj) { - if (obj == null) { - return function(){}; + function unzip(array) { + var length = (array && max(array, getLength).length) || 0; + var result = Array(length); + for (var index = 0; index < length; index++) { + result[index] = pluck(array, index); } - return function(path) { - return !isArray(path) ? obj[path] : deepGet(obj, path); - }; - } - function matcher(attrs) { - attrs = extendOwn({}, attrs); - return function(obj) { - return isMatch(obj, attrs); - }; - } - function times(n, iteratee, context) { - var accum = Array(Math.max(0, n)); - iteratee = optimizeCb(iteratee, context, 1); - for (var i = 0; i < n; i++) accum[i] = iteratee(i); - return accum; + return result; } - function random(min, max) { - if (max == null) { - max = min; - min = 0; + var zip = restArguments(unzip); + function object(list, values) { + var result = {}; + for (var i = 0, length = getLength(list); i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } } - return min + Math.floor(Math.random() * (max - min + 1)); - } - var now = Date.now || function() { - return new Date().getTime(); - }; - var escapeMap = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''', - '`': '`' - }; - var unescapeMap = invert(escapeMap); - function createEscaper(map) { - var escaper = function(match) { - return map[match]; - }; - var source = '(?:' + keys(map).join('|') + ')'; - var testRegexp = RegExp(source); - var replaceRegexp = RegExp(source, 'g'); - return function(string) { - string = string == null ? '' : '' + string; - return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; - }; + return result; } - var escape = createEscaper(escapeMap); - var unescape = createEscaper(unescapeMap); - function result(obj, path, fallback) { - if (!isArray(path)) path = [path]; - var length = path.length; - if (!length) { - return isFunction(fallback) ? fallback.call(obj) : fallback; + function range(start, stop, step) { + if (stop == null) { + stop = start || 0; + start = 0; + } + if (!step) { + step = stop < start ? -1 : 1; } - for (var i = 0; i < length; i++) { - var prop = obj == null ? void 0 : obj[path[i]]; - if (prop === void 0) { - prop = fallback; - i = length; // Ensure we don't continue iterating. - } - obj = isFunction(prop) ? prop.call(obj) : prop; + var length = Math.max(Math.ceil((stop - start) / step), 0); + var range = Array(length); + for (var idx = 0; idx < length; idx++, start += step) { + range[idx] = start; } - return obj; - } - var idCounter = 0; - function uniqueId(prefix) { - var id = ++idCounter + ''; - return prefix ? prefix + id : id; + return range; } - var templateSettings = _.templateSettings = { - evaluate: /<%([\s\S]+?)%>/g, - interpolate: /<%=([\s\S]+?)%>/g, - escape: /<%-([\s\S]+?)%>/g - }; - var noMatch = /(.)^/; - var escapes = { - "'": "'", - '\\': '\\', - '\r': 'r', - '\n': 'n', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; - - var escapeChar = function(match) { - return '\\' + escapes[match]; - }; - function template(text, settings, oldSettings) { - if (!settings && oldSettings) settings = oldSettings; - settings = defaults({}, settings, _.templateSettings); - var matcher = RegExp([ - (settings.escape || noMatch).source, - (settings.interpolate || noMatch).source, - (settings.evaluate || noMatch).source - ].join('|') + '|$', 'g'); - var index = 0; - var source = "__p+='"; - text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { - source += text.slice(index, offset).replace(escapeRegExp, escapeChar); - index = offset + match.length; - - if (escape) { - source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; - } else if (interpolate) { - source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; - } else if (evaluate) { - source += "';\n" + evaluate + "\n__p+='"; - } - return match; - }); - source += "';\n"; - if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; - - source = "var __t,__p='',__j=Array.prototype.join," + - "print=function(){__p+=__j.call(arguments,'');};\n" + - source + 'return __p;\n'; - - var render; - try { - render = new Function(settings.variable || 'obj', '_', source); - } catch (e) { - e.source = source; - throw e; + function chunk(array, count) { + if (count == null || count < 1) return []; + var result = []; + var i = 0, length = array.length; + while (i < length) { + result.push(slice.call(array, i, i += count)); } - - var template = function(data) { - return render.call(this, data, _); - }; - var argument = settings.variable || 'obj'; - template.source = 'function(' + argument + '){\n' + source + '}'; - - return template; - } - function chain(obj) { - var instance = _(obj); - instance._chain = true; - return instance; + return result; } function chainResult(instance, obj) { - return instance._chain ? _(obj).chain() : obj; + return instance._chain ? _$1(obj).chain() : obj; } function mixin(obj) { each(functions(obj), function(name) { - var func = _[name] = obj[name]; - _.prototype[name] = function() { + var func = _$1[name] = obj[name]; + _$1.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); - return chainResult(this, func.apply(_, args)); + return chainResult(this, func.apply(_$1, args)); }; }); - return _; + return _$1; } each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; - _.prototype[name] = function() { + _$1.prototype[name] = function() { var obj = this._wrapped; - method.apply(obj, arguments); - if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; + if (obj != null) { + method.apply(obj, arguments); + if ((name === 'shift' || name === 'splice') && obj.length === 0) { + delete obj[0]; + } + } return chainResult(this, obj); }; }); each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; - _.prototype[name] = function() { - return chainResult(this, method.apply(this._wrapped, arguments)); + _$1.prototype[name] = function() { + var obj = this._wrapped; + if (obj != null) obj = method.apply(obj, arguments); + return chainResult(this, obj); }; }); - _.prototype.value = function() { - return this._wrapped; - }; - _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; - - _.prototype.toString = function() { - return String(this._wrapped); - }; - - var allExports = ({ - 'default': _, + var allExports = { + __proto__: null, VERSION: VERSION, - iteratee: iteratee, restArguments: restArguments, + isObject: isObject, + isNull: isNull, + isUndefined: isUndefined, + isBoolean: isBoolean, + isElement: isElement, + isString: isString, + isNumber: isNumber, + isDate: isDate, + isRegExp: isRegExp, + isError: isError, + isSymbol: isSymbol, + isArrayBuffer: isArrayBuffer, + isDataView: isDataView$1, + isArray: isArray, + isFunction: isFunction$1, + isArguments: isArguments$1, + isFinite: isFinite$1, + isNaN: isNaN$1, + isTypedArray: isTypedArray$1, + isEmpty: isEmpty, + isMatch: isMatch, + isEqual: isEqual, + isMap: isMap, + isWeakMap: isWeakMap, + isSet: isSet, + isWeakSet: isWeakSet, + keys: keys, + allKeys: allKeys, + values: values, + pairs: pairs, + invert: invert, + functions: functions, + methods: functions, + extend: extend, + extendOwn: extendOwn, + assign: extendOwn, + defaults: defaults, + create: create, + clone: clone, + tap: tap, + get: get, + has: has, + mapObject: mapObject, + identity: identity, + constant: constant, + noop: noop, + toPath: toPath$1, + property: property, + propertyOf: propertyOf, + matcher: matcher, + matches: matcher, + times: times, + random: random, + now: now, + escape: _escape, + unescape: _unescape, + templateSettings: templateSettings, + template: template, + result: result, + uniqueId: uniqueId, + chain: chain, + iteratee: iteratee, + partial: partial, + bind: bind, + bindAll: bindAll, + memoize: memoize, + delay: delay, + defer: defer, + throttle: throttle, + debounce: debounce, + wrap: wrap, + negate: negate, + compose: compose, + after: after, + before: before, + once: once, + findKey: findKey, + findIndex: findIndex, + findLastIndex: findLastIndex, + sortedIndex: sortedIndex, + indexOf: indexOf, + lastIndexOf: lastIndexOf, + find: find, + detect: find, + findWhere: findWhere, each: each, forEach: each, map: map, @@ -3635,8 +3822,6 @@ module.exports = slice; inject: reduce, reduceRight: reduceRight, foldr: reduceRight, - find: find, - detect: find, filter: filter, select: filter, reject: reject, @@ -3650,7 +3835,6 @@ module.exports = slice; invoke: invoke, pluck: pluck, where: where, - findWhere: findWhere, max: max, min: min, shuffle: shuffle, @@ -3659,9 +3843,11 @@ module.exports = slice; groupBy: groupBy, indexBy: indexBy, countBy: countBy, + partition: partition, toArray: toArray, size: size, - partition: partition, + pick: pick, + omit: omit, first: first, head: first, take: first, @@ -3679,98 +3865,18 @@ module.exports = slice; intersection: intersection, difference: difference, unzip: unzip, + transpose: unzip, zip: zip, object: object, - findIndex: findIndex, - findLastIndex: findLastIndex, - sortedIndex: sortedIndex, - indexOf: indexOf, - lastIndexOf: lastIndexOf, range: range, chunk: chunk, - bind: bind, - partial: partial, - bindAll: bindAll, - memoize: memoize, - delay: delay, - defer: defer, - throttle: throttle, - debounce: debounce, - wrap: wrap, - negate: negate, - compose: compose, - after: after, - before: before, - once: once, - keys: keys, - allKeys: allKeys, - values: values, - mapObject: mapObject, - pairs: pairs, - invert: invert, - functions: functions, - methods: functions, - extend: extend, - extendOwn: extendOwn, - assign: extendOwn, - findKey: findKey, - pick: pick, - omit: omit, - defaults: defaults, - create: create, - clone: clone, - tap: tap, - isMatch: isMatch, - isEqual: isEqual, - isEmpty: isEmpty, - isElement: isElement, - isArray: isArray, - isObject: isObject, - isArguments: isArguments, - isFunction: isFunction, - isString: isString, - isNumber: isNumber, - isDate: isDate, - isRegExp: isRegExp, - isError: isError, - isSymbol: isSymbol, - isMap: isMap, - isWeakMap: isWeakMap, - isSet: isSet, - isWeakSet: isWeakSet, - isFinite: isFinite, - isNaN: isNaN, - isBoolean: isBoolean, - isNull: isNull, - isUndefined: isUndefined, - has: has, - identity: identity, - constant: constant, - noop: noop, - property: property, - propertyOf: propertyOf, - matcher: matcher, - matches: matcher, - times: times, - random: random, - now: now, - escape: escape, - unescape: unescape, - result: result, - uniqueId: uniqueId, - templateSettings: templateSettings, - template: template, - chain: chain, - mixin: mixin - }); - var _$1 = mixin(allExports); - _$1._ = _$1; - - return _$1; - + mixin: mixin, + 'default': _$1 + }; + var _ = mixin(allExports); + _._ = _; + return _; }))); - - }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],"/../../jshint/src/jshint.js":[function(_dereq_,module,exports){ @@ -9324,7 +9430,7 @@ if (typeof exports === "object" && exports) { exports.JSHINT = JSHINT; } -},{"./lex.js":"/../../jshint/src/lex.js","./messages.js":"/../../jshint/src/messages.js","./options.js":"/../../jshint/src/options.js","./prod-params.js":"/../../jshint/src/prod-params.js","./reg.js":"/../../jshint/src/reg.js","./scope-manager.js":"/../../jshint/src/scope-manager.js","./state.js":"/../../jshint/src/state.js","./style.js":"/../../jshint/src/style.js","./vars.js":"/../../jshint/src/vars.js","console-browserify":"/../../jshint/node_modules/console-browserify/index.js","events":"/../node_modules/events/events.js","lodash.clone":"/../../jshint/node_modules/lodash.clone/index.js","underscore":"/../../jshint/node_modules/underscore/underscore.js"}],"/../../jshint/src/lex.js":[function(_dereq_,module,exports){ +},{"./lex.js":"/../../jshint/src/lex.js","./messages.js":"/../../jshint/src/messages.js","./options.js":"/../../jshint/src/options.js","./prod-params.js":"/../../jshint/src/prod-params.js","./reg.js":"/../../jshint/src/reg.js","./scope-manager.js":"/../../jshint/src/scope-manager.js","./state.js":"/../../jshint/src/state.js","./style.js":"/../../jshint/src/style.js","./vars.js":"/../../jshint/src/vars.js","console-browserify":"/../../jshint/node_modules/console-browserify/index.js","events":"/../node_modules/events/events.js","lodash.clone":"/../../jshint/node_modules/lodash.clone/index.js","underscore":"/../../jshint/node_modules/underscore/underscore-umd.js"}],"/../../jshint/src/lex.js":[function(_dereq_,module,exports){ "use strict"; @@ -11202,7 +11308,7 @@ Lexer.prototype = { exports.Lexer = Lexer; exports.Context = Context; -},{"../data/ascii-identifier-data.js":"/../../jshint/data/ascii-identifier-data.js","../data/es5-identifier-names.js":"/../../jshint/data/es5-identifier-names.js","../data/non-ascii-identifier-part-only.js":"/../../jshint/data/non-ascii-identifier-part-only.js","../data/non-ascii-identifier-start.js":"/../../jshint/data/non-ascii-identifier-start.js","./reg.js":"/../../jshint/src/reg.js","./state.js":"/../../jshint/src/state.js","events":"/../node_modules/events/events.js","underscore":"/../../jshint/node_modules/underscore/underscore.js"}],"/../../jshint/src/messages.js":[function(_dereq_,module,exports){ +},{"../data/ascii-identifier-data.js":"/../../jshint/data/ascii-identifier-data.js","../data/es5-identifier-names.js":"/../../jshint/data/es5-identifier-names.js","../data/non-ascii-identifier-part-only.js":"/../../jshint/data/non-ascii-identifier-part-only.js","../data/non-ascii-identifier-start.js":"/../../jshint/data/non-ascii-identifier-start.js","./reg.js":"/../../jshint/src/reg.js","./state.js":"/../../jshint/src/state.js","events":"/../node_modules/events/events.js","underscore":"/../../jshint/node_modules/underscore/underscore-umd.js"}],"/../../jshint/src/messages.js":[function(_dereq_,module,exports){ "use strict"; var _ = _dereq_("underscore"); @@ -11457,7 +11563,7 @@ _.each(info, function(desc, code) { exports.info[code] = { code: code, desc: desc }; }); -},{"underscore":"/../../jshint/node_modules/underscore/underscore.js"}],"/../../jshint/src/name-stack.js":[function(_dereq_,module,exports){ +},{"underscore":"/../../jshint/node_modules/underscore/underscore-umd.js"}],"/../../jshint/src/name-stack.js":[function(_dereq_,module,exports){ "use strict"; function NameStack() { @@ -12385,7 +12491,7 @@ var scopeManager = function(state, predefined, exported, declared) { module.exports = scopeManager; -},{"events":"/../node_modules/events/events.js","lodash.slice":"/../../jshint/node_modules/lodash.slice/index.js","underscore":"/../../jshint/node_modules/underscore/underscore.js"}],"/../../jshint/src/state.js":[function(_dereq_,module,exports){ +},{"events":"/../node_modules/events/events.js","lodash.slice":"/../../jshint/node_modules/lodash.slice/index.js","underscore":"/../../jshint/node_modules/underscore/underscore-umd.js"}],"/../../jshint/src/state.js":[function(_dereq_,module,exports){ "use strict"; var NameStack = _dereq_("./name-stack.js"); diff --git a/ui-ngx/src/app/shared/models/alarm-rule.models.ts b/ui-ngx/src/app/shared/models/alarm-rule.models.ts index 950c0f9259..e2f563c119 100644 --- a/ui-ngx/src/app/shared/models/alarm-rule.models.ts +++ b/ui-ngx/src/app/shared/models/alarm-rule.models.ts @@ -285,6 +285,23 @@ export function areFiltersAndPredicateArgumentsValid(obj: any, args: Record): boolean { + return areFiltersAndPredicateArgumentsValid(condition?.expression?.filters, args); +} + +export function isAlarmRuleConditionScheduleArgumentValid(condition: AlarmRuleCondition, + args: Record): boolean { + const arg = condition?.schedule?.dynamicValueArgument; + return !arg || Object.keys(args).includes(arg); +} + +export function areAlarmRuleArgumentsValid(alarmRule: AlarmRule, args: Record): boolean { + const condition = alarmRule?.condition; + return !condition || !args || + (areAlarmRuleConditionFilterArgumentsValid(condition, args) && isAlarmRuleConditionScheduleArgumentValid(condition, args)); +} + export function isPredicateArgumentsValid(predicates: any, args: Record): boolean { const validSet = new Set(Object.keys(args)); if (Array.isArray(predicates)) { diff --git a/ui-ngx/src/app/shared/models/audit-log.models.ts b/ui-ngx/src/app/shared/models/audit-log.models.ts index 4f7ed322ea..a006ce11e2 100644 --- a/ui-ngx/src/app/shared/models/audit-log.models.ts +++ b/ui-ngx/src/app/shared/models/audit-log.models.ts @@ -51,7 +51,10 @@ export enum ActionType { TIMESERIES_DELETED = 'TIMESERIES_DELETED', ASSIGNED_TO_EDGE = 'ASSIGNED_TO_EDGE', UNASSIGNED_FROM_EDGE = 'UNASSIGNED_FROM_EDGE', - SMS_SENT = 'SMS_SENT' + SMS_SENT = 'SMS_SENT', + COMMUNITY_GRANT_OFFLINE_CHECKER_RUN = 'COMMUNITY_GRANT_OFFLINE_CHECKER_RUN', + COMMUNITY_GRANT_REQUEST_ACCESS = 'COMMUNITY_GRANT_REQUEST_ACCESS', + COMMUNITY_GRANT_ENROLLMENT = 'COMMUNITY_GRANT_ENROLLMENT' } export enum ActionStatus { @@ -97,6 +100,9 @@ export const actionTypeTranslations = new Map( [ActionType.ASSIGNED_TO_EDGE, 'audit-log.type-assigned-to-edge'], [ActionType.UNASSIGNED_FROM_EDGE, 'audit-log.type-unassigned-from-edge'], [ActionType.SMS_SENT, 'audit-log.type-sms-sent'], + [ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, 'audit-log.type-community-grant-offline-checker-run'], + [ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, 'audit-log.type-community-grant-request-access'], + [ActionType.COMMUNITY_GRANT_ENROLLMENT, 'audit-log.type-community-grant-enrollment'], ] ); diff --git a/ui-ngx/src/app/shared/models/ce-grant/community-grant.models.ts b/ui-ngx/src/app/shared/models/ce-grant/community-grant.models.ts new file mode 100644 index 0000000000..7e04a45a87 --- /dev/null +++ b/ui-ngx/src/app/shared/models/ce-grant/community-grant.models.ts @@ -0,0 +1,479 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { HttpErrorResponse } from '@angular/common/http'; +import { TranslateService } from '@ngx-translate/core'; +import { parseHttpErrorMessage } from '@core/utils'; + +export enum CommunityGrantState { + intro = 'intro', + awaiting = 'awaiting', + verifying = 'verifying', + registered = 'registered', + review = 'review', + offline = 'offline', + verify = 'verify', + result = 'result', + /** The report was carried to the portal by hand; the outcome is read there, never reported back here. */ + handedOver = 'handedOver', + expired = 'expired', + already = 'already', + wrongInstallation = 'wrongInstallation' +} + +export type CommunityGrantMarkTone = 'brand' | 'info'; + +export type CommunityGrantRailKind = 'online' | 'offline'; + +export interface CommunityGrantStateConfig { + icon?: string; + cardIcon?: string; + tone?: CommunityGrantMarkTone; + rail?: CommunityGrantRailKind; + railStep?: number; + hero?: boolean; + live?: boolean; + spinner?: boolean; + topBanner?: string; +} + +export const communityGrantStateConfigs = + new Map([ + [CommunityGrantState.intro, {hero: true}], + [CommunityGrantState.awaiting, {icon: 'ce-grant-waiting', tone: 'brand', rail: 'online', railStep: 0, live: true}], + [CommunityGrantState.verifying, {spinner: true, tone: 'brand', rail: 'online', railStep: 1, live: true}], + [CommunityGrantState.registered, {icon: 'check', tone: 'brand'}], + [CommunityGrantState.review, {icon: 'hourglass_empty', tone: 'brand'}], + [CommunityGrantState.offline, {icon: 'computer', tone: 'brand', rail: 'offline', railStep: 0, topBanner: 'offlineBanner'}], + [CommunityGrantState.verify, {icon: 'upload_file', tone: 'brand', rail: 'offline', railStep: 1}], + [CommunityGrantState.result, {icon: 'assignment_return', tone: 'brand', rail: 'offline', railStep: 2}], + // Opens the report screen, so it shares `result`'s header. + [CommunityGrantState.handedOver, {cardIcon: 'check', icon: 'assignment_return', tone: 'brand', rail: 'offline', railStep: 2}], + [CommunityGrantState.expired, {icon: 'timer_off', tone: 'info'}], + [CommunityGrantState.already, {icon: 'how_to_reg', tone: 'info'}], + [CommunityGrantState.wrongInstallation, {icon: 'link_off', tone: 'info'}] + ]); + +export const communityGrantStateTitles = new Map([ + [CommunityGrantState.awaiting, 'ce-grant.awaiting-title'], + [CommunityGrantState.verifying, 'ce-grant.verifying-title'], + [CommunityGrantState.registered, 'ce-grant.registered-title'], + [CommunityGrantState.review, 'ce-grant.review-title'], + [CommunityGrantState.offline, 'ce-grant.offline-title'], + [CommunityGrantState.verify, 'ce-grant.verify-title'], + [CommunityGrantState.result, 'ce-grant.result-title'], + [CommunityGrantState.handedOver, 'ce-grant.result-title'], + [CommunityGrantState.expired, 'ce-grant.expired-title'], + [CommunityGrantState.already, 'ce-grant.already-title'], + [CommunityGrantState.wrongInstallation, 'ce-grant.wrong-installation-title'] +]); + +export enum CommunityGrantCardState { + progress = 'progress', + status = 'status', + offer = 'offer', + upToDate = 'upToDate', + /** A read is still out, so nothing is rendered. */ + pending = 'pending' +} + +export type CommunityGrantCardBody = CommunityGrantCardState.progress | CommunityGrantCardState.status; + +export interface CommunityGrantCardConfig { + body: CommunityGrantCardBody; + title: string; + text: string; + action?: string; + registrationLink?: string; + /** Label for a link that reopens this dialog, so it carries no external-link arrow. */ + linkAction?: string; + held?: boolean; + waiting?: boolean; + done?: boolean; +} + +/** `intro` and `expired` have no entry on purpose: the card falls through to the release offer. */ +export const communityGrantCardConfigs = new Map([ + [CommunityGrantState.awaiting, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-progress-title', + text: 'ce-grant.card-awaiting-text', + action: 'ce-grant.action-continue' + }], + [CommunityGrantState.verifying, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-progress-title', + text: 'ce-grant.card-verifying-text', + action: 'ce-grant.action-continue' + }], + [CommunityGrantState.offline, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-progress-title', + text: 'ce-grant.card-offline-text', + action: 'ce-grant.action-continue' + }], + [CommunityGrantState.verify, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-verify-title', + text: 'ce-grant.card-verify-text', + action: 'ce-grant.action-verify-deployment', + waiting: true + }], + [CommunityGrantState.result, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-result-title', + text: 'ce-grant.card-result-text', + action: 'ce-grant.action-return-report', + waiting: true + }], + [CommunityGrantState.handedOver, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-handed-over-title', + text: 'ce-grant.card-handed-over-text', + registrationLink: 'ce-grant.card-handed-over-link', + linkAction: 'ce-grant.action-open-report', + done: true + }], + [CommunityGrantState.registered, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-registered-title', + text: 'ce-grant.card-registered-text', + registrationLink: 'ce-grant.card-registered-link', + done: true + }], + [CommunityGrantState.review, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-review-title', + text: 'ce-grant.card-review-text', + done: true + }], + [CommunityGrantState.already, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-already-title', + text: 'ce-grant.card-already-text-no-mask', + action: 'ce-grant.action-see-options', + held: true + }], + // Terminal: without an entry the card would fall through to the release offer. + [CommunityGrantState.wrongInstallation, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-wrong-installation-title', + text: 'ce-grant.card-wrong-installation-text', + action: 'ce-grant.action-see-details', + held: true + }] +]); + +export const communityGrantRailLabels = new Map([ + ['online', ['ce-grant.step-account-and-terms', 'ce-grant.step-verification', 'ce-grant.step-ce-grant']], + ['offline', ['ce-grant.step-account-and-terms', 'ce-grant.step-verification', 'ce-grant.step-report-back']] +]); + +export interface CommunityGrantRegistration { + state: CommunityGrantState; + mode?: CommunityGrantBackendMode; + /** Kept because {@link mapCommunityGrantState} is many-to-one and the dialog needs the raw state. */ + backendState?: CommunityGrantBackendState; + parkReason?: CommunityGrantParkReason; + portalUrl?: string; + /** A bearer credential: it identifies this registration wherever it is opened. */ + registrationLink?: string; + report?: string; + offlineRunInProgress?: boolean; + offlineRunError?: string; +} + +/** How often the dialog re-reads this instance's `GET /state`. */ +export const communityGrantPollInterval = 3000; + +export const communityGrantStallTimeout = 30000; + +/** Used when the server supplies no portal URL or sign-up link. */ +export const communityGrantPortalUrl = 'https://license.thingsboard.io'; + +/** Mirrors the backend's `CommunityGrantState`. */ +export enum CommunityGrantBackendState { + NOT_STARTED = 'NOT_STARTED', + AWAITING_SIGNUP = 'AWAITING_SIGNUP', + COLLECTING = 'COLLECTING', + VALIDATING = 'VALIDATING', + REPORT_HANDED_OVER = 'REPORT_HANDED_OVER', + REGISTERED = 'REGISTERED', + UNDER_REVIEW = 'UNDER_REVIEW', + ALREADY_REGISTERED = 'ALREADY_REGISTERED', + WRONG_INSTALLATION = 'WRONG_INSTALLATION', + RESUME = 'RESUME' +} + +/** Mirrors the backend's `CommunityGrantMode`: the server's own reachability to the portal. */ +export enum CommunityGrantBackendMode { + ONLINE = 'ONLINE', + OFFLINE = 'OFFLINE' +} + +/** Mirrors the backend's `CommunityGrantParkReason`; set only with `RESUME`. */ +export enum CommunityGrantParkReason { + LINK_EXPIRED = 'LINK_EXPIRED', + SIGNUP_ABANDONED = 'SIGNUP_ABANDONED', + CHECK_FAILED = 'CHECK_FAILED', + PORTAL_UNREACHABLE = 'PORTAL_UNREACHABLE' +} + +/** Mirrors the backend's `CommunityGrantStateInfo`. */ +export interface CommunityGrantStateInfo { + mode: CommunityGrantBackendMode; + state: CommunityGrantBackendState; + signUpUrl?: string; + lastPolledAt?: number; + parkReason?: CommunityGrantParkReason; + portalUrl?: string; + /** Present only while the flow sits on the report step; `GET /offline/report` serves it otherwise. */ + offlineReport?: string; + offlineRunInProgress?: boolean; + offlineRunError?: string; +} + +/** Mirrors the backend's `CommunityGrantState.isPollable()`. */ +const communityGrantPollableBackendStates: readonly CommunityGrantBackendState[] = [ + CommunityGrantBackendState.AWAITING_SIGNUP, + CommunityGrantBackendState.COLLECTING, + CommunityGrantBackendState.VALIDATING, + CommunityGrantBackendState.UNDER_REVIEW, + CommunityGrantBackendState.REPORT_HANDED_OVER +]; + +/** + * `VALIDATING` + `ONLINE` maps to `verifying` even when a by-hand report exists; the dialog tells the two + * apart by the report. Throws on a value this build does not know. + */ +export function mapCommunityGrantState(state: CommunityGrantBackendState, + mode: CommunityGrantBackendMode): CommunityGrantState { + switch (state) { + case CommunityGrantBackendState.NOT_STARTED: + return CommunityGrantState.intro; + case CommunityGrantBackendState.AWAITING_SIGNUP: + return mapByMode(mode, CommunityGrantState.awaiting, CommunityGrantState.offline); + case CommunityGrantBackendState.COLLECTING: + return mapByMode(mode, CommunityGrantState.verifying, CommunityGrantState.verify); + case CommunityGrantBackendState.VALIDATING: + return mapByMode(mode, CommunityGrantState.verifying, CommunityGrantState.result); + case CommunityGrantBackendState.REPORT_HANDED_OVER: + return CommunityGrantState.handedOver; + case CommunityGrantBackendState.REGISTERED: + return CommunityGrantState.registered; + case CommunityGrantBackendState.UNDER_REVIEW: + return CommunityGrantState.review; + case CommunityGrantBackendState.ALREADY_REGISTERED: + return CommunityGrantState.already; + case CommunityGrantBackendState.WRONG_INSTALLATION: + return CommunityGrantState.wrongInstallation; + case CommunityGrantBackendState.RESUME: + return CommunityGrantState.expired; + default: + return assertNeverCommunityGrantValue('backend Community Grant state', state); + } +} + +function mapByMode(mode: CommunityGrantBackendMode, + online: CommunityGrantState, + offline: CommunityGrantState): CommunityGrantState { + switch (mode) { + case CommunityGrantBackendMode.ONLINE: + return online; + case CommunityGrantBackendMode.OFFLINE: + return offline; + default: + return assertNeverCommunityGrantValue('backend Community Grant mode', mode); + } +} + +function assertNeverCommunityGrantValue(what: string, value: never): never { + throw new Error(`Unhandled ${what}: ${JSON.stringify(value)}`); +} + +/** Checked in either mode: offline, `handedOver` re-reads `/state` to no effect. */ +export const communityGrantOnlinePollableStates: ReadonlySet = new Set( + communityGrantPollableBackendStates.map(state => mapCommunityGrantState(state, CommunityGrantBackendMode.ONLINE)) +); + +export function communityGrantRegistrationFrom(info: CommunityGrantStateInfo): CommunityGrantRegistration { + return { + state: mapCommunityGrantState(info.state, info.mode), + mode: info.mode, + backendState: info.state, + parkReason: info.parkReason, + portalUrl: info.portalUrl, + registrationLink: info.signUpUrl, + report: info.offlineReport, + offlineRunInProgress: info.offlineRunInProgress, + offlineRunError: info.offlineRunError + }; +} + +/** + * The `TBICBDL1` enrollment bundle the License Portal writes for one installation: + * + * ``` + * offset width field value / constraint + * 0 8 MAGIC "TBICBDL1" + * 8 1 VERSION 0x01 + * 9 4 MANIFEST_LEN uint32 big-endian, 1..8192 + * 13 4 CHECKER_LEN uint32 big-endian, >= 1 + * 17 74 RELSIG a complete TBICSIG1 file, verbatim + * 91 M MANIFEST UTF-8 JSON + * 91+M C CHECKER the executable image + * ``` + */ +const COMMUNITY_GRANT_BUNDLE_MAGIC = 'TBICBDL1'; +const COMMUNITY_GRANT_BUNDLE_VERSION = 1; +const COMMUNITY_GRANT_BUNDLE_HEADER_LEN = 91; +const COMMUNITY_GRANT_BUNDLE_MIN_MANIFEST_LEN = 1; +const COMMUNITY_GRANT_BUNDLE_MAX_MANIFEST_LEN = 8192; + +export interface CommunityGrantBundleManifest { + bundleVersion: number; + os: string; + arch: string; + clusterId: string; + checkerInput: Record; + challengeExpiresAt: number; + issuedAt: number; + checkerFileName: string; +} + +export enum CommunityGrantBundleErrorCode { + /** Too short, wrong magic, or an unsupported version. */ + NOT_A_BUNDLE = 'NOT_A_BUNDLE', + MALFORMED = 'MALFORMED' +} + +export class CommunityGrantBundleParseError extends Error { + constructor(public readonly code: CommunityGrantBundleErrorCode, message: string) { + super(message); + this.name = 'CommunityGrantBundleParseError'; + } +} + +export interface CommunityGrantBundlePreflight { + manifest: CommunityGrantBundleManifest; + /** By this browser's clock. A warning only: the portal's clock decides expiry. */ + challengeExpired: boolean; +} + +/** + * Pre-flight before uploading: reads only the header and manifest, and checks structure alone. The + * installation, platform and release signature are checked by the server. + */ +export async function peekCommunityGrantBundle(file: File): Promise { + if (!file || file.size < COMMUNITY_GRANT_BUNDLE_HEADER_LEN) { + throw notABundle(`The file is ${file ? file.size : 0} bytes, shorter than a bundle's ` + + `${COMMUNITY_GRANT_BUNDLE_HEADER_LEN}-byte header.`); + } + const header = new DataView(await file.slice(0, COMMUNITY_GRANT_BUNDLE_HEADER_LEN).arrayBuffer()); + for (let i = 0; i < COMMUNITY_GRANT_BUNDLE_MAGIC.length; i++) { + if (header.getUint8(i) !== COMMUNITY_GRANT_BUNDLE_MAGIC.charCodeAt(i)) { + throw notABundle('The file does not carry the marker every enrollment bundle begins with.'); + } + } + const version = header.getUint8(COMMUNITY_GRANT_BUNDLE_MAGIC.length); + if (version !== COMMUNITY_GRANT_BUNDLE_VERSION) { + throw notABundle(`The bundle declares format version ${version}, and this server supports version ` + + `${COMMUNITY_GRANT_BUNDLE_VERSION} only.`); + } + const manifestLength = header.getUint32(9); + const checkerLength = header.getUint32(13); + if (manifestLength < COMMUNITY_GRANT_BUNDLE_MIN_MANIFEST_LEN + || manifestLength > COMMUNITY_GRANT_BUNDLE_MAX_MANIFEST_LEN) { + throw malformedBundle(`The bundle declares a manifest of ${manifestLength} bytes, outside the permitted ` + + `range of ${COMMUNITY_GRANT_BUNDLE_MIN_MANIFEST_LEN} to ${COMMUNITY_GRANT_BUNDLE_MAX_MANIFEST_LEN}.`); + } + if (checkerLength < 1) { + throw malformedBundle(`The bundle declares a checker of ${checkerLength} bytes.`); + } + const expectedSize = COMMUNITY_GRANT_BUNDLE_HEADER_LEN + manifestLength + checkerLength; + if (file.size !== expectedSize) { + throw malformedBundle(`The bundle's declared lengths need a file of ${expectedSize} bytes, but this one ` + + `is ${file.size} bytes.`); + } + const manifestBytes = await file + .slice(COMMUNITY_GRANT_BUNDLE_HEADER_LEN, COMMUNITY_GRANT_BUNDLE_HEADER_LEN + manifestLength) + .arrayBuffer(); + const manifest = parseCommunityGrantBundleManifest(manifestBytes); + // Strictly later, as the portal compares: the challenge is still live at the deadline instant. + return {manifest, challengeExpired: Date.now() > manifest.challengeExpiresAt}; +} + +function parseCommunityGrantBundleManifest(bytes: ArrayBuffer): CommunityGrantBundleManifest { + let text: string; + try { + // `fatal`, so binary fails here as unreadable text rather than later as bad JSON. + text = new TextDecoder('utf-8', {fatal: true}).decode(bytes); + } catch { + throw malformedBundle('The bundle\'s manifest is not readable text.'); + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + throw malformedBundle('The bundle\'s manifest is not valid JSON.'); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw malformedBundle('The bundle\'s manifest is not a JSON object.'); + } + const candidate = parsed as Record; + // Presence and type only; the server judges the values. + for (const key of ['os', 'arch', 'clusterId', 'checkerFileName']) { + if (typeof candidate[key] !== 'string' || !(candidate[key] as string).length) { + throw malformedBundle(`The bundle's manifest is missing "${key}".`); + } + } + const checkerInput = candidate.checkerInput; + if (!checkerInput || typeof checkerInput !== 'object' || Array.isArray(checkerInput) + || !Object.keys(checkerInput).length) { + throw malformedBundle('The bundle\'s manifest is missing "checkerInput".'); + } + for (const key of ['bundleVersion', 'challengeExpiresAt', 'issuedAt']) { + if (typeof candidate[key] !== 'number' || !Number.isFinite(candidate[key] as number)) { + throw malformedBundle(`The bundle's manifest is missing "${key}".`); + } + } + if (candidate.bundleVersion !== COMMUNITY_GRANT_BUNDLE_VERSION) { + throw notABundle(`The bundle's manifest declares version ${candidate.bundleVersion}.`); + } + return candidate as unknown as CommunityGrantBundleManifest; +} + +function notABundle(message: string): CommunityGrantBundleParseError { + return new CommunityGrantBundleParseError(CommunityGrantBundleErrorCode.NOT_A_BUNDLE, message); +} + +function malformedBundle(message: string): CommunityGrantBundleParseError { + return new CommunityGrantBundleParseError(CommunityGrantBundleErrorCode.MALFORMED, message); +} + +/** A `text` request's error body arrives as an unparsed JSON string, so it is parsed first. */ +function communityGrantErrorHasServerMessage(error: HttpErrorResponse, responseType?: string): boolean { + let body: unknown = null; + if (responseType === 'text') { + try { + body = error.error ? JSON.parse(error.error) : null; + } catch { + body = null; + } + } else { + body = error.error; + } + return !!(body && typeof body === 'object' && (body as { message?: unknown }).message); +} + +/** + * The server's own message, or the generic one when it sent none — never `HttpErrorResponse.message`, which + * names the request path. Pass the request's `responseType`. + */ +export function resolveCommunityGrantErrorMessage(error: HttpErrorResponse, + translate: TranslateService, + responseType?: string): string { + if (!communityGrantErrorHasServerMessage(error, responseType)) { + return translate.instant('ce-grant.register-error-generic'); + } + return parseHttpErrorMessage(error, translate, responseType).message; +} diff --git a/ui-ngx/src/app/shared/models/icon.models.ts b/ui-ngx/src/app/shared/models/icon.models.ts index 7e76bf2c2d..0d2bed0621 100644 --- a/ui-ngx/src/app/shared/models/icon.models.ts +++ b/ui-ngx/src/app/shared/models/icon.models.ts @@ -60,7 +60,10 @@ export const svgIcons: {[key: string]: string} = { '14.7267L9.61134 13.5985L8.48664 14.7213L7.64059 13.8767L8.76673 12.7525L7.64928 11.6331L8.77533 10.5051L7.64059 9.37227L8.48664 ' + '8.52767L9.61993 9.65905L10.7461 8.53103L9.61465 7.40158L10.4607 6.55697L11.5907 7.68499L12.7169 6.55688L13.843 7.68494L14.9729 ' + '6.55688ZM12.7169 8.24609L13.5629 9.0907L10.1787 12.4691L9.33268 11.6245L12.7169 8.24609ZM13.4262 10.0805L14.2723 10.9251L11.4521 ' + - '13.7404L10.6061 12.8958L13.4262 10.0805ZM14.6909 13.0321L13.8449 12.1875L11.8708 14.1583L12.7168 15.0029L14.6909 13.0321Z"/>' + '13.7404L10.6061 12.8958L13.4262 10.0805ZM14.6909 13.0321L13.8449 12.1875L11.8708 14.1583L12.7168 15.0029L14.6909 13.0321Z"/>', + 'ce-grant-waiting': '' }; export const svgIconsUrl: { [key: string]: string } = { diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index 387f3ad243..c836687a45 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -9,11 +9,6 @@ export interface WidgetInstalledItemDescriptor { widgetTypeId: { id: string }; } -export interface DashboardInstalledItemDescriptor { - type: 'DASHBOARD'; - dashboardId: { id: string }; -} - export interface CalculatedFieldInstalledItemDescriptor { type: 'CALCULATED_FIELD'; calculatedFieldId: { id: string }; @@ -50,7 +45,6 @@ export interface SolutionTemplateInstalledItemDescriptor { export type IotHubInstalledItemDescriptor = | WidgetInstalledItemDescriptor - | DashboardInstalledItemDescriptor | CalculatedFieldInstalledItemDescriptor | AlarmRuleInstalledItemDescriptor | RuleChainInstalledItemDescriptor @@ -140,10 +134,6 @@ export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor): entityId = descriptor.widgetTypeId?.id; entityType = EntityType.WIDGET_TYPE; break; - case 'DASHBOARD': - entityId = descriptor.dashboardId?.id; - entityType = EntityType.DASHBOARD; - break; case 'CALCULATED_FIELD': case 'ALARM_RULE': entityId = descriptor.calculatedFieldId?.id; diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index abdddc1734..23c5738f1f 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -1,8 +1,9 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 +import { Direction } from '@shared/models/page/sort-order'; + export enum ItemType { WIDGET = 'WIDGET', - DASHBOARD = 'DASHBOARD', SOLUTION_TEMPLATE = 'SOLUTION_TEMPLATE', CALCULATED_FIELD = 'CALCULATED_FIELD', ALARM_RULE = 'ALARM_RULE', @@ -13,7 +14,6 @@ export enum ItemType { export const itemTypeTranslations = new Map( [ [ItemType.WIDGET, 'item.type-widget'], - [ItemType.DASHBOARD, 'item.type-dashboard'], [ItemType.SOLUTION_TEMPLATE, 'item.type-solution-template'], [ItemType.CALCULATED_FIELD, 'item.type-calculated-field'], [ItemType.ALARM_RULE, 'item.type-alarm-rule'], @@ -28,7 +28,6 @@ export const itemTypeTranslations = new Map( // mapping stays consistent across the app. export const itemTypeIcons: Record = { [ItemType.WIDGET]: 'widgets', - [ItemType.DASHBOARD]: 'dashboard', [ItemType.SOLUTION_TEMPLATE]: 'apps', [ItemType.CALCULATED_FIELD]: 'mdi:function-variant', [ItemType.RULE_CHAIN]: 'settings_ethernet', @@ -39,11 +38,24 @@ export const itemTypeIcons: Record = { export const getItemTypeIcon = (type?: string | null): string => type && itemTypeIcons[type] ? itemTypeIcons[type] : 'category'; +/** Colour for a type with no colour of its own. */ +export const DEFAULT_ITEM_TYPE_COLOR = '#5f6368'; + +/** Colour per item type, wherever an item's type is marked with one. */ +export const itemTypeColors: Record = { + [ItemType.WIDGET]: '#2c9755', + [ItemType.SOLUTION_TEMPLATE]: '#2b6bb4', + [ItemType.CALCULATED_FIELD]: '#3cb4e0', + [ItemType.RULE_CHAIN]: '#a95ae2', + [ItemType.ALARM_RULE]: '#d66f2e', + [ItemType.DEVICE]: '#4b63cc' +}; + +export const getItemTypeColor = (type?: string | null): string => + type && itemTypeColors[type] ? itemTypeColors[type] : DEFAULT_ITEM_TYPE_COLOR; + /** * Item types discoverable to creators in the marketplace UI. - * DASHBOARD is intentionally absent (IoT Hub no longer accepts Dashboard contributions). - * Defensive code paths (item card, detail dialog descriptor switch, installed-items table, - * install handler, /iot-hub/dashboards route) remain functional for already-installed items. */ export const CREATOR_VISIBLE_ITEM_TYPES: ItemType[] = [ ItemType.WIDGET, @@ -54,6 +66,40 @@ export const CREATOR_VISIBLE_ITEM_TYPES: ItemType[] = [ ItemType.RULE_CHAIN, ]; +/** Item types a cross-type surface (search page, popup) shows, in display order. */ +export const CROSS_TYPE_ITEM_TYPES: ItemType[] = [ + ItemType.DEVICE, + ItemType.SOLUTION_TEMPLATE, + ItemType.WIDGET, + ItemType.CALCULATED_FIELD, + ItemType.ALARM_RULE, + ItemType.RULE_CHAIN, +]; + +/** Types drawn as a coloured icon tile rather than a screenshot. */ +export const isCompactItemType = (type?: string | null): boolean => + type === ItemType.CALCULATED_FIELD || type === ItemType.ALARM_RULE || type === ItemType.RULE_CHAIN; + +/** Sort property served by relevance ranking. */ +export const RELEVANCE_SORT_PROPERTY = 'relevance'; + +export interface SortOption { + value: string; + label: string; + direction: Direction; +} + +/** + * The sort menu of every IoT Hub surface with a search field; the first entry is the default. + * Relevance stays the default with an empty field, where it orders by install count. + */ +export const IOT_HUB_SORT_OPTIONS: SortOption[] = [ + { value: RELEVANCE_SORT_PROPERTY, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, + { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, + { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, + { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } +]; + export interface FilterParamInfo { key: string; totalItems: number; diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 349a4f62e8..a1f5b3077c 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -118,7 +118,10 @@ export interface ListingItemVersionNotFound { } export interface MpItemVersionQueryOptions { + /** Single item type, for a surface pinned to one (the type pages, the add-item dialog). */ type?: string; + /** Several item types at once, sent as a repeated `type` parameter. */ + types?: string[]; peOnly?: boolean; creatorId?: string; categories?: string[]; @@ -131,53 +134,66 @@ export interface MpItemVersionQueryOptions { connectivity?: string[]; vendors?: string[]; scadaFirst?: boolean; + // Serialized only when true: the API matches the value, so `false` would mean "unverified only" + creatorVerified?: boolean; } +/** Every filter, as `&name=value` pairs. */ +function filtersToQuery(o: MpItemVersionQueryOptions): string { + let query = ''; + if (o.type) { + query += `&type=${encodeURIComponent(o.type)}`; + } + if (o.types?.length) { + query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); + } + if (o.peOnly != null) { + query += `&peOnly=${o.peOnly}`; + } + if (o.creatorId) { + query += `&creatorId=${encodeURIComponent(o.creatorId)}`; + } + if (o.categories?.length) { + query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join(''); + } + if (o.useCases?.length) { + query += o.useCases.map(u => `&useCases=${encodeURIComponent(u)}`).join(''); + } + if (o.cfTypes?.length) { + query += o.cfTypes.map(t => `&cfTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.widgetTypes?.length) { + query += o.widgetTypes.map(t => `&widgetTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.ruleChainTypes?.length) { + query += o.ruleChainTypes.map(t => `&ruleChainTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.tbVersion != null) { + query += `&tbVersion=${o.tbVersion}`; + } + if (o.hardwareTypes?.length) { + query += o.hardwareTypes.map(ht => `&hardwareTypes=${encodeURIComponent(ht)}`).join(''); + } + if (o.connectivity?.length) { + query += o.connectivity.map(c => `&connectivity=${encodeURIComponent(c)}`).join(''); + } + if (o.vendors?.length) { + query += o.vendors.map(v => `&vendors=${encodeURIComponent(v)}`).join(''); + } + if (o.scadaFirst != null) { + query += `&scadaFirst=${o.scadaFirst}`; + } + if (o.creatorVerified) { + query += `&creatorVerified=true`; + } + return query; +} + +/** A paged read: the filters, and the page to cut out of them. */ export class MpItemVersionQuery { constructor(public pageLink: PageLink, public options: MpItemVersionQueryOptions = {}) {} public toQuery(): string { - let query = this.pageLink.toQuery(); - const o = this.options; - if (o.type) { - query += `&type=${o.type}`; - } - if (o.peOnly != null) { - query += `&peOnly=${o.peOnly}`; - } - if (o.creatorId) { - query += `&creatorId=${o.creatorId}`; - } - if (o.categories?.length) { - query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join(''); - } - if (o.useCases?.length) { - query += o.useCases.map(u => `&useCases=${encodeURIComponent(u)}`).join(''); - } - if (o.cfTypes?.length) { - query += o.cfTypes.map(t => `&cfTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.widgetTypes?.length) { - query += o.widgetTypes.map(t => `&widgetTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.ruleChainTypes?.length) { - query += o.ruleChainTypes.map(t => `&ruleChainTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.tbVersion != null) { - query += `&tbVersion=${o.tbVersion}`; - } - if (o.hardwareTypes?.length) { - query += o.hardwareTypes.map(ht => `&hardwareTypes=${encodeURIComponent(ht)}`).join(''); - } - if (o.connectivity?.length) { - query += o.connectivity.map(c => `&connectivity=${encodeURIComponent(c)}`).join(''); - } - if (o.vendors?.length) { - query += o.vendors.map(v => `&vendors=${encodeURIComponent(v)}`).join(''); - } - if (o.scadaFirst != null) { - query += `&scadaFirst=${o.scadaFirst}`; - } - return query; + return this.pageLink.toQuery() + filtersToQuery(this.options); } } diff --git a/ui-ngx/src/app/shared/models/widget-settings.models.ts b/ui-ngx/src/app/shared/models/widget-settings.models.ts index 36fbef9c90..455a09cc02 100644 --- a/ui-ngx/src/app/shared/models/widget-settings.models.ts +++ b/ui-ngx/src/app/shared/models/widget-settings.models.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 import { + deepClone, isDefinedAndNotNull, isNotEmptyStr, isNumber, @@ -147,6 +148,28 @@ export interface ColorRangeSettings extends AdvancedColorMode { rangeAdvanced?: AdvancedColorRange[]; } +/** + * Converts any stored rangeList shape to ColorRangeSettings. Always returns a new deep copy (null/undefined pass through), + * so callers may mutate the result freely. + */ +export const normalizeColorRangeSettings = (rangeList: ColorRangeSettings | ColorRange[]): ColorRangeSettings => { + if (!isDefinedAndNotNull(rangeList)) { + return rangeList as ColorRangeSettings; + } + if (Array.isArray(rangeList)) { + return {advancedMode: false, range: deepClone(rangeList)}; + } + const result: ColorRangeSettings = deepClone(rangeList); + result.advancedMode = result.advancedMode ?? false; + // Unwraps the legacy corrupted shape {range: {advancedMode, range: [...]}} (possibly nested several levels deep) + let range: any = result.range; + while (isDefinedAndNotNull(range) && !Array.isArray(range)) { + range = range.range; + } + result.range = range; + return result; +}; + export interface ColorGradientSettings extends AdvancedColorMode { gradient?: string[]; gradientAdvanced?: AdvancedGradient[]; @@ -473,9 +496,9 @@ export abstract class AdvancedModeColorProcessor extends ColorProcessor { class RangeColorProcessor extends AdvancedModeColorProcessor { - constructor(protected settings: ColorSettings, - protected ctx: WidgetContext) { - super(settings, ctx); + constructor(settings: ColorSettings, + ctx: WidgetContext) { + super({...settings, rangeList: normalizeColorRangeSettings(settings.rangeList)}, ctx); } update(value: any): void { @@ -519,15 +542,8 @@ class RangeColorProcessor extends AdvancedModeColorProcessor { } private computeFromRange(value: any): string { - let rangeList: any = this.settings.rangeList as Array; - let advancedMode = false; - - if (isDefinedAndNotNull(this.settings.rangeList?.advancedMode)) { - advancedMode = this.settings.rangeList.advancedMode; - rangeList = advancedMode ? - this.settings.rangeList.rangeAdvanced as Array : - this.settings.rangeList.range as Array; - } + const advancedMode = this.settings.rangeList?.advancedMode ?? false; + const rangeList: any = advancedMode ? this.settings.rangeList?.rangeAdvanced : this.settings.rangeList?.range; if (rangeList?.length && isDefinedAndNotNull(value) && isNumeric(value)) { const num = Number(value); diff --git a/ui-ngx/src/app/shared/models/widget/maps/map.models.ts b/ui-ngx/src/app/shared/models/widget/maps/map.models.ts index ba2e27f52c..68218c30c0 100644 --- a/ui-ngx/src/app/shared/models/widget/maps/map.models.ts +++ b/ui-ngx/src/app/shared/models/widget/maps/map.models.ts @@ -918,6 +918,7 @@ export const defaultMapActionButtonSettings: MapActionButtonSettings = { export enum MapProvider { openstreet = 'openstreet', + carto = 'carto', google = 'google', here = 'here', tencent = 'tencent', @@ -929,6 +930,7 @@ export const mapProviders = Object.keys(MapProvider) as MapProvider[]; export const mapProviderTranslationMap = new Map( [ [MapProvider.openstreet, 'widgets.maps.layer.provider.openstreet.title'], + [MapProvider.carto, 'widgets.maps.layer.provider.carto.title'], [MapProvider.google, 'widgets.maps.layer.provider.google.title'], [MapProvider.here, 'widgets.maps.layer.provider.here.title'], [MapProvider.tencent, 'widgets.maps.layer.provider.tencent.title'], @@ -966,6 +968,9 @@ export const mapLayerValid = (layer: MapLayerSettings): boolean => { case MapProvider.openstreet: const openStreetLayer = layer as OpenStreetMapLayerSettings; return !!openStreetLayer.layerType; + case MapProvider.carto: + const cartoLayer = layer as CartoMapLayerSettings; + return !!cartoLayer.layerType; case MapProvider.google: const googleLayer = layer as GoogleMapLayerSettings; return !!googleLayer.layerType; @@ -999,6 +1004,9 @@ export const defaultLayerTitle = (layer: MapLayerSettings): string => { case MapProvider.openstreet: const openStreetLayer = layer as OpenStreetMapLayerSettings; return openStreetMapLayerTranslationMap.get(openStreetLayer.layerType); + case MapProvider.carto: + const cartoLayer = layer as CartoMapLayerSettings; + return cartoLayerTranslationMap.get(cartoLayer.layerType); case MapProvider.google: const googleLayer = layer as GoogleMapLayerSettings; return googleMapLayerTranslationMap.get(googleLayer.layerType); @@ -1018,9 +1026,7 @@ export enum OpenStreetLayerType { openStreetHot = 'OpenStreetMap.HOT', esriWorldStreetMap = 'Esri.WorldStreetMap', esriWorldTopoMap = 'Esri.WorldTopoMap', - esriWorldImagery = 'Esri.WorldImagery', - cartoDbPositron = 'CartoDB.Positron', - cartoDbDarkMatter = 'CartoDB.DarkMatter' + esriWorldImagery = 'Esri.WorldImagery' } export const openStreetLayerTypes = Object.values(OpenStreetLayerType) as OpenStreetLayerType[]; @@ -1031,9 +1037,7 @@ export const openStreetMapLayerTranslationMap = new Map( + [ + [CartoLayerType.cartoPositron, 'widgets.maps.layer.provider.carto.positron'], + [CartoLayerType.cartoDarkMatter, 'widgets.maps.layer.provider.carto.dark-matter'] + ] +); + +export interface CartoMapLayerSettings extends MapLayerSettings { + provider: MapProvider.carto; + layerType: CartoLayerType; + apiKey?: string; +} + +export const defaultCartoMapLayerSettings: CartoMapLayerSettings = { + provider: MapProvider.carto, + layerType: CartoLayerType.cartoPositron, + apiKey: null +} + export enum GoogleLayerType { roadmap = 'roadmap', satellite = 'satellite', @@ -1107,6 +1137,16 @@ export const defaultHereMapLayerSettings: HereMapLayerSettings = { apiKey: 'kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE' } +const hereV3Variants: {[v2Variant: string]: string} = { + normalDay: 'exploreDay', + normalNight: 'exploreNight', + hybridDay: 'exploreSatelliteDay', + terrainDay: 'topoDay' +}; + +export const hereV3Provider = (layerType: string): string => + `HERE.${hereV3Variants[layerType?.split('.')[1]] || hereV3Variants.normalDay}`; + export enum TencentLayerType { tencentNormal = 'Tencent.Normal', tencentSatellite = 'Tencent.Satellite', @@ -1136,6 +1176,7 @@ export const defaultTencentMapLayerSettings: TencentMapLayerSettings = { export interface CustomMapLayerSettings extends MapLayerSettings { provider: MapProvider.custom; tileUrl: string; + customAttribution?: string; } export const defaultCustomMapLayerSettings: CustomMapLayerSettings = { @@ -1143,10 +1184,29 @@ export const defaultCustomMapLayerSettings: CustomMapLayerSettings = { tileUrl: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' } +export const mapProviderHasApiKey = (provider: MapProvider): boolean => + [MapProvider.carto, MapProvider.google, MapProvider.here].includes(provider); + +export const mapProviderRequiresApiKey = (provider: MapProvider): boolean => + [MapProvider.google, MapProvider.here].includes(provider); + +const legacyOpenStreetCartoLayerTypes = new Set(cartoLayerTypes); + +// CARTO layers used to be stored under the OpenStreetMap provider, keep reading them as CARTO layers +export const normalizeMapLayerSettings = (layer: MapLayerSettings): MapLayerSettings => { + if (layer?.provider === MapProvider.openstreet && + legacyOpenStreetCartoLayerTypes.has((layer as OpenStreetMapLayerSettings).layerType)) { + return {...layer, provider: MapProvider.carto}; + } + return layer; +}; + export const defaultMapLayerSettings = (provider: MapProvider): MapLayerSettings => { switch (provider) { case MapProvider.openstreet: return defaultOpenStreetMapLayerSettings; + case MapProvider.carto: + return defaultCartoMapLayerSettings; case MapProvider.google: return defaultGoogleMapLayerSettings; case MapProvider.here: diff --git a/ui-ngx/src/assets/ce-grant/key-visual-apps.svg b/ui-ngx/src/assets/ce-grant/key-visual-apps.svg new file mode 100644 index 0000000000..ee92510d69 --- /dev/null +++ b/ui-ngx/src/assets/ce-grant/key-visual-apps.svg @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui-ngx/src/assets/iot-hub/items-page-dashboards-hero.svg b/ui-ngx/src/assets/iot-hub/items-page-dashboards-hero.svg deleted file mode 100644 index c699714457..0000000000 --- a/ui-ngx/src/assets/iot-hub/items-page-dashboards-hero.svg +++ /dev/null @@ -1,102 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 052d7ca046..cb00b81daf 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -1082,6 +1082,9 @@ "type-timeseries-updated": "Telemetry updated", "type-timeseries-deleted": "Telemetry deleted", "type-sms-sent": "SMS sent", + "type-community-grant-offline-checker-run": "Community Grant offline check run", + "type-community-grant-request-access": "Community Grant access requested", + "type-community-grant-enrollment": "Community Grant enrollment", "any-type":"Any type", "audit-log-filter-title": "Audit log filter", "filter-title": "Filter", @@ -1660,6 +1663,125 @@ "token": "Token", "token-required": "Token is required." }, + "ce-grant": { + "ce-grant": "Community Grant", + "ce-grant-note": "Free, and it doesn’t expire.", + "title": "Community Grant registration", + "load-error-lede": "Couldn’t check this deployment’s registration status.", + "step-account-and-terms": "Account and terms", + "step-verification": "Verification", + "step-ce-grant": "Community Grant", + "step-report-back": "Report back", + "intro-heading": "Your Community Grant makes the upgrade to 4.4 free", + "intro-lede": "From 4.4, Community and Professional become one source-available platform, and running it takes a license key. What you run today is untouched: 4.3 stays Apache 2.0 permanently.", + "intro-read-announcement": "Read the announcement", + "intro-included-title": "What’s included", + "intro-included-devices-and-servers-lead": "The devices and servers you were running when 4.4 was announced, plus 10% headroom on devices.", + "intro-included-devices-and-servers-text": "Never a grant below 100 devices, with headroom up to 1,000, so normal growth stays free.", + "intro-included-permanent-lead": "Permanent.", + "intro-included-permanent-text": "The grant does not expire, any white-labeling you already run stays, and past use is never charged for.", + "intro-included-security-lead": "SSO, RBAC and Secrets.", + "intro-included-security-text": "The advanced security features that were Professional-only, at no extra cost.", + "intro-included-register-lead": "Register any time until July 20, 2027.", + "intro-included-register-text": "That is the day registration closes and support for 4.3 ends.", + "intro-assurance": "Nothing on this deployment changes today. Registering opens the License Portal in a new tab: create your account there, and this dialog updates on its own.", + "register-error-generic": "Something went wrong starting your registration. Try again, or contact support if this continues.", + "awaiting-title": "Finish in the License Portal", + "awaiting-lede": "Create your account there and accept the grant terms.", + "need-link": "Need the link?", + "link-use-note": "Use it on any machine, or send it to whoever handles licensing.", + "link-share-caution": "Registers this deployment to whoever opens it — share with care.", + "stall-note": "No response from the portal yet. If this deployment’s connection is restricted, finish from any machine using the link above — it’s tied to this deployment wherever it’s opened.", + "verifying-title": "Verifying your deployment", + "verifying-lede": "It runs read-only on this server, and can take a few minutes on a large database.", + "no-report-yet": "No report yet?", + "verifying-stall-note": "If this deployment’s connection is restricted, the check can run here by hand instead — you carry the report to the portal yourself.", + "privacy-online": "It reads entity counts, creation timestamps and table sizes — never telemetry values, device names or personal data — and sends one encrypted report to the portal.", + "privacy-offline": "It reads entity counts, creation timestamps and table sizes — never telemetry values, device names or personal data. Nothing leaves this server; you carry the encrypted report back yourself.", + "registered-title": "This deployment is registered", + "registered-lede": "We’ve emailed you a copy of what was granted. The license key is in your License Portal account — apply it during the upgrade to 4.4, and nothing on this deployment changes before then.", + "review-title": "We’re reviewing your registration", + "review-lede": "You’ll hear from us at the address on your portal account as soon as it’s done. This deployment keeps running as it is until then.", + "offline-title": "Register on a connected machine", + "offline-lede": "Open this link there and create your account. The portal sends you back here once, with a tool to run on this server — and you carry its report back.", + "offline-caution": "This deployment can’t reach the License Portal.", + "verify-title": "Verify this deployment", + "verify-lede": "It runs read-only, and can take a few minutes on a large database.", + "verify-upload-tool": "Upload the deployment verification tool", + "verify-choose-bundle-file": "Choose the bundle file", + "verify-upload-hint": "Upload it as you downloaded it — your deployment opens the file itself, and checks the tool’s signature before running anything.", + "verify-error-no-file": "Choose the bundle file — the one you downloaded from the portal for this server’s platform.", + "verify-error-not-a-bundle": "Invalid enrollment bundle file. Choose the bundle file — the one you downloaded from the portal for this server’s platform.", + "verify-error-malformed": "Malformed enrollment bundle file. Choose the bundle file — the one you downloaded from the portal for this server’s platform.", + "bundle-expired-warning": "This bundle expired on {{ date }}. You can still run the check — if the report is refused, download a fresh bundle.", + "verify-error-failed": "The check couldn’t read this deployment’s database. Try again — if it keeps failing, our team can finish this by hand: contact support.", + "result-title": "Return this report to the portal", + "result-lede": "Paste it into the portal page you started from.", + "result-error-empty": "No report content came back. Try again.", + "result-safe-to-close": "Not pasted yet? This stays here.", + "expired-title": "This registration link has expired", + "expired-lede": "The link timed out or was replaced by a newer one.", + "expired-text": "Start again issues a fresh link for this deployment — nothing else is affected.", + "portal-unreachable-title": "Couldn’t reach the License Portal", + "portal-unreachable-lede": "This deployment stopped getting answers from the portal, so the registration didn’t finish.", + "portal-unreachable-text": "Nothing was registered and nothing here has changed. Trying again checks the connection afresh — and if the portal still can’t be reached, it will offer to register from another machine instead.", + "check-failed-title": "The deployment verification couldn’t finish", + "check-failed-lede": "After several attempts the verification tool didn’t complete on this server.", + "check-failed-text": "Try again — if it keeps failing, our team can finish this by hand: contact support.", + "already-title": "This deployment is already registered", + "already-lede-no-mask": "A deployment can hold only one Community Grant.", + "already-same-organization": "The license key is in the account that registered it. If that’s yours — a restored backup registers under the same identity — sign in to the License Portal and copy it from there.", + "already-someone-else-registered": "If someone else in your organization registered it, ask them for the key — or request access, and we’ll email the registered contact.", + "already-request-sent": "Requested — the registered contact decides what happens next. If you know who they are, asking directly is faster.", + "wrong-installation-title": "This deployment can’t be registered", + "wrong-installation-lede": "This deployment’s installation records don’t match what the License Portal has on file, so a Community Grant can’t be registered from here.", + "wrong-installation-text": "Nothing on this deployment has changed, and no grant was registered. This is rare, and usually follows a database restore or migration — contact support and our team can sort it out.", + "safe-to-close": "Safe to close.", + "card-expired-note": "Your earlier registration link expired — starting again takes a few seconds.", + "card-check-failed-note": "The scale check didn’t finish — trying again takes a few seconds.", + "card-portal-unreachable-note": "The License Portal didn’t answer — trying again re-checks the connection.", + "card-progress-title": "Registering this deployment", + "card-awaiting-text": "Registration continues in the License Portal — this updates on its own once you’ve finished there.", + "card-verifying-text": "Verifying this deployment — a few minutes, all on this server.", + "card-offline-text": "Registration continues in the License Portal on another machine — continue here when a step needs this server.", + "card-verify-title": "Verification waiting here", + "card-verify-text": "Upload the enrollment bundle from the portal, then run verification here.", + "card-result-title": "Report ready to return", + "card-result-text": "Copy it into the License Portal to finish registering.", + "card-registered-title": "Community Grant registered", + "card-registered-text": "Nothing more to do here — apply your license key when you upgrade this deployment to 4.4.", + "card-registered-link": "See what was granted", + "card-handed-over-title": "Report handed over", + "card-handed-over-text": "Your registration finishes in the License Portal — the outcome and the key are there; this deployment isn’t told.", + "card-handed-over-link": "Follow your registration", + "card-review-title": "Registration under review", + "card-review-text": "You’ll hear from us as soon as it’s done. This deployment keeps running as it is.", + "card-wrong-installation-title": "Can’t be registered", + "card-wrong-installation-text": "This deployment’s installation records don’t match the License Portal’s, so no grant was registered.", + "card-already-title": "Already registered", + "card-already-text-no-mask": "A Community Grant for this deployment already exists — a deployment can hold only one.", + "action-not-now": "Not now", + "action-register": "Register this deployment", + "action-close": "Close", + "action-copy": "Copy", + "action-copied": "Copied", + "action-open": "Open", + "action-reissue-link": "Reissue link", + "action-continue-to-verification": "Continue to verification", + "action-try-again": "Try again", + "action-back": "Back", + "action-run-verification": "Run verification", + "action-start-again": "Start again", + "action-request-access": "Request access", + "action-continue": "Continue", + "action-see-options": "See your options", + "action-see-details": "See details", + "action-return-report": "Return the report", + "action-report-handed-over": "Report handed over", + "action-open-report": "Open the report", + "action-verify-by-hand-instead": "Verify by hand instead", + "action-verify-deployment": "Verify this deployment" + }, "confirm-on-exit": { "message": "You have unsaved changes. Are you sure you want to leave this page?", "html-message": "You have unsaved changes.
    Are you sure you want to leave this page?", @@ -4177,8 +4299,6 @@ "item": { "type-widget": "Widget", "type-widget-plural": "Widgets", - "type-dashboard": "Dashboard", - "type-dashboard-plural": "Dashboards", "type-solution-template": "Solution Template", "type-solution-template-plural": "Solution Templates", "type-calculated-field": "Calculated Field", @@ -4200,6 +4320,8 @@ "search": "Search...", "search-published-items": "Search published items...", "see-all-results": "See all results", + "see-all-results-for": "See all {{ count }} results for \"{{ search }}\"", + "see-results-for": "See results for \"{{ search }}\"", "no-search-results": "No results found for '{{ search }}'", "no-items-available": "No items available", "search-results": "Search results", @@ -4222,9 +4344,9 @@ "type": "Type", "items-per-page": "Items per page", "filter": "Filter", + "clear-filters": "Clear filters", "available": "Available", "items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.", - "items-page-desc-dashboards": "Explore dashboards to find pre-built visualization templates and interactive UI layouts you can deploy in minutes to bring your IoT data to life.", "items-page-desc-solution-templates": "Complete IoT solution packages with dashboards, rule chains, and device configurations. Get started with proven architectures.", "items-page-desc-calculated-fields": "Use pre-configured Calculated Fields to automate complex metrics like fuel efficiency or power factor. Skip the manual logic and keep your dashboards clean and actionable.", "items-page-desc-alarm-rules": "Use pre-built Alarm Rule templates to detect critical conditions like low battery, threshold breaches, or devices going offline. Skip writing the rule logic and start reacting to incidents the moment they happen.", @@ -4232,8 +4354,9 @@ "items-page-desc-devices": "Explore the device library to find pre-configured connectivity templates you can deploy in minutes to connect your hardware instantly.", "device-library": "Device Library", "most-popular-in-iot-hub": "Most popular in IoT Hub", - "pe-required-title": "Professional Edition required", - "pe-required-message": "This item is available only on ThingsBoard Professional Edition. You are currently running Community Edition. To install it, upgrade to Professional Edition.", + "pe-required-title": "Not available in your version", + "pe-required-message": "This item requires ThingsBoard 4.4 or newer and isn’t available in your current version.

    If your instance was running before September 29, 2026, the Community Grant Program lets you upgrade for free and keep your current scale.", + "view-upgrade-options": "View upgrade options", "upgrade-required-title": "ThingsBoard upgrade required", "upgrade-required-message": "This item requires ThingsBoard {{minVersion}} or newer. You are currently running {{currentVersion}}. Please upgrade your instance to install it.", "upgrade-instance": "Upgrade instance", @@ -4241,29 +4364,28 @@ "contribute": "Contribute", "creator-profile": "Creator Profile", "title-widgets": "Widgets", - "title-dashboards": "Dashboards", "title-calculated-fields": "Calculated Fields", "title-alarm-rules": "Alarm Rules", "title-rule-chains": "Rule Chains", "title-devices": "Devices", "title-solution-templates": "Solution Templates", "subtitle-widgets": "Browse community widgets for your dashboards", - "subtitle-dashboards": "Browse ready-to-use dashboards", "subtitle-solution-templates": "Browse complete IoT solution packages", "subtitle-calculated-fields": "Browse calculated field templates", "subtitle-alarm-rules": "Browse alarm rule templates", "subtitle-rule-chains": "Browse rule chain templates", "subtitle-devices": "Browse device configurations", - "search-dashboards": "Search dashboards...", "search-solution-templates": "Search solution templates...", "search-calculated-fields": "Search calculated fields...", "search-alarm-rules": "Search alarm rules...", "search-rule-chains": "Search rule chains...", "search-devices": "Search devices...", + "sort-most-relevant": "Most relevant", "sort-most-installed": "Most installed", "sort-newest": "Newest", "sort-name": "Name (A-Z)", "type-filter-label": "Type", + "verified-creators-only": "Verified creators only", "category": "Category", "use-case": "Use case", "vendor": "Vendor", @@ -4337,6 +4459,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", + "install-dependency-error": "Failed to install the dependency '{{name}}': {{error}}", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", @@ -4357,6 +4480,7 @@ "update-confirm": "Update '{{name}}' to version {{version}}?", "update-confirm-title": "Update '{{name}}'?", "update-desc": "Updating this will replace the current version with the latest and reconfigure the associated resources within your tenant", + "update-desc-solution-template": "Updating this solution template will delete and recreate all entities it created, including dashboards, rule chains, devices, and other associated resources within your tenant. Any changes you made to them will be lost", "update-success-desc": "'{{name}}' has been updated successfully", "updating": "Updating...", "update-success-title": "Update Successful", @@ -9162,9 +9286,12 @@ "hot": "HOT", "esri-street": "WorldStreetMap", "esri-topo": "WorldTopoMap", - "esri-imagery": "WorldImagery", - "cartodb-positron": "Positron", - "cartodb-dark-matter": "DarkMatter" + "esri-imagery": "WorldImagery" + }, + "carto": { + "title": "CARTO", + "positron": "Positron", + "dark-matter": "DarkMatter" }, "google": { "title": "Google", @@ -9188,7 +9315,9 @@ }, "custom": { "title": "Custom", - "tile-url": "Tile URL" + "tile-url": "Tile URL", + "attribution": "Copyright text", + "attribution-hint": "Displayed at the bottom of the map. Required by most tile providers." } }, "credentials": { @@ -9485,10 +9614,7 @@ "here-map-hybrid-day": "HERE.hybridDay", "here-map-terrain-day": "HERE.terrainDay", "credentials": "Credentials", - "here-app-id": "HERE app id", - "here-app-code": "HERE app code", "here-api-key": "HERE API key", - "here-use-new-version-api-3": "Use API version 3", "tencent-maps-api-key": "Tencent Maps API Key", "tencent-map-type-roadmap": "Roadmap", "tencent-map-type-satelite": "Satellite", @@ -10299,10 +10425,11 @@ "contact-us": "Contact us", "current-version": "Current version", "current": "Current", - "available-version": "Available version", - "available": "Available", - "upgrade": "Upgrade", - "version-is-up-to-date": "Version is up to date" + "version-is-up-to-date": "Version is up to date", + "thingsboard-version-available": "ThingsBoard {{ version }} is available", + "free-community-grant-text": "4.4 is licensed differently and requires a license key. Your Community Grant is free.", + "get-community-grant": "Get your Community Grant", + "community-grant-registration-close": "Registration closes on July 20, 2027." }, "usage-info": { "title": "Usage", diff --git a/ui-ngx/src/assets/locale/locale.constant-ro_RO.json b/ui-ngx/src/assets/locale/locale.constant-ro_RO.json index f1b712e205..345c5d8aac 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ro_RO.json +++ b/ui-ngx/src/assets/locale/locale.constant-ro_RO.json @@ -1399,7 +1399,7 @@ "metadata-required": "Intrările metadata nu pot fi vide", "output": "Ieşire", "test": "Test", - "help": "Ajutor", + "help": "Ajutor" }, "tenant": { "tenant": "Locatar", diff --git a/ui-ngx/src/styles.scss b/ui-ngx/src/styles.scss index 44ebced31e..9ebf19e219 100644 --- a/ui-ngx/src/styles.scss +++ b/ui-ngx/src/styles.scss @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 /* You can add global styles to this file, and also import other style files */ @import 'typeface-roboto/index.css'; +@import 'typeface-roboto-mono/index.css'; @import 'font-awesome/css/font-awesome.min.css'; @import 'theme.scss'; @import './scss/constants'; diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index 7d184f78dc..0eed33ac38 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -160,88 +160,18 @@ "@angular-devkit/core" "^20.0.0" "@angular/build" "^20.0.0" -"@angular-devkit/architect@0.2003.34", "@angular-devkit/architect@>= 0.2000.0 < 0.2100.0", "@angular-devkit/architect@>=0.2000.0 < 0.2100.0": - version "0.2003.34" - resolved "https://registry.yarnpkg.com/@angular-devkit/architect/-/architect-0.2003.34.tgz#4346108edc5084cf37a6f719b27d91ecfee7ff9a" - integrity sha512-JX68qGFvv8Duy5UL21IJCived83tOZBVCxNcOS2XCII0CS8Z5nCEndRre73JfDsleTNkeS3fo2P5tjqN+/S80A== +"@angular-devkit/architect@0.2003.40", "@angular-devkit/architect@>= 0.2000.0 < 0.2100.0", "@angular-devkit/architect@>=0.2000.0 < 0.2100.0": + version "0.2003.40" + resolved "https://registry.yarnpkg.com/@angular-devkit/architect/-/architect-0.2003.40.tgz#e9d06cc8728241f1677865a9ccf1760548250ed0" + integrity sha512-8XPEUuwzyvaBzTO4e7DZskgDyLepfJI39/blAGzKqsob3NRlbtP/2+6lk9VgwkwuKF1KPJgmU1Sa67MB0qFNUA== dependencies: - "@angular-devkit/core" "20.3.34" + "@angular-devkit/core" "20.3.40" rxjs "7.8.2" -"@angular-devkit/build-angular@20.3.34": - version "20.3.34" - resolved "https://registry.yarnpkg.com/@angular-devkit/build-angular/-/build-angular-20.3.34.tgz#19611effcfae1e3170132560b7d4a4f2283dfe50" - integrity sha512-0pkzrPfFurAJdVzOi3xrsdv4Hraz/G+RrO7SXlwEGpvu/DUy/lZvsnk0kcg2/eZttoQfOLTMwnM8I6TeZx/IcQ== - dependencies: - "@ampproject/remapping" "2.3.0" - "@angular-devkit/architect" "0.2003.34" - "@angular-devkit/build-webpack" "0.2003.34" - "@angular-devkit/core" "20.3.34" - "@angular/build" "20.3.34" - "@babel/core" "7.29.7" - "@babel/generator" "7.28.3" - "@babel/helper-annotate-as-pure" "7.27.3" - "@babel/helper-split-export-declaration" "7.24.7" - "@babel/plugin-transform-async-generator-functions" "7.28.0" - "@babel/plugin-transform-async-to-generator" "7.27.1" - "@babel/plugin-transform-runtime" "7.28.3" - "@babel/preset-env" "7.28.3" - "@babel/runtime" "7.28.3" - "@discoveryjs/json-ext" "0.6.3" - "@ngtools/webpack" "20.3.34" - ansi-colors "4.1.3" - autoprefixer "10.4.21" - babel-loader "10.0.0" - browserslist "^4.21.5" - copy-webpack-plugin "14.0.0" - css-loader "7.1.2" - esbuild-wasm "0.28.1" - fast-glob "3.3.3" - http-proxy-middleware "3.0.7" - istanbul-lib-instrument "6.0.3" - jsonc-parser "3.3.1" - karma-source-map-support "1.4.0" - less "4.4.0" - less-loader "12.3.0" - license-webpack-plugin "4.0.2" - loader-utils "3.3.1" - mini-css-extract-plugin "2.9.4" - open "10.2.0" - ora "8.2.0" - picomatch "4.0.4" - piscina "5.2.0" - postcss "8.5.23" - postcss-loader "8.1.1" - resolve-url-loader "5.0.0" - rxjs "7.8.2" - sass "1.90.0" - sass-loader "16.0.5" - semver "7.7.2" - source-map-loader "5.0.0" - source-map-support "0.5.21" - terser "5.43.1" - tree-kill "1.2.2" - tslib "2.8.1" - webpack "5.105.0" - webpack-dev-middleware "7.4.2" - webpack-dev-server "5.2.5" - webpack-merge "6.0.1" - webpack-subresource-integrity "5.1.0" - optionalDependencies: - esbuild "0.28.1" - -"@angular-devkit/build-webpack@0.2003.34": - version "0.2003.34" - resolved "https://registry.yarnpkg.com/@angular-devkit/build-webpack/-/build-webpack-0.2003.34.tgz#148e55c7bbe7b12749bf4e7a168ccf04dcb5550c" - integrity sha512-IHl8e5dClTfzpqeqanBi4s5dti6i+kueIlfASl/cfyBYW7ASr+FDLbffIonpLYvb3uyucFdo22ND9+/HZZdrKQ== - dependencies: - "@angular-devkit/architect" "0.2003.34" - rxjs "7.8.2" - -"@angular-devkit/core@20.3.34", "@angular-devkit/core@>= 20.0.0 < 21.0.0", "@angular-devkit/core@^20.0.0": - version "20.3.34" - resolved "https://registry.yarnpkg.com/@angular-devkit/core/-/core-20.3.34.tgz#10beedd0c5af94f3115a16f1244acf004c741b0a" - integrity sha512-vcDaXzF3E+gGD62gdPa0AZlEertqB3raufEjT5Y0bl9MO4t2CCanEbbIfIyPtpLp22SJOyOErx/39weeEbfmjQ== +"@angular-devkit/core@20.3.40", "@angular-devkit/core@>= 20.0.0 < 21.0.0", "@angular-devkit/core@^20.0.0": + version "20.3.40" + resolved "https://registry.yarnpkg.com/@angular-devkit/core/-/core-20.3.40.tgz#8186dd58e5d0e71ad93e72eca943dacdb4d97fc3" + integrity sha512-H7A7p3hP4/6rZmZGrjyipWMFMMW1iWILxAizfGNUEef2ymMIs7uX/uuCdL4BP1vDF8MorLCgeCChLJ2QZuv8UQ== dependencies: ajv "8.18.0" ajv-formats "3.0.1" @@ -250,12 +180,12 @@ rxjs "7.8.2" source-map "0.7.6" -"@angular-devkit/schematics@20.3.34", "@angular-devkit/schematics@>= 20.0.0 < 21.0.0": - version "20.3.34" - resolved "https://registry.yarnpkg.com/@angular-devkit/schematics/-/schematics-20.3.34.tgz#2628c1319f56f3506ce8c60da0594d2dbe5c78e1" - integrity sha512-JW+RmDOeCGrzcdiTthw/ZlYMmsI3n2akWAdOUeczMdnbWfygMcbft3r8D+k1uefuxfAhJ4PgTtvECKhDqLN67g== +"@angular-devkit/schematics@20.3.40", "@angular-devkit/schematics@>= 20.0.0 < 21.0.0": + version "20.3.40" + resolved "https://registry.yarnpkg.com/@angular-devkit/schematics/-/schematics-20.3.40.tgz#5aef43cac0ac19f3b338d6b08f3cedbf2ef97cdf" + integrity sha512-mGWSkJStNLsLhy+FRxqKHkF7drSfkxrL82/UbQ+aizLHnbUZrir6PPToUmm6xRxKZcwbZegi4jjlyive0/nJcQ== dependencies: - "@angular-devkit/core" "20.3.34" + "@angular-devkit/core" "20.3.40" jsonc-parser "3.3.1" magic-string "0.30.17" ora "8.2.0" @@ -321,20 +251,20 @@ dependencies: "@angular-eslint/bundled-angular-compiler" "20.7.0" -"@angular/animations@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/animations/-/animations-20.3.28.tgz#d0a75dcb0ad859ba4be9cdabb5a18706e196c39f" - integrity sha512-cd0zEamoqHT94JG/ejUCkZLRxty9sD3nD9yWrwdymCBI5l6Fdfk5tp5QdhU8qjKy9FAMFxnCTjz3stPByrDgBQ== +"@angular/animations@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/animations/-/animations-20.3.34.tgz#5a81e2dc33df16cf5ad73d67abfe17f3d17d91da" + integrity sha512-HdDfbLwpxzx49wAWz4oOUQKSkZcFNRpWEGsDEgufZ3ExwxRk1/2QPJuvZ2CbhKeEcLPrLKUorQ8XlGrNsJmNiQ== dependencies: tslib "^2.3.0" -"@angular/build@20.3.34", "@angular/build@^20.0.0": - version "20.3.34" - resolved "https://registry.yarnpkg.com/@angular/build/-/build-20.3.34.tgz#1cd20f8b87faf033e563d1ca0b216d950e474a0a" - integrity sha512-uV7zgmvbLwaT/blpYqVVWkrJnHBGSjkuB+ADCruIou7j+/kmo9k/dXCnXVAlP22nR/gdKi24NBahDBNXxrBpzg== +"@angular/build@20.3.40", "@angular/build@^20.0.0": + version "20.3.40" + resolved "https://registry.yarnpkg.com/@angular/build/-/build-20.3.40.tgz#777619c9ad8db033197f1eae9f4e01dd48f4fc6e" + integrity sha512-lFa1DVul9/VncuoZgmhEij86jdPC77/mX5QrTB5OPFwQeBrlK1FRwEh46hrtdsW5qnVVMAf+wx5+B/N7FuvcKw== dependencies: "@ampproject/remapping" "2.3.0" - "@angular-devkit/architect" "0.2003.34" + "@angular-devkit/architect" "0.2003.40" "@babel/core" "7.29.7" "@babel/helper-annotate-as-pure" "7.27.3" "@babel/helper-split-export-declaration" "7.24.7" @@ -351,7 +281,7 @@ mrmime "2.0.1" parse5-html-rewriting-stream "8.0.0" picomatch "4.0.4" - piscina "5.2.0" + piscina "5.3.2" rollup "4.59.0" sass "1.90.0" semver "7.7.2" @@ -370,18 +300,18 @@ parse5 "^8.0.0" tslib "^2.3.0" -"@angular/cli@20.3.34": - version "20.3.34" - resolved "https://registry.yarnpkg.com/@angular/cli/-/cli-20.3.34.tgz#0b9f674b1a316c7c07ea2fd97453e0ca9998b4f0" - integrity sha512-Q/6dR2TmVTt9GT4tczREqg3DOlqkkMWI+5AVXgM1EcJRbt91XVlbooXw1GKr6gefxCtbdIi1fXjY4Yled/r23A== +"@angular/cli@20.3.40": + version "20.3.40" + resolved "https://registry.yarnpkg.com/@angular/cli/-/cli-20.3.40.tgz#b7cf6428e6ade35aa2ffe7d331387c42dd641c1a" + integrity sha512-Gca1MtSCJiZdzXM/nmXBe6rmv0IauG8x2jO4GMPcpQvqscdGGm5EUWT4fduC/k/uWXHHewr3aOHwFDimtHaPPw== dependencies: - "@angular-devkit/architect" "0.2003.34" - "@angular-devkit/core" "20.3.34" - "@angular-devkit/schematics" "20.3.34" + "@angular-devkit/architect" "0.2003.40" + "@angular-devkit/core" "20.3.40" + "@angular-devkit/schematics" "20.3.40" "@inquirer/prompts" "7.8.2" "@listr2/prompt-adapter-inquirer" "3.0.1" - "@modelcontextprotocol/sdk" "1.30.0" - "@schematics/angular" "20.3.34" + "@modelcontextprotocol/sdk" "1.31.0" + "@schematics/angular" "20.3.40" "@yarnpkg/lockfile" "1.1.0" algoliasearch "5.35.0" ini "5.0.0" @@ -392,19 +322,19 @@ resolve "1.22.10" semver "7.7.2" yargs "18.0.0" - zod "4.1.13" + zod "4.6.6" -"@angular/common@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/common/-/common-20.3.28.tgz#c3b639fe112b62498913cdca8b82330d469df8ef" - integrity sha512-vvMrBI0POHYeUE8EnN4ohYOqLkmZXI6oKJnMvarfukySnw7mZ4VuY4DNAnRSbEZEqO55sOmVCQ7jbxDDt34tZw== +"@angular/common@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/common/-/common-20.3.34.tgz#44a342d381f5b7a16d9f11a99f36028855585f08" + integrity sha512-OhB/l0cNldOvQeICqbWqRUzK5fF6zNYy44Q4cIGJZql8HXL/invGiqWLE9f+kU8z4jRisofHIGTBtyJQYYOudg== dependencies: tslib "^2.3.0" -"@angular/compiler-cli@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/compiler-cli/-/compiler-cli-20.3.28.tgz#07af1834005bfe4630500761e3f16840305f3807" - integrity sha512-HZH4HH02mMOlZuXOXnnnHWK39bsPjbKRK6XJhLTu7T/0/iUFOiH0NTkkWrpjKXwn5eSDYhmJGCmWcJyW/LUaLQ== +"@angular/compiler-cli@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/compiler-cli/-/compiler-cli-20.3.34.tgz#0e6ad2f56cc26d150297c1c1337acfc1a86b9ce2" + integrity sha512-PKHzhSOyDUFh64Ull3fUwgFlxnsQNEAuRyz4KqQ8FsTGZ4pOpUaZntO+2Xn1nX/gT2whSyGBJhD3H37zA8ZGEQ== dependencies: "@babel/core" "7.29.7" "@jridgewell/sourcemap-codec" "^1.4.14" @@ -415,31 +345,31 @@ tslib "^2.3.0" yargs "^18.0.0" -"@angular/compiler@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/compiler/-/compiler-20.3.28.tgz#d5f6c12a7686fcd4ddb197771b19749eef1c7d79" - integrity sha512-3iSkIWJEVrdG4Zv0vQs0ieO185aJfb5Vn3whi/D7QEDUNEsHGZSxRDxT1hyDGIaj52FN6+Qo5SFSSsDf+vgUAA== +"@angular/compiler@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/compiler/-/compiler-20.3.34.tgz#2cb3f68e7a051a07e39af1f47722a02313123bb0" + integrity sha512-8agPW384c/JER1ersPTmJJfcCOnlYcBbdj0MYRxNdiYe+7gtnspF3ORuJmxqCEpMS17AljSmk2skwUcYnHB6xA== dependencies: tslib "^2.3.0" -"@angular/core@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/core/-/core-20.3.28.tgz#ece2fdf6bf0af1b4d76e768eacb3d0bf90cb419c" - integrity sha512-R28TMoEr+mBUswemFWZdHAuK2WDSs+6eYFBg6XrBmlMlmG4YkWeNFxRbJNYDkF8RH+fpguS+iUH63yLpts22dA== +"@angular/core@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/core/-/core-20.3.34.tgz#341b148c6fcd894fac1b3ec2775536315ee28f49" + integrity sha512-xOvSmGoao3SVPz//R7zTrq7+WdrIGi+WNpAdxJEvJJXuSpLGS3kSUqukjY4kOMochg2v0NCEPIdCyH+yPs8JSw== dependencies: tslib "^2.3.0" -"@angular/forms@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/forms/-/forms-20.3.28.tgz#45246be5023ba1bb5ffbe79338d863c948b41527" - integrity sha512-at81TpBs/NxvOyR5IhtUClG+2WVMLVDieFRz+rAH+ok9dtRrDHoKPQOgMAEw9q5N4yO4CZKhfAPq+5P/gnnjsw== +"@angular/forms@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/forms/-/forms-20.3.34.tgz#73d148e08c6f386a105179533576a22de170eec4" + integrity sha512-DndQJEoORsdthFFVRvT9WHn8YcA85jkjMxCLtXyf+TDVk0zbqObbFDfrloRnJwsINqfDNsJrz23ko3YU6sjnTw== dependencies: tslib "^2.3.0" -"@angular/language-service@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/language-service/-/language-service-20.3.28.tgz#0f5768108615ef06251e9f4316ae66d4cc5c9515" - integrity sha512-7jx5mXLCmOC6Tub8+r+3GYBFF5IcntsBu7F2oTV9Pg6FuZnbMd2ooBRk9dtn1btX0sK/vqTiUsjjTyQ5vXRJVA== +"@angular/language-service@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/language-service/-/language-service-20.3.34.tgz#7d47a3bc7ec27e3850ba64fda7137cc627ccb291" + integrity sha512-ennTeEZiNrTgidBw7cyAfyO9+0ijaop10V+stInzhpn2Se+h9kDJKT7IXWqc6v4E6DNJinzazN68/QwSZoZW1A== "@angular/material@20.2.14": version "20.2.14" @@ -448,24 +378,24 @@ dependencies: tslib "^2.3.0" -"@angular/platform-browser-dynamic@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/platform-browser-dynamic/-/platform-browser-dynamic-20.3.28.tgz#139b0fc545e5c6ddde31b1e6f678e2402de3bb10" - integrity sha512-wy3694EfbGyDsnppaoNy4X/JGH3auDFMB4c+B7GZzVAtCO3eNanoNctAKKkkmN0FMAdzGHHEPhIIyJj702S+rw== +"@angular/platform-browser-dynamic@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/platform-browser-dynamic/-/platform-browser-dynamic-20.3.34.tgz#d58f17a52ae2f468636f7da4529aaf85c98d4565" + integrity sha512-vqKzExmUDf5jpIlNZRuICsLzaLWY5yTvuXsJhe97KTbC29BD71LhRGhEu7fjmR5uYy+LForpWYm5IsYlJcJAGQ== dependencies: tslib "^2.3.0" -"@angular/platform-browser@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/platform-browser/-/platform-browser-20.3.28.tgz#785008d8d0293176c9938a63ee45f700626fefc2" - integrity sha512-TER/xSXlDsqlbM4Eufkjzm7HvB88K6pbudl7Xs6H3huTkg9Lw4zuFIpnk+fpLOGcc7/rpFIb00k/LhzkwuQiIw== +"@angular/platform-browser@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/platform-browser/-/platform-browser-20.3.34.tgz#8791d8d5e02d5dd5a7fc14b722fc043028d19bb1" + integrity sha512-0bd2Bj05WPoBTFM0A13IwbzxKVQPstx/N+7X0ZWKCifliyydIc7DBHu+r37ybJpl8ZsCVBe7DoR9Gon4lZ+zlw== dependencies: tslib "^2.3.0" -"@angular/router@20.3.28": - version "20.3.28" - resolved "https://registry.yarnpkg.com/@angular/router/-/router-20.3.28.tgz#5ab760f5e37db5bdbb98ab157f6c41d935eae2f1" - integrity sha512-W4sNTrYT2oavpJ/MgUYpnCkhJ0vBS3KXZVRNruURUI/wLirF+AoXvMSlke9SlytrdvPAx8Www+nq0dyY2Ln96Q== +"@angular/router@20.3.34": + version "20.3.34" + resolved "https://registry.yarnpkg.com/@angular/router/-/router-20.3.34.tgz#00fd332cf00c905cd70ddcc102bf37280891dc1e" + integrity sha512-vQo2f/94nUoNMZaxGY0+fK1t9Oe7zJuxHhoMVYhDbCqKxINVmxMX/9uEHlHeu9UIE7JMazepQjRzBLo7bf9xCw== dependencies: tslib "^2.3.0" @@ -484,7 +414,7 @@ dependencies: tslib "^2.0.0" -"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.29.7": +"@babel/code-frame@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.29.7.tgz#f2fbbfea87c44a21590ec515b778b2c26d8866e7" integrity sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw== @@ -493,7 +423,7 @@ js-tokens "^4.0.0" picocolors "^1.1.1" -"@babel/compat-data@^7.27.7", "@babel/compat-data@^7.28.0", "@babel/compat-data@^7.29.7": +"@babel/compat-data@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.29.7.tgz#6f0237f0f36d2e51c0570a636faed9d2d0efe629" integrity sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg== @@ -519,17 +449,6 @@ json5 "^2.2.3" semver "^6.3.1" -"@babel/generator@7.28.3": - version "7.28.3" - resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.28.3.tgz#9626c1741c650cbac39121694a0f2d7451b8ef3e" - integrity sha512-3lSpxGgvnmZznmBkCRnVREPUFJv2wrv9iAoFDvADJc0ypmdOxdUtcLeBgBJ6zE0PMeTKnxeQzyk0xTBq4Ep7zw== - dependencies: - "@babel/parser" "^7.28.3" - "@babel/types" "^7.28.2" - "@jridgewell/gen-mapping" "^0.3.12" - "@jridgewell/trace-mapping" "^0.3.28" - jsesc "^3.0.2" - "@babel/generator@^7.29.7", "@babel/generator@^7.29.8": version "7.29.8" resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.29.8.tgz#4b0b887885422643339e09022148a4c4ebaa4979" @@ -541,14 +460,14 @@ "@jridgewell/trace-mapping" "^0.3.28" jsesc "^3.0.2" -"@babel/helper-annotate-as-pure@7.27.3", "@babel/helper-annotate-as-pure@^7.27.1", "@babel/helper-annotate-as-pure@^7.27.3": +"@babel/helper-annotate-as-pure@7.27.3": version "7.27.3" resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.27.3.tgz#f31fd86b915fc4daf1f3ac6976c59be7084ed9c5" integrity sha512-fXSwMQqitTGeHLBC08Eq5yXz2m37E4pJX1qAU1+2cNedz/ifv/bVXft90VeSav5nFO61EcNgwr0aJxbyPaWBPg== dependencies: "@babel/types" "^7.27.3" -"@babel/helper-compilation-targets@^7.27.1", "@babel/helper-compilation-targets@^7.27.2", "@babel/helper-compilation-targets@^7.28.6", "@babel/helper-compilation-targets@^7.29.7": +"@babel/helper-compilation-targets@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz#7a1def704302401c47f64fa85589e974ae217042" integrity sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g== @@ -559,53 +478,12 @@ lru-cache "^5.1.1" semver "^6.3.1" -"@babel/helper-create-class-features-plugin@^7.28.6": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.28.6.tgz#611ff5482da9ef0db6291bcd24303400bca170fb" - integrity sha512-dTOdvsjnG3xNT9Y0AUg1wAl38y+4Rl4sf9caSQZOXdNqVn+H+HbbJ4IyyHaIqNR6SW9oJpA/RuRjsjCw2IdIow== - dependencies: - "@babel/helper-annotate-as-pure" "^7.27.3" - "@babel/helper-member-expression-to-functions" "^7.28.5" - "@babel/helper-optimise-call-expression" "^7.27.1" - "@babel/helper-replace-supers" "^7.28.6" - "@babel/helper-skip-transparent-expression-wrappers" "^7.27.1" - "@babel/traverse" "^7.28.6" - semver "^6.3.1" - -"@babel/helper-create-regexp-features-plugin@^7.18.6", "@babel/helper-create-regexp-features-plugin@^7.27.1", "@babel/helper-create-regexp-features-plugin@^7.28.5": - version "7.28.5" - resolved "https://registry.yarnpkg.com/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.28.5.tgz#7c1ddd64b2065c7f78034b25b43346a7e19ed997" - integrity sha512-N1EhvLtHzOvj7QQOUCCS3NrPJP8c5W6ZXCHDn7Yialuy1iu4r5EmIYkXlKNqT99Ciw+W0mDqWoR6HWMZlFP3hw== - dependencies: - "@babel/helper-annotate-as-pure" "^7.27.3" - regexpu-core "^6.3.1" - semver "^6.3.1" - -"@babel/helper-define-polyfill-provider@^0.6.5": - version "0.6.5" - resolved "https://registry.yarnpkg.com/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.5.tgz#742ccf1cb003c07b48859fc9fa2c1bbe40e5f753" - integrity sha512-uJnGFcPsWQK8fvjgGP5LZUZZsYGIoPeRjSF5PGwrelYgq7Q15/Ft9NGFp1zglwgIv//W0uG4BevRuSJRyylZPg== - dependencies: - "@babel/helper-compilation-targets" "^7.27.2" - "@babel/helper-plugin-utils" "^7.27.1" - debug "^4.4.1" - lodash.debounce "^4.0.8" - resolve "^1.22.10" - -"@babel/helper-globals@^7.28.0", "@babel/helper-globals@^7.29.7": +"@babel/helper-globals@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/helper-globals/-/helper-globals-7.29.7.tgz#f04a96fbd8473241b1079243f5b3f03a3010ab7b" integrity sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA== -"@babel/helper-member-expression-to-functions@^7.28.5": - version "7.28.5" - resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.28.5.tgz#f3e07a10be37ed7a63461c63e6929575945a6150" - integrity sha512-cwM7SBRZcPCLgl8a7cY0soT1SptSzAlMH39vwiRpOQkJlh53r5hdHwLSCZpQdVLT39sZt+CRpNwYG4Y2v77atg== - dependencies: - "@babel/traverse" "^7.28.5" - "@babel/types" "^7.28.5" - -"@babel/helper-module-imports@^7.27.1", "@babel/helper-module-imports@^7.28.6", "@babel/helper-module-imports@^7.29.7": +"@babel/helper-module-imports@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz#ef25048a518e828d7393fac5882ddd73921d7396" integrity sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g== @@ -613,7 +491,7 @@ "@babel/traverse" "^7.29.7" "@babel/types" "^7.29.7" -"@babel/helper-module-transforms@^7.27.1", "@babel/helper-module-transforms@^7.28.6", "@babel/helper-module-transforms@^7.29.7": +"@babel/helper-module-transforms@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz#b062747a5997ba138637201328bbff77960574ae" integrity sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg== @@ -622,44 +500,6 @@ "@babel/helper-validator-identifier" "^7.29.7" "@babel/traverse" "^7.29.7" -"@babel/helper-optimise-call-expression@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.27.1.tgz#c65221b61a643f3e62705e5dd2b5f115e35f9200" - integrity sha512-URMGH08NzYFhubNSGJrpUEphGKQwMQYBySzat5cAByY1/YgIRkULnIy3tAMeszlL/so2HbeilYloUmSpd7GdVw== - dependencies: - "@babel/types" "^7.27.1" - -"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.18.6", "@babel/helper-plugin-utils@^7.27.1", "@babel/helper-plugin-utils@^7.28.6": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz#6f13ea251b68c8532e985fd532f28741a8af9ac8" - integrity sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug== - -"@babel/helper-remap-async-to-generator@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.27.1.tgz#4601d5c7ce2eb2aea58328d43725523fcd362ce6" - integrity sha512-7fiA521aVw8lSPeI4ZOD3vRFkoqkJcS+z4hFo82bFSH/2tNd6eJ5qCVMS5OzDmZh/kaHQeBaeyxK6wljcPtveA== - dependencies: - "@babel/helper-annotate-as-pure" "^7.27.1" - "@babel/helper-wrap-function" "^7.27.1" - "@babel/traverse" "^7.27.1" - -"@babel/helper-replace-supers@^7.27.1", "@babel/helper-replace-supers@^7.28.6": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/helper-replace-supers/-/helper-replace-supers-7.28.6.tgz#94aa9a1d7423a00aead3f204f78834ce7d53fe44" - integrity sha512-mq8e+laIk94/yFec3DxSjCRD2Z0TAjhVbEJY3UQrlwVo15Lmt7C2wAUbK4bjnTs4APkwsYLTahXRraQXhb1WCg== - dependencies: - "@babel/helper-member-expression-to-functions" "^7.28.5" - "@babel/helper-optimise-call-expression" "^7.27.1" - "@babel/traverse" "^7.28.6" - -"@babel/helper-skip-transparent-expression-wrappers@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.27.1.tgz#62bb91b3abba8c7f1fec0252d9dbea11b3ee7a56" - integrity sha512-Tub4ZKEXqbPjXgWLl2+3JpQAYBJ8+ikpQ2Ocj/q/r0LwE3UhENh7EUabyHjz2kCEsrRY83ew2DQdHluuiDQFzg== - dependencies: - "@babel/traverse" "^7.27.1" - "@babel/types" "^7.27.1" - "@babel/helper-split-export-declaration@7.24.7": version "7.24.7" resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.24.7.tgz#83949436890e07fa3d6873c61a96e3bbf692d856" @@ -672,25 +512,16 @@ resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz#7f0871d99824d23137d60f86fcf6130fd5a1b51f" integrity sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw== -"@babel/helper-validator-identifier@^7.28.5", "@babel/helper-validator-identifier@^7.29.7": +"@babel/helper-validator-identifier@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz#bd87084ced0c796ec46bda492de6e83d29e89fc2" integrity sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg== -"@babel/helper-validator-option@^7.27.1", "@babel/helper-validator-option@^7.29.7": +"@babel/helper-validator-option@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz#cf315be940213b354eb4abcc0bd01ebe3f73bc2a" integrity sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw== -"@babel/helper-wrap-function@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/helper-wrap-function/-/helper-wrap-function-7.28.6.tgz#4e349ff9222dab69a93a019cc296cdd8442e279a" - integrity sha512-z+PwLziMNBeSQJonizz2AGnndLsP2DeGHIxDAn+wdHOGuo4Fo1x1HBPPXeE9TAOPHNNWQKCSlA2VZyYyyibDnQ== - dependencies: - "@babel/template" "^7.28.6" - "@babel/traverse" "^7.28.6" - "@babel/types" "^7.28.6" - "@babel/helpers@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.29.7.tgz#45abfde7548997e34376c3e69feb475cffb4a607" @@ -699,597 +530,14 @@ "@babel/template" "^7.29.7" "@babel/types" "^7.29.7" -"@babel/parser@^7.23.9", "@babel/parser@^7.28.3", "@babel/parser@^7.29.7", "@babel/parser@^7.29.8": +"@babel/parser@^7.23.9", "@babel/parser@^7.29.7", "@babel/parser@^7.29.8": version "7.29.8" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.29.8.tgz#9653716a2f10c677b98fbc63d4bfb000c302cf17" integrity sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA== dependencies: "@babel/types" "^7.29.8" -"@babel/plugin-bugfix-firefox-class-in-computed-class-key@^7.27.1": - version "7.28.5" - resolved "https://registry.yarnpkg.com/@babel/plugin-bugfix-firefox-class-in-computed-class-key/-/plugin-bugfix-firefox-class-in-computed-class-key-7.28.5.tgz#fbde57974707bbfa0376d34d425ff4fa6c732421" - integrity sha512-87GDMS3tsmMSi/3bWOte1UblL+YUTFMV8SZPZ2eSEL17s74Cw/l63rR6NmGVKMYW2GYi85nE+/d6Hw5N0bEk2Q== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/traverse" "^7.28.5" - -"@babel/plugin-bugfix-safari-class-field-initializer-scope@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-bugfix-safari-class-field-initializer-scope/-/plugin-bugfix-safari-class-field-initializer-scope-7.27.1.tgz#43f70a6d7efd52370eefbdf55ae03d91b293856d" - integrity sha512-qNeq3bCKnGgLkEXUuFry6dPlGfCdQNZbn7yUAPCInwAJHMU7THJfrBSozkcWq5sNM6RcF3S8XyQL2A52KNR9IA== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.27.1.tgz#beb623bd573b8b6f3047bd04c32506adc3e58a72" - integrity sha512-g4L7OYun04N1WyqMNjldFwlfPCLVkgB54A/YCXICZYBsvJJE3kByKv9c9+R/nAfmIfjl2rKYLNyMHboYbZaWaA== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-7.27.1.tgz#e134a5479eb2ba9c02714e8c1ebf1ec9076124fd" - integrity sha512-oO02gcONcD5O1iTLi/6frMJBIwWEHceWGSGqrpCmEL8nogiS6J9PBlE48CaK20/Jx1LuRml9aDftLgdjXT8+Cw== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/helper-skip-transparent-expression-wrappers" "^7.27.1" - "@babel/plugin-transform-optional-chaining" "^7.27.1" - -"@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly@^7.28.3": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-7.28.6.tgz#0e8289cec28baaf05d54fd08d81ae3676065f69f" - integrity sha512-a0aBScVTlNaiUe35UtfxAN7A/tehvvG4/ByO6+46VPKTRSlfnAFsgKy0FUh+qAkQrDTmhDkT+IBOKlOoMUxQ0g== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/traverse" "^7.28.6" - -"@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2": - version "7.21.0-placeholder-for-preset-env.2" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz#7844f9289546efa9febac2de4cfe358a050bd703" - integrity sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w== - -"@babel/plugin-syntax-import-assertions@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.28.6.tgz#ae9bc1923a6ba527b70104dd2191b0cd872c8507" - integrity sha512-pSJUpFHdx9z5nqTSirOCMtYVP2wFgoWhP0p3g8ONK/4IHhLIBd0B9NYqAvIUAhq+OkhO4VM1tENCt0cjlsNShw== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-syntax-import-attributes@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.28.6.tgz#b71d5914665f60124e133696f17cd7669062c503" - integrity sha512-jiLC0ma9XkQT3TKJ9uYvlakm66Pamywo+qwL+oL8HJOvc6TWdZXVfhqJr8CCzbSGUAbDOzlGHJC1U+vRfLQDvw== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-syntax-unicode-sets-regex@^7.18.6": - version "7.18.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-unicode-sets-regex/-/plugin-syntax-unicode-sets-regex-7.18.6.tgz#d49a3b3e6b52e5be6740022317580234a6a47357" - integrity sha512-727YkEAPwSIQTv5im8QHz3upqp92JTWhidIC81Tdx4VJYIte/VndKf1qKrfnnhPLiPghStWfvC/iFaMCQu7Nqg== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.18.6" - "@babel/helper-plugin-utils" "^7.18.6" - -"@babel/plugin-transform-arrow-functions@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.27.1.tgz#6e2061067ba3ab0266d834a9f94811196f2aba9a" - integrity sha512-8Z4TGic6xW70FKThA5HYEKKyBpOOsucTOD1DjU3fZxDg+K3zBJcXMFnt/4yQiZnf5+MiOMSXQ9PaEK/Ilh1DeA== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-async-generator-functions@7.28.0": - version "7.28.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.28.0.tgz#1276e6c7285ab2cd1eccb0bc7356b7a69ff842c2" - integrity sha512-BEOdvX4+M765icNPZeidyADIvQ1m1gmunXufXxvRESy/jNNyfovIqUyE7MVgGBjWktCoJlzvFA1To2O4ymIO3Q== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/helper-remap-async-to-generator" "^7.27.1" - "@babel/traverse" "^7.28.0" - -"@babel/plugin-transform-async-generator-functions@^7.28.0": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.28.6.tgz#80cb86d3eaa2102e18ae90dd05ab87bdcad3877d" - integrity sha512-9knsChgsMzBV5Yh3kkhrZNxH3oCYAfMBkNNaVN4cP2RVlFPe8wYdwwcnOsAbkdDoV9UjFtOXWrWB52M8W4jNeA== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/helper-remap-async-to-generator" "^7.27.1" - "@babel/traverse" "^7.28.6" - -"@babel/plugin-transform-async-to-generator@7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.27.1.tgz#9a93893b9379b39466c74474f55af03de78c66e7" - integrity sha512-NREkZsZVJS4xmTr8qzE5y8AfIPqsdQfRuUiLRTEzb7Qii8iFWCyDKaUV2c0rCuh4ljDZ98ALHP/PetiBV2nddA== - dependencies: - "@babel/helper-module-imports" "^7.27.1" - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/helper-remap-async-to-generator" "^7.27.1" - -"@babel/plugin-transform-async-to-generator@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.28.6.tgz#bd97b42237b2d1bc90d74bcb486c39be5b4d7e77" - integrity sha512-ilTRcmbuXjsMmcZ3HASTe4caH5Tpo93PkTxF9oG2VZsSWsahydmcEHhix9Ik122RcTnZnUzPbmux4wh1swfv7g== - dependencies: - "@babel/helper-module-imports" "^7.28.6" - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/helper-remap-async-to-generator" "^7.27.1" - -"@babel/plugin-transform-block-scoped-functions@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.27.1.tgz#558a9d6e24cf72802dd3b62a4b51e0d62c0f57f9" - integrity sha512-cnqkuOtZLapWYZUYM5rVIdv1nXYuFVIltZ6ZJ7nIj585QsjKM5dhL2Fu/lICXZ1OyIAFc7Qy+bvDAtTXqGrlhg== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-block-scoping@^7.28.0": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.28.6.tgz#e1ef5633448c24e76346125c2534eeb359699a99" - integrity sha512-tt/7wOtBmwHPNMPu7ax4pdPz6shjFrmHDghvNC+FG9Qvj7D6mJcoRQIF5dy4njmxR941l6rgtvfSB2zX3VlUIw== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-class-properties@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.28.6.tgz#d274a4478b6e782d9ea987fda09bdb6d28d66b72" - integrity sha512-dY2wS3I2G7D697VHndN91TJr8/AAfXQNt5ynCTI/MpxMsSzHp+52uNivYT5wCPax3whc47DR8Ba7cmlQMg24bw== - dependencies: - "@babel/helper-create-class-features-plugin" "^7.28.6" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-class-static-block@^7.28.3": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.28.6.tgz#1257491e8259c6d125ac4d9a6f39f9d2bf3dba70" - integrity sha512-rfQ++ghVwTWTqQ7w8qyDxL1XGihjBss4CmTgGRCTAC9RIbhVpyp4fOeZtta0Lbf+dTNIVJer6ych2ibHwkZqsQ== - dependencies: - "@babel/helper-create-class-features-plugin" "^7.28.6" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-classes@^7.28.3": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-classes/-/plugin-transform-classes-7.28.6.tgz#8f6fb79ba3703978e701ce2a97e373aae7dda4b7" - integrity sha512-EF5KONAqC5zAqT783iMGuM2ZtmEBy+mJMOKl2BCvPZ2lVrwvXnB6o+OBWCS+CoeCCpVRF2sA2RBKUxvT8tQT5Q== - dependencies: - "@babel/helper-annotate-as-pure" "^7.27.3" - "@babel/helper-compilation-targets" "^7.28.6" - "@babel/helper-globals" "^7.28.0" - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/helper-replace-supers" "^7.28.6" - "@babel/traverse" "^7.28.6" - -"@babel/plugin-transform-computed-properties@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.28.6.tgz#936824fc71c26cb5c433485776d79c8e7b0202d2" - integrity sha512-bcc3k0ijhHbc2lEfpFHgx7eYw9KNXqOerKWfzbxEHUGKnS3sz9C4CNL9OiFN1297bDNfUiSO7DaLzbvHQQQ1BQ== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/template" "^7.28.6" - -"@babel/plugin-transform-destructuring@^7.28.0", "@babel/plugin-transform-destructuring@^7.28.5": - version "7.28.5" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.28.5.tgz#b8402764df96179a2070bb7b501a1586cf8ad7a7" - integrity sha512-Kl9Bc6D0zTUcFUvkNuQh4eGXPKKNDOJQXVyyM4ZAQPMveniJdxi8XMJwLo+xSoW3MIq81bD33lcUe9kZpl0MCw== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/traverse" "^7.28.5" - -"@babel/plugin-transform-dotall-regex@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.28.6.tgz#def31ed84e0fb6e25c71e53c124e7b76a4ab8e61" - integrity sha512-SljjowuNKB7q5Oayv4FoPzeB74g3QgLt8IVJw9ADvWy3QnUb/01aw8I4AVv8wYnPvQz2GDDZ/g3GhcNyDBI4Bg== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.28.5" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-duplicate-keys@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.27.1.tgz#f1fbf628ece18e12e7b32b175940e68358f546d1" - integrity sha512-MTyJk98sHvSs+cvZ4nOauwTTG1JeonDjSGvGGUNHreGQns+Mpt6WX/dVzWBHgg+dYZhkC4X+zTDfkTU+Vy9y7Q== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-duplicate-named-capturing-groups-regex@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-7.28.6.tgz#e0c59ba54f1655dd682f2edf5f101b5910a8f6f3" - integrity sha512-5suVoXjC14lUN6ZL9OLKIHCNVWCrqGqlmEp/ixdXjvgnEl/kauLvvMO/Xw9NyMc95Joj1AeLVPVMvibBgSoFlA== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.28.5" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-dynamic-import@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-7.27.1.tgz#4c78f35552ac0e06aa1f6e3c573d67695e8af5a4" - integrity sha512-MHzkWQcEmjzzVW9j2q8LGjwGWpG2mjwaaB0BNQwst3FIjqsg8Ct/mIZlvSPJvfi9y2AC8mi/ktxbFVL9pZ1I4A== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-explicit-resource-management@^7.28.0": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.28.6.tgz#dd6788f982c8b77e86779d1d029591e39d9d8be7" - integrity sha512-Iao5Konzx2b6g7EPqTy40UZbcdXE126tTxVFr/nAIj+WItNxjKSYTEw3RC+A2/ZetmdJsgueL1KhaMCQHkLPIg== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/plugin-transform-destructuring" "^7.28.5" - -"@babel/plugin-transform-exponentiation-operator@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.28.6.tgz#5e477eb7eafaf2ab5537a04aaafcf37e2d7f1091" - integrity sha512-WitabqiGjV/vJ0aPOLSFfNY1u9U3R7W36B03r5I2KoNix+a3sOhJ3pKFB3R5It9/UiK78NiO0KE9P21cMhlPkw== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-export-namespace-from@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-7.27.1.tgz#71ca69d3471edd6daa711cf4dfc3400415df9c23" - integrity sha512-tQvHWSZ3/jH2xuq/vZDy0jNn+ZdXJeM8gHvX4lnJmsc3+50yPlWdZXIc5ay+umX+2/tJIqHqiEqcJvxlmIvRvQ== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-for-of@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.27.1.tgz#bc24f7080e9ff721b63a70ac7b2564ca15b6c40a" - integrity sha512-BfbWFFEJFQzLCQ5N8VocnCtA8J1CLkNTe2Ms2wocj75dd6VpiqS5Z5quTYcUoo4Yq+DN0rtikODccuv7RU81sw== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/helper-skip-transparent-expression-wrappers" "^7.27.1" - -"@babel/plugin-transform-function-name@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.27.1.tgz#4d0bf307720e4dce6d7c30fcb1fd6ca77bdeb3a7" - integrity sha512-1bQeydJF9Nr1eBCMMbC+hdwmRlsv5XYOMu03YSWFwNs0HsAmtSxxF1fyuYPqemVldVyFmlCU7w8UE14LupUSZQ== - dependencies: - "@babel/helper-compilation-targets" "^7.27.1" - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/traverse" "^7.27.1" - -"@babel/plugin-transform-json-strings@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.28.6.tgz#4c8c15b2dc49e285d110a4cf3dac52fd2dfc3038" - integrity sha512-Nr+hEN+0geQkzhbdgQVPoqr47lZbm+5fCUmO70722xJZd0Mvb59+33QLImGj6F+DkK3xgDi1YVysP8whD6FQAw== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-literals@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-literals/-/plugin-transform-literals-7.27.1.tgz#baaefa4d10a1d4206f9dcdda50d7d5827bb70b24" - integrity sha512-0HCFSepIpLTkLcsi86GG3mTUzxV5jpmbv97hTETW3yzrAij8aqlD36toB1D0daVFJM8NK6GvKO0gslVQmm+zZA== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-logical-assignment-operators@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.28.6.tgz#53028a3d77e33c50ef30a8fce5ca17065936e605" - integrity sha512-+anKKair6gpi8VsM/95kmomGNMD0eLz1NQ8+Pfw5sAwWH9fGYXT50E55ZpV0pHUHWf6IUTWPM+f/7AAff+wr9A== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-member-expression-literals@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.27.1.tgz#37b88ba594d852418e99536f5612f795f23aeaf9" - integrity sha512-hqoBX4dcZ1I33jCSWcXrP+1Ku7kdqXf1oeah7ooKOIiAdKQ+uqftgCFNOSzA5AMS2XIHEYeGFg4cKRCdpxzVOQ== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-modules-amd@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.27.1.tgz#a4145f9d87c2291fe2d05f994b65dba4e3e7196f" - integrity sha512-iCsytMg/N9/oFq6n+gFTvUYDZQOMK5kEdeYxmxt91fcJGycfxVP9CnrxoliM0oumFERba2i8ZtwRUCMhvP1LnA== - dependencies: - "@babel/helper-module-transforms" "^7.27.1" - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-modules-commonjs@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.28.6.tgz#c0232e0dfe66a734cc4ad0d5e75fc3321b6fdef1" - integrity sha512-jppVbf8IV9iWWwWTQIxJMAJCWBuuKx71475wHwYytrRGQ2CWiDvYlADQno3tcYpS/T2UUWFQp3nVtYfK/YBQrA== - dependencies: - "@babel/helper-module-transforms" "^7.28.6" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-modules-systemjs@^7.27.1": - version "7.29.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.29.4.tgz#f621105da99919c15cf4bde6fcc7346ef95e7b20" - integrity sha512-N7QmZ0xRZfjHOfZeQLJjwgX2zS9pdGHSVl/cjSGlo4dXMqvurfxXDMKY4RqEKzPozV78VMcd0lxyG13mlbKc4w== - dependencies: - "@babel/helper-module-transforms" "^7.28.6" - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/helper-validator-identifier" "^7.28.5" - "@babel/traverse" "^7.29.0" - -"@babel/plugin-transform-modules-umd@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.27.1.tgz#63f2cf4f6dc15debc12f694e44714863d34cd334" - integrity sha512-iQBE/xC5BV1OxJbp6WG7jq9IWiD+xxlZhLrdwpPkTX3ydmXdvoCpyfJN7acaIBZaOqTfr76pgzqBJflNbeRK+w== - dependencies: - "@babel/helper-module-transforms" "^7.27.1" - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-named-capturing-groups-regex@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.27.1.tgz#f32b8f7818d8fc0cc46ee20a8ef75f071af976e1" - integrity sha512-SstR5JYy8ddZvD6MhV0tM/j16Qds4mIpJTOd1Yu9J9pJjH93bxHECF7pgtc28XvkzTD6Pxcm/0Z73Hvk7kb3Ng== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.27.1" - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-new-target@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.27.1.tgz#259c43939728cad1706ac17351b7e6a7bea1abeb" - integrity sha512-f6PiYeqXQ05lYq3TIfIDu/MtliKUbNwkGApPUvyo6+tc7uaR4cPjPe7DFPr15Uyycg2lZU6btZ575CuQoYh7MQ== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-nullish-coalescing-operator@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.28.6.tgz#9bc62096e90ab7a887f3ca9c469f6adec5679757" - integrity sha512-3wKbRgmzYbw24mDJXT7N+ADXw8BC/imU9yo9c9X9NKaLF1fW+e5H1U5QjMUBe4Qo4Ox/o++IyUkl1sVCLgevKg== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-numeric-separator@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.28.6.tgz#1310b0292762e7a4a335df5f580c3320ee7d9e9f" - integrity sha512-SJR8hPynj8outz+SlStQSwvziMN4+Bq99it4tMIf5/Caq+3iOc0JtKyse8puvyXkk3eFRIA5ID/XfunGgO5i6w== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-object-rest-spread@^7.28.0": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.28.6.tgz#fdd4bc2d72480db6ca42aed5c051f148d7b067f7" - integrity sha512-5rh+JR4JBC4pGkXLAcYdLHZjXudVxWMXbB6u6+E9lRL5TrGVbHt1TjxGbZ8CkmYw9zjkB7jutzOROArsqtncEA== - dependencies: - "@babel/helper-compilation-targets" "^7.28.6" - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/plugin-transform-destructuring" "^7.28.5" - "@babel/plugin-transform-parameters" "^7.27.7" - "@babel/traverse" "^7.28.6" - -"@babel/plugin-transform-object-super@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.27.1.tgz#1c932cd27bf3874c43a5cac4f43ebf970c9871b5" - integrity sha512-SFy8S9plRPbIcxlJ8A6mT/CxFdJx/c04JEctz4jf8YZaVS2px34j7NXRrlGlHkN/M2gnpL37ZpGRGVFLd3l8Ng== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/helper-replace-supers" "^7.27.1" - -"@babel/plugin-transform-optional-catch-binding@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.28.6.tgz#75107be14c78385978201a49c86414a150a20b4c" - integrity sha512-R8ja/Pyrv0OGAvAXQhSTmWyPJPml+0TMqXlO5w+AsMEiwb2fg3WkOvob7UxFSL3OIttFSGSRFKQsOhJ/X6HQdQ== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-optional-chaining@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.28.6.tgz#926cf150bd421fc8362753e911b4a1b1ce4356cd" - integrity sha512-A4zobikRGJTsX9uqVFdafzGkqD30t26ck2LmOzAuLL8b2x6k3TIqRiT2xVvA9fNmFeTX484VpsdgmKNA0bS23w== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/helper-skip-transparent-expression-wrappers" "^7.27.1" - -"@babel/plugin-transform-parameters@^7.27.7": - version "7.27.7" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.27.7.tgz#1fd2febb7c74e7d21cf3b05f7aebc907940af53a" - integrity sha512-qBkYTYCb76RRxUM6CcZA5KRu8K4SM8ajzVeUgVdMVO9NN9uI/GaVmBg/WKJJGnNokV9SY8FxNOVWGXzqzUidBg== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-private-methods@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.28.6.tgz#c76fbfef3b86c775db7f7c106fff544610bdb411" - integrity sha512-piiuapX9CRv7+0st8lmuUlRSmX6mBcVeNQ1b4AYzJxfCMuBfB0vBXDiGSmm03pKJw1v6cZ8KSeM+oUnM6yAExg== - dependencies: - "@babel/helper-create-class-features-plugin" "^7.28.6" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-private-property-in-object@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.28.6.tgz#4fafef1e13129d79f1d75ac180c52aafefdb2811" - integrity sha512-b97jvNSOb5+ehyQmBpmhOCiUC5oVK4PMnpRvO7+ymFBoqYjeDHIU9jnrNUuwHOiL9RpGDoKBpSViarV+BU+eVA== - dependencies: - "@babel/helper-annotate-as-pure" "^7.27.3" - "@babel/helper-create-class-features-plugin" "^7.28.6" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-property-literals@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.27.1.tgz#07eafd618800591e88073a0af1b940d9a42c6424" - integrity sha512-oThy3BCuCha8kDZ8ZkgOg2exvPYUlprMukKQXI1r1pJ47NCvxfkEy8vK+r/hT9nF0Aa4H1WUPZZjHTFtAhGfmQ== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-regenerator@^7.28.3": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.28.6.tgz#6ca2ed5b76cff87980f96eaacfc2ce833e8e7a1b" - integrity sha512-eZhoEZHYQLL5uc1gS5e9/oTknS0sSSAtd5TkKMUp3J+S/CaUjagc0kOUPsEbDmMeva0nC3WWl4SxVY6+OBuxfw== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-regexp-modifiers@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-7.28.6.tgz#7ef0163bd8b4a610481b2509c58cf217f065290b" - integrity sha512-QGWAepm9qxpaIs7UM9FvUSnCGlb8Ua1RhyM4/veAxLwt3gMat/LSGrZixyuj4I6+Kn9iwvqCyPTtbdxanYoWYg== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.28.5" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-reserved-words@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.27.1.tgz#40fba4878ccbd1c56605a4479a3a891ac0274bb4" - integrity sha512-V2ABPHIJX4kC7HegLkYoDpfg9PVmuWy/i6vUM5eGK22bx4YVFD3M5F0QQnWQoDs6AGsUWTVOopBiMFQgHaSkVw== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-runtime@7.28.3": - version "7.28.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.28.3.tgz#f5990a1b2d2bde950ed493915e0719841c8d0eaa" - integrity sha512-Y6ab1kGqZ0u42Zv/4a7l0l72n9DKP/MKoKWaUSBylrhNZO2prYuqFOLbn5aW5SIFXwSH93yfjbgllL8lxuGKLg== - dependencies: - "@babel/helper-module-imports" "^7.27.1" - "@babel/helper-plugin-utils" "^7.27.1" - babel-plugin-polyfill-corejs2 "^0.4.14" - babel-plugin-polyfill-corejs3 "^0.13.0" - babel-plugin-polyfill-regenerator "^0.6.5" - semver "^6.3.1" - -"@babel/plugin-transform-shorthand-properties@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.27.1.tgz#532abdacdec87bfee1e0ef8e2fcdee543fe32b90" - integrity sha512-N/wH1vcn4oYawbJ13Y/FxcQrWk63jhfNa7jef0ih7PHSIHX2LB7GWE1rkPrOnka9kwMxb6hMl19p7lidA+EHmQ== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-spread@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-spread/-/plugin-transform-spread-7.28.6.tgz#40a2b423f6db7b70f043ad027a58bcb44a9757b6" - integrity sha512-9U4QObUC0FtJl05AsUcodau/RWDytrU6uKgkxu09mLR9HLDAtUMoPuuskm5huQsoktmsYpI+bGmq+iapDcriKA== - dependencies: - "@babel/helper-plugin-utils" "^7.28.6" - "@babel/helper-skip-transparent-expression-wrappers" "^7.27.1" - -"@babel/plugin-transform-sticky-regex@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.27.1.tgz#18984935d9d2296843a491d78a014939f7dcd280" - integrity sha512-lhInBO5bi/Kowe2/aLdBAawijx+q1pQzicSgnkB6dUPc1+RC8QmJHKf2OjvU+NZWitguJHEaEmbV6VWEouT58g== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-template-literals@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.27.1.tgz#1a0eb35d8bb3e6efc06c9fd40eb0bcef548328b8" - integrity sha512-fBJKiV7F2DxZUkg5EtHKXQdbsbURW3DZKQUWphDum0uRP6eHGGa/He9mc0mypL680pb+e/lDIthRohlv8NCHkg== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-typeof-symbol@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.27.1.tgz#70e966bb492e03509cf37eafa6dcc3051f844369" - integrity sha512-RiSILC+nRJM7FY5srIyc4/fGIwUhyDuuBSdWn4y6yT6gm652DpCHZjIipgn6B7MQ1ITOUnAKWixEUjQRIBIcLw== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-unicode-escapes@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.27.1.tgz#3e3143f8438aef842de28816ece58780190cf806" - integrity sha512-Ysg4v6AmF26k9vpfFuTZg8HRfVWzsh1kVfowA23y9j/Gu6dOuahdUVhkLqpObp3JIv27MLSii6noRnuKN8H0Mg== - dependencies: - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-unicode-property-regex@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.28.6.tgz#63a7a6c21a0e75dae9b1861454111ea5caa22821" - integrity sha512-4Wlbdl/sIZjzi/8St0evF0gEZrgOswVO6aOzqxh1kDZOl9WmLrHq2HtGhnOJZmHZYKP8WZ1MDLCt5DAWwRo57A== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.28.5" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/plugin-transform-unicode-regex@^7.27.1": - version "7.27.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.27.1.tgz#25948f5c395db15f609028e370667ed8bae9af97" - integrity sha512-xvINq24TRojDuyt6JGtHmkVkrfVV3FPT16uytxImLeBZqW3/H52yN+kM1MGuyPkIQxrzKwPHs5U/MP3qKyzkGw== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.27.1" - "@babel/helper-plugin-utils" "^7.27.1" - -"@babel/plugin-transform-unicode-sets-regex@^7.27.1": - version "7.28.6" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.28.6.tgz#924912914e5df9fe615ec472f88ff4788ce04d4e" - integrity sha512-/wHc/paTUmsDYN7SZkpWxogTOBNnlx7nBQYfy6JJlCT7G3mVhltk3e++N7zV0XfgGsrqBxd4rJQt9H16I21Y1Q== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.28.5" - "@babel/helper-plugin-utils" "^7.28.6" - -"@babel/preset-env@7.28.3": - version "7.28.3" - resolved "https://registry.yarnpkg.com/@babel/preset-env/-/preset-env-7.28.3.tgz#2b18d9aff9e69643789057ae4b942b1654f88187" - integrity sha512-ROiDcM+GbYVPYBOeCR6uBXKkQpBExLl8k9HO1ygXEyds39j+vCCsjmj7S8GOniZQlEs81QlkdJZe76IpLSiqpg== - dependencies: - "@babel/compat-data" "^7.28.0" - "@babel/helper-compilation-targets" "^7.27.2" - "@babel/helper-plugin-utils" "^7.27.1" - "@babel/helper-validator-option" "^7.27.1" - "@babel/plugin-bugfix-firefox-class-in-computed-class-key" "^7.27.1" - "@babel/plugin-bugfix-safari-class-field-initializer-scope" "^7.27.1" - "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression" "^7.27.1" - "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining" "^7.27.1" - "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly" "^7.28.3" - "@babel/plugin-proposal-private-property-in-object" "7.21.0-placeholder-for-preset-env.2" - "@babel/plugin-syntax-import-assertions" "^7.27.1" - "@babel/plugin-syntax-import-attributes" "^7.27.1" - "@babel/plugin-syntax-unicode-sets-regex" "^7.18.6" - "@babel/plugin-transform-arrow-functions" "^7.27.1" - "@babel/plugin-transform-async-generator-functions" "^7.28.0" - "@babel/plugin-transform-async-to-generator" "^7.27.1" - "@babel/plugin-transform-block-scoped-functions" "^7.27.1" - "@babel/plugin-transform-block-scoping" "^7.28.0" - "@babel/plugin-transform-class-properties" "^7.27.1" - "@babel/plugin-transform-class-static-block" "^7.28.3" - "@babel/plugin-transform-classes" "^7.28.3" - "@babel/plugin-transform-computed-properties" "^7.27.1" - "@babel/plugin-transform-destructuring" "^7.28.0" - "@babel/plugin-transform-dotall-regex" "^7.27.1" - "@babel/plugin-transform-duplicate-keys" "^7.27.1" - "@babel/plugin-transform-duplicate-named-capturing-groups-regex" "^7.27.1" - "@babel/plugin-transform-dynamic-import" "^7.27.1" - "@babel/plugin-transform-explicit-resource-management" "^7.28.0" - "@babel/plugin-transform-exponentiation-operator" "^7.27.1" - "@babel/plugin-transform-export-namespace-from" "^7.27.1" - "@babel/plugin-transform-for-of" "^7.27.1" - "@babel/plugin-transform-function-name" "^7.27.1" - "@babel/plugin-transform-json-strings" "^7.27.1" - "@babel/plugin-transform-literals" "^7.27.1" - "@babel/plugin-transform-logical-assignment-operators" "^7.27.1" - "@babel/plugin-transform-member-expression-literals" "^7.27.1" - "@babel/plugin-transform-modules-amd" "^7.27.1" - "@babel/plugin-transform-modules-commonjs" "^7.27.1" - "@babel/plugin-transform-modules-systemjs" "^7.27.1" - "@babel/plugin-transform-modules-umd" "^7.27.1" - "@babel/plugin-transform-named-capturing-groups-regex" "^7.27.1" - "@babel/plugin-transform-new-target" "^7.27.1" - "@babel/plugin-transform-nullish-coalescing-operator" "^7.27.1" - "@babel/plugin-transform-numeric-separator" "^7.27.1" - "@babel/plugin-transform-object-rest-spread" "^7.28.0" - "@babel/plugin-transform-object-super" "^7.27.1" - "@babel/plugin-transform-optional-catch-binding" "^7.27.1" - "@babel/plugin-transform-optional-chaining" "^7.27.1" - "@babel/plugin-transform-parameters" "^7.27.7" - "@babel/plugin-transform-private-methods" "^7.27.1" - "@babel/plugin-transform-private-property-in-object" "^7.27.1" - "@babel/plugin-transform-property-literals" "^7.27.1" - "@babel/plugin-transform-regenerator" "^7.28.3" - "@babel/plugin-transform-regexp-modifiers" "^7.27.1" - "@babel/plugin-transform-reserved-words" "^7.27.1" - "@babel/plugin-transform-shorthand-properties" "^7.27.1" - "@babel/plugin-transform-spread" "^7.27.1" - "@babel/plugin-transform-sticky-regex" "^7.27.1" - "@babel/plugin-transform-template-literals" "^7.27.1" - "@babel/plugin-transform-typeof-symbol" "^7.27.1" - "@babel/plugin-transform-unicode-escapes" "^7.27.1" - "@babel/plugin-transform-unicode-property-regex" "^7.27.1" - "@babel/plugin-transform-unicode-regex" "^7.27.1" - "@babel/plugin-transform-unicode-sets-regex" "^7.27.1" - "@babel/preset-modules" "0.1.6-no-external-plugins" - babel-plugin-polyfill-corejs2 "^0.4.14" - babel-plugin-polyfill-corejs3 "^0.13.0" - babel-plugin-polyfill-regenerator "^0.6.5" - core-js-compat "^3.43.0" - semver "^6.3.1" - -"@babel/preset-modules@0.1.6-no-external-plugins": - version "0.1.6-no-external-plugins" - resolved "https://registry.yarnpkg.com/@babel/preset-modules/-/preset-modules-0.1.6-no-external-plugins.tgz#ccb88a2c49c817236861fee7826080573b8a923a" - integrity sha512-HrcgcIESLm9aIR842yhJ5RWan/gebQUJ6E/E5+rf0y9o6oj7w0Br+sWuL6kEQ/o/AdfvR1Je9jG18/gnpwjEyA== - dependencies: - "@babel/helper-plugin-utils" "^7.0.0" - "@babel/types" "^7.4.4" - esutils "^2.0.2" - -"@babel/runtime@7.28.3": - version "7.28.3" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.28.3.tgz#75c5034b55ba868121668be5d5bb31cc64e6e61a" - integrity sha512-9uIQ10o0WGdpP6GDhXcdOJPJuDgFtIDtN/9+ArJQ2NAfAmiuhTQdzkaTGR33v43GYS2UrSA0eX2pPPHoFVvpxA== - -"@babel/template@^7.28.6", "@babel/template@^7.29.7": +"@babel/template@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.29.7.tgz#4d9d4004f645cdd304de958c725162784ecac700" integrity sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg== @@ -1298,7 +546,7 @@ "@babel/parser" "^7.29.7" "@babel/types" "^7.29.7" -"@babel/traverse@^7.27.1", "@babel/traverse@^7.28.0", "@babel/traverse@^7.28.5", "@babel/traverse@^7.28.6", "@babel/traverse@^7.29.0", "@babel/traverse@^7.29.7": +"@babel/traverse@^7.29.7": version "7.29.8" resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.29.8.tgz#4111014cdc71a0f95d9471907590baa0b8a6b28a" integrity sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg== @@ -1311,7 +559,7 @@ "@babel/types" "^7.29.8" debug "^4.3.1" -"@babel/types@^7.24.7", "@babel/types@^7.27.1", "@babel/types@^7.27.3", "@babel/types@^7.28.2", "@babel/types@^7.28.5", "@babel/types@^7.28.6", "@babel/types@^7.29.7", "@babel/types@^7.29.8", "@babel/types@^7.4.4": +"@babel/types@^7.24.7", "@babel/types@^7.27.3", "@babel/types@^7.29.7", "@babel/types@^7.29.8": version "7.29.8" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.29.8.tgz#1229eef31d85156d70fa3f4cd859376d0eaf6863" integrity sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg== @@ -1361,11 +609,6 @@ dependencies: "@jridgewell/trace-mapping" "0.3.9" -"@discoveryjs/json-ext@0.6.3": - version "0.6.3" - resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.6.3.tgz#f13c7c205915eb91ae54c557f5e92bddd8be0e83" - integrity sha512-4B4OijXeVNOPZlYA2oEwWOTkzyltLao+xbotHQeqN++Rv27Y6s818+n2Qkp8q+Fxhn0t/5lA5X1Mxktud8eayQ== - "@es-joy/jsdoccomment@~0.83.0": version "0.83.0" resolved "https://registry.yarnpkg.com/@es-joy/jsdoccomment/-/jsdoccomment-0.83.0.tgz#db1eda42d7e10d81e2dbc871459d556897ab8b8f" @@ -1547,10 +790,10 @@ dependencies: "@types/json-schema" "^7.0.15" -"@eslint/eslintrc@^3.3.5": - version "3.3.6" - resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-3.3.6.tgz#d22bfd6b3a7d8e1f2c0b2f2e6de111b53ec6e13e" - integrity sha512-l2Ul9PrHsPCKcEY/ac7VgFj9D80C7S68sOKc618SyHDPK36s1XcFebXY0iTzUVn4Yq+YbwvSnDmCz9yxjX+QrA== +"@eslint/eslintrc@^3.3.6": + version "3.3.7" + resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-3.3.7.tgz#76d3dedec4a30ea32df797bf8a0085c1311b7316" + integrity sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw== dependencies: ajv "^6.14.0" debug "^4.3.2" @@ -1558,14 +801,14 @@ globals "^14.0.0" ignore "^5.2.0" import-fresh "^3.2.1" - js-yaml "^4.3.0" + js-yaml "^4.3.2" minimatch "^3.1.5" strip-json-comments "^3.1.1" -"@eslint/js@9.39.4": - version "9.39.4" - resolved "https://registry.yarnpkg.com/@eslint/js/-/js-9.39.4.tgz#a3f83bfc6fd9bf33a853dfacd0b49b398eb596c1" - integrity sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw== +"@eslint/js@9.39.5": + version "9.39.5" + resolved "https://registry.yarnpkg.com/@eslint/js/-/js-9.39.5.tgz#6f2fbcff75500d229d535e0a949ae13472c84787" + integrity sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A== "@eslint/object-schema@^2.1.7": version "2.1.7" @@ -1879,14 +1122,6 @@ resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz#7a0ee601f60f99a20c7c7c5ff0c80388c1189bd6" integrity sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw== -"@jridgewell/source-map@^0.3.3": - version "0.3.6" - resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.6.tgz#9d71ca886e32502eb9362c9a74a46787c36df81a" - integrity sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ== - dependencies: - "@jridgewell/gen-mapping" "^0.3.5" - "@jridgewell/trace-mapping" "^0.3.25" - "@jridgewell/sourcemap-codec@^1.4.10", "@jridgewell/sourcemap-codec@^1.4.14", "@jridgewell/sourcemap-codec@^1.5.0": version "1.5.5" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz#6912b00d2c631c0d15ce1a7ab57cd657f2a8f8ba" @@ -1900,7 +1135,7 @@ "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" -"@jridgewell/trace-mapping@^0.3.24", "@jridgewell/trace-mapping@^0.3.25", "@jridgewell/trace-mapping@^0.3.28": +"@jridgewell/trace-mapping@^0.3.24", "@jridgewell/trace-mapping@^0.3.28": version "0.3.31" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz#db15d6781c931f3a251a3dac39501c98a6082fd0" integrity sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw== @@ -1908,171 +1143,6 @@ "@jridgewell/resolve-uri" "^3.1.0" "@jridgewell/sourcemap-codec" "^1.4.14" -"@jsonjoy.com/base64@17.65.0": - version "17.65.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/base64/-/base64-17.65.0.tgz#ba3b023c69ab311e5b706289414a44ee46117824" - integrity sha512-Xrh7Fm/M0QAYpekSgmskdZYnFdSGnsxJ/tHaolA4bNwWdG9i65S8m83Meh7FOxyJyQAdo4d4J97NOomBLEfkDQ== - -"@jsonjoy.com/base64@^1.1.2": - version "1.1.2" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/base64/-/base64-1.1.2.tgz#cf8ea9dcb849b81c95f14fc0aaa151c6b54d2578" - integrity sha512-q6XAnWQDIMA3+FTiOYajoYqySkO+JSat0ytXGSuRdq9uXE7o92gzuQwQM14xaCRlBLGq3v5miDGC4vkVTn54xA== - -"@jsonjoy.com/buffers@17.65.0", "@jsonjoy.com/buffers@^17.65.0": - version "17.65.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/buffers/-/buffers-17.65.0.tgz#d6890737d9cbc49c17e2c5d1a2d796c57205152c" - integrity sha512-eBrIXd0/Ld3p9lpDDlMaMn6IEfWqtHMD+z61u0JrIiPzsV1r7m6xDZFRxJyvIFTEO+SWdYF9EiQbXZGd8BzPfA== - -"@jsonjoy.com/buffers@^1.0.0", "@jsonjoy.com/buffers@^1.2.0": - version "1.2.1" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/buffers/-/buffers-1.2.1.tgz#8d99c7f67eaf724d3428dfd9826c6455266a5c83" - integrity sha512-12cdlDwX4RUM3QxmUbVJWqZ/mrK6dFQH4Zxq6+r1YXKXYBNgZXndx2qbCJwh3+WWkCSn67IjnlG3XYTvmvYtgA== - -"@jsonjoy.com/codegen@17.65.0": - version "17.65.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/codegen/-/codegen-17.65.0.tgz#531524f37fd3e1d1189de18fef346e998eee8952" - integrity sha512-7MXcRYe7n3BG+fo3jicvjB0+6ypl2Y/bQp79Sp7KeSiiCgLqw4Oled6chVv07/xLVTdo3qa1CD0VCCnPaw+RGA== - -"@jsonjoy.com/codegen@^1.0.0": - version "1.0.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/codegen/-/codegen-1.0.0.tgz#5c23f796c47675f166d23b948cdb889184b93207" - integrity sha512-E8Oy+08cmCf0EK/NMxpaJZmOxPqM+6iSe2S4nlSBrPZOORoDJILxtbSUEDKQyTamm/BVAhIGllOBNU79/dwf0g== - -"@jsonjoy.com/fs-core@4.56.10": - version "4.56.10" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/fs-core/-/fs-core-4.56.10.tgz#320728b4b7bef63abb60e7630351623899237411" - integrity sha512-PyAEA/3cnHhsGcdY+AmIU+ZPqTuZkDhCXQ2wkXypdLitSpd6d5Ivxhnq4wa2ETRWFVJGabYynBWxIijOswSmOw== - dependencies: - "@jsonjoy.com/fs-node-builtins" "4.56.10" - "@jsonjoy.com/fs-node-utils" "4.56.10" - thingies "^2.5.0" - -"@jsonjoy.com/fs-fsa@4.56.10": - version "4.56.10" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/fs-fsa/-/fs-fsa-4.56.10.tgz#02bac88c4968ddf2effbd7452861aaed60ba3557" - integrity sha512-/FVK63ysNzTPOnCCcPoPHt77TOmachdMS422txM4KhxddLdbW1fIbFMYH0AM0ow/YchCyS5gqEjKLNyv71j/5Q== - dependencies: - "@jsonjoy.com/fs-core" "4.56.10" - "@jsonjoy.com/fs-node-builtins" "4.56.10" - "@jsonjoy.com/fs-node-utils" "4.56.10" - thingies "^2.5.0" - -"@jsonjoy.com/fs-node-builtins@4.56.10": - version "4.56.10" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/fs-node-builtins/-/fs-node-builtins-4.56.10.tgz#a32a5bcb093f8b34a99aa8957e993a52ec316662" - integrity sha512-uUnKz8R0YJyKq5jXpZtkGV9U0pJDt8hmYcLRrPjROheIfjMXsz82kXMgAA/qNg0wrZ1Kv+hrg7azqEZx6XZCVw== - -"@jsonjoy.com/fs-node-to-fsa@4.56.10": - version "4.56.10" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/fs-node-to-fsa/-/fs-node-to-fsa-4.56.10.tgz#33fc503e50d283ac5fc510e3accced7fccecf2f4" - integrity sha512-oH+O6Y4lhn9NyG6aEoFwIBNKZeYy66toP5LJcDOMBgL99BKQMUf/zWJspdRhMdn/3hbzQsZ8EHHsuekbFLGUWw== - dependencies: - "@jsonjoy.com/fs-fsa" "4.56.10" - "@jsonjoy.com/fs-node-builtins" "4.56.10" - "@jsonjoy.com/fs-node-utils" "4.56.10" - -"@jsonjoy.com/fs-node-utils@4.56.10": - version "4.56.10" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/fs-node-utils/-/fs-node-utils-4.56.10.tgz#788e95052aa99744f6e8e55b5098afc203df2b9e" - integrity sha512-8EuPBgVI2aDPwFdaNQeNpHsyqPi3rr+85tMNG/lHvQLiVjzoZsvxA//Xd8aB567LUhy4QS03ptT+unkD/DIsNg== - dependencies: - "@jsonjoy.com/fs-node-builtins" "4.56.10" - -"@jsonjoy.com/fs-node@4.56.10": - version "4.56.10" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/fs-node/-/fs-node-4.56.10.tgz#70b18bfaf14544a9820d2016e913dde12c6de991" - integrity sha512-7R4Gv3tkUdW3dXfXiOkqxkElxKNVdd8BDOWC0/dbERd0pXpPY+s2s1Mino+aTvkGrFPiY+mmVxA7zhskm4Ue4Q== - dependencies: - "@jsonjoy.com/fs-core" "4.56.10" - "@jsonjoy.com/fs-node-builtins" "4.56.10" - "@jsonjoy.com/fs-node-utils" "4.56.10" - "@jsonjoy.com/fs-print" "4.56.10" - "@jsonjoy.com/fs-snapshot" "4.56.10" - glob-to-regex.js "^1.0.0" - thingies "^2.5.0" - -"@jsonjoy.com/fs-print@4.56.10": - version "4.56.10" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/fs-print/-/fs-print-4.56.10.tgz#7c181b9aefcc1b268be0e6233bff26310c355335" - integrity sha512-JW4fp5mAYepzFsSGrQ48ep8FXxpg4niFWHdF78wDrFGof7F3tKDJln72QFDEn/27M1yHd4v7sKHHVPh78aWcEw== - dependencies: - "@jsonjoy.com/fs-node-utils" "4.56.10" - tree-dump "^1.1.0" - -"@jsonjoy.com/fs-snapshot@4.56.10": - version "4.56.10" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/fs-snapshot/-/fs-snapshot-4.56.10.tgz#05aadd2c0eaa855b13d6cb17d29b7c8cee239c8c" - integrity sha512-DkR6l5fj7+qj0+fVKm/OOXMGfDFCGXLfyHkORH3DF8hxkpDgIHbhf/DwncBMs2igu/ST7OEkexn1gIqoU6Y+9g== - dependencies: - "@jsonjoy.com/buffers" "^17.65.0" - "@jsonjoy.com/fs-node-utils" "4.56.10" - "@jsonjoy.com/json-pack" "^17.65.0" - "@jsonjoy.com/util" "^17.65.0" - -"@jsonjoy.com/json-pack@^1.11.0": - version "1.21.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/json-pack/-/json-pack-1.21.0.tgz#93f8dd57fe3a3a92132b33d1eb182dcd9e7629fa" - integrity sha512-+AKG+R2cfZMShzrF2uQw34v3zbeDYUqnQ+jg7ORic3BGtfw9p/+N6RJbq/kkV8JmYZaINknaEQ2m0/f693ZPpg== - dependencies: - "@jsonjoy.com/base64" "^1.1.2" - "@jsonjoy.com/buffers" "^1.2.0" - "@jsonjoy.com/codegen" "^1.0.0" - "@jsonjoy.com/json-pointer" "^1.0.2" - "@jsonjoy.com/util" "^1.9.0" - hyperdyperid "^1.2.0" - thingies "^2.5.0" - tree-dump "^1.1.0" - -"@jsonjoy.com/json-pack@^17.65.0": - version "17.65.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/json-pack/-/json-pack-17.65.0.tgz#4ea06dd0aee1c29954bd978c4f107401dbf713fb" - integrity sha512-e0SG/6qUCnVhHa0rjDJHgnXnbsacooHVqQHxspjvlYQSkHm+66wkHw6Gql+3u/WxI/b1VsOdUi0M+fOtkgKGdQ== - dependencies: - "@jsonjoy.com/base64" "17.65.0" - "@jsonjoy.com/buffers" "17.65.0" - "@jsonjoy.com/codegen" "17.65.0" - "@jsonjoy.com/json-pointer" "17.65.0" - "@jsonjoy.com/util" "17.65.0" - hyperdyperid "^1.2.0" - thingies "^2.5.0" - tree-dump "^1.1.0" - -"@jsonjoy.com/json-pointer@17.65.0": - version "17.65.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/json-pointer/-/json-pointer-17.65.0.tgz#4bad42d86c9ee0ad1758c082b065bd5e16f8dc36" - integrity sha512-uhTe+XhlIZpWOxgPcnO+iSCDgKKBpwkDVTyYiXX9VayGV8HSFVJM67M6pUE71zdnXF1W0Da21AvnhlmdwYPpow== - dependencies: - "@jsonjoy.com/util" "17.65.0" - -"@jsonjoy.com/json-pointer@^1.0.2": - version "1.0.2" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/json-pointer/-/json-pointer-1.0.2.tgz#049cb530ac24e84cba08590c5e36b431c4843408" - integrity sha512-Fsn6wM2zlDzY1U+v4Nc8bo3bVqgfNTGcn6dMgs6FjrEnt4ZCe60o6ByKRjOGlI2gow0aE/Q41QOigdTqkyK5fg== - dependencies: - "@jsonjoy.com/codegen" "^1.0.0" - "@jsonjoy.com/util" "^1.9.0" - -"@jsonjoy.com/util@17.65.0", "@jsonjoy.com/util@^17.65.0": - version "17.65.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/util/-/util-17.65.0.tgz#b27832bdf7aeaf4a36f9cb8721cb4ffb086f06a1" - integrity sha512-cWiEHZccQORf96q2y6zU3wDeIVPeidmGqd9cNKJRYoVHTV0S1eHPy5JTbHpMnGfDvtvujQwQozOqgO9ABu6h0w== - dependencies: - "@jsonjoy.com/buffers" "17.65.0" - "@jsonjoy.com/codegen" "17.65.0" - -"@jsonjoy.com/util@^1.9.0": - version "1.9.0" - resolved "https://registry.yarnpkg.com/@jsonjoy.com/util/-/util-1.9.0.tgz#7ee95586aed0a766b746cd8d8363e336c3c47c46" - integrity sha512-pLuQo+VPRnN8hfPqUTLTHk126wuYdXVxE6aDmjSeV4NCAgyxWbiOIeNJVtID3h1Vzpoi9m4jXezf73I6LgabgQ== - dependencies: - "@jsonjoy.com/buffers" "^1.0.0" - "@jsonjoy.com/codegen" "^1.0.0" - -"@leichtgewicht/ip-codec@^2.0.1": - version "2.0.5" - resolved "https://registry.yarnpkg.com/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz#4fc56c15c580b9adb7dc3c333a134e540b44bfb1" - integrity sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw== - "@listr2/prompt-adapter-inquirer@3.0.1": version "3.0.1" resolved "https://registry.yarnpkg.com/@listr2/prompt-adapter-inquirer/-/prompt-adapter-inquirer-3.0.1.tgz#7e081b4dcde2f1bd5ac16c620ee2402908f03fe7" @@ -2115,59 +1185,70 @@ resolved "https://registry.yarnpkg.com/@lmdb/lmdb-win32-x64/-/lmdb-win32-x64-3.4.2.tgz#99caf114bb74d39c9e1baca99b907353ad8bf461" integrity sha512-IY+r3bxKW6Q6sIPiMC0L533DEfRJSXibjSI3Ft/w9Q8KQBNqEIvUFXt+09wV8S5BRk0a8uSF19YWxuRwEfI90g== -"@mapbox/geojson-rewind@^0.5.2": - version "0.5.2" - resolved "https://registry.yarnpkg.com/@mapbox/geojson-rewind/-/geojson-rewind-0.5.2.tgz#591a5d71a9cd1da1a0bf3420b3bea31b0fc7946a" - integrity sha512-tJaT+RbYGJYStt7wI3cq4Nl4SXxG8W7JDG5DMJu97V25RnbNg3QtQtf+KD+VLjNpWKYsRvXDNmNrBgEETr1ifA== - dependencies: - get-stream "^6.0.1" - minimist "^1.2.6" - -"@mapbox/jsonlint-lines-primitives@^2.0.2", "@mapbox/jsonlint-lines-primitives@~2.0.2": - version "2.0.2" - resolved "https://registry.yarnpkg.com/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.2.tgz#ce56e539f83552b58d10d672ea4d6fc9adc7b234" - integrity sha512-rY0o9A5ECsTQRVhv7tL/OyDpGAoUB4tTvLiW1DSzQGq4bvTPhNw1VpSNjDJc5GFZ2XuyOtSWSVN05qOtcD71qQ== +"@mapbox/jsonlint-lines-primitives@^2.0.3": + version "2.0.3" + resolved "https://registry.yarnpkg.com/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.3.tgz#7d7b0b971fbaf6d60953272db4df03020d3fb004" + integrity sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg== -"@mapbox/point-geometry@0.1.0", "@mapbox/point-geometry@^0.1.0", "@mapbox/point-geometry@~0.1.0": - version "0.1.0" - resolved "https://registry.yarnpkg.com/@mapbox/point-geometry/-/point-geometry-0.1.0.tgz#8a83f9335c7860effa2eeeca254332aa0aeed8f2" - integrity sha512-6j56HdLTwWGO0fJPlrZtdU/B13q8Uwmo18Ck2GnGgN9PCFyKTZ3UbXeEdRFh18i9XQ92eH2VdtpJHpBD3aripQ== +"@mapbox/point-geometry@^1.1.0", "@mapbox/point-geometry@~1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz#3328fb54b3a1273bc619bf0a6baad8de37181749" + integrity sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ== -"@mapbox/tiny-sdf@^2.0.6": - version "2.0.7" - resolved "https://registry.yarnpkg.com/@mapbox/tiny-sdf/-/tiny-sdf-2.0.7.tgz#0d67d65a43195003b282764f2297c619736bbc6e" - integrity sha512-25gQLQMcpivjOSA40g3gO6qgiFPDpWRoMfd+G/GoppPIeP6JDaMMkMrEJnMZhKyyS6iKwVt5YKu02vCUyJM3Ug== +"@mapbox/tiny-sdf@^2.2.0": + version "2.2.0" + resolved "https://registry.yarnpkg.com/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz#95dae0dc371b8c55c53d70f3e25d56823427f4c8" + integrity sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg== -"@mapbox/unitbezier@^0.0.1": - version "0.0.1" - resolved "https://registry.yarnpkg.com/@mapbox/unitbezier/-/unitbezier-0.0.1.tgz#d32deb66c7177e9e9dfc3bbd697083e2e657ff01" - integrity sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw== +"@mapbox/unitbezier@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@mapbox/unitbezier/-/unitbezier-1.0.0.tgz#54319aff6c467bb1b909e04895c08cdb966bfbff" + integrity sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ== -"@mapbox/vector-tile@^1.3.1": - version "1.3.1" - resolved "https://registry.yarnpkg.com/@mapbox/vector-tile/-/vector-tile-1.3.1.tgz#d3a74c90402d06e89ec66de49ec817ff53409666" - integrity sha512-MCEddb8u44/xfQ3oD+Srl/tNcQoqTw3goGk2oLsrFxOTc3dUp+kAnby3PvAeeBYSMSjSPD1nd1AJA6W49WnoUw== +"@mapbox/vector-tile@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@mapbox/vector-tile/-/vector-tile-3.0.0.tgz#71a75acb5ee20c20adca5c4e1ffb5ef95a56e351" + integrity sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q== dependencies: - "@mapbox/point-geometry" "~0.1.0" + "@mapbox/point-geometry" "~1.1.0" + "@types/geojson" "^7946.0.16" + pbf "^5.0.0" -"@mapbox/whoots-js@^3.1.0": - version "3.1.0" - resolved "https://registry.yarnpkg.com/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz#497c67a1cef50d1a2459ba60f315e448d2ad87fe" - integrity sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q== +"@maplibre/geojson-vt@^6.1.1": + version "6.1.1" + resolved "https://registry.yarnpkg.com/@maplibre/geojson-vt/-/geojson-vt-6.1.1.tgz#25a032435b4ce2236ea0ba911aff5fb6d5454fc1" + integrity sha512-FVMOcmSP/yqol45t7StApEyTL5/vmqBCuFhH9n+fFuINenhaX+YgHHIt1yJ86S8kln3uJLcMvmEU2cfn6E2eCQ== + dependencies: + kdbush "^4.1.0" -"@maplibre/maplibre-gl-style-spec@^23.1.0": - version "23.3.0" - resolved "https://registry.yarnpkg.com/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-23.3.0.tgz#b69ab48cb3abead4e49213396c8f83492638b97c" - integrity sha512-IGJtuBbaGzOUgODdBRg66p8stnwj9iDXkgbYKoYcNiiQmaez5WVRfXm4b03MCDwmZyX93csbfHFWEJJYHnn5oA== +"@maplibre/maplibre-gl-style-spec@^26.4.4": + version "26.4.4" + resolved "https://registry.yarnpkg.com/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.4.tgz#e103d50f9eed8a44f1fde1c4970c5d2a47b19b78" + integrity sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA== dependencies: - "@mapbox/jsonlint-lines-primitives" "~2.0.2" - "@mapbox/unitbezier" "^0.0.1" + "@mapbox/jsonlint-lines-primitives" "^2.0.3" + "@mapbox/unitbezier" "^1.0.0" json-stringify-pretty-compact "^4.0.0" minimist "^1.2.8" quickselect "^3.0.0" - rw "^1.3.3" tinyqueue "^3.0.0" +"@maplibre/mlt@^1.3.0": + version "1.3.0" + resolved "https://registry.yarnpkg.com/@maplibre/mlt/-/mlt-1.3.0.tgz#3a9467d12a0b6edfcdba429dd3a260ca48f11129" + integrity sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + +"@maplibre/vt-pbf@^4.3.2": + version "4.3.2" + resolved "https://registry.yarnpkg.com/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz#cfcdbdadaf88b4cb8645e43c8eead77cd6546030" + integrity sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + "@types/geojson" "^7946.0.16" + pbf "^5.1.0" + "@mat-datetimepicker/core@~16.0.1": version "16.0.1" resolved "https://registry.yarnpkg.com/@mat-datetimepicker/core/-/core-16.0.1.tgz#f2b19b6ed85f83a83f93be866af1a9564ac0d978" @@ -2187,46 +1268,46 @@ dependencies: langium "^4.0.0" -"@messageformat/core@^3.4.0": - version "3.4.0" - resolved "https://registry.yarnpkg.com/@messageformat/core/-/core-3.4.0.tgz#2814c23383dec7bddf535d54f2a03e410165ca9f" - integrity sha512-NgCFubFFIdMWJGN5WuQhHCNmzk7QgiVfrViFxcS99j7F5dDS5EP6raR54I+2ydhe4+5/XTn/YIEppFaqqVWHsw== +"@messageformat/core@^3.4.1": + version "3.4.1" + resolved "https://registry.yarnpkg.com/@messageformat/core/-/core-3.4.1.tgz#85b4dd381c3caf1bb2a5c4984de87c91518c998f" + integrity sha512-98uXHLDjPe2WZ8Xr05MhFQGfpMRbUcJDEYgjLV5ZBTgnntIkKS0VKGE+g8ug/hbgggyPEAeZBRJryIsBUp1vvw== dependencies: - "@messageformat/date-skeleton" "^1.0.0" - "@messageformat/number-skeleton" "^1.0.0" - "@messageformat/parser" "^5.1.0" - "@messageformat/runtime" "^3.0.1" + "@messageformat/date-skeleton" "2.0.0-0" + "@messageformat/number-skeleton" "2.0.0-0" + "@messageformat/parser" "^5.2.0" + "@messageformat/runtime" "^3.0.3" make-plural "^7.0.0" safe-identifier "^0.4.1" -"@messageformat/date-skeleton@^1.0.0": - version "1.1.0" - resolved "https://registry.yarnpkg.com/@messageformat/date-skeleton/-/date-skeleton-1.1.0.tgz#3bad068cbf5873d14592cfc7a73dd4d8615e2739" - integrity sha512-rmGAfB1tIPER+gh3p/RgA+PVeRE/gxuQ2w4snFWPF5xtb5mbWR7Cbw7wCOftcUypbD6HVoxrVdyyghPm3WzP5A== +"@messageformat/date-skeleton@2.0.0-0": + version "2.0.0-0" + resolved "https://registry.yarnpkg.com/@messageformat/date-skeleton/-/date-skeleton-2.0.0-0.tgz#a2b2038b49d7c5c1972bd56d3deca10ec739e3d4" + integrity sha512-gkCatAK4MYlhjKYWxkfRM6Ql0M1VmA1DK6A9rszUBprZpQox/XqX987AI2w7YoEz0p5DgkPOpI6PK1mW08yNqQ== -"@messageformat/number-skeleton@^1.0.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@messageformat/number-skeleton/-/number-skeleton-1.2.0.tgz#e7c245c41a1b2722bc59dad68f4d454f761bc9b4" - integrity sha512-xsgwcL7J7WhlHJ3RNbaVgssaIwcEyFkBqxHdcdaiJzwTZAWEOD8BuUFxnxV9k5S0qHN3v/KzUpq0IUpjH1seRg== +"@messageformat/number-skeleton@2.0.0-0": + version "2.0.0-0" + resolved "https://registry.yarnpkg.com/@messageformat/number-skeleton/-/number-skeleton-2.0.0-0.tgz#cbb72acbabd76f9258c16de3837ed96cd8b68f1f" + integrity sha512-bDrIrVSKwn0sNrbU+N6tjwljV+Zl9pRCR/D9Xim6Q7lLzZ20nFYtuuKOZ3QKisN+vPxa9sTqu3ufJ+uwKNpHbQ== -"@messageformat/parser@^5.1.0": - version "5.1.0" - resolved "https://registry.yarnpkg.com/@messageformat/parser/-/parser-5.1.0.tgz#05e4851c782d633ad735791dd0a68ee65d2a7201" - integrity sha512-jKlkls3Gewgw6qMjKZ9SFfHUpdzEVdovKFtW1qRhJ3WI4FW5R/NnGDqr8SDGz+krWDO3ki94boMmQvGke1HwUQ== +"@messageformat/parser@^5.2.0": + version "5.2.0" + resolved "https://registry.yarnpkg.com/@messageformat/parser/-/parser-5.2.0.tgz#8a476fadea25e1bb7835aaf806eb3f5ad2fb4f8a" + integrity sha512-sc3hNZ0JtC32GhL5nUgPbh2ilcwji4G+Vmj/vhMd8hZaH//NDOvkfwKK1mFnRWG5h2DpksN8xr/HB5/+vMg3iw== dependencies: moo "^0.5.1" -"@messageformat/runtime@^3.0.1": - version "3.0.1" - resolved "https://registry.yarnpkg.com/@messageformat/runtime/-/runtime-3.0.1.tgz#94d1f6c43265c28ef7aed98ecfcc0968c6c849ac" - integrity sha512-6RU5ol2lDtO8bD9Yxe6CZkl0DArdv0qkuoZC+ZwowU+cdRlVE1157wjCmlA5Rsf1Xc/brACnsZa5PZpEDfTFFg== +"@messageformat/runtime@^3.0.3": + version "3.0.3" + resolved "https://registry.yarnpkg.com/@messageformat/runtime/-/runtime-3.0.3.tgz#38741ccb348d561bd8c556597f43e1e6363a842d" + integrity sha512-FE0hP0m15+9p/ia5HWQ/JsUSNLcxZkl1jl1HlRrWCiMAsgiulg7AuOFLaBR6dpPqtPWWuApY7VLo3rIAcrgrkA== dependencies: make-plural "^7.0.0" -"@modelcontextprotocol/sdk@1.30.0": - version "1.30.0" - resolved "https://registry.yarnpkg.com/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz#dfa8a48347ec2d2c0d47917d7dc57f754e37f5ff" - integrity sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA== +"@modelcontextprotocol/sdk@1.31.0", "@modelcontextprotocol/sdk@1.32.1": + version "1.32.1" + resolved "https://registry.yarnpkg.com/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz#853286b3240b6d8143f5f8e6d58af85c77d475ab" + integrity sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw== dependencies: "@hono/node-server" "^1.19.9 || ^2.0.5" ajv "^8.17.1" @@ -2412,11 +1493,6 @@ dependencies: tslib "^2.0.0" -"@ngtools/webpack@20.3.34": - version "20.3.34" - resolved "https://registry.yarnpkg.com/@ngtools/webpack/-/webpack-20.3.34.tgz#22ed9dd4afec7285cb944aa773e7889997314eee" - integrity sha512-YLnHgzZUmR8zYAD77HUK6rE49/6KYgvTx0aNRGqEV3r67Iue3CcQdbulwNUCtJbX/tWhW4E0j9WpjVhx9Ulb7A== - "@ngx-translate/core@^17.0.0": version "17.0.0" resolved "https://registry.yarnpkg.com/@ngx-translate/core/-/core-17.0.0.tgz#d6c0738c5004b53273bc97e6ca5488f6a6816f25" @@ -2424,11 +1500,6 @@ dependencies: tslib "^2.3.0" -"@noble/hashes@1.4.0": - version "1.4.0" - resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.4.0.tgz#45814aa329f30e4fe0ba49426f49dfccdd066426" - integrity sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg== - "@nodelib/fs.scandir@2.1.5": version "2.1.5" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5" @@ -2626,136 +1697,6 @@ "@parcel/watcher-win32-ia32" "2.5.6" "@parcel/watcher-win32-x64" "2.5.6" -"@peculiar/asn1-cms@^2.6.0", "@peculiar/asn1-cms@^2.9.3": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-cms/-/asn1-cms-2.9.3.tgz#6b37ef792477b4af803e1cbcc1ede95281860704" - integrity sha512-N3POfw5RA7efAliAATiudtmvKQqukVEOzrMQuqQY/us2EPKczMy2WiecLt1SX6s3b0OwcFaPUXGF6uIYlBUTbg== - dependencies: - "@peculiar/asn1-schema" "^2.9.3" - "@peculiar/asn1-x509" "^2.9.3" - "@peculiar/asn1-x509-attr" "^2.9.3" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-csr@^2.6.0": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-csr/-/asn1-csr-2.9.3.tgz#eab9270c844ae894b6123cd03c2dee871772ded3" - integrity sha512-E9zYmC5mk7eiDKqQAOsZGrJ7mUCIDC0031s4Nsl7dj1Za5EBKcHVqY+1vD/a4xbk480PGqvi455W2b4FeHRJ8Q== - dependencies: - "@peculiar/asn1-schema" "^2.9.3" - "@peculiar/asn1-x509" "^2.9.3" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-ecc@^2.6.0": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-ecc/-/asn1-ecc-2.9.3.tgz#4a167c8ed47d35c95bda10eec8d9db3066e9fb3f" - integrity sha512-4xmeZiZ46VI2qGbiZPzdv6p9IhMtjWdbwZf3VCgN8OAVcued60ej5Ki2FF94srVH4Ot/h45Co7T5C/fpQXP4rA== - dependencies: - "@peculiar/asn1-schema" "^2.9.3" - "@peculiar/asn1-x509" "^2.9.3" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-pfx@^2.9.3": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-pfx/-/asn1-pfx-2.9.3.tgz#8344148158b056b041e8c2854704f9004072cb8f" - integrity sha512-Nzwoj+fRr1XB9CQuc4AanUuvQ3OIXAY+ngZIYP+eZUqd+Sonj+ZHTnrg+egQuUJ64/iMi9HFPN04MokGrFTK0w== - dependencies: - "@peculiar/asn1-cms" "^2.9.3" - "@peculiar/asn1-pkcs8" "^2.9.3" - "@peculiar/asn1-rsa" "^2.9.3" - "@peculiar/asn1-schema" "^2.9.3" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-pkcs8@^2.9.3": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.9.3.tgz#191b877fb7201798a4d242160230601e422e87f3" - integrity sha512-ecGZpkY6Lq5bSgTFU+LS74WjawzDgjWHcjFMVNPH/1C0j53Xi9dmLcPMdmZyk8gdsd2RKeV1fP9EbLB6W6zZ1g== - dependencies: - "@peculiar/asn1-schema" "^2.9.3" - "@peculiar/asn1-x509" "^2.9.3" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-pkcs9@^2.6.0": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.9.3.tgz#275b4b3e00849e58d17620561f3f2a4e3512390c" - integrity sha512-yjWVrQEmPp2y9lWjLLE28BRHbt7wYdwWvwXjFgNuekP9mDD/ofz31muVI8qOg2as7XZs1bZIZGPPnJ/0osTClQ== - dependencies: - "@peculiar/asn1-cms" "^2.9.3" - "@peculiar/asn1-pfx" "^2.9.3" - "@peculiar/asn1-pkcs8" "^2.9.3" - "@peculiar/asn1-schema" "^2.9.3" - "@peculiar/asn1-x509" "^2.9.3" - "@peculiar/asn1-x509-attr" "^2.9.3" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-rsa@^2.6.0", "@peculiar/asn1-rsa@^2.9.3": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-rsa/-/asn1-rsa-2.9.3.tgz#9b73ff82e2f88cb2da952e4991cb053df49e5b9d" - integrity sha512-t7m3e9p/Gf9YoMM+hLsHUqB+NhOlifiOkENAIG4RV2BFWVGTATVzbXoR8L0EgNWpiriPaeIjBCS5B9PTtkaxQw== - dependencies: - "@peculiar/asn1-schema" "^2.9.3" - "@peculiar/asn1-x509" "^2.9.3" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-schema@^2.6.0", "@peculiar/asn1-schema@^2.9.3": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-schema/-/asn1-schema-2.9.3.tgz#13398a990b8b89f003e720db9876511af0974a35" - integrity sha512-SOux4+jikCnOwoJvpBp/grOqzFmJPnNSwe3sAg1Bn93YdmCiDtvolZifJIhiRq0UWMTnLRPj9/ZCMAc2W9VsMQ== - dependencies: - "@peculiar/utils" "^2.0.2" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-x509-attr@^2.9.3": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.9.3.tgz#0f791e33f39b786d74d0485225aa4d061bc205f8" - integrity sha512-v5Oa6p7hCT3ONqYHQyTFQYcycD06eMhHbr0m7evpvPQSpWJIq8GgbdnvA9bVGTUlOx6KOeDrX7Z0W4s/yboNTg== - dependencies: - "@peculiar/asn1-schema" "^2.9.3" - "@peculiar/asn1-x509" "^2.9.3" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/asn1-x509@^2.6.0", "@peculiar/asn1-x509@^2.9.3": - version "2.9.3" - resolved "https://registry.yarnpkg.com/@peculiar/asn1-x509/-/asn1-x509-2.9.3.tgz#e029a18de8f06bf8f061b26a2296193e3af29db3" - integrity sha512-HE+ejy9dX9JP3yLL6CGYoWym4Cted1lGXH7DxsbNDGiq8KabwVR7mzYidwsyNZ/m0hNWjiS+dzSwrsgMB/OIaQ== - dependencies: - "@peculiar/asn1-schema" "^2.9.3" - "@peculiar/utils" "^2.0.2" - asn1js "^3.0.10" - tslib "^2.8.1" - -"@peculiar/utils@^2.0.2": - version "2.0.3" - resolved "https://registry.yarnpkg.com/@peculiar/utils/-/utils-2.0.3.tgz#a27ca4c4b73652e110f19a7d16d664f458a5528e" - integrity sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ== - dependencies: - tslib "^2.8.1" - -"@peculiar/x509@^1.14.2": - version "1.14.3" - resolved "https://registry.yarnpkg.com/@peculiar/x509/-/x509-1.14.3.tgz#2c44c2b89474346afec38a0c2803ec4fb8ce959e" - integrity sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA== - dependencies: - "@peculiar/asn1-cms" "^2.6.0" - "@peculiar/asn1-csr" "^2.6.0" - "@peculiar/asn1-ecc" "^2.6.0" - "@peculiar/asn1-pkcs9" "^2.6.0" - "@peculiar/asn1-rsa" "^2.6.0" - "@peculiar/asn1-schema" "^2.6.0" - "@peculiar/asn1-x509" "^2.6.0" - pvtsutils "^1.3.6" - reflect-metadata "^0.2.2" - tslib "^2.8.1" - tsyringe "^4.10.0" - "@pkgjs/parseargs@^0.11.0": version "0.11.0" resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" @@ -2901,13 +1842,13 @@ resolved "https://registry.yarnpkg.com/@sanity/diff-match-patch/-/diff-match-patch-3.2.0.tgz#7ce587273f7372a146308cb1075ba26177d42cdb" integrity sha512-4hPADs0qUThFZkBK/crnfKKHg71qkRowfktBljH2UIxGHHTxIzt8g8fBiXItyCjxkuNy+zpYOdRMifQNv8+Yww== -"@schematics/angular@20.3.34": - version "20.3.34" - resolved "https://registry.yarnpkg.com/@schematics/angular/-/angular-20.3.34.tgz#900f8d33eb3bf3c815361080a76178192363d523" - integrity sha512-Yja14zhlb59TaADWx2/4FptSJ85FuhSfSlB6RgQx9t8N7mVLNyUVhxBw6RaCcgazhSP4i4XcgOvY9pMiqO8a2g== +"@schematics/angular@20.3.40": + version "20.3.40" + resolved "https://registry.yarnpkg.com/@schematics/angular/-/angular-20.3.40.tgz#e80cc5237ebe2a7432496262fd76828c0bb0a66d" + integrity sha512-jU12K5YJUpK7bsPhWUgxoZf0R1fkt6z+AiOu+qHybQgWRmV8VuwZhPsp4N6lwMUkRrNmPOgk2143xNmTXEBjcQ== dependencies: - "@angular-devkit/core" "20.3.34" - "@angular-devkit/schematics" "20.3.34" + "@angular-devkit/core" "20.3.40" + "@angular-devkit/schematics" "20.3.40" jsonc-parser "3.3.1" "@sigstore/bundle@^4.0.0": @@ -2961,24 +1902,20 @@ resolved "https://registry.yarnpkg.com/@sindresorhus/base62/-/base62-1.0.0.tgz#c47c42410e5212e4fa4657670e118ddfba39acd6" integrity sha512-TeheYy0ILzBEI/CO55CP6zJCSdSWeRtGnHy8U8dWSUH4I68iqTsy7HkMktR4xakThc9jotkPQUXT4ITdbV7cHA== -"@svgdotjs/svg.filter.js@^3.0.9": - version "3.0.9" - resolved "https://registry.yarnpkg.com/@svgdotjs/svg.filter.js/-/svg.filter.js-3.0.9.tgz#758e336b79e73a6797358d655b60842131a9a52b" - integrity sha512-/69XMRCDoam2HgC4ldHIaDgeQf1ViHIsa0Ld4uWgiXtZ+E24DWHe/9Ib6kbNiZ7WRIdlVokUDR1Fg0kjIpkfbw== - dependencies: - "@svgdotjs/svg.js" "^3.2.4" +"@svgdotjs/svg.filter.js@^3.0.10": + version "3.0.10" + resolved "https://registry.yarnpkg.com/@svgdotjs/svg.filter.js/-/svg.filter.js-3.0.10.tgz#c47bb8c0a9c38cc0515337cbd85544e6320e96d8" + integrity sha512-ynuqRmTRiQgy0XDV/aVV63+RMAAGxRa3qRxb0rowTFRfEJ7qJZ/CbMSuH87/TP1j1zauQhE48DFWQcxrxBv5aQ== -"@svgdotjs/svg.js@3.2.4", "@svgdotjs/svg.js@^3.0.16", "@svgdotjs/svg.js@^3.2.4": - version "3.2.4" - resolved "https://registry.yarnpkg.com/@svgdotjs/svg.js/-/svg.js-3.2.4.tgz#4716be92a64c66b29921b63f7235fcfb953fb13a" - integrity sha512-BjJ/7vWNowlX3Z8O4ywT58DqbNRyYlkk6Yz/D13aB7hGmfQTvGX4Tkgtm/ApYlu9M7lCQi15xUEidqMUmdMYwg== +"@svgdotjs/svg.js@3.2.8": + version "3.2.8" + resolved "https://registry.yarnpkg.com/@svgdotjs/svg.js/-/svg.js-3.2.8.tgz#1b16c8792407f25e265f9326143bcb55fb85754c" + integrity sha512-NUdbI/7FDdqGpzKmqr09IQoy9MUcrAC/3bC8gLgXi6OfJuyri450zMLvJekFUhuq3iN5gpdPjoSoStNl9Eijfg== -"@svgdotjs/svg.panzoom.js@^2.1.2": - version "2.1.2" - resolved "https://registry.yarnpkg.com/@svgdotjs/svg.panzoom.js/-/svg.panzoom.js-2.1.2.tgz#50e66a861f7c4f9e3992707f8e62e6e8da5c5223" - integrity sha512-0Nzo2TRlTebW3pzfAPtHx8Ye7Y3kuMEkK7hwVJi0SgQUB/vstjg7fvCJxB++EqsuDEetP0/SC+4CpLMVm6Lh2g== - dependencies: - "@svgdotjs/svg.js" "^3.0.16" +"@svgdotjs/svg.panzoom.js@^2.1.3": + version "2.1.3" + resolved "https://registry.yarnpkg.com/@svgdotjs/svg.panzoom.js/-/svg.panzoom.js-2.1.3.tgz#b6f0686f7ef195e8690210f1a71d932df03c9eb8" + integrity sha512-FJY+teGwGV6cQLNn9pTMLJSeLBUtQPcFb0dF4ebmdCZ41DC6kMQBI28aVOKoI6rNq08ovFYjS4iWneBri39YKQ== "@tsconfig/node10@^1.0.7": version "1.0.11" @@ -3180,41 +2117,11 @@ resolved "https://registry.yarnpkg.com/@types/ace-diff/-/ace-diff-2.1.4.tgz#0bf9952c9b23fb3cb6f5cf96f1e8bbed8f603fcd" integrity sha512-Jd9J35hi9PdsQzAAXWzPlXTuxRxnxuaNBMzBNts3EUDoQ8yuWp4Y36GjPASke8D6yVwKrapOnAaVp3km/CxPRw== -"@types/body-parser@*": - version "1.19.5" - resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.5.tgz#04ce9a3b677dc8bd681a17da1ab9835dc9d3ede4" - integrity sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg== - dependencies: - "@types/connect" "*" - "@types/node" "*" - -"@types/bonjour@^3.5.13": - version "3.5.13" - resolved "https://registry.yarnpkg.com/@types/bonjour/-/bonjour-3.5.13.tgz#adf90ce1a105e81dd1f9c61fdc5afda1bfb92956" - integrity sha512-z9fJ5Im06zvUL548KvYNecEVlA7cVDkGUi6kZusb04mpyEFKCIZJvloCcmpmLaIahDpOQGHaHmG6imtPMmPXGQ== - dependencies: - "@types/node" "*" - "@types/canvas-gauges@^2.1.8": version "2.1.8" resolved "https://registry.yarnpkg.com/@types/canvas-gauges/-/canvas-gauges-2.1.8.tgz#5bdd199c598fd45f8618127bec2e2f4e49d7477f" integrity sha512-sbxlEPEPnEYfvzC/yPIJZNkxKfAJaI45dxnQrkg3g2l3+1lWX6lwduRo8+hrsDw7VdJ5ijuRi1sQ7XBFu1R2qg== -"@types/connect-history-api-fallback@^1.5.4": - version "1.5.4" - resolved "https://registry.yarnpkg.com/@types/connect-history-api-fallback/-/connect-history-api-fallback-1.5.4.tgz#7de71645a103056b48ac3ce07b3520b819c1d5b3" - integrity sha512-n6Cr2xS1h4uAulPRdlw6Jl6s1oG8KrVilPN2yUITEs+K48EzMJJ3W1xy8K5eWuFvjp3R74AOIGSmp2UfBJ8HFw== - dependencies: - "@types/express-serve-static-core" "*" - "@types/node" "*" - -"@types/connect@*": - version "3.4.38" - resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.38.tgz#5ba7f3bc4fbbdeaff8dded952e5ff2cc53f8d858" - integrity sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug== - dependencies: - "@types/node" "*" - "@types/d3-array@*": version "3.2.2" resolved "https://registry.yarnpkg.com/@types/d3-array/-/d3-array-3.2.2.tgz#e02151464d02d4a1b44646d0fcdb93faf88fde8c" @@ -3425,72 +2332,16 @@ "@types/d3-transition" "*" "@types/d3-zoom" "*" -"@types/eslint-scope@^3.7.7": - version "3.7.7" - resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.7.tgz#3108bd5f18b0cdb277c867b3dd449c9ed7079ac5" - integrity sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg== - dependencies: - "@types/eslint" "*" - "@types/estree" "*" - -"@types/eslint@*": - version "9.6.1" - resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-9.6.1.tgz#d5795ad732ce81715f27f75da913004a56751584" - integrity sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag== - dependencies: - "@types/estree" "*" - "@types/json-schema" "*" - "@types/esrecurse@^4.3.1": version "4.3.1" resolved "https://registry.yarnpkg.com/@types/esrecurse/-/esrecurse-4.3.1.tgz#6f636af962fbe6191b830bd676ba5986926bccec" integrity sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw== -"@types/estree@*", "@types/estree@1.0.8", "@types/estree@^1.0.6", "@types/estree@^1.0.8": +"@types/estree@1.0.8", "@types/estree@^1.0.6", "@types/estree@^1.0.8": version "1.0.8" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.8.tgz#958b91c991b1867ced318bedea0e215ee050726e" integrity sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w== -"@types/express-serve-static-core@*", "@types/express-serve-static-core@^5.0.0": - version "5.0.0" - resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-5.0.0.tgz#91f06cda1049e8f17eeab364798ed79c97488a1c" - integrity sha512-AbXMTZGt40T+KON9/Fdxx0B2WK5hsgxcfXJLr5bFpZ7b4JCex2WyQPTEKdXqfHiY5nKKBScZ7yCoO6Pvgxfvnw== - dependencies: - "@types/node" "*" - "@types/qs" "*" - "@types/range-parser" "*" - "@types/send" "*" - -"@types/express-serve-static-core@^4.17.21", "@types/express-serve-static-core@^4.17.33": - version "4.19.8" - resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.19.8.tgz#99b960322a4d576b239a640ab52ef191989b036f" - integrity sha512-02S5fmqeoKzVZCHPZid4b8JH2eM5HzQLZWN2FohQEy/0eXTq8VXZfSN6Pcr3F6N9R/vNrj7cpgbhjie6m/1tCA== - dependencies: - "@types/node" "*" - "@types/qs" "*" - "@types/range-parser" "*" - "@types/send" "*" - -"@types/express@*": - version "5.0.0" - resolved "https://registry.yarnpkg.com/@types/express/-/express-5.0.0.tgz#13a7d1f75295e90d19ed6e74cab3678488eaa96c" - integrity sha512-DvZriSMehGHL1ZNLzi6MidnsDhUZM/x2pRdDIKdwbUNqqwHxMlRdkxtn6/EPKyqKpHqTl/4nRZsRNLpZxZRpPQ== - dependencies: - "@types/body-parser" "*" - "@types/express-serve-static-core" "^5.0.0" - "@types/qs" "*" - "@types/serve-static" "*" - -"@types/express@^4.17.25": - version "4.17.25" - resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.25.tgz#070c8c73a6fee6936d65c195dbbfb7da5026649b" - integrity sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw== - dependencies: - "@types/body-parser" "*" - "@types/express-serve-static-core" "^4.17.33" - "@types/qs" "*" - "@types/serve-static" "^1" - "@types/flot@^0.0.36": version "0.0.36" resolved "https://registry.yarnpkg.com/@types/flot/-/flot-0.0.36.tgz#59961afa913561236ed7dd2f2c710de0695ec3e2" @@ -3503,13 +2354,6 @@ resolved "https://registry.yarnpkg.com/@types/flowjs/-/flowjs-2.13.14.tgz#62cdd8d5d8e0222e505e4a140e73cd385c0a496c" integrity sha512-OlZFH9hbOq5B+GeBjcM3UvvSailseRT+sKoi9jyFFczvvS1n1LTiTKJysDSLVWnUvGD+tsn7kxb6eC2uaJD+Zw== -"@types/geojson-vt@3.2.5": - version "3.2.5" - resolved "https://registry.yarnpkg.com/@types/geojson-vt/-/geojson-vt-3.2.5.tgz#b6c356874991d9ab4207533476dfbcdb21e38408" - integrity sha512-qDO7wqtprzlpe8FfQ//ClPV9xiuoh2nkIgiouIptON9w5jvD/fA4szvP9GBlDVdJ5dldAl0kX/sy3URbWwLx0g== - dependencies: - "@types/geojson" "*" - "@types/geojson@*", "@types/geojson@^7946.0.10", "@types/geojson@^7946.0.16": version "7946.0.16" resolved "https://registry.yarnpkg.com/@types/geojson/-/geojson-7946.0.16.tgz#8ebe53d69efada7044454e3305c19017d97ced2a" @@ -3520,18 +2364,6 @@ resolved "https://registry.yarnpkg.com/@types/hammerjs/-/hammerjs-2.0.45.tgz#ffa764bb68a66c08db6efb9c816eb7be850577b1" integrity sha512-qkcUlZmX6c4J8q45taBKTL3p+LbITgyx7qhlPYOdOHZB7B31K0mXbP5YA7i7SgDeEGuI9MnumiKPEMrxg8j3KQ== -"@types/http-errors@*": - version "2.0.4" - resolved "https://registry.yarnpkg.com/@types/http-errors/-/http-errors-2.0.4.tgz#7eb47726c391b7345a6ec35ad7f4de469cf5ba4f" - integrity sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA== - -"@types/http-proxy@^1.17.15", "@types/http-proxy@^1.17.8": - version "1.17.15" - resolved "https://registry.yarnpkg.com/@types/http-proxy/-/http-proxy-1.17.15.tgz#12118141ce9775a6499ecb4c01d02f90fc839d36" - integrity sha512-25g5atgiVNTIv0LBDTg1H74Hvayx0ajtJPLLcYE3whFv75J0pWNtOBzaXJQgDTmrX1bx5U9YC2w/n65BN1HwRQ== - dependencies: - "@types/node" "*" - "@types/jquery@*", "@types/jquery@^3.5.29", "@types/jquery@^3.5.33": version "3.5.33" resolved "https://registry.yarnpkg.com/@types/jquery/-/jquery-3.5.33.tgz#f42f40bac3edd84abdc9f6297d28e570fe463b35" @@ -3544,7 +2376,7 @@ resolved "https://registry.yarnpkg.com/@types/js-beautify/-/js-beautify-1.14.3.tgz#6ced76f79935e37e0d613110dea369881d93c1ff" integrity sha512-FMbQHz+qd9DoGvgLHxeqqVPaNRffpIu5ZjozwV8hf9JAGpIOzuAf4wGbRSo8LNITHqGjmmVjaMggTT5P4v4IHg== -"@types/json-schema@*", "@types/json-schema@^7.0.15", "@types/json-schema@^7.0.9": +"@types/json-schema@^7.0.15": version "7.0.15" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== @@ -3594,105 +2426,28 @@ resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.17.23.tgz#c1bb06db218acc8fc232da0447473fc2fb9d9841" integrity sha512-RDvF6wTulMPjrNdCoYRC8gNR880JNGT8uB+REUpC2Ns4pRqQJhGz90wh7rgdXDPpCczF3VGktDuFGVnz8zP7HA== -"@types/mapbox__point-geometry@*", "@types/mapbox__point-geometry@^0.1.4": - version "0.1.4" - resolved "https://registry.yarnpkg.com/@types/mapbox__point-geometry/-/mapbox__point-geometry-0.1.4.tgz#0ef017b75eedce02ff6243b4189210e2e6d5e56d" - integrity sha512-mUWlSxAmYLfwnRBmgYV86tgYmMIICX4kza8YnE/eIlywGe2XoOxlpVnXWwir92xRLjwyarqwpu2EJKD2pk0IUA== - -"@types/mapbox__vector-tile@^1.3.4": - version "1.3.4" - resolved "https://registry.yarnpkg.com/@types/mapbox__vector-tile/-/mapbox__vector-tile-1.3.4.tgz#ad757441ef1d34628d9e098afd9c91423c1f8734" - integrity sha512-bpd8dRn9pr6xKvuEBQup8pwQfD4VUyqO/2deGjfpe6AwC8YRlyEipvefyRJUSiCJTZuCb8Pl1ciVV5ekqJ96Bg== - dependencies: - "@types/geojson" "*" - "@types/mapbox__point-geometry" "*" - "@types/pbf" "*" - -"@types/mime@^1": - version "1.3.5" - resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.5.tgz#1ef302e01cf7d2b5a0fa526790c9123bf1d06690" - integrity sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w== - "@types/mousetrap@^1.6.9": version "1.6.15" resolved "https://registry.yarnpkg.com/@types/mousetrap/-/mousetrap-1.6.15.tgz#f144a0c539a4cef553a631824651d48267e53c86" integrity sha512-qL0hyIMNPow317QWW/63RvL1x5MVMV+Ru3NaY9f/CuEpCqrmb7WeuK2071ZY5hczOnm38qExWM2i2WtkXLSqFw== -"@types/node@*", "@types/node@~22.18.13": +"@types/node@~22.18.13": version "22.18.13" resolved "https://registry.yarnpkg.com/@types/node/-/node-22.18.13.tgz#a037c4f474b860be660e05dbe92a9ef945472e28" integrity sha512-Bo45YKIjnmFtv6I1TuC8AaHBbqXtIo+Om5fE4QiU1Tj8QR/qt+8O3BAtOimG5IFmwaWiPmB3Mv3jtYzBA4Us2A== dependencies: undici-types "~6.21.0" -"@types/pbf@*", "@types/pbf@^3.0.5": - version "3.0.5" - resolved "https://registry.yarnpkg.com/@types/pbf/-/pbf-3.0.5.tgz#a9495a58d8c75be4ffe9a0bd749a307715c07404" - integrity sha512-j3pOPiEcWZ34R6a6mN07mUkM4o4Lwf6hPNt8eilOeZhTFbxFXmKhvXl9Y28jotFPaI1bpPDJsbCprUoNke6OrA== - -"@types/qs@*": - version "6.9.16" - resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.16.tgz#52bba125a07c0482d26747d5d4947a64daf8f794" - integrity sha512-7i+zxXdPD0T4cKDuxCUXJ4wHcsJLwENa6Z3dCu8cfCK743OGy5Nu1RmAGqDPsoTDINVEcdXKRvR/zre+P2Ku1A== - -"@types/range-parser@*": - version "1.2.7" - resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.7.tgz#50ae4353eaaddc04044279812f52c8c65857dbcb" - integrity sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ== - "@types/raphael@^2.3.9": version "2.3.9" resolved "https://registry.yarnpkg.com/@types/raphael/-/raphael-2.3.9.tgz#d53bb8930431524f42987a8a19815c0d42a61eb5" integrity sha512-K1dZwoLNvEN+mvleFU/t2swG9Z4SE5Vub7dA5wDYojH0bVTQ8ZAP+lNsl91t1njdu/B+roSEL4QXC67I7Hpiag== -"@types/retry@0.12.2": - version "0.12.2" - resolved "https://registry.yarnpkg.com/@types/retry/-/retry-0.12.2.tgz#ed279a64fa438bb69f2480eda44937912bb7480a" - integrity sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow== - -"@types/send@*", "@types/send@<1": - version "0.17.6" - resolved "https://registry.yarnpkg.com/@types/send/-/send-0.17.6.tgz#aeb5385be62ff58a52cd5459daa509ae91651d25" - integrity sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og== - dependencies: - "@types/mime" "^1" - "@types/node" "*" - -"@types/serve-index@^1.9.4": - version "1.9.4" - resolved "https://registry.yarnpkg.com/@types/serve-index/-/serve-index-1.9.4.tgz#e6ae13d5053cb06ed36392110b4f9a49ac4ec898" - integrity sha512-qLpGZ/c2fhSs5gnYsQxtDEq3Oy8SXPClIXkW5ghvAvsNuVSA8k+gCONcUCS/UjLEYvYps+e8uBtfgXgvhwfNug== - dependencies: - "@types/express" "*" - -"@types/serve-static@*", "@types/serve-static@^1", "@types/serve-static@^1.15.5": - version "1.15.10" - resolved "https://registry.yarnpkg.com/@types/serve-static/-/serve-static-1.15.10.tgz#768169145a778f8f5dfcb6360aead414a3994fee" - integrity sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw== - dependencies: - "@types/http-errors" "*" - "@types/node" "*" - "@types/send" "<1" - "@types/sizzle@*": version "2.3.9" resolved "https://registry.yarnpkg.com/@types/sizzle/-/sizzle-2.3.9.tgz#d4597dbd4618264c414d7429363e3f50acb66ea2" integrity sha512-xzLEyKB50yqCUPUJkIsrVvoWNfFUbIZI+RspLWt8u+tIW/BetMBZtgV2LY/2o+tYH8dRvQ+eoPf3NdhQCcLE2w== -"@types/sockjs@^0.3.36": - version "0.3.36" - resolved "https://registry.yarnpkg.com/@types/sockjs/-/sockjs-0.3.36.tgz#ce322cf07bcc119d4cbf7f88954f3a3bd0f67535" - integrity sha512-MK9V6NzAS1+Ud7JV9lJLFqW85VbC9dq3LmwZCuBe4wBDgKC0Kj/jd8Xl+nSviU+Qc3+m7umHHyHg//2KSa0a0Q== - dependencies: - "@types/node" "*" - -"@types/supercluster@^7.1.3": - version "7.1.3" - resolved "https://registry.yarnpkg.com/@types/supercluster/-/supercluster-7.1.3.tgz#1a1bc2401b09174d9c9e44124931ec7874a72b27" - integrity sha512-Z0pOY34GDFl3Q6hUFYf3HkTwKEE02e7QgtJppBt+beEAxnyOpJua+voGFvxINBHa06GwLFFym7gRPY2SiKIfIA== - dependencies: - "@types/geojson" "*" - "@types/systemjs@6.15.3": version "6.15.3" resolved "https://registry.yarnpkg.com/@types/systemjs/-/systemjs-6.15.3.tgz#d758dceafee62d2ed4aad7d07342b145d623e260" @@ -3715,13 +2470,6 @@ resolved "https://registry.yarnpkg.com/@types/trusted-types/-/trusted-types-2.0.7.tgz#baccb07a970b91707df3a3e8ba6896c57ead2d11" integrity sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw== -"@types/ws@^8.5.10": - version "8.5.12" - resolved "https://registry.yarnpkg.com/@types/ws/-/ws-8.5.12.tgz#619475fe98f35ccca2a2f6c137702d85ec247b7e" - integrity sha512-3tPRkv1EtkDpzlgyKyI8pGsGZAGPEaXeu0DOj5DI25Ja91bdAYddYHbADRYVrZMRbfW+1l5YwXVDKohDJNQxkQ== - dependencies: - "@types/node" "*" - "@typescript-eslint/eslint-plugin@8.54.0": version "8.54.0" resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.54.0.tgz#d8899e5c2eccf5c4a20d01c036a193753748454d" @@ -3831,137 +2579,6 @@ resolved "https://registry.yarnpkg.com/@vitejs/plugin-basic-ssl/-/plugin-basic-ssl-2.1.0.tgz#c70d2a922bc437f154089d7ef0505db4b383eb7b" integrity sha512-dOxxrhgyDIEUADhb/8OlV9JIqYLgos03YorAueTIeOUskLJSEsfwCByjbu98ctXitUN3znXKp0bYD/WHSudCeA== -"@webassemblyjs/ast@1.14.1", "@webassemblyjs/ast@^1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.14.1.tgz#a9f6a07f2b03c95c8d38c4536a1fdfb521ff55b6" - integrity sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ== - dependencies: - "@webassemblyjs/helper-numbers" "1.13.2" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - -"@webassemblyjs/floating-point-hex-parser@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz#fcca1eeddb1cc4e7b6eed4fc7956d6813b21b9fb" - integrity sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA== - -"@webassemblyjs/helper-api-error@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz#e0a16152248bc38daee76dd7e21f15c5ef3ab1e7" - integrity sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ== - -"@webassemblyjs/helper-buffer@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz#822a9bc603166531f7d5df84e67b5bf99b72b96b" - integrity sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA== - -"@webassemblyjs/helper-numbers@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz#dbd932548e7119f4b8a7877fd5a8d20e63490b2d" - integrity sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA== - dependencies: - "@webassemblyjs/floating-point-hex-parser" "1.13.2" - "@webassemblyjs/helper-api-error" "1.13.2" - "@xtuc/long" "4.2.2" - -"@webassemblyjs/helper-wasm-bytecode@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz#e556108758f448aae84c850e593ce18a0eb31e0b" - integrity sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA== - -"@webassemblyjs/helper-wasm-section@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz#9629dda9c4430eab54b591053d6dc6f3ba050348" - integrity sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-buffer" "1.14.1" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - "@webassemblyjs/wasm-gen" "1.14.1" - -"@webassemblyjs/ieee754@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz#1c5eaace1d606ada2c7fd7045ea9356c59ee0dba" - integrity sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw== - dependencies: - "@xtuc/ieee754" "^1.2.0" - -"@webassemblyjs/leb128@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/leb128/-/leb128-1.13.2.tgz#57c5c3deb0105d02ce25fa3fd74f4ebc9fd0bbb0" - integrity sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw== - dependencies: - "@xtuc/long" "4.2.2" - -"@webassemblyjs/utf8@1.13.2": - version "1.13.2" - resolved "https://registry.yarnpkg.com/@webassemblyjs/utf8/-/utf8-1.13.2.tgz#917a20e93f71ad5602966c2d685ae0c6c21f60f1" - integrity sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ== - -"@webassemblyjs/wasm-edit@^1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz#ac6689f502219b59198ddec42dcd496b1004d597" - integrity sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-buffer" "1.14.1" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - "@webassemblyjs/helper-wasm-section" "1.14.1" - "@webassemblyjs/wasm-gen" "1.14.1" - "@webassemblyjs/wasm-opt" "1.14.1" - "@webassemblyjs/wasm-parser" "1.14.1" - "@webassemblyjs/wast-printer" "1.14.1" - -"@webassemblyjs/wasm-gen@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz#991e7f0c090cb0bb62bbac882076e3d219da9570" - integrity sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - "@webassemblyjs/ieee754" "1.13.2" - "@webassemblyjs/leb128" "1.13.2" - "@webassemblyjs/utf8" "1.13.2" - -"@webassemblyjs/wasm-opt@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz#e6f71ed7ccae46781c206017d3c14c50efa8106b" - integrity sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-buffer" "1.14.1" - "@webassemblyjs/wasm-gen" "1.14.1" - "@webassemblyjs/wasm-parser" "1.14.1" - -"@webassemblyjs/wasm-parser@1.14.1", "@webassemblyjs/wasm-parser@^1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz#b3e13f1893605ca78b52c68e54cf6a865f90b9fb" - integrity sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@webassemblyjs/helper-api-error" "1.13.2" - "@webassemblyjs/helper-wasm-bytecode" "1.13.2" - "@webassemblyjs/ieee754" "1.13.2" - "@webassemblyjs/leb128" "1.13.2" - "@webassemblyjs/utf8" "1.13.2" - -"@webassemblyjs/wast-printer@1.14.1": - version "1.14.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz#3bb3e9638a8ae5fdaf9610e7a06b4d9f9aa6fe07" - integrity sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw== - dependencies: - "@webassemblyjs/ast" "1.14.1" - "@xtuc/long" "4.2.2" - -"@xtuc/ieee754@^1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@xtuc/ieee754/-/ieee754-1.2.0.tgz#eef014a3145ae477a1cbc00cd1e552336dceb790" - integrity sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA== - -"@xtuc/long@4.2.2": - version "4.2.2" - resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d" - integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== - "@yarnpkg/lockfile@1.1.0", "@yarnpkg/lockfile@^1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz#e77a97fbd345b76d83245edcd17d393b1b41fb31" @@ -3985,14 +2602,6 @@ accepts@^2.0.0: mime-types "^3.0.0" negotiator "^1.0.0" -accepts@~1.3.4, accepts@~1.3.8: - version "1.3.8" - resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.8.tgz#0bf0be125b67014adcb0b0921e62db7bffe16b2e" - integrity sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw== - dependencies: - mime-types "~2.1.34" - negotiator "0.6.3" - ace-builds@1.43.6: version "1.43.6" resolved "https://registry.yarnpkg.com/ace-builds/-/ace-builds-1.43.6.tgz#6feffd0283da5bbf45a2052470fe0fc3c442831a" @@ -4005,11 +2614,6 @@ ace-diff@^3.3.0: dependencies: "@sanity/diff-match-patch" "3.2.0" -acorn-import-phases@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/acorn-import-phases/-/acorn-import-phases-1.0.4.tgz#16eb850ba99a056cb7cbfe872ffb8972e18c8bd7" - integrity sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ== - acorn-jsx@^5.3.2: version "5.3.2" resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937" @@ -4022,19 +2626,11 @@ acorn-walk@^8.1.1: dependencies: acorn "^8.11.0" -acorn@^8.11.0, acorn@^8.14.0, acorn@^8.15.0, acorn@^8.16.0, acorn@^8.4.1: +acorn@^8.11.0, acorn@^8.15.0, acorn@^8.16.0, acorn@^8.4.1: version "8.16.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.16.0.tgz#4ce79c89be40afe7afe8f3adb902a1f1ce9ac08a" integrity sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw== -adjust-sourcemap-loader@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/adjust-sourcemap-loader/-/adjust-sourcemap-loader-4.0.0.tgz#fc4a0fd080f7d10471f30a7320f25560ade28c99" - integrity sha512-OXwN5b9pCUXNQHJpwwD2qP40byEmSgzj8B4ydSN0uMNYWiFmJ6x6KwUllMmfk8Rwu/HJDFR7U8ubsWBoN0Xp0A== - dependencies: - loader-utils "^2.0.0" - regex-parser "^2.2.11" - agent-base@^7.1.0, agent-base@^7.1.2: version "7.1.4" resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-7.1.4.tgz#e3cd76d4c548ee895d3c3fd8dc1f6c5b9032e7a8" @@ -4042,26 +2638,12 @@ agent-base@^7.1.0, agent-base@^7.1.2: ajv-formats@3.0.1, ajv-formats@^3.0.1: version "3.0.1" - resolved "https://registry.yarnpkg.com/ajv-formats/-/ajv-formats-3.0.1.tgz#3d5dc762bca17679c3c2ea7e90ad6b7532309578" - integrity sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ== - dependencies: - ajv "^8.0.0" - -ajv-formats@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ajv-formats/-/ajv-formats-2.1.1.tgz#6e669400659eb74973bbf2e33327180a0996b520" - integrity sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA== + resolved "https://registry.yarnpkg.com/ajv-formats/-/ajv-formats-3.0.1.tgz#3d5dc762bca17679c3c2ea7e90ad6b7532309578" + integrity sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ== dependencies: ajv "^8.0.0" -ajv-keywords@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-5.1.0.tgz#69d4d385a4733cdbeab44964a1170a88f87f0e16" - integrity sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw== - dependencies: - fast-deep-equal "^3.1.3" - -ajv@8.18.0, ajv@^8.0.0, ajv@^8.17.1, ajv@^8.9.0: +ajv@8.18.0, ajv@^8.0.0, ajv@^8.17.1: version "8.18.0" resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.18.0.tgz#8864186b6738d003eb3a933172bb3833e10cefbc" integrity sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A== @@ -4132,11 +2714,6 @@ angular2-hotkeys@^16.0.1: mousetrap "^1.6.5" tslib "^2.3.1" -ansi-colors@4.1.3: - version "4.1.3" - resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.3.tgz#37611340eb2243e70cc604cad35d63270d48781b" - integrity sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw== - ansi-escapes@^7.0.0: version "7.3.0" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-7.3.0.tgz#5395bb74b2150a4a1d6e3c2565f4aeca78d28627" @@ -4144,11 +2721,6 @@ ansi-escapes@^7.0.0: dependencies: environment "^1.0.0" -ansi-html-community@^0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/ansi-html-community/-/ansi-html-community-0.0.8.tgz#69fbc4d6ccbe383f9736934ae34c3f8290f1bf41" - integrity sha512-1APHAyr3+PCamwNw3bXCPp4HFLONZt/yIH0sZp0/469KWNTEy+qN5jQ3GVX6DMZ1UXAi34yVwtTeaG/HpBuuzw== - ansi-regex@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" @@ -4246,11 +2818,6 @@ array-buffer-byte-length@^1.0.1, array-buffer-byte-length@^1.0.2: call-bound "^1.0.3" is-array-buffer "^3.0.5" -array-flatten@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" - integrity sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg== - array-includes@^3.1.9: version "3.1.9" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.9.tgz#1f0ccaa08e90cdbc3eb433210f903ad0f17c3f3a" @@ -4311,15 +2878,6 @@ arraybuffer.prototype.slice@^1.0.4: get-intrinsic "^1.2.6" is-array-buffer "^3.0.4" -asn1js@^3.0.10, asn1js@^3.0.6: - version "3.0.10" - resolved "https://registry.yarnpkg.com/asn1js/-/asn1js-3.0.10.tgz#df26c874c8a8b41ca605efea47b2ad07551013dd" - integrity sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg== - dependencies: - pvtsutils "^1.3.6" - pvutils "^1.1.5" - tslib "^2.8.1" - async-function@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/async-function/-/async-function-1.0.0.tgz#509c9fca60eaf85034c6829838188e4e4c8ffb2b" @@ -4332,18 +2890,6 @@ async@~2.6.3: dependencies: lodash "^4.17.14" -autoprefixer@10.4.21: - version "10.4.21" - resolved "https://registry.yarnpkg.com/autoprefixer/-/autoprefixer-10.4.21.tgz#77189468e7a8ad1d9a37fbc08efc9f480cf0a95d" - integrity sha512-O+A6LWV5LDHSJD3LjHYoNi4VLsj/Whi7k6zG12xTYaU4cQ8oxQGckXNX8cRHK5yOZ/ppVHe0ZBXGzSV9jXdVbQ== - dependencies: - browserslist "^4.24.4" - caniuse-lite "^1.0.30001702" - fraction.js "^4.3.7" - normalize-range "^0.1.2" - picocolors "^1.1.1" - postcss-value-parser "^4.2.0" - autoprefixer@^10.4.23: version "10.4.23" resolved "https://registry.yarnpkg.com/autoprefixer/-/autoprefixer-10.4.23.tgz#c6aa6db8e7376fcd900f9fd79d143ceebad8c4e6" @@ -4367,37 +2913,6 @@ axobject-query@4.1.0: resolved "https://registry.yarnpkg.com/axobject-query/-/axobject-query-4.1.0.tgz#28768c76d0e3cff21bc62a9e2d0b6ac30042a1ee" integrity sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ== -babel-loader@10.0.0: - version "10.0.0" - resolved "https://registry.yarnpkg.com/babel-loader/-/babel-loader-10.0.0.tgz#b9743714c0e1e084b3e4adef3cd5faee33089977" - integrity sha512-z8jt+EdS61AMw22nSfoNJAZ0vrtmhPRVi6ghL3rCeRZI8cdNYFiV5xeV3HbE7rlZZNmGH8BVccwWt8/ED0QOHA== - dependencies: - find-up "^5.0.0" - -babel-plugin-polyfill-corejs2@^0.4.14: - version "0.4.14" - resolved "https://registry.yarnpkg.com/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.14.tgz#8101b82b769c568835611542488d463395c2ef8f" - integrity sha512-Co2Y9wX854ts6U8gAAPXfn0GmAyctHuK8n0Yhfjd6t30g7yvKjspvvOo9yG+z52PZRgFErt7Ka2pYnXCjLKEpg== - dependencies: - "@babel/compat-data" "^7.27.7" - "@babel/helper-define-polyfill-provider" "^0.6.5" - semver "^6.3.1" - -babel-plugin-polyfill-corejs3@^0.13.0: - version "0.13.0" - resolved "https://registry.yarnpkg.com/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.13.0.tgz#bb7f6aeef7addff17f7602a08a6d19a128c30164" - integrity sha512-U+GNwMdSFgzVmfhNm8GJUX88AadB3uo9KpJqS3FaqNIPKgySuvMb+bHPsOmmuWyIcuqZj/pzt1RUIUZns4y2+A== - dependencies: - "@babel/helper-define-polyfill-provider" "^0.6.5" - core-js-compat "^3.43.0" - -babel-plugin-polyfill-regenerator@^0.6.5: - version "0.6.5" - resolved "https://registry.yarnpkg.com/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.5.tgz#32752e38ab6f6767b92650347bf26a31b16ae8c5" - integrity sha512-ISqQ2frbiNU9vIJkzg7dlPpznPZ4jOiUQ1uSmB0fEHeowtN3COYRsXr/xexn64NpU13P06jc/L5TgiJXOgrbEg== - dependencies: - "@babel/helper-define-polyfill-provider" "^0.6.5" - balanced-match@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" @@ -4418,11 +2933,6 @@ baseline-browser-mapping@^2.11.20: resolved "https://registry.yarnpkg.com/baseline-browser-mapping/-/baseline-browser-mapping-2.11.21.tgz#99af73cb8e54007e4f5345e132278e26c2662f2c" integrity sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ== -batch@0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/batch/-/batch-0.6.1.tgz#dc34314f4e679318093fc760272525f94bf25c16" - integrity sha512-x+VAiMRL6UPkx+kudNvxTl6hB2XNNCG2r+7wixVfIYwu/2HKRXimwQyaumLjMveWvT2Hkd/cAJw+QBMfJ/EKVw== - beasties@0.3.5: version "0.3.5" resolved "https://registry.yarnpkg.com/beasties/-/beasties-0.3.5.tgz#a52abea4ead105c1aded66b1a01a74e96585dc81" @@ -4437,10 +2947,12 @@ beasties@0.3.5: postcss "^8.4.49" postcss-media-query-parser "^0.2.3" -big.js@^5.2.2: - version "5.2.2" - resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" - integrity sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ== +bidi-js@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/bidi-js/-/bidi-js-1.1.0.tgz#c92efafe3fce3b9fdd30ba67bdddf0dd4d424af7" + integrity sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg== + dependencies: + require-from-string "^2.0.2" bignumber.js@^9.1.0: version "9.1.2" @@ -4467,49 +2979,23 @@ body-parser@^2.2.1: raw-body "^3.0.1" type-is "^2.0.1" -body-parser@~1.20.5: - version "1.20.6" - resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.20.6.tgz#60c789c78e0992d906da0a29d71ae01d15c1ed76" - integrity sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g== - dependencies: - bytes "~3.1.2" - content-type "~1.0.5" - debug "2.6.9" - depd "2.0.0" - destroy "~1.2.0" - http-errors "~2.0.1" - iconv-lite "~0.4.24" - on-finished "~2.4.1" - qs "~6.15.1" - raw-body "~2.5.3" - type-is "~1.6.18" - unpipe "~1.0.0" - -bonjour-service@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/bonjour-service/-/bonjour-service-1.2.1.tgz#eb41b3085183df3321da1264719fbada12478d02" - integrity sha512-oSzCS2zV14bh2kji6vNe7vrpJYCHGvcZnlffFQ1MEoX/WOeQ/teD8SYWKR942OI3INjq8OMNJlbPK5LLLUxFDw== - dependencies: - fast-deep-equal "^3.1.3" - multicast-dns "^7.2.5" - boolbase@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" integrity sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww== brace-expansion@^1.1.7: - version "1.1.18" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.18.tgz#3ce74d89885136be1535341f8c3d4425c29a5cab" - integrity sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw== + version "1.1.21" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.21.tgz#edf4fab5c64d051aea5a8def49aba1c7522279f3" + integrity sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" brace-expansion@^5.0.2: - version "5.0.9" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-5.0.9.tgz#7c72438809b5fa5babf54199a1f1c281a6984fcf" - integrity sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg== + version "5.0.12" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-5.0.12.tgz#995fbb4750a77c4d16a7dc942ff2ca6ef8e675ec" + integrity sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ== dependencies: balanced-match "^4.0.2" @@ -4520,7 +3006,7 @@ braces@^3.0.3, braces@~3.0.2: dependencies: fill-range "^7.1.1" -browserslist@^4.21.5, browserslist@^4.23.0, browserslist@^4.24.0, browserslist@^4.24.4, browserslist@^4.28.1: +browserslist@^4.23.0, browserslist@^4.24.0, browserslist@^4.28.1: version "4.28.9" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.28.9.tgz#07ce6b449b90af880eb9bfb7cd39372cc4f71c8c" integrity sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg== @@ -4536,23 +3022,11 @@ buffer-from@^1.0.0: resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== -bundle-name@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/bundle-name/-/bundle-name-4.1.0.tgz#f3b96b34160d6431a19d7688135af7cfb8797889" - integrity sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q== - dependencies: - run-applescript "^7.0.0" - -bytes@3.1.2, bytes@^3.1.2, bytes@~3.1.2: +bytes@^3.1.2, bytes@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5" integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg== -bytestreamjs@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/bytestreamjs/-/bytestreamjs-2.0.1.tgz#a32947c7ce389a6fa11a09a9a563d0a45889535e" - integrity sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ== - cacache@^20.0.0, cacache@^20.0.1: version "20.0.3" resolved "https://registry.yarnpkg.com/cacache/-/cacache-20.0.3.tgz#bd65205d5e6d86e02bbfaf8e4ce6008f1b81d119" @@ -4611,12 +3085,7 @@ camelcase@^5.0.0: resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== -caniuse-lite@^1.0.30001702, caniuse-lite@^1.0.30001760: - version "1.0.30001775" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001775.tgz#9572266e3f7f77efee5deac1efeb4795879d1b7f" - integrity sha512-s3Qv7Lht9zbVKE9XoTyRG6wVDCKdtOFIjBGg3+Yhn6JaytuNKPIjBMTMIY1AnOH3seL5mvF+x33oGAyK3hVt3A== - -caniuse-lite@^1.0.30001810: +caniuse-lite@^1.0.30001760, caniuse-lite@^1.0.30001810: version "1.0.30001810" resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz#4970b477dea3278374de9bc43aa8f5d39fc3cda2" integrity sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg== @@ -4698,11 +3167,6 @@ chownr@^3.0.0: resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== -chrome-trace-event@^1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz#05bffd7ff928465093314708c93bdfa9bd1f0f5b" - integrity sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ== - ci-info@^3.7.0: version "3.9.0" resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-3.9.0.tgz#4279a62028a7b1f262f3473fc9605f5e218c59b4" @@ -4760,15 +3224,6 @@ cliui@^9.0.1: strip-ansi "^7.1.0" wrap-ansi "^9.0.0" -clone-deep@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/clone-deep/-/clone-deep-4.0.1.tgz#c19fd9bdbbf85942b4fd979c84dcf7d5f07c2387" - integrity sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ== - dependencies: - is-plain-object "^2.0.4" - kind-of "^6.0.2" - shallow-clone "^3.0.0" - clone@^1.0.2: version "1.0.4" resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" @@ -4798,7 +3253,7 @@ color-name@~1.1.4: resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== -colorette@^2.0.10, colorette@^2.0.20: +colorette@^2.0.20: version "2.0.20" resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.20.tgz#9eb793e6833067f7235902fcd3b09917a000a95a" integrity sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w== @@ -4833,11 +3288,6 @@ commander@^10.0.0: resolved "https://registry.yarnpkg.com/commander/-/commander-10.0.1.tgz#881ee46b4f77d1c1dccc5823433aa39b022cbe06" integrity sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug== -commander@^2.20.0: - version "2.20.3" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" - integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== - commander@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" @@ -4853,26 +3303,6 @@ comment-parser@1.4.5: resolved "https://registry.yarnpkg.com/comment-parser/-/comment-parser-1.4.5.tgz#6c595cd090737a1010fe5ff40d86e1d21b7bd6ce" integrity sha512-aRDkn3uyIlCFfk5NUA+VdwMmMsh8JGhc4hapfV4yxymHGQ3BVskMQfoXGpCo5IoBuQ9tS5iiVKhCpTcB4pW4qw== -compressible@~2.0.18: - version "2.0.18" - resolved "https://registry.yarnpkg.com/compressible/-/compressible-2.0.18.tgz#af53cca6b070d4c3c0750fbd77286a6d7cc46fba" - integrity sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg== - dependencies: - mime-db ">= 1.43.0 < 2" - -compression@^1.8.1: - version "1.8.1" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.1.tgz#4a45d909ac16509195a9a28bd91094889c180d79" - integrity sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w== - dependencies: - bytes "3.1.2" - compressible "~2.0.18" - debug "2.6.9" - negotiator "~0.6.4" - on-headers "~1.1.0" - safe-buffer "5.2.1" - vary "~1.1.2" - concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" @@ -4891,29 +3321,17 @@ config-chain@^1.1.13: ini "^1.3.4" proto-list "~1.2.1" -connect-history-api-fallback@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/connect-history-api-fallback/-/connect-history-api-fallback-2.0.0.tgz#647264845251a0daf25b97ce87834cace0f5f1c8" - integrity sha512-U73+6lQFmfiNPrYbXqr6kZ1i1wiRqXnp2nhMsINseWXO8lDau0LGEffJ8kQi4EjLZympVgRdvqjAgiZ1tgzDDA== - content-disposition@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-1.0.1.tgz#a8b7bbeb2904befdfb6787e5c0c086959f605f9b" integrity sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q== -content-disposition@~0.5.4: - version "0.5.4" - resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.4.tgz#8b82b4efac82512a02bb0b1dcec9d2c5e8eb5bfe" - integrity sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ== - dependencies: - safe-buffer "5.2.1" - -content-type@^1.0.5, content-type@~1.0.4, content-type@~1.0.5: +content-type@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.5.tgz#8b773162656d1d1086784c8f23a54ce6d73d7918" integrity sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA== -convert-source-map@^1.5.1, convert-source-map@^1.7.0: +convert-source-map@^1.5.1: version "1.9.0" resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.9.0.tgz#7faae62353fb4213366d0ca98358d22e8368b05f" integrity sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A== @@ -4928,41 +3346,11 @@ cookie-signature@^1.2.1: resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.2.2.tgz#57c7fc3cc293acab9fec54d73e15690ebe4a1793" integrity sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg== -cookie-signature@~1.0.6: - version "1.0.7" - resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.7.tgz#ab5dd7ab757c54e60f37ef6550f481c426d10454" - integrity sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA== - -cookie@^0.7.1, cookie@~0.7.1: +cookie@^0.7.1: version "0.7.2" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.7.2.tgz#556369c472a2ba910f2979891b526b3436237ed7" integrity sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w== -copy-anything@^3.0.5: - version "3.0.5" - resolved "https://registry.yarnpkg.com/copy-anything/-/copy-anything-3.0.5.tgz#2d92dce8c498f790fa7ad16b01a1ae5a45b020a0" - integrity sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w== - dependencies: - is-what "^4.1.8" - -copy-webpack-plugin@14.0.0: - version "14.0.0" - resolved "https://registry.yarnpkg.com/copy-webpack-plugin/-/copy-webpack-plugin-14.0.0.tgz#cd253b60e8e55bb41019dfe3ef2979ba705592c7" - integrity sha512-3JLW90aBGeaTLpM7mYQKpnVdgsUZRExY55giiZgLuX/xTQRUs1dOCwbBnWnvY6Q6rfZoXMNwzOQJCSZPppfqXA== - dependencies: - glob-parent "^6.0.1" - normalize-path "^3.0.0" - schema-utils "^4.2.0" - serialize-javascript "^7.0.3" - tinyglobby "^0.2.12" - -core-js-compat@^3.43.0: - version "3.48.0" - resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.48.0.tgz#7efbe1fc1cbad44008190462217cc5558adaeaa6" - integrity sha512-OM4cAF3D6VtH/WkLtWvyNC56EZVXsZdU3iqaMG2B4WvYrlqU831pc4UtG5yp0sE9z8Y02wVN7PjW5Zf9Gt0f1Q== - dependencies: - browserslist "^4.28.1" - core-js@^3.48.0: version "3.48.0" resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.48.0.tgz#1f813220a47bbf0e667e3885c36cd6f0593bf14d" @@ -4995,16 +3383,6 @@ cose-base@^2.2.0: dependencies: layout-base "^2.0.0" -cosmiconfig@^9.0.0: - version "9.0.0" - resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-9.0.0.tgz#34c3fc58287b915f3ae905ab6dc3de258b55ad9d" - integrity sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg== - dependencies: - env-paths "^2.2.1" - import-fresh "^3.3.0" - js-yaml "^4.1.0" - parse-json "^5.2.0" - create-require@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" @@ -5026,20 +3404,6 @@ css-line-break@^2.1.0: dependencies: utrie "^1.0.2" -css-loader@7.1.2: - version "7.1.2" - resolved "https://registry.yarnpkg.com/css-loader/-/css-loader-7.1.2.tgz#64671541c6efe06b0e22e750503106bdd86880f8" - integrity sha512-6WvYYn7l/XEGN8Xu2vWFt9nVzrCn39vKyTEFf/ExEyoksJjjSZV/0/35XPlMbpnr6VGhZIUg5yJrL8tGfes/FA== - dependencies: - icss-utils "^5.1.0" - postcss "^8.4.33" - postcss-modules-extract-imports "^3.1.0" - postcss-modules-local-by-default "^4.0.5" - postcss-modules-scope "^3.2.0" - postcss-modules-values "^4.0.0" - postcss-value-parser "^4.2.0" - semver "^7.5.4" - css-select@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/css-select/-/css-select-6.0.0.tgz#7e63f09881ad118084091048ed543786dad96644" @@ -5396,21 +3760,14 @@ dayjs@1.11.20, dayjs@^1.11.19, dayjs@^1.11.5: resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.20.tgz#88d919fd639dc991415da5f4cb6f1b6650811938" integrity sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ== -debug@2, debug@2.6.9: - version "2.6.9" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" - integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== - dependencies: - ms "2.0.0" - -debug@4, debug@^4.1.0, debug@^4.3.1, debug@^4.3.2, debug@^4.3.4, debug@^4.3.6, debug@^4.4.0, debug@^4.4.1, debug@^4.4.3: +debug@4, debug@^4.1.0, debug@^4.3.1, debug@^4.3.2, debug@^4.3.4, debug@^4.4.0, debug@^4.4.3: version "4.4.3" resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.3.tgz#c6ae432d9bd9662582fce08709b038c58e9e3d6a" integrity sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA== dependencies: ms "^2.1.3" -debug@^3.2.6, debug@^3.2.7: +debug@^3.2.7: version "3.2.7" resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.7.tgz#72580b7e9145fb39b6676f9c5e5fb100b934179a" integrity sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ== @@ -5437,19 +3794,6 @@ deep-is@^0.1.3: resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831" integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ== -default-browser-id@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/default-browser-id/-/default-browser-id-5.0.0.tgz#a1d98bf960c15082d8a3fa69e83150ccccc3af26" - integrity sha512-A6p/pu/6fyBcA1TRz/GqWYPViplrftcW2gZC9q79ngNCKAeR/X3gcEdXQHl4KNXV+3wgIJ1CPkJQ3IHM6lcsyA== - -default-browser@^5.2.1: - version "5.2.1" - resolved "https://registry.yarnpkg.com/default-browser/-/default-browser-5.2.1.tgz#7b7ba61204ff3e425b556869ae6d3e9d9f1712cf" - integrity sha512-WY/3TUME0x3KPYdRRxEJJvXRHV4PyPoUsxtZa78lwItwRQRHhd2U9xOscaT/YTf8uCXIAjeJOFBVEh/7FtD8Xg== - dependencies: - bundle-name "^4.1.0" - default-browser-id "^5.0.0" - defaults@^1.0.3: version "1.0.4" resolved "https://registry.yarnpkg.com/defaults/-/defaults-1.0.4.tgz#b0b02062c1e2aa62ff5d9528f0f98baa90978d7a" @@ -5466,11 +3810,6 @@ define-data-property@^1.0.1, define-data-property@^1.1.4: es-errors "^1.3.0" gopd "^1.0.1" -define-lazy-prop@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz#dbb19adfb746d7fc6d734a06b72f4a00d021255f" - integrity sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg== - define-properties@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.2.1.tgz#10781cc616eb951a80a034bafcaa7377f6af2b6c" @@ -5492,31 +3831,16 @@ delegate@^3.1.2: resolved "https://registry.yarnpkg.com/delegate/-/delegate-3.2.0.tgz#b66b71c3158522e8ab5744f720d8ca0c2af59166" integrity sha512-IofjkYBZaZivn0V8nnsMJGBr4jVLxHDheKSW88PyxS5QC4Vo9ZbZVvhzlSxY87fVq3STR6r+4cGepyHkcWOQSw== -depd@2.0.0, depd@^2.0.0, depd@~2.0.0: +depd@^2.0.0, depd@~2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== -depd@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" - integrity sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ== - -destroy@1.2.0, destroy@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" - integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== - detect-libc@^2.0.1, detect-libc@^2.0.3: version "2.1.2" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.1.2.tgz#689c5dcdc1900ef5583a4cb9f6d7b473742074ad" integrity sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ== -detect-node@^2.0.4: - version "2.1.0" - resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1" - integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g== - didyoumean@^1.2.2: version "1.2.2" resolved "https://registry.yarnpkg.com/didyoumean/-/didyoumean-1.2.2.tgz#989346ffe9e839b4555ecf5666edea0d3e8ad037" @@ -5545,13 +3869,6 @@ dlv@^1.1.3: resolved "https://registry.yarnpkg.com/dlv/-/dlv-1.1.3.tgz#5c198a8a11453596e751494d49874bc7732f2e79" integrity sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA== -dns-packet@^5.2.2: - version "5.6.1" - resolved "https://registry.yarnpkg.com/dns-packet/-/dns-packet-5.6.1.tgz#ae888ad425a9d1478a0674256ab866de1012cf2f" - integrity sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw== - dependencies: - "@leichtgewicht/ip-codec" "^2.0.1" - doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" @@ -5605,10 +3922,10 @@ dunder-proto@^1.0.0, dunder-proto@^1.0.1: es-errors "^1.3.0" gopd "^1.2.0" -earcut@^3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/earcut/-/earcut-3.0.2.tgz#d478a29aaf99acf418151493048aa197d0512248" - integrity sha512-X7hshQbLyMJ/3RPhyObLARM2sNxxmRALLKx1+NVFFnQ9gKzmCrxm9+uLIAdBcvc8FNLpctqlQ2V6AE92Ol9UDQ== +earcut@^3.2.3: + version "3.2.3" + resolved "https://registry.yarnpkg.com/earcut/-/earcut-3.2.3.tgz#74aec19555a7e28773429826729d2e4bfeb19022" + integrity sha512-vnS4AVwp1KHAF13i1vp1/2D5evWy3k5u/iW/B81QVsUZtV8cv2tU0b2VNFlqvh4kYwrFMDdjPCfAmfyJW9y14Q== eastasianwidth@^0.2.0: version "0.2.0" @@ -5662,12 +3979,7 @@ emoji-regex@^9.2.2: resolved "https://registry.yarnpkg.com/emoji-toolkit/-/emoji-toolkit-9.0.1.tgz#b3da51a4d9b1e89608b6a8506a5df6dbc3125495" integrity sha512-sMMNqKNLVHXJfIKoPbrRJwtYuysVNC9GlKetr72zE3SSVbHqoeDLWVrxP0uM0AE0qvdl3hbUk+tJhhwXZrDHaw== -emojis-list@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-3.0.0.tgz#5570662046ad29e2e916e71aae260abdff4f6a78" - integrity sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q== - -encodeurl@^2.0.0, encodeurl@~2.0.0: +encodeurl@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-2.0.0.tgz#7b8ea898077d7e409d3ac45474ea38eaf0857a58" integrity sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg== @@ -5679,14 +3991,6 @@ encoding@^0.1.13: dependencies: iconv-lite "^0.6.2" -enhanced-resolve@^5.19.0: - version "5.19.0" - resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.19.0.tgz#6687446a15e969eaa63c2fa2694510e17ae6d97c" - integrity sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg== - dependencies: - graceful-fs "^4.2.4" - tapable "^2.3.0" - entities@^4.2.0: version "4.5.0" resolved "https://registry.yarnpkg.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48" @@ -5702,7 +4006,7 @@ entities@^7.0.1: resolved "https://registry.yarnpkg.com/entities/-/entities-7.0.1.tgz#26e8a88889db63417dcb9a1e79a3f1bc92b5976b" integrity sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA== -env-paths@^2.2.0, env-paths@^2.2.1: +env-paths@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2" integrity sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A== @@ -5717,20 +4021,6 @@ err-code@^2.0.2: resolved "https://registry.yarnpkg.com/err-code/-/err-code-2.0.3.tgz#23c2f3b756ffdfc608d30e27c9a941024807e7f9" integrity sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA== -errno@^0.1.1: - version "0.1.8" - resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.8.tgz#8bb3e9c7d463be4976ff888f76b4809ebc2e811f" - integrity sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A== - dependencies: - prr "~1.0.1" - -error-ex@^1.3.1: - version "1.3.2" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" - integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== - dependencies: - is-arrayish "^0.2.1" - es-abstract@^1.23.2, es-abstract@^1.23.5, es-abstract@^1.23.9, es-abstract@^1.24.0: version "1.24.1" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.24.1.tgz#f0c131ed5ea1bb2411134a8dd94def09c46c7899" @@ -5801,11 +4091,6 @@ es-errors@^1.3.0: resolved "https://registry.yarnpkg.com/es-errors/-/es-errors-1.3.0.tgz#05f75a25dab98e4fb1dcd5e1472c0546d5057c8f" integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw== -es-module-lexer@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-2.0.0.tgz#f657cd7a9448dcdda9c070a3cb75e5dc1e85f5b1" - integrity sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw== - es-object-atoms@^1.0.0, es-object-atoms@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz#1c4f2c4837327597ce69d2ca190a7fdd172338c1" @@ -5839,11 +4124,6 @@ es-to-primitive@^1.3.0: is-date-object "^1.0.5" is-symbol "^1.0.4" -esbuild-wasm@0.28.1: - version "0.28.1" - resolved "https://registry.yarnpkg.com/esbuild-wasm/-/esbuild-wasm-0.28.1.tgz#b173826abdc645419c3c7ac77e2d9128286a7a79" - integrity sha512-p/GD4E8oYRjg3kjdKrnMb0s4PzXgJF42e0MF4H0+ACyK/kIlFRp3e0fzOleIG+wBBm6MM3XQrbpe7soEA+vJIA== - esbuild@0.28.1, "esbuild@^0.27.0 || ^0.28.0": version "0.28.1" resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.28.1.tgz#ef45b4634c9c9d97a296aea4114a5f9840f95578" @@ -5881,7 +4161,7 @@ escalade@^3.1.1, escalade@^3.2.0: resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.2.0.tgz#011a3f69856ba189dffa7dc8fcce99d2a87903e5" integrity sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA== -escape-html@^1.0.3, escape-html@~1.0.3: +escape-html@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" integrity sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow== @@ -5970,14 +4250,6 @@ eslint-plugin-tailwindcss@^3.18.2: fast-glob "^3.2.5" postcss "^8.4.4" -eslint-scope@5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" - integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== - dependencies: - esrecurse "^4.3.0" - estraverse "^4.1.1" - eslint-scope@^8.4.0: version "8.4.0" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-8.4.0.tgz#88e646a207fad61436ffa39eb505147200655c82" @@ -6011,18 +4283,18 @@ eslint-visitor-keys@^5.0.0: resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-5.0.0.tgz#b9aa1a74aa48c44b3ae46c1597ce7171246a94a9" integrity sha512-A0XeIi7CXU7nPlfHS9loMYEKxUaONu/hTEzHTGba9Huu94Cq1hPivf+DE5erJozZOky0LfvXAyrV/tcswpLI0Q== -eslint@9.39.4: - version "9.39.4" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-9.39.4.tgz#855da1b2e2ad66dc5991195f35e262bcec8117b5" - integrity sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ== +eslint@9.39.5: + version "9.39.5" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-9.39.5.tgz#2a4e3c8b0f753196efae943c8ffaa8730fc6a3fa" + integrity sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw== dependencies: "@eslint-community/eslint-utils" "^4.8.0" "@eslint-community/regexpp" "^4.12.1" "@eslint/config-array" "^0.21.2" "@eslint/config-helpers" "^0.4.2" "@eslint/core" "^0.17.0" - "@eslint/eslintrc" "^3.3.5" - "@eslint/js" "9.39.4" + "@eslint/eslintrc" "^3.3.6" + "@eslint/js" "9.39.5" "@eslint/plugin-kit" "^0.4.1" "@humanfs/node" "^0.16.6" "@humanwhocodes/module-importer" "^1.0.1" @@ -6083,11 +4355,6 @@ esrecurse@^4.3.0: dependencies: estraverse "^5.2.0" -estraverse@^4.1.1: - version "4.3.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" - integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== - estraverse@^5.1.0, estraverse@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" @@ -6098,7 +4365,7 @@ esutils@^2.0.2: resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== -etag@^1.8.1, etag@~1.8.1: +etag@^1.8.1: version "1.8.1" resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887" integrity sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg== @@ -6108,21 +4375,11 @@ eve-raphael@0.5.0: resolved "https://registry.yarnpkg.com/eve-raphael/-/eve-raphael-0.5.0.tgz#17c754b792beef3fa6684d79cf5a47c63c4cda30" integrity sha512-jrxnPsCGqng1UZuEp9DecX/AuSyAszATSjf4oEcRxvfxa1Oux4KkIPKBAAWWnpdwfARtr+Q0o9aPYWjsROD7ug== -eventemitter3@^4.0.0: - version "4.0.7" - resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-4.0.7.tgz#2de9b68f6528d5644ef5c59526a1b4a07306169f" - integrity sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw== - eventemitter3@^5.0.1: version "5.0.4" resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-5.0.4.tgz#a86d66170433712dde814707ac52b5271ceb1feb" integrity sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw== -events@^3.2.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400" - integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q== - eventsource-parser@^3.0.0, eventsource-parser@^3.0.1: version "3.0.6" resolved "https://registry.yarnpkg.com/eventsource-parser/-/eventsource-parser-3.0.6.tgz#292e165e34cacbc936c3c92719ef326d4aeb4e90" @@ -6148,43 +4405,6 @@ express-rate-limit@^8.2.1: debug "^4.4.3" ip-address "^10.2.0" -express@^4.22.1: - version "4.22.2" - resolved "https://registry.yarnpkg.com/express/-/express-4.22.2.tgz#c17ae0981e5efc24b22272f0e041c4662503b700" - integrity sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q== - dependencies: - accepts "~1.3.8" - array-flatten "1.1.1" - body-parser "~1.20.5" - content-disposition "~0.5.4" - content-type "~1.0.4" - cookie "~0.7.1" - cookie-signature "~1.0.6" - debug "2.6.9" - depd "2.0.0" - encodeurl "~2.0.0" - escape-html "~1.0.3" - etag "~1.8.1" - finalhandler "~1.3.1" - fresh "~0.5.2" - http-errors "~2.0.0" - merge-descriptors "1.0.3" - methods "~1.1.2" - on-finished "~2.4.1" - parseurl "~1.3.3" - path-to-regexp "~0.1.12" - proxy-addr "~2.0.7" - qs "~6.15.1" - range-parser "~1.2.1" - safe-buffer "5.2.1" - send "~0.19.0" - serve-static "~1.16.2" - setprototypeof "1.2.0" - statuses "~2.0.1" - type-is "~1.6.18" - utils-merge "1.0.1" - vary "~1.1.2" - express@^5.2.1: version "5.2.1" resolved "https://registry.yarnpkg.com/express/-/express-5.2.1.tgz#8f21d15b6d327f92b4794ecf8cb08a72f956ac04" @@ -6224,7 +4444,7 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== -fast-glob@3.3.3, fast-glob@^3.2.5, fast-glob@^3.3.2: +fast-glob@^3.2.5, fast-glob@^3.3.2: version "3.3.3" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.3.tgz#d06d585ce8dba90a16b0505c543c3ccfb3aeb818" integrity sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg== @@ -6257,13 +4477,6 @@ fastq@^1.6.0: dependencies: reusify "^1.0.4" -faye-websocket@^0.11.3: - version "0.11.4" - resolved "https://registry.yarnpkg.com/faye-websocket/-/faye-websocket-0.11.4.tgz#7f0d9275cfdd86a1c963dc8b65fcc451edcbb1da" - integrity sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g== - dependencies: - websocket-driver ">=0.5.1" - fdir@^6.4.4, fdir@^6.5.0: version "6.5.0" resolved "https://registry.yarnpkg.com/fdir/-/fdir-6.5.0.tgz#ed2ab967a331ade62f18d077dae192684d50d350" @@ -6303,19 +4516,6 @@ finalhandler@^2.1.0: parseurl "^1.3.3" statuses "^2.0.1" -finalhandler@~1.3.1: - version "1.3.2" - resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.3.2.tgz#1ebc2228fc7673aac4a472c310cc05b77d852b88" - integrity sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg== - dependencies: - debug "2.6.9" - encodeurl "~2.0.0" - escape-html "~1.0.3" - on-finished "~2.4.1" - parseurl "~1.3.3" - statuses "~2.0.2" - unpipe "~1.0.0" - find-replace@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/find-replace/-/find-replace-3.0.0.tgz#3e7e23d3b05167a76f770c9fbd5258b0def68c38" @@ -6354,11 +4554,6 @@ flat-cache@^4.0.0: flatted "^3.2.9" keyv "^4.5.4" -flat@^5.0.2: - version "5.0.2" - resolved "https://registry.yarnpkg.com/flat/-/flat-5.0.2.tgz#8ca6fe332069ffa9d324c327198c598259ceb241" - integrity sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ== - flatted@^3.2.9: version "3.4.2" resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.4.2.tgz#f5c23c107f0f37de8dbdf24f13722b3b98d52726" @@ -6372,11 +4567,6 @@ flatted@^3.2.9: version "0.9.0-alpha" resolved "https://github.com/thingsboard/flot.git#c2734540477d8b261d04ee18d4d38af3b0ecb81b" -follow-redirects@^1.0.0: - version "1.16.0" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.16.0.tgz#28474a159d3b9d11ef62050a14ed60e4df6d61bc" - integrity sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw== - font-awesome@^4.7.0: version "4.7.0" resolved "https://registry.yarnpkg.com/font-awesome/-/font-awesome-4.7.0.tgz#8fa8cf0411a1a31afd07b06d2902bb9fc815a133" @@ -6409,11 +4599,6 @@ forwarded@0.2.0: resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.2.0.tgz#2269936428aad4c15c7ebe9779a84bf0b2a81811" integrity sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow== -fraction.js@^4.3.7: - version "4.3.7" - resolved "https://registry.yarnpkg.com/fraction.js/-/fraction.js-4.3.7.tgz#06ca0085157e42fda7f9e726e79fefc4068840f7" - integrity sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew== - fraction.js@^5.3.4: version "5.3.4" resolved "https://registry.yarnpkg.com/fraction.js/-/fraction.js-5.3.4.tgz#8c0fcc6a9908262df4ed197427bdeef563e0699a" @@ -6424,11 +4609,6 @@ fresh@^2.0.0: resolved "https://registry.yarnpkg.com/fresh/-/fresh-2.0.0.tgz#8dd7df6a1b3a1b3a5cf186c05a5dd267622635a4" integrity sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A== -fresh@~0.5.2: - version "0.5.2" - resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7" - integrity sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q== - fs-extra@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-10.1.0.tgz#02873cfbc4084dde127eaa5f9905eef2325d1abf" @@ -6482,11 +4662,6 @@ gensync@^1.0.0-beta.2: resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" integrity sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg== -geojson-vt@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/geojson-vt/-/geojson-vt-4.0.2.tgz#1162f6c7d61a0ba305b1030621e6e111f847828a" - integrity sha512-AV9ROqlNqoZEIJGfm1ncNjEXfkz2hdFlZf0qkVfmkwdKa8vj7H16YUOT81rJw1rdFhyEDlN2Tds91p/glzbl5A== - get-caller-file@^2.0.1, get-caller-file@^2.0.5: version "2.0.5" resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" @@ -6521,11 +4696,6 @@ get-proto@^1.0.1: dunder-proto "^1.0.1" es-object-atoms "^1.0.0" -get-stream@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" - integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== - get-symbol-description@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/get-symbol-description/-/get-symbol-description-1.1.0.tgz#7bdd54e0befe8ffc9f3b4e203220d9f1e881b6ee" @@ -6535,7 +4705,7 @@ get-symbol-description@^1.1.0: es-errors "^1.3.0" get-intrinsic "^1.2.6" -gl-matrix@^3.4.3: +gl-matrix@^3.4.4: version "3.4.4" resolved "https://registry.yarnpkg.com/gl-matrix/-/gl-matrix-3.4.4.tgz#7789ee4982f62c7a7af447ee488f3bd6b0c77003" integrity sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ== @@ -6547,18 +4717,13 @@ glob-parent@^5.1.2, glob-parent@~5.1.2: dependencies: is-glob "^4.0.1" -glob-parent@^6.0.1, glob-parent@^6.0.2: +glob-parent@^6.0.2: version "6.0.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-6.0.2.tgz#6d237d99083950c79290f24c7642a3de9a28f9e3" integrity sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A== dependencies: is-glob "^4.0.3" -glob-to-regex.js@^1.0.0, glob-to-regex.js@^1.0.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/glob-to-regex.js/-/glob-to-regex.js-1.2.0.tgz#2b323728271d133830850e32311f40766c5f6413" - integrity sha512-QMwlOQKU/IzqMUOAZWubUOT8Qft+Y0KQWnX9nK3ch0CJg0tTp4TvGZsTfudYKv2NzoQSyPcnA6TYeIQ3jGichQ== - glob-to-regexp@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" @@ -6585,15 +4750,6 @@ glob@^13.0.0: minipass "^7.1.2" path-scurry "^2.0.0" -global-prefix@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-4.0.0.tgz#e9cc79aab9be1d03287e156a3f912dd0895463ed" - integrity sha512-w0Uf9Y9/nyHinEk5vMJKRie+wa4kR5hmDbEhGGds/kG1PwGLLHKRoNMeJOyCQjjBkANlnScqgzcFwGHgmgLkVA== - dependencies: - ini "^4.1.3" - kind-of "^6.0.3" - which "^4.0.0" - globals@^14.0.0: version "14.0.0" resolved "https://registry.yarnpkg.com/globals/-/globals-14.0.0.tgz#898d7413c29babcf6bafe56fcadded858ada724e" @@ -6619,7 +4775,7 @@ gopd@^1.0.1, gopd@^1.2.0: resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1" integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg== -graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.11, graceful-fs@^4.2.4, graceful-fs@^4.2.6: +graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.6: version "4.2.11" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== @@ -6634,11 +4790,6 @@ hammerjs@^2.0.8: resolved "https://registry.yarnpkg.com/hammerjs/-/hammerjs-2.0.8.tgz#04ef77862cff2bb79d30f7692095930222bf60f1" integrity sha512-tSQXBXS/MWQOn/RKckawJ61vvsDpCom87JgxiYdGwHdOa0ht0vzUWDlfioofFCRU0L+6NGDt6XzbgoJvZkMeRQ== -handle-thing@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/handle-thing/-/handle-thing-2.0.1.tgz#857f79ce359580c340d43081cc648970d0bb234e" - integrity sha512-9Qn4yBxelxoh2Ow62nP+Ka/kMnOXRi8BXnRaUwezLNhqelnN49xKz4F/dPP8OYLxLxq6JDtZb2i9XznUQbNPTg== - has-bigints@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/has-bigints/-/has-bigints-1.0.2.tgz#0871bd3e3d51626f6ca0966668ba35d5602d6eaa" @@ -6699,16 +4850,6 @@ hosted-git-info@^9.0.0: dependencies: lru-cache "^11.1.0" -hpack.js@^2.1.6: - version "2.1.6" - resolved "https://registry.yarnpkg.com/hpack.js/-/hpack.js-2.1.6.tgz#87774c0949e513f42e84575b3c45681fade2a0b2" - integrity sha512-zJxVehUdMGIKsRaNt7apO2Gqp0BdqW5yaiGHXXmbpvxgBYVZnAql+BJb4RO5ad2MgpbZKn5G6nMnegrH1FcNYQ== - dependencies: - inherits "^2.0.1" - obuf "^1.0.0" - readable-stream "^2.0.1" - wbuf "^1.1.0" - html-entities@^2.6.0: version "2.6.0" resolved "https://registry.yarnpkg.com/html-entities/-/html-entities-2.6.0.tgz#7c64f1ea3b36818ccae3d3fb48b6974208e984f8" @@ -6733,16 +4874,11 @@ htmlparser2@^10.0.0: entities "^7.0.1" http-cache-semantics@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a" - integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ== - -http-deceiver@^1.2.7: - version "1.2.7" - resolved "https://registry.yarnpkg.com/http-deceiver/-/http-deceiver-1.2.7.tgz#fa7168944ab9a519d337cb0bec7284dc3e723d87" - integrity sha512-LmpOGxTfbpgtGVxJrj5k7asXHCgNZp5nLfp+hWc8QQRqtb7fUy6kRY3BO1h9ddF6yIPYUARgxGOwB42DnxIaNw== + version "4.3.0" + resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz#09eead3b16c6d85552857cc3fbd888d8353a2aaf" + integrity sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA== -http-errors@^2.0.0, http-errors@^2.0.1, http-errors@~2.0.0, http-errors@~2.0.1: +http-errors@^2.0.0, http-errors@^2.0.1, http-errors@~2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.1.tgz#36d2f65bc909c8790018dd36fb4d93da6caae06b" integrity sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ== @@ -6753,21 +4889,6 @@ http-errors@^2.0.0, http-errors@^2.0.1, http-errors@~2.0.0, http-errors@~2.0.1: statuses "~2.0.2" toidentifier "~1.0.1" -http-errors@~1.6.2: - version "1.6.3" - resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.3.tgz#8b55680bb4be283a0b5bf4ea2e38580be1d9320d" - integrity sha512-lks+lVC8dgGyh97jxvxeYTWQFvh4uw4yC12gVl63Cg30sjPX4wuGcdkICVXDAESr6OJGjqGA8Iz5mkeN6zlD7A== - dependencies: - depd "~1.1.2" - inherits "2.0.3" - setprototypeof "1.1.0" - statuses ">= 1.4.0 < 2" - -http-parser-js@>=0.5.1: - version "0.5.8" - resolved "https://registry.yarnpkg.com/http-parser-js/-/http-parser-js-0.5.8.tgz#af23090d9ac4e24573de6f6aecc9d84a48bf20e3" - integrity sha512-SGeBX54F94Wgu5RH3X5jsDtf4eHyRogWX1XGT3b4HuW3tQPM4AaBzoUji/4AAJNXCEOWZ5O0DgZmJw1947gD5Q== - http-proxy-agent@^7.0.0: version "7.0.2" resolved "https://registry.yarnpkg.com/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz#9a8b1f246866c028509486585f62b8f2c18c270e" @@ -6776,38 +4897,6 @@ http-proxy-agent@^7.0.0: agent-base "^7.1.0" debug "^4.3.4" -http-proxy-middleware@3.0.7: - version "3.0.7" - resolved "https://registry.yarnpkg.com/http-proxy-middleware/-/http-proxy-middleware-3.0.7.tgz#53d3a1fe175bcacc507711cc52a0b32baf2c3442" - integrity sha512-iwbQltVlx8bCrqePUM8C+hllHvdawVhQJaLrj1X7qllkvFQdXFsr16pW/mo9+JDVjN+QO2XUx9jd8SmoFkE5qw== - dependencies: - "@types/http-proxy" "^1.17.15" - debug "^4.3.6" - http-proxy "^1.18.1" - is-glob "^4.0.3" - is-plain-object "^5.0.0" - micromatch "^4.0.8" - -http-proxy-middleware@^2.0.9: - version "2.0.9" - resolved "https://registry.yarnpkg.com/http-proxy-middleware/-/http-proxy-middleware-2.0.9.tgz#e9e63d68afaa4eee3d147f39149ab84c0c2815ef" - integrity sha512-c1IyJYLYppU574+YI7R4QyX2ystMtVXZwIdzazUIPIJsHuWNd+mho2j+bKoHftndicGj9yh+xjd+l0yj7VeT1Q== - dependencies: - "@types/http-proxy" "^1.17.8" - http-proxy "^1.18.1" - is-glob "^4.0.1" - is-plain-obj "^3.0.0" - micromatch "^4.0.2" - -http-proxy@^1.18.1: - version "1.18.1" - resolved "https://registry.yarnpkg.com/http-proxy/-/http-proxy-1.18.1.tgz#401541f0534884bbf95260334e72f88ee3976549" - integrity sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ== - dependencies: - eventemitter3 "^4.0.0" - follow-redirects "^1.0.0" - requires-port "^1.0.0" - https-proxy-agent@7.0.6, https-proxy-agent@^7.0.1: version "7.0.6" resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz#da8dfeac7da130b05c2ba4b59c9b6cd66611a6b9" @@ -6821,11 +4910,6 @@ hugerte@~1.0.12: resolved "https://registry.yarnpkg.com/hugerte/-/hugerte-1.0.12.tgz#84337116bd7e76c39e851a51d5dc0214af9882b8" integrity sha512-/JDCdJy1C83a7+RjlfWx6EjRvxqmmHFA5Pzcq8Y0ngdBESiC+2xa4ogsqnRPeadF04Cs95YfTd1SKquDdksjRw== -hyperdyperid@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/hyperdyperid/-/hyperdyperid-1.2.0.tgz#59668d323ada92228d2a869d3e474d5a33b69e6b" - integrity sha512-Y93lCzHYgGWdrJ66yIktxiaGULYc6oGiABxhcO5AufBeOyoIdZF7bIfLaOrbM0iGIOXQQgxxRrFEnb+Y6w1n4A== - iconv-lite@0.6, iconv-lite@^0.6.2, iconv-lite@^0.6.3: version "0.6.3" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.6.3.tgz#a52f80bf38da1952eb5c681790719871a1a72501" @@ -6833,13 +4917,6 @@ iconv-lite@0.6, iconv-lite@^0.6.2, iconv-lite@^0.6.3: dependencies: safer-buffer ">= 2.1.2 < 3.0.0" -iconv-lite@^0.4.4, iconv-lite@~0.4.24: - version "0.4.24" - resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" - integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== - dependencies: - safer-buffer ">= 2.1.2 < 3" - iconv-lite@^0.7.0, iconv-lite@~0.7.0: version "0.7.2" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.7.2.tgz#d0bdeac3f12b4835b7359c2ad89c422a4d1cc72e" @@ -6847,16 +4924,6 @@ iconv-lite@^0.7.0, iconv-lite@~0.7.0: dependencies: safer-buffer ">= 2.1.2 < 3.0.0" -icss-utils@^5.0.0, icss-utils@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/icss-utils/-/icss-utils-5.1.0.tgz#c6be6858abd013d768e98366ae47e25d5887b1ae" - integrity sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA== - -ieee754@^1.1.12: - version "1.2.1" - resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" - integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== - ignore-walk@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-8.0.0.tgz#380c173badc3a18c57ff33440753f0052f572b14" @@ -6884,7 +4951,7 @@ immutable@^5.0.2: resolved "https://registry.yarnpkg.com/immutable/-/immutable-5.1.9.tgz#ac23c3a01992ab665e14ac9ffff298f28cd74a0c" integrity sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg== -import-fresh@^3.2.1, import-fresh@^3.3.0: +import-fresh@^3.2.1: version "3.3.0" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b" integrity sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw== @@ -6897,12 +4964,7 @@ imurmurhash@^0.1.4: resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" integrity sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA== -inherits@2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" - integrity sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw== - -inherits@^2.0.1, inherits@^2.0.3, inherits@~2.0.3, inherits@~2.0.4: +inherits@~2.0.3, inherits@~2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -6917,11 +4979,6 @@ ini@^1.3.4: resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== -ini@^4.1.3: - version "4.1.3" - resolved "https://registry.yarnpkg.com/ini/-/ini-4.1.3.tgz#4c359675a6071a46985eb39b14e4a2c0ec98a795" - integrity sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg== - ini@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/ini/-/ini-6.0.0.tgz#efc7642b276f6a37d22fdf56ef50889d7146bf30" @@ -6956,11 +5013,6 @@ ipaddr.js@1.9.1: resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3" integrity sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g== -ipaddr.js@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-2.2.0.tgz#d33fa7bac284f4de7af949638c9d68157c6b92e8" - integrity sha512-Ag3wB2o37wslZS19hZqorUnrnzSkpOVy+IiiDEiTqNubEYpYuHWIf6K4psgN2ZWKExS4xhVCrRVfb/wfW8fWJA== - is-array-buffer@^3.0.4, is-array-buffer@^3.0.5: version "3.0.5" resolved "https://registry.yarnpkg.com/is-array-buffer/-/is-array-buffer-3.0.5.tgz#65742e1e687bd2cc666253068fd8707fe4d44280" @@ -6970,11 +5022,6 @@ is-array-buffer@^3.0.4, is-array-buffer@^3.0.5: call-bound "^1.0.3" get-intrinsic "^1.2.6" -is-arrayish@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" - integrity sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg== - is-async-function@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/is-async-function/-/is-async-function-2.1.1.tgz#3e69018c8e04e73b738793d020bfe884b9fd3523" @@ -7042,11 +5089,6 @@ is-docker@^2.0.0: resolved "https://registry.yarnpkg.com/is-docker/-/is-docker-2.2.1.tgz#33eeabe23cfe86f14bde4408a02c0cfb853acdaa" integrity sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ== -is-docker@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-docker/-/is-docker-3.0.0.tgz#90093aa3106277d8a77a5910dbae71747e15a200" - integrity sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ== - is-extglob@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" @@ -7094,13 +5136,6 @@ is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3, is-glob@~4.0.1: dependencies: is-extglob "^2.1.1" -is-inside-container@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-inside-container/-/is-inside-container-1.0.0.tgz#e81fba699662eb31dbdaf26766a61d4814717ea4" - integrity sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA== - dependencies: - is-docker "^3.0.0" - is-interactive@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-2.0.0.tgz#40c57614593826da1100ade6059778d597f16e90" @@ -7116,11 +5151,6 @@ is-negative-zero@^2.0.3: resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.3.tgz#ced903a027aca6381b777a5743069d7376a49747" integrity sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw== -is-network-error@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/is-network-error/-/is-network-error-1.1.0.tgz#d26a760e3770226d11c169052f266a4803d9c997" - integrity sha512-tUdRRAnhT+OtCZR/LxZelH/C7QtjtFrTu5tXCA8pl55eTUElUHT+GPYV8MBMBvea/j+NxQqVt3LbWMRir7Gx9g== - is-number-object@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/is-number-object/-/is-number-object-1.1.1.tgz#144b21e95a1bc148205dcc2814a9134ec41b2541" @@ -7134,23 +5164,6 @@ is-number@^7.0.0: resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== -is-plain-obj@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-3.0.0.tgz#af6f2ea14ac5a646183a5bbdb5baabbc156ad9d7" - integrity sha512-gwsOE28k+23GP1B6vFl1oVh/WOzmawBrKwo5Ev6wMKzPkaXaCDIQKzLnvsA42DRlbVTWorkgTKIviAKCWkfUwA== - -is-plain-object@^2.0.4: - version "2.0.4" - resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" - integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== - dependencies: - isobject "^3.0.1" - -is-plain-object@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344" - integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q== - is-promise@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-promise/-/is-promise-4.0.0.tgz#42ff9f84206c1991d26debf520dd5c01042dd2f3" @@ -7232,11 +5245,6 @@ is-weakset@^2.0.3: call-bound "^1.0.3" get-intrinsic "^1.2.6" -is-what@^4.1.8: - version "4.1.16" - resolved "https://registry.yarnpkg.com/is-what/-/is-what-4.1.16.tgz#1ad860a19da8b4895ad5495da3182ce2acdd7a6f" - integrity sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A== - is-wsl@^2.1.1: version "2.2.0" resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-2.2.0.tgz#74a4c76e77ca9fd3f932f290c17ea326cd157271" @@ -7244,13 +5252,6 @@ is-wsl@^2.1.1: dependencies: is-docker "^2.0.0" -is-wsl@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-3.1.0.tgz#e1c657e39c10090afcbedec61720f6b924c3cbd2" - integrity sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw== - dependencies: - is-inside-container "^1.0.0" - isarray@^2.0.5: version "2.0.5" resolved "https://registry.yarnpkg.com/isarray/-/isarray-2.0.5.tgz#8af1e4c1221244cc62459faf38940d4e644a5723" @@ -7271,11 +5272,6 @@ isexe@^3.1.1: resolved "https://registry.yarnpkg.com/isexe/-/isexe-3.1.1.tgz#4a407e2bd78ddfb14bea0c27c6f7072dde775f0d" integrity sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ== -isobject@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" - integrity sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg== - istanbul-lib-coverage@^3.2.0: version "3.2.2" resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz#2d166c4b0644d43a39f04bf6c2edd1e585f31756" @@ -7301,16 +5297,7 @@ jackspeak@^3.1.2: optionalDependencies: "@pkgjs/parseargs" "^0.11.0" -jest-worker@^27.4.5: - version "27.5.1" - resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.5.1.tgz#8d146f0900e8973b106b6f73cc1e9a8cb86f8db0" - integrity sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg== - dependencies: - "@types/node" "*" - merge-stream "^2.0.0" - supports-color "^8.0.0" - -jiti@^1.20.0, jiti@^1.21.7: +jiti@^1.21.7: version "1.21.7" resolved "https://registry.yarnpkg.com/jiti/-/jiti-1.21.7.tgz#9dd81043424a3d28458b193d965f0d18a2300ba9" integrity sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A== @@ -7362,10 +5349,10 @@ js-tokens@^4.0.0: resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== -js-yaml@^4.1.0, js-yaml@^4.3.0: - version "4.3.1" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.3.1.tgz#01216c001d67f48e2cd560d708c7af21090a3848" - integrity sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ== +js-yaml@^4.3.2: + version "4.3.2" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.3.2.tgz#8e44fb14a2643c59726bb15787b5f1512cb3d3fb" + integrity sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA== dependencies: argparse "^2.0.1" @@ -7374,7 +5361,7 @@ jsdoc-type-pratt-parser@~7.1.0: resolved "https://registry.yarnpkg.com/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-7.1.0.tgz#f2d63cbbc3d0d4eaea257eb5f847e8ebc5908dd5" integrity sha512-SX7q7XyCwzM/MEDCYz0l8GgGbJAACGFII9+WfNYr5SLEKukHWRy2Jk3iWRe7P+lpYJNs7oQ+OSei4JtKGUjd7A== -jsesc@^3.0.2, jsesc@~3.1.0: +jsesc@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-3.1.0.tgz#74d335a234f67ed19907fdadfac7ccf9d409825d" integrity sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA== @@ -7384,11 +5371,6 @@ json-buffer@3.0.1: resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.1.tgz#9338802a30d3b6605fbe0613e094008ca8c05a13" integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== -json-parse-even-better-errors@^2.3.0, json-parse-even-better-errors@^2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" - integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== - json-parse-even-better-errors@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-5.0.0.tgz#93c89f529f022e5dadc233409324f0167b1e903e" @@ -7443,7 +5425,7 @@ json5@^1.0.2: dependencies: minimist "^1.2.0" -json5@^2.1.2, json5@^2.2.2, json5@^2.2.3: +json5@^2.2.2, json5@^2.2.3: version "2.2.3" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== @@ -7496,13 +5478,6 @@ jszip@^3.10.1: readable-stream "~2.3.6" setimmediate "^1.0.5" -karma-source-map-support@1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/karma-source-map-support/-/karma-source-map-support-1.4.0.tgz#58526ceccf7e8730e56effd97a4de8d712ac0d6b" - integrity sha512-RsBECncGO17KAoJCYXjv+ckIz+Ii9NCi+9enk+rq6XC81ezYkb4/RHE6CTXdA7IOJqoF3wcaLfVG0CPmE5ca6A== - dependencies: - source-map-support "^0.5.5" - katex@^0.16.0, katex@^0.16.25: version "0.16.45" resolved "https://registry.yarnpkg.com/katex/-/katex-0.16.45.tgz#ba60d39c54746b6b8d39ce0e7f6eace07143149c" @@ -7510,10 +5485,10 @@ katex@^0.16.0, katex@^0.16.25: dependencies: commander "^8.3.0" -kdbush@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/kdbush/-/kdbush-4.0.2.tgz#2f7b7246328b4657dd122b6c7f025fbc2c868e39" - integrity sha512-WbCVYJ27Sz8zi9Q7Q0xHC+05iwkm3Znipc2XTlrnJbsHMYktW4hPhXUE8Ys1engBrvffoSCqbil1JQAa7clRpA== +kdbush@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/kdbush/-/kdbush-4.1.0.tgz#d504bc0447a59be4fb75533a5c25e316b3ed8859" + integrity sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ== keyv@^4.5.4: version "4.5.4" @@ -7527,11 +5502,6 @@ khroma@^2.1.0: resolved "https://registry.yarnpkg.com/khroma/-/khroma-2.1.0.tgz#45f2ce94ce231a437cf5b63c2e886e6eb42bbbb1" integrity sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw== -kind-of@^6.0.2, kind-of@^6.0.3: - version "6.0.3" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" - integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== - klaw-sync@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/klaw-sync/-/klaw-sync-6.0.0.tgz#1fd2cfd56ebb6250181114f0a581167099c2b28c" @@ -7551,14 +5521,6 @@ langium@^4.0.0: vscode-languageserver-textdocument "~1.0.11" vscode-uri "~3.1.0" -launch-editor@^2.6.1: - version "2.9.1" - resolved "https://registry.yarnpkg.com/launch-editor/-/launch-editor-2.9.1.tgz#253f173bd441e342d4344b4dae58291abb425047" - integrity sha512-Gcnl4Bd+hRO9P9icCP/RVVT2o8SFlPXofuCxvA2SaZuH45whSvf5p8x5oih5ftLiVhEI4sp5xDY+R+b3zJBh5w== - dependencies: - picocolors "^1.0.0" - shell-quote "^1.8.1" - layout-base@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/layout-base/-/layout-base-1.0.2.tgz#1291e296883c322a9dd4c5dd82063721b53e26e2" @@ -7576,10 +5538,10 @@ leaflet-polylinedecorator@1.6.0: dependencies: leaflet-rotatedmarker "^0.2.0" -leaflet-providers@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/leaflet-providers/-/leaflet-providers-2.0.0.tgz#dfdab9ca2dccc57c79e1462bc3dd20f78910afcb" - integrity sha512-CWwKEnHd66Qsx0m4o5q5ZOa60s00B91pMxnlr4Y22msubfs7dhbZhdMIz8bvZQkrZqi67ppI1fsZRS6vtrLcOA== +leaflet-providers@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/leaflet-providers/-/leaflet-providers-4.0.0.tgz#a98c5631a671c366739d8658e40be1d02e2c57cb" + integrity sha512-4m3Q4t0e+cHVNIPzlkW9HFWEgplImFRv8cnUFJYOfFoS6p2KosAfmh2Do6qk4HMdqutqbHMpv3F7sn/CUSw6oQ== leaflet-rotatedmarker@^0.2.0: version "0.2.0" @@ -7601,27 +5563,6 @@ leaflet@1.9.4: resolved "https://registry.yarnpkg.com/leaflet/-/leaflet-1.9.4.tgz#23fae724e282fa25745aff82ca4d394748db7d8d" integrity sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA== -less-loader@12.3.0: - version "12.3.0" - resolved "https://registry.yarnpkg.com/less-loader/-/less-loader-12.3.0.tgz#d4a00361568be86a97da3df4f16954b0d4c15340" - integrity sha512-0M6+uYulvYIWs52y0LqN4+QM9TqWAohYSNTo4htE8Z7Cn3G/qQMEmktfHmyJT23k+20kU9zHH2wrfFXkxNLtVw== - -less@4.4.0, less@>=4.9.0: - version "4.9.0" - resolved "https://registry.yarnpkg.com/less/-/less-4.9.0.tgz#df49f940f89a1d158c315609735d3ca12da3e740" - integrity sha512-umRhrCH7fCi8Uj2RcwKjJdvUORTjeWqkdKx0LbcZvjIwsAVsnIAGcxHaqowPeBFBjQuWOeC/bve0AlpFzF/+SQ== - dependencies: - copy-anything "^3.0.5" - parse-node-version "^1.0.1" - optionalDependencies: - errno "^0.1.1" - graceful-fs "^4.1.2" - make-dir "^5.1.0" - mime "^1.4.1" - needle "^3.1.0" - probe-image-size "^7.2.3" - source-map "~0.6.0" - levn@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade" @@ -7635,13 +5576,6 @@ libphonenumber-js@^1.12.35: resolved "https://registry.yarnpkg.com/libphonenumber-js/-/libphonenumber-js-1.12.35.tgz#149d4a66b2a7a518998c430c6d33465abaed23c4" integrity sha512-T/Cz6iLcsZdb5jDncDcUNhSAJ0VlSC9TnsqtBNdpkaAmy24/R1RhErtNWVWBrcUZKs9hSgaVsBkc7HxYnazIfw== -license-webpack-plugin@4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/license-webpack-plugin/-/license-webpack-plugin-4.0.2.tgz#1e18442ed20b754b82f1adeff42249b81d11aec6" - integrity sha512-771TFWFD70G1wLTC4oU2Cw4qvtmNrIw+wRvBtn+okgHl7slJVi7zfNcdmqDL72BojM30VNJ2UHylr1o77U37Jw== - dependencies: - webpack-sources "^3.0.0" - lie@~3.3.0: version "3.3.0" resolved "https://registry.yarnpkg.com/lie/-/lie-3.3.0.tgz#dcf82dee545f46074daf200c7c1c5a08e0f40f6a" @@ -7690,25 +5624,6 @@ lmdb@3.4.2: "@lmdb/lmdb-win32-arm64" "3.4.2" "@lmdb/lmdb-win32-x64" "3.4.2" -loader-runner@^4.3.1: - version "4.3.1" - resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-4.3.1.tgz#6c76ed29b0ccce9af379208299f07f876de737e3" - integrity sha512-IWqP2SCPhyVFTBtRcgMHdzlf9ul25NwaFx4wCEH/KjAXuuHY4yNjvPXsBokp8jCB936PyWRaPKUNh8NvylLp2Q== - -loader-utils@3.3.1: - version "3.3.1" - resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-3.3.1.tgz#735b9a19fd63648ca7adbd31c2327dfe281304e5" - integrity sha512-FMJTLMXfCLMLfJxcX9PFqX5qD88Z5MRGaZCVzfuqeZSPsyiBzs+pahDQjbIWz2QIzPZz0NX9Zy4FX3lmK6YHIg== - -loader-utils@^2.0.0: - version "2.0.4" - resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c" - integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw== - dependencies: - big.js "^5.2.2" - emojis-list "^3.0.0" - json5 "^2.1.2" - locate-path@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" @@ -7733,11 +5648,6 @@ lodash.camelcase@^4.3.0: resolved "https://registry.yarnpkg.com/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz#b28aa6288a2b9fc651035c7711f65ab6190331a6" integrity sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA== -lodash.debounce@^4.0.8: - version "4.0.8" - resolved "https://registry.yarnpkg.com/lodash.debounce/-/lodash.debounce-4.0.8.tgz#82d79bff30a67c4005ffd5e2515300ad9ca4d7af" - integrity sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow== - lodash.merge@^4.6.2: version "4.6.2" resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a" @@ -7791,11 +5701,6 @@ magic-string@0.30.17: dependencies: "@jridgewell/sourcemap-codec" "^1.5.0" -make-dir@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-5.1.0.tgz#59b2d9acf7ffa543d14238617a697458fa8dd5c9" - integrity sha512-IfpFq6UM39dUNiphpA6uDezNx/AvWyhwfICWPR3t1VspkgkMZrL+Rk1RbN1bx+aeNYwOrqGJgEgV3yotk+ZUVw== - make-error@^1.1.1: version "1.3.6" resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" @@ -7824,37 +5729,29 @@ make-plural@^7.0.0: resolved "https://registry.yarnpkg.com/make-plural/-/make-plural-7.4.0.tgz#fa6990dd550dea4de6b20163f74e5ed83d8a8d6d" integrity sha512-4/gC9KVNTV6pvYg2gFeQYTW3mWaoJt7WZE5vrp1KnQDgW92JtYZnzmZT81oj/dUTqAIu0ufI2x3dkgu3bB1tYg== -maplibre-gl@5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/maplibre-gl/-/maplibre-gl-5.2.0.tgz#e3cdb66c82232cffbe149b032776484722caee4e" - integrity sha512-9zZKD0M80qtDsqBet+EDuAhoCeA/cnAuZAA0p3hcGKGbyjM/SH+R6wQvnBEgvJz9UhDynnkoKdUwhI+fUkHoXQ== - dependencies: - "@mapbox/geojson-rewind" "^0.5.2" - "@mapbox/jsonlint-lines-primitives" "^2.0.2" - "@mapbox/point-geometry" "^0.1.0" - "@mapbox/tiny-sdf" "^2.0.6" - "@mapbox/unitbezier" "^0.0.1" - "@mapbox/vector-tile" "^1.3.1" - "@mapbox/whoots-js" "^3.1.0" - "@maplibre/maplibre-gl-style-spec" "^23.1.0" +maplibre-gl@6.11.2: + version "6.11.2" + resolved "https://registry.yarnpkg.com/maplibre-gl/-/maplibre-gl-6.11.2.tgz#25f1266666c16f6b935cabccba554c238a3cf394" + integrity sha512-Xh06pxoipjX/Ad1sUPGhiNh9go9naCNGZZ1IJm3sIeqK1kYGuMaMDSTIGDQ2igOLfVyukJU7kvEOA089VO7Z7g== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + "@mapbox/tiny-sdf" "^2.2.0" + "@mapbox/unitbezier" "^1.0.0" + "@mapbox/vector-tile" "^3.0.0" + "@maplibre/geojson-vt" "^6.1.1" + "@maplibre/maplibre-gl-style-spec" "^26.4.4" + "@maplibre/mlt" "^1.3.0" + "@maplibre/vt-pbf" "^4.3.2" "@types/geojson" "^7946.0.16" - "@types/geojson-vt" "3.2.5" - "@types/mapbox__point-geometry" "^0.1.4" - "@types/mapbox__vector-tile" "^1.3.4" - "@types/pbf" "^3.0.5" - "@types/supercluster" "^7.1.3" - earcut "^3.0.1" - geojson-vt "^4.0.2" - gl-matrix "^3.4.3" - global-prefix "^4.0.0" - kdbush "^4.0.2" + bidi-js "^1.1.0" + earcut "^3.2.3" + gl-matrix "^3.4.4" + kdbush "^4.1.0" murmurhash-js "^1.0.0" - pbf "^3.3.0" - potpack "^2.0.0" + pbf "^5.1.2" + potpack "^2.1.0" quickselect "^3.0.0" - supercluster "^8.0.1" tinyqueue "^3.0.0" - vt-pbf "^3.1.3" marked@^16.3.0, marked@~16.4.2: version "16.4.2" @@ -7866,50 +5763,15 @@ math-intrinsics@^1.1.0: resolved "https://registry.yarnpkg.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz#a0dd74be81e2aa5c2f27e65ce283605ee4e2b7f9" integrity sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g== -media-typer@0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" - integrity sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ== - media-typer@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-1.1.0.tgz#6ab74b8f2d3320f2064b2a87a38e7931ff3a5561" integrity sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw== -memfs@^4.43.1, memfs@^4.6.0: - version "4.56.10" - resolved "https://registry.yarnpkg.com/memfs/-/memfs-4.56.10.tgz#eaf2f6556db10f91f1e9ad9f1274fd988c646202" - integrity sha512-eLvzyrwqLHnLYalJP7YZ3wBe79MXktMdfQbvMrVD80K+NhrIukCVBvgP30zTJYEEDh9hZ/ep9z0KOdD7FSHo7w== - dependencies: - "@jsonjoy.com/fs-core" "4.56.10" - "@jsonjoy.com/fs-fsa" "4.56.10" - "@jsonjoy.com/fs-node" "4.56.10" - "@jsonjoy.com/fs-node-builtins" "4.56.10" - "@jsonjoy.com/fs-node-to-fsa" "4.56.10" - "@jsonjoy.com/fs-node-utils" "4.56.10" - "@jsonjoy.com/fs-print" "4.56.10" - "@jsonjoy.com/fs-snapshot" "4.56.10" - "@jsonjoy.com/json-pack" "^1.11.0" - "@jsonjoy.com/util" "^1.9.0" - glob-to-regex.js "^1.0.1" - thingies "^2.5.0" - tree-dump "^1.0.3" - tslib "^2.0.0" - -merge-descriptors@1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.3.tgz#d80319a65f3c7935351e5cfdac8f9318504dbed5" - integrity sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ== - merge-descriptors@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-2.0.0.tgz#ea922f660635a2249ee565e0449f951e6b603808" - integrity sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g== - -merge-stream@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" - integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== + integrity sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g== merge2@^1.3.0: version "1.4.1" @@ -7943,11 +5805,6 @@ merge2@^1.3.0: ts-dedent "^2.2.0" uuid "^11.1.0" -methods@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee" - integrity sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w== - micromatch@^4.0.2, micromatch@^4.0.8: version "4.0.8" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.8.tgz#d66fa18f3a47076789320b9b1af32bd86d9fa202" @@ -7956,53 +5813,23 @@ micromatch@^4.0.2, micromatch@^4.0.8: braces "^3.0.3" picomatch "^2.3.1" -mime-db@1.52.0: - version "1.52.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" - integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== - -"mime-db@>= 1.43.0 < 2", mime-db@^1.54.0: +mime-db@^1.54.0: version "1.54.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.54.0.tgz#cddb3ee4f9c64530dff640236661d42cb6a314f5" integrity sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ== -mime-types@^2.1.27, mime-types@^2.1.31, mime-types@~2.1.17, mime-types@~2.1.24, mime-types@~2.1.34: - version "2.1.35" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" - integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== - dependencies: - mime-db "1.52.0" - -mime-types@^3.0.0, mime-types@^3.0.1, mime-types@^3.0.2: +mime-types@^3.0.0, mime-types@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-3.0.2.tgz#39002d4182575d5af036ffa118100f2524b2e2ab" integrity sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A== dependencies: mime-db "^1.54.0" -mime@1.6.0, mime@^1.4.1: - version "1.6.0" - resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" - integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== - mimic-function@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/mimic-function/-/mimic-function-5.0.1.tgz#acbe2b3349f99b9deaca7fb70e48b83e94e67076" integrity sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA== -mini-css-extract-plugin@2.9.4: - version "2.9.4" - resolved "https://registry.yarnpkg.com/mini-css-extract-plugin/-/mini-css-extract-plugin-2.9.4.tgz#cafa1a42f8c71357f49cd1566810d74ff1cb0200" - integrity sha512-ZWYT7ln73Hptxqxk2DxPU9MmapXRhxkJD6tkSR04dnQxm8BGu2hzgKLugK5yySD97u/8yy7Ma7E76k9ZdvtjkQ== - dependencies: - schema-utils "^4.0.0" - tapable "^2.2.1" - -minimalistic-assert@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" - integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A== - minimatch@9.0.1, minimatch@^9.0.4, minimatch@^9.0.5, minimatch@^9.0.7: version "9.0.7" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.7.tgz#d76c4d0b3b527877016d6cc1b9922fc8e0ffe7b0" @@ -8097,17 +5924,17 @@ mlly@^1.7.4, mlly@^1.8.0: pkg-types "^1.3.1" ufo "^1.6.3" -moment-timezone@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/moment-timezone/-/moment-timezone-0.6.0.tgz#c5a6519171f31a64739ea75d33f5c136c08ff608" - integrity sha512-ldA5lRNm3iJCWZcBCab4pnNL3HSZYXVb/3TYr75/1WCTWYuTqYUb5f/S384pncYjJ88lbO8Z4uPDvmoluHJc8Q== +moment-timezone@^0.6.5: + version "0.6.5" + resolved "https://registry.yarnpkg.com/moment-timezone/-/moment-timezone-0.6.5.tgz#a8153ebe88199bd76f2d2ce329eb1d568eafbdee" + integrity sha512-KKzZAxGv2Qx4cnk6eSlvf4C+DLFW52vmMY5MN7UARY7GONbozkutylQG3DrrtmLCTXdQ5XZrqao9cI16bLFzXA== dependencies: moment "^2.29.4" -moment@^2.29.4, moment@^2.30.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== +moment@^2.29.4, moment@^2.31.0: + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== moo@^0.5.1: version "0.5.2" @@ -8124,12 +5951,7 @@ mrmime@2.0.1: resolved "https://registry.yarnpkg.com/mrmime/-/mrmime-2.0.1.tgz#bc3e87f7987853a54c9850eeb1f1078cd44adddc" integrity sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ== -ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" - integrity sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A== - -ms@2.1.3, ms@^2.1.1, ms@^2.1.3: +ms@^2.1.1, ms@^2.1.3: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== @@ -8155,14 +5977,6 @@ msgpackr@^1.11.2: optionalDependencies: msgpackr-extract "^3.0.2" -multicast-dns@^7.2.5: - version "7.2.5" - resolved "https://registry.yarnpkg.com/multicast-dns/-/multicast-dns-7.2.5.tgz#77eb46057f4d7adbd16d9290fa7299f6fa64cced" - integrity sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg== - dependencies: - dns-packet "^5.2.2" - thunky "^1.0.2" - murmurhash-js@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/murmurhash-js/-/murmurhash-js-1.0.0.tgz#b06278e21fc6c37fa5313732b0412bcb6ae15f51" @@ -8192,43 +6006,11 @@ natural-compare@^1.4.0: resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== -needle@^2.5.2: - version "2.9.1" - resolved "https://registry.yarnpkg.com/needle/-/needle-2.9.1.tgz#22d1dffbe3490c2b83e301f7709b6736cd8f2684" - integrity sha512-6R9fqJ5Zcmf+uYaFgdIHmLwNldn5HbK8L5ybn7Uz+ylX/rnOsSp1AHcvQSrCaFN+qNM1wpymHqD7mVasEOlHGQ== - dependencies: - debug "^3.2.6" - iconv-lite "^0.4.4" - sax "^1.2.4" - -needle@^3.1.0: - version "3.3.1" - resolved "https://registry.yarnpkg.com/needle/-/needle-3.3.1.tgz#63f75aec580c2e77e209f3f324e2cdf3d29bd049" - integrity sha512-6k0YULvhpw+RoLNiQCRKOl09Rv1dPLr8hHnVjHqdolKwDrdNyk+Hmrthi4lIGPPz3r39dLx0hsF5s40sZ3Us4Q== - dependencies: - iconv-lite "^0.6.3" - sax "^1.2.4" - -negotiator@0.6.3: - version "0.6.3" - resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.3.tgz#58e323a72fedc0d6f9cd4d31fe49f51479590ccd" - integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg== - negotiator@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-1.0.0.tgz#b6c91bb47172d69f93cfd7c357bbb529019b5f6a" integrity sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg== -negotiator@~0.6.4: - version "0.6.4" - resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.4.tgz#777948e2452651c570b712dd01c23e262713fff7" - integrity sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w== - -neo-async@^2.6.2: - version "2.6.2" - resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" - integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== - ngrx-store-freeze@^0.2.4: version "0.2.4" resolved "https://registry.yarnpkg.com/ngrx-store-freeze/-/ngrx-store-freeze-0.2.4.tgz#146687cdf7e21244eb9003c7e883f2125847076c" @@ -8382,11 +6164,6 @@ normalize-path@^3.0.0, normalize-path@~3.0.0: resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== -normalize-range@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/normalize-range/-/normalize-range-0.1.2.tgz#2d10c06bdfd312ea9777695a4d28439456b75942" - integrity sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA== - npm-bundled@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/npm-bundled/-/npm-bundled-5.0.0.tgz#5025d847cfd06c7b8d9432df01695d0133d9ee80" @@ -8536,23 +6313,13 @@ objectpath@^2.0.0: resolved "https://registry.yarnpkg.com/objectpath/-/objectpath-2.0.0.tgz#c4463123fcf00469be8282a2ea51704fb9469cc1" integrity sha512-IWH9JOBUJz4HHBtXm1qqwoPiDAB8Qp+ZBE4PpXsOlXVEnxGa+fAgfAZFwN6L1cUYvzPpFeJ1HsY1WAhoOqQq7Q== -obuf@^1.0.0, obuf@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/obuf/-/obuf-1.1.2.tgz#09bea3343d41859ebd446292d11c9d4db619084e" - integrity sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg== - -on-finished@^2.4.1, on-finished@~2.4.1: +on-finished@^2.4.1: version "2.4.1" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f" integrity sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg== dependencies: ee-first "1.1.1" -on-headers@~1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/on-headers/-/on-headers-1.1.0.tgz#59da4f91c45f5f989c6e4bcedc5a3b0aed70ff65" - integrity sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A== - once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" @@ -8567,16 +6334,6 @@ onetime@^7.0.0: dependencies: mimic-function "^5.0.0" -open@10.2.0, open@^10.0.3: - version "10.2.0" - resolved "https://registry.yarnpkg.com/open/-/open-10.2.0.tgz#b9d855be007620e80b6fb05fac98141fe62db73c" - integrity sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA== - dependencies: - default-browser "^5.2.1" - define-lazy-prop "^3.0.0" - is-inside-container "^1.0.0" - wsl-utils "^0.1.0" - open@^7.4.2: version "7.4.2" resolved "https://registry.yarnpkg.com/open/-/open-7.4.2.tgz#b8147e26dcf3e426316c730089fd71edd29c2321" @@ -8659,15 +6416,6 @@ p-map@^7.0.2: resolved "https://registry.yarnpkg.com/p-map/-/p-map-7.0.4.tgz#b81814255f542e252d5729dca4d66e5ec14935b8" integrity sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ== -p-retry@^6.2.0: - version "6.2.0" - resolved "https://registry.yarnpkg.com/p-retry/-/p-retry-6.2.0.tgz#8d6df01af298750009691ce2f9b3ad2d5968f3bd" - integrity sha512-JA6nkq6hKyWLLasXQXUrO4z8BUZGUt/LjlJxx8Gb2+2ntodU/SS63YZ8b0LUTbQ8ZB9iwOfhEPhg4ykKnn2KsA== - dependencies: - "@types/retry" "0.12.2" - is-network-error "^1.0.0" - retry "^0.13.1" - p-try@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" @@ -8725,21 +6473,6 @@ parse-imports-exports@^0.2.4: dependencies: parse-statements "1.0.11" -parse-json@^5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.2.0.tgz#c76fc66dee54231c962b22bcc8a72cf2f99753cd" - integrity sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg== - dependencies: - "@babel/code-frame" "^7.0.0" - error-ex "^1.3.1" - json-parse-even-better-errors "^2.3.0" - lines-and-columns "^1.1.6" - -parse-node-version@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/parse-node-version/-/parse-node-version-1.0.1.tgz#e2b5dbede00e7fa9bc363607f53327e8b073189b" - integrity sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA== - parse-statements@1.0.11: version "1.0.11" resolved "https://registry.yarnpkg.com/parse-statements/-/parse-statements-1.0.11.tgz#8787c5d383ae5746568571614be72b0689584344" @@ -8768,7 +6501,7 @@ parse5@^8.0.0: dependencies: entities "^6.0.0" -parseurl@^1.3.3, parseurl@~1.3.2, parseurl@~1.3.3: +parseurl@^1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== @@ -8834,22 +6567,16 @@ path-to-regexp@^8.0.0: resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-8.4.0.tgz#8e98fcd94826aff01a90c544ef74ffbaca3a78ed" integrity sha512-PuseHIvAnz3bjrM2rGJtSgo1zjgxapTLZ7x2pjhzWwlp4SJQgK3f3iZIQwkpEnBaKz6seKBADpM4B4ySkuYypg== -path-to-regexp@~0.1.12: - version "0.1.13" - resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.13.tgz#9b22ec16bc3ab88d05a0c7e369869421401ab17d" - integrity sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA== - pathe@^2.0.1, pathe@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/pathe/-/pathe-2.0.3.tgz#3ecbec55421685b70a9da872b2cff3e1cbed1716" integrity sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w== -pbf@^3.2.1, pbf@^3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/pbf/-/pbf-3.3.0.tgz#1790f3d99118333cc7f498de816028a346ef367f" - integrity sha512-XDF38WCH3z5OV/OVa8GKUNtLAyneuzbCisx7QUCF8Q6Nutx0WnJrQe5O+kOtBlLfRNUws98Y58Lblp+NJG5T4Q== +pbf@^5.0.0, pbf@^5.1.0, pbf@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/pbf/-/pbf-5.1.2.tgz#07c427819eda32f02f1ec9741558f61444f2e1c0" + integrity sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w== dependencies: - ieee754 "^1.1.12" resolve-protobuf-schema "^2.1.0" photoswipe@^5.4.4: @@ -8857,7 +6584,7 @@ photoswipe@^5.4.4: resolved "https://registry.yarnpkg.com/photoswipe/-/photoswipe-5.4.4.tgz#e045dc036453493188d5c8665b0e8f1000ac4d6e" integrity sha512-WNFHoKrkZNnvFFhbHL93WDkW3ifwVOXSW3w1UuZZelSmgXpIGiZSNlZJq37rR8YejqME2rHs9EhH9ZvlvFH2NA== -picocolors@^1.0.0, picocolors@^1.1.1: +picocolors@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== @@ -8882,10 +6609,10 @@ pirates@^4.0.1: resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.7.tgz#643b4a18c4257c8a65104b73f3049ce9a0a15e22" integrity sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA== -piscina@5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/piscina/-/piscina-5.2.0.tgz#3a9a568ab9e3a0556b5c94522ba305962de13e3b" - integrity sha512-DszUCKeVN/5G5QKo6jAVHL8fmKnkJvQ0ACiVgY7YGCq3TUB2oznAOayvZPIAdEThvhczkXR+qm3IHsNXpFCYfA== +piscina@5.3.2: + version "5.3.2" + resolved "https://registry.yarnpkg.com/piscina/-/piscina-5.3.2.tgz#ea9376457c47f54d01ecd7556eed94c49160f400" + integrity sha512-vv7l/mM7B9WgrhDaudIqv1x6v4LOBRYYmpWGdWushhpbCmVHp11sUB2v4hj1CAeTGXVxuZFz6xOU1RalAiPKfQ== optionalDependencies: "@napi-rs/nice" "^1.0.4" @@ -8903,18 +6630,6 @@ pkg-types@^1.3.1: mlly "^1.7.4" pathe "^2.0.1" -pkijs@^3.3.3: - version "3.4.0" - resolved "https://registry.yarnpkg.com/pkijs/-/pkijs-3.4.0.tgz#d9164def30ff6d97be2d88966d5e36192499ca9c" - integrity sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw== - dependencies: - "@noble/hashes" "1.4.0" - asn1js "^3.0.6" - bytestreamjs "^2.0.1" - pvtsutils "^1.3.6" - pvutils "^1.1.3" - tslib "^2.8.1" - pngjs@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/pngjs/-/pngjs-5.0.0.tgz#e79dd2b215767fd9c04561c01236df960bce7fbb" @@ -8976,48 +6691,11 @@ postcss-js@^4.0.1: dependencies: lilconfig "^3.1.1" -postcss-loader@8.1.1: - version "8.1.1" - resolved "https://registry.yarnpkg.com/postcss-loader/-/postcss-loader-8.1.1.tgz#2822589e7522927344954acb55bbf26e8b195dfe" - integrity sha512-0IeqyAsG6tYiDRCYKQJLAmgQr47DX6N7sFSWvQxt6AcupX8DIdmykuk/o/tx0Lze3ErGHJEp5OSRxrelC6+NdQ== - dependencies: - cosmiconfig "^9.0.0" - jiti "^1.20.0" - semver "^7.5.4" - postcss-media-query-parser@^0.2.3: version "0.2.3" resolved "https://registry.yarnpkg.com/postcss-media-query-parser/-/postcss-media-query-parser-0.2.3.tgz#27b39c6f4d94f81b1a73b8f76351c609e5cef244" integrity sha512-3sOlxmbKcSHMjlUXQZKQ06jOswE7oVkXPxmZdoB1r5l0q6gTFTQSHxNxOrCccElbW7dxNytifNEo8qidX2Vsig== -postcss-modules-extract-imports@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.1.0.tgz#b4497cb85a9c0c4b5aabeb759bb25e8d89f15002" - integrity sha512-k3kNe0aNFQDAZGbin48pL2VNidTF0w4/eASDsxlyspobzU3wZQLOGj7L9gfRe0Jo9/4uud09DsjFNH7winGv8Q== - -postcss-modules-local-by-default@^4.0.5: - version "4.0.5" - resolved "https://registry.yarnpkg.com/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.0.5.tgz#f1b9bd757a8edf4d8556e8d0f4f894260e3df78f" - integrity sha512-6MieY7sIfTK0hYfafw1OMEG+2bg8Q1ocHCpoWLqOKj3JXlKu4G7btkmM/B7lFubYkYWmRSPLZi5chid63ZaZYw== - dependencies: - icss-utils "^5.0.0" - postcss-selector-parser "^6.0.2" - postcss-value-parser "^4.1.0" - -postcss-modules-scope@^3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/postcss-modules-scope/-/postcss-modules-scope-3.2.0.tgz#a43d28289a169ce2c15c00c4e64c0858e43457d5" - integrity sha512-oq+g1ssrsZOsx9M96c5w8laRmvEu9C3adDSjI8oTcbfkrTE8hx/zfyobUoWIxaKPO8bt6S62kxpw5GqypEw1QQ== - dependencies: - postcss-selector-parser "^6.0.4" - -postcss-modules-values@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz#d7c5e7e68c3bb3c9b27cbf48ca0bb3ffb4602c9c" - integrity sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ== - dependencies: - icss-utils "^5.0.0" - postcss-nested@^6.2.0: version "6.2.0" resolved "https://registry.yarnpkg.com/postcss-nested/-/postcss-nested-6.2.0.tgz#4c2d22ab5f20b9cb61e2c5c5915950784d068131" @@ -9025,7 +6703,7 @@ postcss-nested@^6.2.0: dependencies: postcss-selector-parser "^6.1.1" -postcss-selector-parser@^6.0.2, postcss-selector-parser@^6.0.4, postcss-selector-parser@^6.1.1, postcss-selector-parser@^6.1.2: +postcss-selector-parser@^6.1.1, postcss-selector-parser@^6.1.2: version "6.1.2" resolved "https://registry.yarnpkg.com/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz#27ecb41fb0e3b6ba7a1ec84fff347f734c7929de" integrity sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg== @@ -9033,12 +6711,12 @@ postcss-selector-parser@^6.0.2, postcss-selector-parser@^6.0.4, postcss-selector cssesc "^3.0.0" util-deprecate "^1.0.2" -postcss-value-parser@^4.0.0, postcss-value-parser@^4.1.0, postcss-value-parser@^4.2.0: +postcss-value-parser@^4.0.0, postcss-value-parser@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz#723c09920836ba6d3e5af019f92bc0971c02e514" integrity sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ== -postcss@8.5.23, postcss@^8.2.14, postcss@^8.4.33, postcss@^8.4.4, postcss@^8.4.47, postcss@^8.4.49, postcss@^8.5.6: +postcss@^8.4.4, postcss@^8.4.47, postcss@^8.4.49, postcss@^8.5.6: version "8.5.23" resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.5.23.tgz#3493550116f478487298301d2c2e8dc5a56e6594" integrity sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg== @@ -9052,7 +6730,7 @@ postinstall-prepare@^2.0.0: resolved "https://registry.yarnpkg.com/postinstall-prepare/-/postinstall-prepare-2.0.0.tgz#2a6867c1a13a05502aa115d0495efbbd778769cb" integrity sha512-lLFwEKdnGLAaRAm8OpXP6HwrXRW+b8Hh9vRhVHZKmCdobd+D21YM38BCDsi3zrePLSe8Tt0H/mbYkh7/ySQQMg== -potpack@^2.0.0: +potpack@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/potpack/-/potpack-2.1.0.tgz#fe548e2f9061e9937f17191c1ab6dd98ca30e02f" integrity sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ== @@ -9067,15 +6745,6 @@ prismjs@^1.30.0: resolved "https://registry.yarnpkg.com/prismjs/-/prismjs-1.30.0.tgz#d9709969d9d4e16403f6f348c63553b19f0975a9" integrity sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw== -probe-image-size@^7.2.3: - version "7.4.0" - resolved "https://registry.yarnpkg.com/probe-image-size/-/probe-image-size-7.4.0.tgz#c189ae04e9aad1e3fa3a0998a956a7e9aab7f66d" - integrity sha512-cdEprVtZxV+awMde9X+4jILBFYh4CARxVrQaMl4wY4YcPWbul9jntXrIW95NInBDyJwcVUP3U0T6yukN8rMBaQ== - dependencies: - lodash.merge "^4.6.2" - needle "^2.5.2" - stream-parser "~0.3.1" - proc-log@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/proc-log/-/proc-log-5.0.0.tgz#e6c93cf37aef33f835c53485f314f50ea906a9d8" @@ -9109,36 +6778,19 @@ protocol-buffers-schema@^3.3.1: resolved "https://registry.yarnpkg.com/protocol-buffers-schema/-/protocol-buffers-schema-3.6.0.tgz#77bc75a48b2ff142c1ad5b5b90c94cd0fa2efd03" integrity sha512-TdDRD+/QNdrCGCE7v8340QyuXd4kIWIgapsE2+n/SaGiSSbomYl4TjHlvIoCWRpE7wFt02EpB35VVA2ImcBVqw== -proxy-addr@^2.0.7, proxy-addr@~2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== +proxy-addr@^2.0.7: + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" -prr@~1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" - integrity sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw== - punycode@^2.1.0: version "2.3.1" resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.1.tgz#027422e2faec0b25e1549c3e1bd8309b9133b6e5" integrity sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg== -pvtsutils@^1.3.6: - version "1.3.6" - resolved "https://registry.yarnpkg.com/pvtsutils/-/pvtsutils-1.3.6.tgz#ec46e34db7422b9e4fdc5490578c1883657d6001" - integrity sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg== - dependencies: - tslib "^2.8.1" - -pvutils@^1.1.3, pvutils@^1.1.5: - version "1.2.0" - resolved "https://registry.yarnpkg.com/pvutils/-/pvutils-1.2.0.tgz#4b5487a9cccd52d275b0538775790a3ca982bc22" - integrity sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg== - qrcode@^1.5.4: version "1.5.4" resolved "https://registry.yarnpkg.com/qrcode/-/qrcode-1.5.4.tgz#5cb81d86eb57c675febb08cf007fff963405da88" @@ -9148,10 +6800,10 @@ qrcode@^1.5.4: pngjs "^5.0.0" yargs "^15.3.1" -qs@^6.14.0, qs@^6.14.1, qs@~6.15.1: - version "6.15.3" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.15.3.tgz#76852132a58ed5c7c0ef67e4441b9bb5d6061b3b" - integrity sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A== +qs@^6.14.0, qs@^6.14.1: + version "6.16.1" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.16.1.tgz#0643e17993e551759c85078e1f0bc4b9fe908020" + integrity sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg== dependencies: es-define-property "^1.0.1" side-channel "^1.1.1" @@ -9171,7 +6823,7 @@ quickselect@^3.0.0: resolved "https://registry.yarnpkg.com/quickselect/-/quickselect-3.0.0.tgz#a37fc953867d56f095a20ac71c6d27063d2de603" integrity sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g== -range-parser@^1.2.1, range-parser@~1.2.1: +range-parser@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== @@ -9193,16 +6845,6 @@ raw-body@^3.0.0, raw-body@^3.0.1: iconv-lite "~0.7.0" unpipe "~1.0.0" -raw-body@~2.5.3: - version "2.5.3" - resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.5.3.tgz#11c6650ee770a7de1b494f197927de0c923822e2" - integrity sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA== - dependencies: - bytes "~3.1.2" - http-errors "~2.0.1" - iconv-lite "~0.4.24" - unpipe "~1.0.0" - rbush@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/rbush/-/rbush-3.0.1.tgz#5fafa8a79b3b9afdfe5008403a720cc1de882ecf" @@ -9217,7 +6859,7 @@ read-cache@^1.0.0: dependencies: pify "^2.3.0" -readable-stream@^2.0.1, readable-stream@~2.3.6: +readable-stream@~2.3.6: version "2.3.8" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.8.tgz#91125e8042bba1b9887f49345f6277027ce8be9b" integrity sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA== @@ -9230,15 +6872,6 @@ readable-stream@^2.0.1, readable-stream@~2.3.6: string_decoder "~1.1.1" util-deprecate "~1.0.1" -readable-stream@^3.0.6: - version "3.6.2" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.2.tgz#56a9b36ea965c00c5a93ef31eb111a0f11056967" - integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== - dependencies: - inherits "^2.0.3" - string_decoder "^1.1.1" - util-deprecate "^1.0.1" - readdirp@^4.0.1: version "4.1.2" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-4.1.2.tgz#eb85801435fbf2a7ee58f19e0921b068fc69948d" @@ -9256,7 +6889,7 @@ reduce-flatten@^2.0.0: resolved "https://registry.yarnpkg.com/reduce-flatten/-/reduce-flatten-2.0.0.tgz#734fd84e65f375d7ca4465c69798c25c9d10ae27" integrity sha512-EJ4UNY/U1t2P/2k6oqotuX2Cc3T6nxJwsM0N0asT7dhrtH1ltUxDn4NalSYmPE2rCkVpcf/X6R0wDwcFpzhd4w== -reflect-metadata@^0.2.0, reflect-metadata@^0.2.2: +reflect-metadata@^0.2.0: version "0.2.2" resolved "https://registry.yarnpkg.com/reflect-metadata/-/reflect-metadata-0.2.2.tgz#400c845b6cba87a21f2c65c4aeb158f4fa4d9c5b" integrity sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q== @@ -9275,23 +6908,6 @@ reflect.getprototypeof@^1.0.6, reflect.getprototypeof@^1.0.9: get-proto "^1.0.1" which-builtin-type "^1.2.1" -regenerate-unicode-properties@^10.2.2: - version "10.2.2" - resolved "https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-10.2.2.tgz#aa113812ba899b630658c7623466be71e1f86f66" - integrity sha512-m03P+zhBeQd1RGnYxrGyDAPpWX/epKirLrp8e3qevZdVkKtnCrjjWczIbYc8+xd6vcTStVlqfycTx1KR4LOr0g== - dependencies: - regenerate "^1.4.2" - -regenerate@^1.4.2: - version "1.4.2" - resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.4.2.tgz#b9346d8827e8f5a32f7ba29637d398b69014848a" - integrity sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A== - -regex-parser@^2.2.11: - version "2.3.0" - resolved "https://registry.yarnpkg.com/regex-parser/-/regex-parser-2.3.0.tgz#4bb61461b1a19b8b913f3960364bb57887f920ee" - integrity sha512-TVILVSz2jY5D47F4mA4MppkBrafEaiUWJO/TcZHEIuI13AqoZMkK1WMA4Om1YkYbTx+9Ki1/tSUXbceyr9saRg== - regexp.prototype.flags@^1.5.4: version "1.5.4" resolved "https://registry.yarnpkg.com/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz#1ad6c62d44a259007e55b3970e00f746efbcaa19" @@ -9304,30 +6920,6 @@ regexp.prototype.flags@^1.5.4: gopd "^1.2.0" set-function-name "^2.0.2" -regexpu-core@^6.3.1: - version "6.4.0" - resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-6.4.0.tgz#3580ce0c4faedef599eccb146612436b62a176e5" - integrity sha512-0ghuzq67LI9bLXpOX/ISfve/Mq33a4aFRzoQYhnnok1JOFpmE/A2TBGkNVenOGEeSBCjIiWcc6MVOG5HEQv0sA== - dependencies: - regenerate "^1.4.2" - regenerate-unicode-properties "^10.2.2" - regjsgen "^0.8.0" - regjsparser "^0.13.0" - unicode-match-property-ecmascript "^2.0.0" - unicode-match-property-value-ecmascript "^2.2.1" - -regjsgen@^0.8.0: - version "0.8.0" - resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.8.0.tgz#df23ff26e0c5b300a6470cad160a9d090c3a37ab" - integrity sha512-RvwtGe3d7LvWiDQXeQw8p5asZUmfU1G/l6WbUXeHta7Y2PEIvBTwH6E2EfmYUK8pxcxEdEmaomqyp0vZZ7C+3Q== - -regjsparser@^0.13.0: - version "0.13.0" - resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.13.0.tgz#01f8351335cf7898d43686bc74d2dd71c847ecc0" - integrity sha512-NZQZdC5wOE/H3UT28fVGL+ikOZcEzfMGk/c3iN9UGxzWHMa1op7274oyiUVrAG4B2EuFhus8SvkaYnhvW92p9Q== - dependencies: - jsesc "~3.1.0" - require-directory@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" @@ -9343,11 +6935,6 @@ require-main-filename@^2.0.0: resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg== -requires-port@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff" - integrity sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ== - reserved-identifiers@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/reserved-identifiers/-/reserved-identifiers-1.2.0.tgz#d2982cd698e317dd3dced1ee1c52412dbd64fc64" @@ -9365,17 +6952,6 @@ resolve-protobuf-schema@^2.1.0: dependencies: protocol-buffers-schema "^3.3.1" -resolve-url-loader@5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/resolve-url-loader/-/resolve-url-loader-5.0.0.tgz#ee3142fb1f1e0d9db9524d539cfa166e9314f795" - integrity sha512-uZtduh8/8srhBoMx//5bwqjQ+rfYOUq8zC9NrMUGtjBiGTtFJM42s58/36+hTqeqINcnYe08Nj3LkK9lW4N8Xg== - dependencies: - adjust-sourcemap-loader "^4.0.0" - convert-source-map "^1.7.0" - loader-utils "^2.0.0" - postcss "^8.2.14" - source-map "0.6.1" - resolve@1.22.10: version "1.22.10" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.10.tgz#b663e83ffb09bbf2386944736baae803029b8b39" @@ -9385,7 +6961,7 @@ resolve@1.22.10: path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" -resolve@^1.1.7, resolve@^1.22.10, resolve@^1.22.4, resolve@^1.22.8: +resolve@^1.1.7, resolve@^1.22.4, resolve@^1.22.8: version "1.22.11" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.11.tgz#aad857ce1ffb8bfa9b0b1ac29f1156383f68c262" integrity sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ== @@ -9407,11 +6983,6 @@ retry@^0.12.0: resolved "https://registry.yarnpkg.com/retry/-/retry-0.12.0.tgz#1b42a6266a21f07421d1b0b54b7dc167b01c013b" integrity sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow== -retry@^0.13.1: - version "0.13.1" - resolved "https://registry.yarnpkg.com/retry/-/retry-0.13.1.tgz#185b1587acf67919d63b357349e03537b2484658" - integrity sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg== - reusify@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" @@ -9482,11 +7053,6 @@ router@^2.2.0: parseurl "^1.3.3" path-to-regexp "^8.0.0" -run-applescript@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/run-applescript/-/run-applescript-7.0.0.tgz#e5a553c2bffd620e169d276c1cd8f1b64778fbeb" - integrity sha512-9by4Ij99JUr/MCFBUkDKLWK3G9HVXmabKz9U5MlIAIuvuzkiOicRYs8XJLxX+xahD+mLiiCYDqF9dKAgtzKP1A== - run-parallel@^1.1.9: version "1.2.0" resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.2.0.tgz#66d1368da7bdf921eb9d95bd1a9229e7f21a43ee" @@ -9494,7 +7060,7 @@ run-parallel@^1.1.9: dependencies: queue-microtask "^1.2.2" -rw@1, rw@^1.3.3: +rw@1: version "1.3.3" resolved "https://registry.yarnpkg.com/rw/-/rw-1.3.3.tgz#3f862dfa91ab766b14885ef4d01124bfda074fb4" integrity sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ== @@ -9517,11 +7083,6 @@ safe-array-concat@^1.1.3: has-symbols "^1.1.0" isarray "^2.0.5" -safe-buffer@5.2.1, safe-buffer@>=5.1.0, safe-buffer@~5.2.0: - version "5.2.1" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" - integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== - safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" @@ -9549,18 +7110,11 @@ safe-regex-test@^1.1.0: es-errors "^1.3.0" is-regex "^1.2.1" -"safer-buffer@>= 2.1.2 < 3", "safer-buffer@>= 2.1.2 < 3.0.0": +"safer-buffer@>= 2.1.2 < 3.0.0": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== -sass-loader@16.0.5: - version "16.0.5" - resolved "https://registry.yarnpkg.com/sass-loader/-/sass-loader-16.0.5.tgz#257bc90119ade066851cafe7f2c3f3504c7cda98" - integrity sha512-oL+CMBXrj6BZ/zOq4os+UECPL+bWqt6OAC6DWS8Ln8GZRcMDjlJ4JC3FBDuHJdYaFWIdKNIBYmtZtK2MaMkNIw== - dependencies: - neo-async "^2.6.2" - sass@1.90.0: version "1.90.0" resolved "https://registry.yarnpkg.com/sass/-/sass-1.90.0.tgz#d6fc2be49c7c086ce86ea0b231a35bf9e33cb84b" @@ -9572,11 +7126,6 @@ sass@1.90.0: optionalDependencies: "@parcel/watcher" "^2.4.1" -sax@^1.2.4: - version "1.4.1" - resolved "https://registry.yarnpkg.com/sax/-/sax-1.4.1.tgz#44cc8988377f126304d3b3fc1010c733b929ef0f" - integrity sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg== - schema-inspector@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/schema-inspector/-/schema-inspector-2.1.0.tgz#85096fbc78162a420262ed41b82e60ac927767b2" @@ -9584,39 +7133,16 @@ schema-inspector@^2.1.0: dependencies: async "~2.6.3" -schema-utils@^4.0.0, schema-utils@^4.2.0, schema-utils@^4.3.0, schema-utils@^4.3.3: - version "4.3.3" - resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-4.3.3.tgz#5b1850912fa31df90716963d45d9121fdfc09f46" - integrity sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA== - dependencies: - "@types/json-schema" "^7.0.9" - ajv "^8.9.0" - ajv-formats "^2.1.1" - ajv-keywords "^5.1.0" - screenfull@^6.0.2: version "6.0.2" resolved "https://registry.yarnpkg.com/screenfull/-/screenfull-6.0.2.tgz#3dbe4b8c4f8f49fb8e33caa8f69d0bca730ab238" integrity sha512-AQdy8s4WhNvUZ6P8F6PB21tSPIYKniic+Ogx0AacBMjKP1GUHN2E9URxQHtCusiwxudnCKkdy4GrHXPPJSkCCw== -select-hose@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/select-hose/-/select-hose-2.0.0.tgz#625d8658f865af43ec962bfc376a37359a4994ca" - integrity sha512-mEugaLK+YfkijB4fx0e6kImuJdCIt2LxCRcbEYPqRGCs4F2ogyfZU5IAZRdjCP8JPq2AtdNoC/Dux63d9Kiryg== - select@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/select/-/select-1.1.2.tgz#0e7350acdec80b1108528786ec1d4418d11b396d" integrity sha512-OwpTSOfy6xSs1+pwcNrv0RBMOzI39Lp3qQKUTPVVPRjCdNa5JH/oPRiqsesIskK8TVgmRiHwO4KXlV2Li9dANA== -selfsigned@^5.5.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/selfsigned/-/selfsigned-5.5.0.tgz#4c9ab7c7c9f35f18fb6a9882c253eb0e6bd6557b" - integrity sha512-ftnu3TW4+3eBfLRFnDEkzGxSF/10BJBkaLJuBHZX0kiPS7bRdlpZGu6YGt4KngMkdTwJE6MbjavFpqHvqVt+Ew== - dependencies: - "@peculiar/x509" "^1.14.2" - pkijs "^3.3.3" - semver@7.7.2: version "7.7.2" resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.2.tgz#67d99fdcd35cec21e6f8b87a7fd515a33f982b58" @@ -9654,43 +7180,6 @@ send@^1.1.0, send@^1.2.0: range-parser "^1.2.1" statuses "^2.0.2" -send@~0.19.0, send@~0.19.1: - version "0.19.2" - resolved "https://registry.yarnpkg.com/send/-/send-0.19.2.tgz#59bc0da1b4ea7ad42736fd642b1c4294e114ff29" - integrity sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg== - dependencies: - debug "2.6.9" - depd "2.0.0" - destroy "1.2.0" - encodeurl "~2.0.0" - escape-html "~1.0.3" - etag "~1.8.1" - fresh "~0.5.2" - http-errors "~2.0.1" - mime "1.6.0" - ms "2.1.3" - on-finished "~2.4.1" - range-parser "~1.2.1" - statuses "~2.0.2" - -serialize-javascript@^7.0.3: - version "7.0.4" - resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-7.0.4.tgz#c517735bd5b7631dd1fc191ee19cbb713ff8e05c" - integrity sha512-DuGdB+Po43Q5Jxwpzt1lhyFSYKryqoNjQSA9M92tyw0lyHIOur+XCalOUe0KTJpyqzT8+fQ5A0Jf7vCx/NKmIg== - -serve-index@^1.9.1: - version "1.9.1" - resolved "https://registry.yarnpkg.com/serve-index/-/serve-index-1.9.1.tgz#d3768d69b1e7d82e5ce050fff5b453bea12a9239" - integrity sha512-pXHfKNP4qujrtteMrSBb0rc8HJ9Ms/GrXwcUtUtD5s4ewDJI8bT3Cz2zTVRMKtri49pLx2e0Ya8ziP5Ya2pZZw== - dependencies: - accepts "~1.3.4" - batch "0.6.1" - debug "2.6.9" - escape-html "~1.0.3" - http-errors "~1.6.2" - mime-types "~2.1.17" - parseurl "~1.3.2" - serve-static@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-2.2.1.tgz#7f186a4a4e5f5b663ad7a4294ff1bf37cf0e98a9" @@ -9701,16 +7190,6 @@ serve-static@^2.2.0: parseurl "^1.3.3" send "^1.2.0" -serve-static@~1.16.2: - version "1.16.3" - resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.16.3.tgz#a97b74d955778583f3862a4f0b841eb4d5d78cf9" - integrity sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA== - dependencies: - encodeurl "~2.0.0" - escape-html "~1.0.3" - parseurl "~1.3.3" - send "~0.19.1" - set-blocking@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" @@ -9752,23 +7231,11 @@ setimmediate@^1.0.5: resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" integrity sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA== -setprototypeof@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.0.tgz#d0bd85536887b6fe7c0d818cb962d9d91c54e656" - integrity sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ== - -setprototypeof@1.2.0, setprototypeof@~1.2.0: +setprototypeof@~1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw== -shallow-clone@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/shallow-clone/-/shallow-clone-3.0.1.tgz#8f2981ad92531f55035b01fb230769a40e02efa3" - integrity sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA== - dependencies: - kind-of "^6.0.2" - shebang-command@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" @@ -9781,11 +7248,6 @@ shebang-regex@^3.0.0: resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== -shell-quote@^1.8.1: - version "1.10.0" - resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-1.10.0.tgz#482033e192e4f5c07151521ffa03400ec71b1b0f" - integrity sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA== - side-channel-list@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.1.tgz#c2e0b5a14a540aebee3bbc6c3f8666cc9b509127" @@ -9869,15 +7331,6 @@ smart-buffer@^4.2.0: resolved "https://registry.yarnpkg.com/smart-buffer/-/smart-buffer-4.2.0.tgz#6e1d71fa4f18c05f7d0ff216dd16a481d0e8d9ae" integrity sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg== -sockjs@^0.3.24: - version "0.3.24" - resolved "https://registry.yarnpkg.com/sockjs/-/sockjs-0.3.24.tgz#c9bc8995f33a111bea0395ec30aa3206bdb5ccce" - integrity sha512-GJgLTZ7vYb/JtPSSZ10hsOYIvEYsjbNU+zPdIHcUaWVNUEPivzxku31865sSSud0Da0W4lEeOPlmw93zLQchuQ== - dependencies: - faye-websocket "^0.11.3" - uuid "^8.3.2" - websocket-driver "^0.7.4" - socks-proxy-agent@^8.0.3: version "8.0.5" resolved "https://registry.yarnpkg.com/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz#b9cdb4e7e998509d7659d689ce7697ac21645bee" @@ -9900,20 +7353,12 @@ sorted-btree@^1.8.1: resolved "https://registry.yarnpkg.com/sorted-btree/-/sorted-btree-1.8.1.tgz#6e6275f7955e5892bb8737149cbe495be10f426f" integrity sha512-395+XIP+wqNn3USkFSrNz7G3Ss/MXlZEqesxvzCRFwL14h6e8LukDHdLBePn5pwbm5OQ9vGu8mDyz2lLDIqamQ== -"source-map-js@>=0.6.2 <2.0.0", source-map-js@^1.0.2, source-map-js@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.2.1.tgz#1ce5650fddd87abc099eda37dcff024c2667ae46" - integrity sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA== - -source-map-loader@5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/source-map-loader/-/source-map-loader-5.0.0.tgz#f593a916e1cc54471cfc8851b905c8a845fc7e38" - integrity sha512-k2Dur7CbSLcAH73sBcIkV5xjPV4SzqO1NJ7+XaQl8if3VODDUj3FNchNGpqgJSKbvUfJuhVdv8K2Eu8/TNl2eA== - dependencies: - iconv-lite "^0.6.3" - source-map-js "^1.0.2" +"source-map-js@>=0.6.2 <2.0.0", source-map-js@^1.2.1: + version "1.2.2" + resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.2.2.tgz#79fb88d97535a21cb27162cb05d211b67acea4ab" + integrity sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw== -source-map-support@0.5.21, source-map-support@^0.5.5, source-map-support@~0.5.20: +source-map-support@0.5.21: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== @@ -9921,16 +7366,16 @@ source-map-support@0.5.21, source-map-support@^0.5.5, source-map-support@~0.5.20 buffer-from "^1.0.0" source-map "^0.6.0" -source-map@0.6.1, source-map@^0.6.0, source-map@~0.6.0: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" - integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== - source-map@0.7.6: version "0.7.6" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.7.6.tgz#a3658ab87e5b6429c8a1f3ba0083d4c61ca3ef02" integrity sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ== +source-map@^0.6.0: + version "0.6.1" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" + integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== + spdx-correct@^3.0.0: version "3.2.0" resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.2.0.tgz#4f5ab0668f0059e34f9c00dce331784a12de4e9c" @@ -9965,29 +7410,6 @@ spdx-license-ids@^3.0.0: resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.20.tgz#e44ed19ed318dd1e5888f93325cee800f0f51b89" integrity sha512-jg25NiDV/1fLtSgEgyvVyDunvaNHbuwF9lfNV17gSmPFAlYzdfNBlLtLzXTevwkPj7DhGbmN9VnmJIgLnhvaBw== -spdy-transport@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/spdy-transport/-/spdy-transport-3.0.0.tgz#00d4863a6400ad75df93361a1608605e5dcdcf31" - integrity sha512-hsLVFE5SjA6TCisWeJXFKniGGOpBgMLmerfO2aCyCU5s7nJ/rpAepqmFifv/GCbSbueEeAJJnmSQ2rKC/g8Fcw== - dependencies: - debug "^4.1.0" - detect-node "^2.0.4" - hpack.js "^2.1.6" - obuf "^1.1.2" - readable-stream "^3.0.6" - wbuf "^1.7.3" - -spdy@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/spdy/-/spdy-4.0.2.tgz#b74f466203a3eda452c02492b91fb9e84a27677b" - integrity sha512-r46gZQZQV+Kl9oItvl1JZZqJKGr+oEkB08A6BzkiR7593/7IbtuncXHd2YoYeTsG4157ZssMu9KYvUHLcjcDoA== - dependencies: - debug "^4.1.0" - handle-thing "^2.0.0" - http-deceiver "^1.2.7" - select-hose "^2.0.0" - spdy-transport "^3.0.0" - splaytree-ts@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/splaytree-ts/-/splaytree-ts-1.0.2.tgz#34963704587aff45eaa09c24713f552bbf56e8f0" @@ -10010,12 +7432,7 @@ ssri@^13.0.0: dependencies: minipass "^7.0.3" -"statuses@>= 1.4.0 < 2": - version "1.5.0" - resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c" - integrity sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA== - -statuses@^2.0.1, statuses@^2.0.2, statuses@~2.0.1, statuses@~2.0.2: +statuses@^2.0.1, statuses@^2.0.2, statuses@~2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.2.tgz#8f75eecef765b5e1cfcdc080da59409ed424e382" integrity sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw== @@ -10033,13 +7450,6 @@ stop-iteration-iterator@^1.1.0: es-errors "^1.3.0" internal-slot "^1.1.0" -stream-parser@~0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/stream-parser/-/stream-parser-0.3.1.tgz#1618548694420021a1182ff0af1911c129761773" - integrity sha512-bJ/HgKq41nlKvlhccD5kaCr/P+Hu0wPNKPJOH7en+YrJu/9EgqUF+88w5Jb6KNcjOFMhfX4B2asfeAtIGuHObQ== - dependencies: - debug "2" - "string-width-cjs@npm:string-width@^4.2.0": version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" @@ -10108,13 +7518,6 @@ string.prototype.trimstart@^1.0.8: define-properties "^1.2.1" es-object-atoms "^1.0.0" -string_decoder@^1.1.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" - integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== - dependencies: - safe-buffer "~5.2.0" - string_decoder@~1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" @@ -10171,13 +7574,6 @@ sucrase@^3.35.0: tinyglobby "^0.2.11" ts-interface-checker "^0.1.9" -supercluster@^8.0.1: - version "8.0.1" - resolved "https://registry.yarnpkg.com/supercluster/-/supercluster-8.0.1.tgz#9946ba123538e9e9ab15de472531f604e7372df5" - integrity sha512-IiOea5kJ9iqzD2t7QJq/cREyLHTtSmUT6gQsweojg9WH2sYJqZK9SswTu6jrscO6D1G5v5vYZ9ru/eq85lXeZQ== - dependencies: - kdbush "^4.0.2" - supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" @@ -10192,13 +7588,6 @@ supports-color@^7.1.0: dependencies: has-flag "^4.0.0" -supports-color@^8.0.0: - version "8.1.1" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" - integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== - dependencies: - has-flag "^4.0.0" - supports-preserve-symlinks-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" @@ -10254,11 +7643,6 @@ tailwindcss@^3.4.19: resolve "^1.22.8" sucrase "^3.35.0" -tapable@^2.2.1, tapable@^2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.3.0.tgz#7e3ea6d5ca31ba8e078b560f0d83ce9a14aa8be6" - integrity sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg== - tar@^7.4.3, tar@^7.5.2: version "7.5.22" resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.22.tgz#a696f998136e71487dc3f869a85bba2c67971ba9" @@ -10270,36 +7654,6 @@ tar@^7.4.3, tar@^7.5.2: minizlib "^3.1.0" yallist "^5.0.0" -terser-webpack-plugin@^5.3.16: - version "5.4.0" - resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-5.4.0.tgz#95fc4cf4437e587be11ecf37d08636089174d76b" - integrity sha512-Bn5vxm48flOIfkdl5CaD2+1CiUVbonWQ3KQPyP7/EuIl9Gbzq/gQFOzaMFUEgVjB1396tcK0SG8XcNJ/2kDH8g== - dependencies: - "@jridgewell/trace-mapping" "^0.3.25" - jest-worker "^27.4.5" - schema-utils "^4.3.0" - terser "^5.31.1" - -terser@5.43.1: - version "5.43.1" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.43.1.tgz#88387f4f9794ff1a29e7ad61fb2932e25b4fdb6d" - integrity sha512-+6erLbBm0+LROX2sPXlUYx/ux5PyE9K/a92Wrt6oA+WDAoFTdpHE5tCYCI5PNzq2y8df4rA+QgHLJuR4jNymsg== - dependencies: - "@jridgewell/source-map" "^0.3.3" - acorn "^8.14.0" - commander "^2.20.0" - source-map-support "~0.5.20" - -terser@^5.31.1: - version "5.46.0" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.46.0.tgz#1b81e560d584bbdd74a8ede87b4d9477b0ff9695" - integrity sha512-jTwoImyr/QbOWFFso3YoU3ik0jBBDJ6JTOQiy/J2YxVJdZCc+5u7skhNwiOR3FQIygFqVUPHl7qbbxtjW2K3Qg== - dependencies: - "@jridgewell/source-map" "^0.3.3" - acorn "^8.15.0" - commander "^2.20.0" - source-map-support "~0.5.20" - text-segmentation@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/text-segmentation/-/text-segmentation-1.0.3.tgz#52a388159efffe746b24a63ba311b6ac9f2d7943" @@ -10321,16 +7675,6 @@ thenify-all@^1.0.0: dependencies: any-promise "^1.0.0" -thingies@^2.5.0: - version "2.5.0" - resolved "https://registry.yarnpkg.com/thingies/-/thingies-2.5.0.tgz#5f7b882c933b85989f8466b528a6247a6881e04f" - integrity sha512-s+2Bwztg6PhWUD7XMfeYm5qliDdSiZm7M7n8KjTkIsm3l/2lgVRc2/Gx/v+ZX8lT4FMA+i8aQvhcWylldc+ZNw== - -thunky@^1.0.2: - version "1.1.0" - resolved "https://registry.yarnpkg.com/thunky/-/thunky-1.1.0.tgz#5abaf714a9405db0504732bbccd2cedd9ef9537d" - integrity sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA== - tiny-emitter@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/tiny-emitter/-/tiny-emitter-2.1.0.tgz#1d1a56edfc51c43e863cbb5382a72330e3555423" @@ -10402,16 +7746,6 @@ tooltipster@^4.2.8: resolved "https://registry.yarnpkg.com/tooltipster/-/tooltipster-4.2.8.tgz#ad1970dd71ad853034e64e3fdd1745f7f3485071" integrity sha512-Znmbt5UMzaiFCRlVaRtfRZYQqxrmNlj1+3xX/aT0OiA3xkQZhXYGbLJmZPigx0YiReYZpO7Lm2XKbUxXsiU/pg== -tree-dump@^1.0.3, tree-dump@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/tree-dump/-/tree-dump-1.1.0.tgz#ab29129169dc46004414f5a9d4a3c6e89f13e8a4" - integrity sha512-rMuvhU4MCDbcbnleZTFezWsaZXRFemSqAM+7jPnzUl1fo9w3YEKOxAeui0fz3OI4EU4hf23iyA7uQRVko+UaBA== - -tree-kill@1.2.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/tree-kill/-/tree-kill-1.2.2.tgz#4ca09a9092c88b73a7cdc5e8a01b507b0790a0cc" - integrity sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A== - ts-api-utils@^2.1.0, ts-api-utils@^2.4.0: version "2.4.0" resolved "https://registry.yarnpkg.com/ts-api-utils/-/ts-api-utils-2.4.0.tgz#2690579f96d2790253bdcf1ca35d569ad78f9ad8" @@ -10475,18 +7809,6 @@ tslib@2.8.1, tslib@^2.0.0, tslib@^2.1.0, tslib@^2.3.0, tslib@^2.3.1, tslib@^2.4. resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f" integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w== -tslib@^1.9.3: - version "1.14.1" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" - integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== - -tsyringe@^4.10.0: - version "4.10.0" - resolved "https://registry.yarnpkg.com/tsyringe/-/tsyringe-4.10.0.tgz#d0c95815d584464214060285eaaadd94aa03299c" - integrity sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw== - dependencies: - tslib "^1.9.3" - tuf-js@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/tuf-js/-/tuf-js-4.1.0.tgz#ae4ef9afa456fcb4af103dc50a43bc031f066603" @@ -10512,14 +7834,6 @@ type-is@^2.0.1: media-typer "^1.1.0" mime-types "^3.0.0" -type-is@~1.6.18: - version "1.6.18" - resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131" - integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g== - dependencies: - media-typer "0.3.0" - mime-types "~2.1.24" - typed-array-buffer@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz#a72395450a4869ec033fd549371b47af3a2ee536" @@ -10565,10 +7879,10 @@ typed-array-length@^1.0.7: possible-typed-array-names "^1.0.0" reflect.getprototypeof "^1.0.6" -typed-assert@^1.0.8: - version "1.0.9" - resolved "https://registry.yarnpkg.com/typed-assert/-/typed-assert-1.0.9.tgz#8af9d4f93432c4970ec717e3006f33f135b06213" - integrity sha512-KNNZtayBCtmnNmbo5mG47p1XsCyrx6iVqomjcZnec/1Y5GGARaxPs6r49RnSPeUP3YjNYiU9sQHAtY4BBvnZwg== +typeface-roboto-mono@^1.1.13: + version "1.1.13" + resolved "https://registry.yarnpkg.com/typeface-roboto-mono/-/typeface-roboto-mono-1.1.13.tgz#2af8662db8f9119c00efd55d6ed8877d2a69ec94" + integrity sha512-pnzDc70b7ywJHin/BUFL7HZX8DyOTBLT2qxlJ92eH1UJOFcENIBXa9IZrxsJX/gEKjbEDKhW5vz/TKRBNk/ufQ== typeface-roboto@^1.1.13: version "1.1.13" @@ -10620,29 +7934,6 @@ undici-types@~6.21.0: resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.21.0.tgz#691d00af3909be93a7faa13be61b3a5b50ef12cb" integrity sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ== -unicode-canonical-property-names-ecmascript@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.1.tgz#cb3173fe47ca743e228216e4a3ddc4c84d628cc2" - integrity sha512-dA8WbNeb2a6oQzAQ55YlT5vQAWGV9WXOsi3SskE3bcCdM0P4SDd+24zS/OCacdRq5BkdsRj9q3Pg6YyQoxIGqg== - -unicode-match-property-ecmascript@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-2.0.0.tgz#54fd16e0ecb167cf04cf1f756bdcc92eba7976c3" - integrity sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q== - dependencies: - unicode-canonical-property-names-ecmascript "^2.0.0" - unicode-property-aliases-ecmascript "^2.0.0" - -unicode-match-property-value-ecmascript@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-2.2.1.tgz#65a7adfad8574c219890e219285ce4c64ed67eaa" - integrity sha512-JQ84qTuMg4nVkx8ga4A16a1epI9H6uTXAknqxkGF/aFfRLw1xC/Bp24HNLaZhHSkWd3+84t8iXnp1J0kYcZHhg== - -unicode-property-aliases-ecmascript@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.1.0.tgz#43d41e3be698bd493ef911077c9b131f827e8ccd" - integrity sha512-6t3foTQI9qne+OZoVQB/8x8rk2k1eVy1gRXhV3oFQ5T6R1dqQ1xtin3XqSlx3+ATBkliTaR/hHyJBm+LVPNM8w== - unique-filename@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/unique-filename/-/unique-filename-5.0.0.tgz#8b17bbde1a7ca322dd1a1d23fe17c2b798c43f8f" @@ -10682,16 +7973,11 @@ uri-js@^4.2.2: dependencies: punycode "^2.1.0" -util-deprecate@^1.0.1, util-deprecate@^1.0.2, util-deprecate@~1.0.1: +util-deprecate@^1.0.2, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw== -utils-merge@1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" - integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA== - utrie@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/utrie/-/utrie-1.0.2.tgz#d42fe44de9bc0119c25de7f564a6ed1b2c87a645" @@ -10704,11 +7990,6 @@ uuid@^11.1.0: resolved "https://registry.yarnpkg.com/uuid/-/uuid-11.1.0.tgz#9549028be1753bb934fc96e2bca09bb4105ae912" integrity sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A== -uuid@^8.3.2: - version "8.3.2" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" - integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== - v8-compile-cache-lib@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf" @@ -10732,7 +8013,7 @@ validate-npm-package-name@^7.0.0: resolved "https://registry.yarnpkg.com/validate-npm-package-name/-/validate-npm-package-name-7.0.2.tgz#e57c3d721a4c8bbff454a246e7f7da811559ea0d" integrity sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A== -vary@^1, vary@^1.1.2, vary@~1.1.2: +vary@^1, vary@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc" integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg== @@ -10786,15 +8067,6 @@ vscode-uri@~3.1.0: resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.1.0.tgz#dd09ec5a66a38b5c3fffc774015713496d14e09c" integrity sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ== -vt-pbf@^3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/vt-pbf/-/vt-pbf-3.1.3.tgz#68fd150756465e2edae1cc5c048e063916dcfaac" - integrity sha512-2LzDFzt0mZKZ9IpVF2r69G9bXaP2Q2sArJCmcCgvfTdCCZzSyz4aCLoQyUilu37Ll56tCblIZrXFIjNUpGIlmA== - dependencies: - "@mapbox/point-geometry" "0.1.0" - "@mapbox/vector-tile" "^1.3.1" - pbf "^3.2.1" - watchpack@2.4.4: version "2.4.4" resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.4.tgz#473bda72f0850453da6425081ea46fc0d7602947" @@ -10803,21 +8075,6 @@ watchpack@2.4.4: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" -watchpack@^2.5.1: - version "2.5.1" - resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.5.1.tgz#dd38b601f669e0cbf567cb802e75cead82cde102" - integrity sha512-Zn5uXdcFNIA1+1Ei5McRd+iRzfhENPCe7LeABkJtNulSxjma+l7ltNx55BWZkRlwRnpOgHqxnjyaDgJnNXnqzg== - dependencies: - glob-to-regexp "^0.4.1" - graceful-fs "^4.1.2" - -wbuf@^1.1.0, wbuf@^1.7.3: - version "1.7.3" - resolved "https://registry.yarnpkg.com/wbuf/-/wbuf-1.7.3.tgz#c1d8d149316d3ea852848895cb6a0bfe887b87df" - integrity sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA== - dependencies: - minimalistic-assert "^1.0.0" - wcwidth@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8" @@ -10835,130 +8092,6 @@ web-streams-polyfill@^3.0.3: resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz#2073b91a2fdb1fbfbd401e7de0ac9f8214cecb4b" integrity sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw== -webpack-dev-middleware@7.4.2: - version "7.4.2" - resolved "https://registry.yarnpkg.com/webpack-dev-middleware/-/webpack-dev-middleware-7.4.2.tgz#40e265a3d3d26795585cff8207630d3a8ff05877" - integrity sha512-xOO8n6eggxnwYpy1NlzUKpvrjfJTvae5/D6WOK0S2LSo7vjmo5gCM1DbLUmFqrMTJP+W/0YZNctm7jasWvLuBA== - dependencies: - colorette "^2.0.10" - memfs "^4.6.0" - mime-types "^2.1.31" - on-finished "^2.4.1" - range-parser "^1.2.1" - schema-utils "^4.0.0" - -webpack-dev-middleware@^7.4.2: - version "7.4.5" - resolved "https://registry.yarnpkg.com/webpack-dev-middleware/-/webpack-dev-middleware-7.4.5.tgz#d4e8720aa29cb03bc158084a94edb4594e3b7ac0" - integrity sha512-uxQ6YqGdE4hgDKNf7hUiPXOdtkXvBJXrfEGYSx7P7LC8hnUYGK70X6xQXUvXeNyBDDcsiQXpG2m3G9vxowaEuA== - dependencies: - colorette "^2.0.10" - memfs "^4.43.1" - mime-types "^3.0.1" - on-finished "^2.4.1" - range-parser "^1.2.1" - schema-utils "^4.0.0" - -webpack-dev-server@5.2.5: - version "5.2.5" - resolved "https://registry.yarnpkg.com/webpack-dev-server/-/webpack-dev-server-5.2.5.tgz#648fceaac6a5736b0935e5c1e55d6aa1d0626119" - integrity sha512-4wZtCquSuv9CKX8oybo+mqxtxZqWz47uM1Ch94lxowBztOhWCbhqvRbfC/mODOwxgV2brY+JGZpHq58/SuVFYg== - dependencies: - "@types/bonjour" "^3.5.13" - "@types/connect-history-api-fallback" "^1.5.4" - "@types/express" "^4.17.25" - "@types/express-serve-static-core" "^4.17.21" - "@types/serve-index" "^1.9.4" - "@types/serve-static" "^1.15.5" - "@types/sockjs" "^0.3.36" - "@types/ws" "^8.5.10" - ansi-html-community "^0.0.8" - bonjour-service "^1.2.1" - chokidar "^3.6.0" - colorette "^2.0.10" - compression "^1.8.1" - connect-history-api-fallback "^2.0.0" - express "^4.22.1" - graceful-fs "^4.2.6" - http-proxy-middleware "^2.0.9" - ipaddr.js "^2.1.0" - launch-editor "^2.6.1" - open "^10.0.3" - p-retry "^6.2.0" - schema-utils "^4.2.0" - selfsigned "^5.5.0" - serve-index "^1.9.1" - sockjs "^0.3.24" - spdy "^4.0.2" - webpack-dev-middleware "^7.4.2" - ws "^8.18.0" - -webpack-merge@6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/webpack-merge/-/webpack-merge-6.0.1.tgz#50c776868e080574725abc5869bd6e4ef0a16c6a" - integrity sha512-hXXvrjtx2PLYx4qruKl+kyRSLc52V+cCvMxRjmKwoA+CBbbF5GfIBtR6kCvl0fYGqTUPKB+1ktVmTHqMOzgCBg== - dependencies: - clone-deep "^4.0.1" - flat "^5.0.2" - wildcard "^2.0.1" - -webpack-sources@^3.0.0, webpack-sources@^3.3.3: - version "3.3.3" - resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.3.3.tgz#d4bf7f9909675d7a070ff14d0ef2a4f3c982c723" - integrity sha512-yd1RBzSGanHkitROoPFd6qsrxt+oFhg/129YzheDGqeustzX0vTZJZsSsQjVQC4yzBQ56K55XU8gaNCtIzOnTg== - -webpack-subresource-integrity@5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/webpack-subresource-integrity/-/webpack-subresource-integrity-5.1.0.tgz#8b7606b033c6ccac14e684267cb7fb1f5c2a132a" - integrity sha512-sacXoX+xd8r4WKsy9MvH/q/vBtEHr86cpImXwyg74pFIpERKt6FmB8cXpeuh0ZLgclOlHI4Wcll7+R5L02xk9Q== - dependencies: - typed-assert "^1.0.8" - -webpack@5.105.0: - version "5.105.0" - resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.105.0.tgz#38b5e6c5db8cbe81debbd16e089335ada05ea23a" - integrity sha512-gX/dMkRQc7QOMzgTe6KsYFM7DxeIONQSui1s0n/0xht36HvrgbxtM1xBlgx596NbpHuQU8P7QpKwrZYwUX48nw== - dependencies: - "@types/eslint-scope" "^3.7.7" - "@types/estree" "^1.0.8" - "@types/json-schema" "^7.0.15" - "@webassemblyjs/ast" "^1.14.1" - "@webassemblyjs/wasm-edit" "^1.14.1" - "@webassemblyjs/wasm-parser" "^1.14.1" - acorn "^8.15.0" - acorn-import-phases "^1.0.3" - browserslist "^4.28.1" - chrome-trace-event "^1.0.2" - enhanced-resolve "^5.19.0" - es-module-lexer "^2.0.0" - eslint-scope "5.1.1" - events "^3.2.0" - glob-to-regexp "^0.4.1" - graceful-fs "^4.2.11" - json-parse-even-better-errors "^2.3.1" - loader-runner "^4.3.1" - mime-types "^2.1.27" - neo-async "^2.6.2" - schema-utils "^4.3.3" - tapable "^2.3.0" - terser-webpack-plugin "^5.3.16" - watchpack "^2.5.1" - webpack-sources "^3.3.3" - -websocket-driver@>=0.5.1, websocket-driver@^0.7.4: - version "0.7.5" - resolved "https://registry.yarnpkg.com/websocket-driver/-/websocket-driver-0.7.5.tgz#569d22764ab21f2de20af0e74b411e8ae5a0fa46" - integrity sha512-ZL2+3c7kMBdIRCMz6l8jQMHyGVxj+UL+xVk74Ombiciboca8rHa15L86B19E5oh1pL9Ii/uj54gtsIrZGMo6zA== - dependencies: - http-parser-js ">=0.5.1" - safe-buffer ">=5.1.0" - websocket-extensions ">=0.1.1" - -websocket-extensions@>=0.1.1: - version "0.1.4" - resolved "https://registry.yarnpkg.com/websocket-extensions/-/websocket-extensions-0.1.4.tgz#7f8473bc839dfd87608adb95d7eb075211578a42" - integrity sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg== - which-boxed-primitive@^1.1.0, which-boxed-primitive@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz#d76ec27df7fa165f18d5808374a5fe23c29b176e" @@ -11024,13 +8157,6 @@ which@^2.0.1: dependencies: isexe "^2.0.0" -which@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/which/-/which-4.0.0.tgz#cd60b5e74503a3fbcfbf6cd6b4138a8bae644c1a" - integrity sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg== - dependencies: - isexe "^3.1.1" - which@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/which/-/which-6.0.0.tgz#a3a721a14cdd9b991a722e493c177eeff82ff32a" @@ -11038,11 +8164,6 @@ which@^6.0.0: dependencies: isexe "^3.1.1" -wildcard@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/wildcard/-/wildcard-2.0.1.tgz#5ab10d02487198954836b6349f74fff961e10f67" - integrity sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ== - word-wrap@^1.2.5: version "1.2.5" resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.5.tgz#d2c45c6dd4fbce621a66f136cbe328afd0410b34" @@ -11097,18 +8218,6 @@ wrappy@1: resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ== -ws@^8.18.0: - version "8.21.0" - resolved "https://registry.yarnpkg.com/ws/-/ws-8.21.0.tgz#012e413fc07429945121b0c153158c4343086951" - integrity sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g== - -wsl-utils@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/wsl-utils/-/wsl-utils-0.1.0.tgz#8783d4df671d4d50365be2ee4c71917a0557baab" - integrity sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw== - dependencies: - is-wsl "^3.1.0" - y18n@^4.0.0: version "4.0.3" resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.3.tgz#b5f259c82cd6e336921efd7bfd8bf560de9eeedf" @@ -11201,15 +8310,10 @@ zod-to-json-schema@^3.25.1: resolved "https://registry.yarnpkg.com/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz#7f24962101a439ddade2bf1aeab3c3bfec7d84ba" integrity sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA== -zod@4.1.13: - version "4.1.13" - resolved "https://registry.yarnpkg.com/zod/-/zod-4.1.13.tgz#93699a8afe937ba96badbb0ce8be6033c0a4b6b1" - integrity sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig== - -"zod@^3.25 || ^4.0": - version "4.3.6" - resolved "https://registry.yarnpkg.com/zod/-/zod-4.3.6.tgz#89c56e0aa7d2b05107d894412227087885ab112a" - integrity sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg== +zod@4.6.6, "zod@^3.25 || ^4.0": + version "4.6.6" + resolved "https://registry.yarnpkg.com/zod/-/zod-4.6.6.tgz#0bb0cf57b87011a71ec28ed2e1b51f6455563f9a" + integrity sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA== zone.js@~0.15.1: version "0.15.1"