diff --git a/.github/workflows/develop-pipeline.yml b/.github/workflows/develop-pipeline.yml index e53e77acf..05fc77488 100644 --- a/.github/workflows/develop-pipeline.yml +++ b/.github/workflows/develop-pipeline.yml @@ -29,10 +29,10 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - name: Set Up JDK 25 - uses: actions/setup-java@v5 + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 with: java-version: '25' distribution: 'temurin' @@ -47,14 +47,14 @@ jobs: continue-on-error: true - name: Publish Backend Test Results - uses: EnricoMi/publish-unit-test-result-action@v2 + uses: EnricoMi/publish-unit-test-result-action@c950f6fb443cb5af20a377fd0dfaa78838901040 # v2 if: always() with: files: booklore-api/build/test-results/**/*.xml check_name: Backend Test Results - name: Upload Backend Test Reports - uses: actions/upload-artifact@v6 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 if: always() with: name: backend-test-reports @@ -82,18 +82,27 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - name: Set Up Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6 with: - node-version: '22' + node-version: '24' cache: 'npm' cache-dependency-path: booklore-ui/package-lock.json - name: Install Frontend Dependencies working-directory: ./booklore-ui - run: npm ci --force + run: npm ci + + - name: Audit Frontend Dependencies + working-directory: ./booklore-ui + run: npm audit --audit-level=high + + - name: Validate Dependency Tree + working-directory: ./booklore-ui + run: npm ls --depth=0 + - name: Execute Frontend Tests id: frontend_tests @@ -104,14 +113,14 @@ jobs: continue-on-error: true - name: Publish Frontend Test Results - uses: EnricoMi/publish-unit-test-result-action@v2 + uses: EnricoMi/publish-unit-test-result-action@c950f6fb443cb5af20a377fd0dfaa78838901040 # v2 if: always() with: files: booklore-ui/test-results/vitest-results.xml check_name: Frontend Test Results - name: Upload Frontend Test Reports - uses: actions/upload-artifact@v6 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 if: always() with: name: frontend-test-reports @@ -136,7 +145,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: fetch-depth: 0 @@ -161,15 +170,24 @@ jobs: # Native Angular build # ---------------------------------------- - name: Set Up Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6 with: - node-version: '22' + node-version: '24' cache: 'npm' cache-dependency-path: booklore-ui/package-lock.json - name: Install Frontend Dependencies working-directory: ./booklore-ui - run: npm ci --force + run: npm ci + + - name: Audit Frontend Dependencies + working-directory: ./booklore-ui + run: npm audit --audit-level=high + + - name: Validate Dependency Tree + working-directory: ./booklore-ui + run: npm ls --depth=0 + - name: Build Angular App working-directory: ./booklore-ui @@ -179,7 +197,7 @@ jobs: # Native Gradle build # ---------------------------------------- - name: Set Up JDK 25 - uses: actions/setup-java@v5 + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 with: java-version: '25' distribution: 'temurin' @@ -204,24 +222,24 @@ jobs: # Environment setup # ---------------------------------------- - name: Set Up QEMU for Multi-Arch Builds - uses: docker/setup-qemu-action@v3 + uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3 - name: Set Up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 # ---------------------------------------- # Docker login (pushes & internal PRs only) # ---------------------------------------- - name: Authenticate to Docker Hub if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository - uses: docker/login-action@v3 + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Authenticate to GitHub Container Registry if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository - uses: docker/login-action@v3 + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 with: registry: ghcr.io username: ${{ github.actor }} @@ -232,7 +250,7 @@ jobs: # ---------------------------------------- - name: Build and push Docker image if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository - uses: docker/build-push-action@v6 + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 with: context: . file: Dockerfile.ci diff --git a/.github/workflows/master-pipeline.yml b/.github/workflows/master-pipeline.yml index 82ed25c55..d51f0817e 100644 --- a/.github/workflows/master-pipeline.yml +++ b/.github/workflows/master-pipeline.yml @@ -13,7 +13,7 @@ jobs: base_ref: ${{ steps.get_base.outputs.base_ref }} steps: - name: Checkout Repository - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: fetch-depth: 2 - name: Get Base Ref @@ -41,10 +41,10 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - name: Set Up JDK 25 - uses: actions/setup-java@v5 + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 with: java-version: '25' distribution: 'temurin' @@ -59,14 +59,14 @@ jobs: continue-on-error: true - name: Publish Backend Test Results - uses: EnricoMi/publish-unit-test-result-action@v2 + uses: EnricoMi/publish-unit-test-result-action@c950f6fb443cb5af20a377fd0dfaa78838901040 # v2 if: always() with: files: booklore-api/build/test-results/**/*.xml check_name: Backend Test Results - name: Upload Backend Test Reports - uses: actions/upload-artifact@v6 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 if: always() with: name: backend-test-reports @@ -94,18 +94,27 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - name: Set Up Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6 with: - node-version: '22' + node-version: '24' cache: 'npm' cache-dependency-path: booklore-ui/package-lock.json - name: Install Frontend Dependencies working-directory: ./booklore-ui - run: npm ci --force + run: npm ci + + - name: Audit Frontend Dependencies + working-directory: ./booklore-ui + run: npm audit --audit-level=high + + - name: Validate Dependency Tree + working-directory: ./booklore-ui + run: npm ls --depth=0 + - name: Execute Frontend Tests id: frontend_tests @@ -116,14 +125,14 @@ jobs: continue-on-error: true - name: Publish Frontend Test Results - uses: EnricoMi/publish-unit-test-result-action@v2 + uses: EnricoMi/publish-unit-test-result-action@c950f6fb443cb5af20a377fd0dfaa78838901040 # v2 if: always() with: files: booklore-ui/test-results/vitest-results.xml check_name: Frontend Test Results - name: Upload Frontend Test Reports - uses: actions/upload-artifact@v6 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 if: always() with: name: frontend-test-reports @@ -148,28 +157,28 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: fetch-depth: 0 - name: Authenticate to Docker Hub - uses: docker/login-action@v3 + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Authenticate to GitHub Container Registry - uses: docker/login-action@v3 + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ github.token }} - name: Set Up QEMU for Multi-Architecture Builds - uses: docker/setup-qemu-action@v3 + uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3 - name: Set Up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 - name: Retrieve Latest Master Version Tag id: get_version @@ -238,15 +247,24 @@ jobs: # Native Angular build # ---------------------------------------- - name: Set Up Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6 with: - node-version: '22' + node-version: '24' cache: 'npm' cache-dependency-path: booklore-ui/package-lock.json - name: Install Frontend Dependencies working-directory: ./booklore-ui - run: npm ci --force + run: npm ci + + - name: Audit Frontend Dependencies + working-directory: ./booklore-ui + run: npm audit --audit-level=high + + - name: Validate Dependency Tree + working-directory: ./booklore-ui + run: npm ls --depth=0 + - name: Build Angular App working-directory: ./booklore-ui @@ -256,7 +274,7 @@ jobs: # Native Gradle build # ---------------------------------------- - name: Set Up JDK 25 - uses: actions/setup-java@v5 + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 with: java-version: '25' distribution: 'temurin' @@ -281,7 +299,7 @@ jobs: # Docker build & push # ---------------------------------------- - name: Build and push Docker image - uses: docker/build-push-action@v6 + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 with: context: . file: Dockerfile.ci @@ -303,7 +321,7 @@ jobs: type=registry,ref=ghcr.io/booklore-app/booklore:buildcache,mode=max - name: Update GitHub Release Draft - uses: release-drafter/release-drafter@v6 + uses: release-drafter/release-drafter@6db134d15f3909ccc9eefd369f02bd1e9cffdf97 # v6 with: tag: ${{ env.new_tag }} name: "Release ${{ env.new_tag }}" diff --git a/.github/workflows/migrations-check.yml b/.github/workflows/migrations-check.yml index ffa87ab64..2e2ba4954 100644 --- a/.github/workflows/migrations-check.yml +++ b/.github/workflows/migrations-check.yml @@ -24,7 +24,7 @@ jobs: has_migrations: ${{ steps.check_migrations.outputs.has_migrations }} steps: - name: Checkout Repository - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: fetch-depth: 0 @@ -61,7 +61,7 @@ jobs: steps: - name: Checkout Base Branch - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: ref: ${{ inputs.base_ref }} fetch-depth: 0 @@ -78,7 +78,7 @@ jobs: migrate - name: Checkout Head Branch - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: ref: ${{ inputs.head_ref }} fetch-depth: 0 diff --git a/Dockerfile b/Dockerfile index a45739992..457890888 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Stage 1: Build the Angular app -FROM node:22-alpine AS angular-build +FROM node:24-alpine AS angular-build WORKDIR /angular-app @@ -56,9 +56,13 @@ LABEL org.opencontainers.image.title="BookLore" \ ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+UseContainerSupport -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=75.0" -RUN apk update && apk add --no-cache su-exec && \ +ARG TARGETARCH +RUN apk update && apk add --no-cache su-exec libstdc++ libgcc && \ mkdir -p /bookdrop +COPY docker/unrar/unrar-${TARGETARCH} /usr/local/bin/unrar +RUN chmod 755 /usr/local/bin/unrar + COPY entrypoint.sh /usr/local/bin/entrypoint.sh RUN chmod +x /usr/local/bin/entrypoint.sh COPY --from=springboot-build /springboot-app/build/libs/booklore-api-0.0.1-SNAPSHOT.jar /app/app.jar diff --git a/Dockerfile.ci b/Dockerfile.ci index 9c04ae2c9..ee66725c7 100644 --- a/Dockerfile.ci +++ b/Dockerfile.ci @@ -18,7 +18,11 @@ LABEL org.opencontainers.image.title="BookLore" \ ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+UseContainerSupport -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=75.0" -RUN apk update && apk add --no-cache su-exec +ARG TARGETARCH +RUN apk update && apk add --no-cache su-exec libstdc++ libgcc + +COPY docker/unrar/unrar-${TARGETARCH} /usr/local/bin/unrar +RUN chmod 755 /usr/local/bin/unrar COPY entrypoint.sh /usr/local/bin/entrypoint.sh RUN chmod +x /usr/local/bin/entrypoint.sh diff --git a/booklore-api/src/main/java/org/booklore/config/WebSocketConfig.java b/booklore-api/src/main/java/org/booklore/config/WebSocketConfig.java index c85065bf7..383c7bdec 100644 --- a/booklore-api/src/main/java/org/booklore/config/WebSocketConfig.java +++ b/booklore-api/src/main/java/org/booklore/config/WebSocketConfig.java @@ -3,21 +3,26 @@ package org.booklore.config; import org.booklore.config.security.interceptor.WebSocketAuthInterceptor; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; +import java.util.Arrays; + @Slf4j @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { private final WebSocketAuthInterceptor webSocketAuthInterceptor; + private final Environment env; - public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor) { + public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor, Environment env) { this.webSocketAuthInterceptor = webSocketAuthInterceptor; + this.env = env; } @Override @@ -29,8 +34,22 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { - registry.addEndpoint("/ws").setAllowedOrigins("*"); - log.info("WebSocket endpoint registered at /ws"); + String allowedOrigins = env.getProperty("app.cors.allowed-origins", "*").trim(); + var endpoint = registry.addEndpoint("/ws"); + if ("*".equals(allowedOrigins)) { + endpoint.setAllowedOriginPatterns("*"); + log.warn("WebSocket endpoint is configured to allow all origins (*). " + + "This is the default for backward compatibility, but it's recommended to set 'app.cors.allowed-origins' to an explicit list."); + } else if (allowedOrigins.isEmpty()) { + // No explicit origins configured: enforce same-origin check (Spring WebSocket default) + log.info("WebSocket endpoint registered at /ws (same-origin only)"); + } else { + String[] origins = Arrays.stream(allowedOrigins.split("\\s*,\\s*")) + .filter(s -> !s.isEmpty()) + .toArray(String[]::new); + endpoint.setAllowedOriginPatterns(origins); + log.info("WebSocket endpoint registered at /ws with allowed origins: {}", Arrays.toString(origins)); + } } @Override diff --git a/booklore-api/src/main/java/org/booklore/config/security/SecurityConfig.java b/booklore-api/src/main/java/org/booklore/config/security/SecurityConfig.java index ad5896b3e..0c05f1235 100644 --- a/booklore-api/src/main/java/org/booklore/config/security/SecurityConfig.java +++ b/booklore-api/src/main/java/org/booklore/config/security/SecurityConfig.java @@ -5,9 +5,11 @@ import org.booklore.config.security.service.OpdsUserDetailsService; import jakarta.servlet.DispatcherType; import jakarta.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; +import org.booklore.util.FileService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; +import org.springframework.core.env.Environment; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; @@ -19,21 +21,41 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.client.RestTemplate; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import java.io.IOException; +import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.regex.Pattern; +import lombok.extern.slf4j.Slf4j; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SNIHostName; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import java.net.InetAddress; +import java.net.Socket; +import java.util.Collections; + +@Slf4j @AllArgsConstructor @EnableMethodSecurity @Configuration public class SecurityConfig { + private static final Pattern ALLOWED = Pattern.compile("\\s*,\\s*"); private final OpdsUserDetailsService opdsUserDetailsService; private final DualJwtAuthenticationFilter dualJwtAuthenticationFilter; + private final Environment env; private static final String[] COMMON_PUBLIC_ENDPOINTS = { "/ws/**", // WebSocket connections (auth handled in WebSocketAuthInterceptor) @@ -197,6 +219,10 @@ public class SecurityConfig { .cors(cors -> cors.configurationSource(corsConfigurationSource())) .csrf(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .headers(headers -> headers + .referrerPolicy(referrer -> referrer.policy( + ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)) + ) .authorizeHttpRequests(auth -> auth .dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll() .requestMatchers(publicEndpoints.toArray(new String[0])).permitAll() @@ -212,7 +238,11 @@ public class SecurityConfig { http .csrf(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)) + .headers(headers -> headers + .frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin) + .referrerPolicy(referrer -> referrer.policy( + ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)) + ) .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()); return http.build(); } @@ -224,10 +254,92 @@ public class SecurityConfig { return auth.build(); } + @Bean("noRedirectRestTemplate") + public RestTemplate noRedirectRestTemplate() { + return new RestTemplate( + new SimpleClientHttpRequestFactory() { + @Override + protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { + super.prepareConnection(connection, httpMethod); + connection.setInstanceFollowRedirects(false); + if (connection instanceof HttpsURLConnection httpsConnection) { + String targetHost = FileService.getTargetHost(); + if (targetHost != null) { + // Set original host for SNI (even if connecting to IP) + SSLSocketFactory defaultFactory = httpsConnection.getSSLSocketFactory(); + httpsConnection.setSSLSocketFactory(new SniSSLSocketFactory(defaultFactory, targetHost)); + + httpsConnection.setHostnameVerifier((hostname, session) -> { + String expectedHost = FileService.getTargetHost(); + if (expectedHost != null) { + // Verify certificate against the original expected hostname, even if connecting via IP + return HttpsURLConnection.getDefaultHostnameVerifier().verify(expectedHost, session); + } + // Fallback: use default verifier for the hostname we connected to + return HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session); + }); + } + } + } + } + ); + } + + private static class SniSSLSocketFactory extends SSLSocketFactory { + private final SSLSocketFactory delegate; + private final String targetHost; + + public SniSSLSocketFactory(SSLSocketFactory delegate, String targetHost) { + this.delegate = delegate; + this.targetHost = targetHost; + } + + @Override + public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } + @Override + public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } + + @Override + public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { + // Pass targetHost instead of host (which is the IP) so the internal SSLSession gets the correct peer host + Socket socket = delegate.createSocket(s, targetHost, port, autoClose); + if (socket instanceof SSLSocket sslSocket) { + SNIHostName serverName = new SNIHostName(targetHost); + SSLParameters params = sslSocket.getSSLParameters(); + params.setServerNames(Collections.singletonList(serverName)); + // Explicitly set EndpointIdentificationAlgorithm so Java verifies the certificate against targetHost + params.setEndpointIdentificationAlgorithm("HTTPS"); + sslSocket.setSSLParameters(params); + } + return socket; + } + + @Override public Socket createSocket(String host, int port) throws IOException { return delegate.createSocket(host, port); } + @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { return delegate.createSocket(host, port, localHost, localPort); } + @Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); } + @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); } + } + @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); - configuration.setAllowedOriginPatterns(List.of("*")); + + String allowedOriginsStr = env.getProperty("app.cors.allowed-origins", "*").trim(); + if ("*".equals(allowedOriginsStr) || allowedOriginsStr.isEmpty()) { + log.warn( + "CORS is configured to allow all origins (*) because 'app.cors.allowed-origins' is '{}'. " + + "This maintains backward compatibility, but it's recommended to set it to an explicit origin list.", + allowedOriginsStr.isEmpty() ? "empty" : "*" + ); + configuration.setAllowedOriginPatterns(List.of("*")); + } else { + List origins = Arrays.stream(ALLOWED.split(allowedOriginsStr)) + .filter(s -> !s.isEmpty()) + .map(String::trim) + .toList(); + configuration.setAllowedOriginPatterns(origins); + } + configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")); configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Range", "If-None-Match")); configuration.setExposedHeaders(List.of("Content-Disposition", "Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Date")); @@ -238,4 +350,4 @@ public class SecurityConfig { return source; } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/org/booklore/config/security/service/AuthRateLimitService.java b/booklore-api/src/main/java/org/booklore/config/security/service/AuthRateLimitService.java index 2898a1c49..11d0d8a2e 100644 --- a/booklore-api/src/main/java/org/booklore/config/security/service/AuthRateLimitService.java +++ b/booklore-api/src/main/java/org/booklore/config/security/service/AuthRateLimitService.java @@ -23,6 +23,7 @@ public class AuthRateLimitService { public AuthRateLimitService(AuditService auditService) { this.auditService = auditService; this.attemptCache = Caffeine.newBuilder() + .maximumSize(10000) .expireAfterWrite(Duration.ofMinutes(15)) .build(); } @@ -30,15 +31,30 @@ public class AuthRateLimitService { // --- Login rate limiting --- public void checkLoginRateLimit(String ip) { - checkRateLimit("login:" + ip, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for IP: " + ip); + checkRateLimit("login:ip:" + ip, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for IP: " + ip); + } + + public void checkLoginRateLimitByUsername(String username) { + String normalizedUsername = normalizeUsername(username); + checkRateLimit("login:user:" + normalizedUsername, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for username: " + normalizedUsername); } public void recordFailedLoginAttempt(String ip) { - recordFailedAttempt("login:" + ip); + recordFailedAttempt("login:ip:" + ip); + } + + public void recordFailedLoginAttemptByUsername(String username) { + String normalizedUsername = normalizeUsername(username); + recordFailedAttempt("login:user:" + normalizedUsername); } public void resetLoginAttempts(String ip) { - resetAttempts("login:" + ip); + resetAttempts("login:ip:" + ip); + } + + public void resetLoginAttemptsByUsername(String username) { + String normalizedUsername = normalizeUsername(username); + resetAttempts("login:user:" + normalizedUsername); } // --- Refresh token rate limiting --- @@ -72,4 +88,8 @@ public class AuthRateLimitService { private void resetAttempts(String key) { attemptCache.invalidate(key); } + + private String normalizeUsername(String username) { + return username != null ? username.trim().toLowerCase() : ""; + } } diff --git a/booklore-api/src/main/java/org/booklore/config/security/service/AuthenticationService.java b/booklore-api/src/main/java/org/booklore/config/security/service/AuthenticationService.java index ded58f79a..d6c905dfb 100644 --- a/booklore-api/src/main/java/org/booklore/config/security/service/AuthenticationService.java +++ b/booklore-api/src/main/java/org/booklore/config/security/service/AuthenticationService.java @@ -1,6 +1,7 @@ package org.booklore.config.security.service; -import lombok.AllArgsConstructor; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.booklore.config.AppProperties; import org.booklore.config.security.JwtUtils; @@ -31,10 +32,12 @@ import org.booklore.service.audit.AuditService; import org.booklore.util.RequestUtils; @Slf4j -@AllArgsConstructor +@RequiredArgsConstructor @Service public class AuthenticationService { + private String dummyPasswordHash; + private final AppProperties appProperties; private final UserRepository userRepository; private final RefreshTokenRepository refreshTokenRepository; @@ -45,6 +48,11 @@ public class AuthenticationService { private final AuditService auditService; private final AuthRateLimitService authRateLimitService; + @PostConstruct + void initDummyHash() { + this.dummyPasswordHash = passwordEncoder.encode("_dummy_placeholder_for_timing_equalization_"); + } + public BookLoreUser getAuthenticatedUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { @@ -93,21 +101,31 @@ public class AuthenticationService { public ResponseEntity> loginUser(UserLoginRequest loginRequest) { String ip = RequestUtils.getCurrentRequest().getRemoteAddr(); + String username = loginRequest.getUsername(); authRateLimitService.checkLoginRateLimit(ip); + authRateLimitService.checkLoginRateLimitByUsername(username); - BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> { - auditService.log(AuditAction.LOGIN_FAILED, "Login failed for unknown user: " + loginRequest.getUsername()); + BookLoreUserEntity user = userRepository.findByUsername(username).orElse(null); + + if (user == null) { + // Constant-time dummy BCrypt check prevents timing-based user enumeration: + // without this, unknown-user responses are ~3x faster than wrong-password responses. + passwordEncoder.matches(loginRequest.getPassword(), dummyPasswordHash); + auditService.log(AuditAction.LOGIN_FAILED, "Login failed for unknown user: " + username); authRateLimitService.recordFailedLoginAttempt(ip); - return ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()); - }); + authRateLimitService.recordFailedLoginAttemptByUsername(username); + throw ApiError.INVALID_CREDENTIALS.createException(); + } if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) { - auditService.log(AuditAction.LOGIN_FAILED, "Login failed for user: " + loginRequest.getUsername()); + auditService.log(AuditAction.LOGIN_FAILED, "Login failed for user: " + username); authRateLimitService.recordFailedLoginAttempt(ip); + authRateLimitService.recordFailedLoginAttemptByUsername(username); throw ApiError.INVALID_CREDENTIALS.createException(); } authRateLimitService.resetLoginAttempts(ip); + authRateLimitService.resetLoginAttemptsByUsername(username); return loginUser(user); } diff --git a/booklore-api/src/main/java/org/booklore/config/security/service/OpdsUserDetailsService.java b/booklore-api/src/main/java/org/booklore/config/security/service/OpdsUserDetailsService.java index ff3e77810..9d6146b00 100644 --- a/booklore-api/src/main/java/org/booklore/config/security/service/OpdsUserDetailsService.java +++ b/booklore-api/src/main/java/org/booklore/config/security/service/OpdsUserDetailsService.java @@ -22,7 +22,7 @@ public class OpdsUserDetailsService implements UserDetailsService { @Override public OpdsUserDetails loadUserByUsername(String username) throws UsernameNotFoundException { OpdsUserV2Entity userV2 = opdsUserV2Repository.findByUsername(username) - .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username)); + .orElseThrow(() -> new UsernameNotFoundException("Invalid credentials")); OpdsUserV2 mappedCredential = opdsUserV2Mapper.toDto(userV2); return new OpdsUserDetails(mappedCredential); } diff --git a/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java b/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java index 22bc8e94b..25eb3101c 100644 --- a/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java +++ b/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java @@ -1,6 +1,7 @@ package org.booklore.controller; import org.booklore.service.AuthorMetadataService; +import org.booklore.config.security.annotation.CheckBookAccess; import org.booklore.service.book.BookService; import org.booklore.service.bookdrop.BookDropService; import org.booklore.service.reader.CbxReaderService; @@ -32,6 +33,7 @@ public class BookMediaController { @Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.") @ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully") @GetMapping("/book/{bookId}/thumbnail") + @CheckBookAccess(bookIdParam = "bookId") public ResponseEntity getBookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) { return ResponseEntity.ok(bookService.getBookThumbnail(bookId)); } @@ -39,6 +41,7 @@ public class BookMediaController { @Operation(summary = "Get book cover", description = "Retrieve the cover image for a specific book.") @ApiResponse(responseCode = "200", description = "Book cover returned successfully") @GetMapping("/book/{bookId}/cover") + @CheckBookAccess(bookIdParam = "bookId") public ResponseEntity getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) { return ResponseEntity.ok(bookService.getBookCover(bookId)); } @@ -46,6 +49,7 @@ public class BookMediaController { @Operation(summary = "Get audiobook thumbnail", description = "Retrieve the audiobook thumbnail image for a specific book.") @ApiResponse(responseCode = "200", description = "Audiobook thumbnail returned successfully") @GetMapping("/book/{bookId}/audiobook-thumbnail") + @CheckBookAccess(bookIdParam = "bookId") public ResponseEntity getAudiobookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) { return ResponseEntity.ok(bookService.getAudiobookThumbnail(bookId)); } @@ -53,6 +57,7 @@ public class BookMediaController { @Operation(summary = "Get audiobook cover", description = "Retrieve the audiobook cover image for a specific book.") @ApiResponse(responseCode = "200", description = "Audiobook cover returned successfully") @GetMapping("/book/{bookId}/audiobook-cover") + @CheckBookAccess(bookIdParam = "bookId") public ResponseEntity getAudiobookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) { return ResponseEntity.ok(bookService.getAudiobookCover(bookId)); } @@ -60,6 +65,7 @@ public class BookMediaController { @Operation(summary = "Get CBX page as image", description = "Retrieve a specific page from a CBX book as an image.") @ApiResponse(responseCode = "200", description = "CBX page image returned successfully") @GetMapping("/book/{bookId}/cbx/pages/{pageNumber}") + @CheckBookAccess(bookIdParam = "bookId") public void getCbxPage( @Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "Page number to retrieve") @PathVariable int pageNumber, diff --git a/booklore-api/src/main/java/org/booklore/controller/SetupController.java b/booklore-api/src/main/java/org/booklore/controller/SetupController.java index 5eef5c867..5bf6e7ae5 100644 --- a/booklore-api/src/main/java/org/booklore/controller/SetupController.java +++ b/booklore-api/src/main/java/org/booklore/controller/SetupController.java @@ -1,5 +1,6 @@ package org.booklore.controller; +import jakarta.validation.Valid; import org.booklore.exception.ErrorResponse; import org.booklore.model.dto.request.InitialUserRequest; import org.booklore.model.dto.response.SuccessResponse; @@ -35,7 +36,7 @@ public class SetupController { @ApiResponse(responseCode = "200", description = "Admin user created successfully") @PostMapping public ResponseEntity setupFirstUser( - @Parameter(description = "Initial user request") @RequestBody InitialUserRequest request) { + @Parameter(description = "Initial user request") @RequestBody @Valid InitialUserRequest request) { if (userProvisioningService.isInitialUserAlreadyProvisioned()) { return ResponseEntity.status(403).body(new ErrorResponse(403, "Setup is disabled after the first user is created.")); } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/UserCreateRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/UserCreateRequest.java index f33e892a5..05816b4ee 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/UserCreateRequest.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/UserCreateRequest.java @@ -1,14 +1,27 @@ package org.booklore.model.dto; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; import lombok.Data; import java.util.Set; @Data public class UserCreateRequest { + + @NotBlank private String username; + + @NotBlank + @Size(min = 8, max = 72, message = "Password must be at least 8 characters long") private String password; + + @NotBlank private String name; + + @NotBlank + @Email private String email; private boolean permissionUpload; diff --git a/booklore-api/src/main/java/org/booklore/model/dto/request/InitialUserRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/request/InitialUserRequest.java index ffcd44919..9911cd75b 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/request/InitialUserRequest.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/request/InitialUserRequest.java @@ -2,6 +2,7 @@ package org.booklore.model.dto.request; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; import lombok.Data; @Data @@ -17,5 +18,6 @@ public class InitialUserRequest { private String name; @NotBlank + @Size(min = 8, max = 72, message = "Password must be between 8 and 72 characters long") private String password; } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/settings/KoboSettings.java b/booklore-api/src/main/java/org/booklore/model/dto/settings/KoboSettings.java index 9c99a9a58..c2a267214 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/settings/KoboSettings.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/settings/KoboSettings.java @@ -1,5 +1,7 @@ package org.booklore.model.dto.settings; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -10,10 +12,16 @@ import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor public class KoboSettings { - private boolean convertToKepub; - private int conversionLimitInMb; - private boolean convertCbxToEpub; - private int conversionLimitInMbForCbx; - private boolean forceEnableHyphenation; - private int conversionImageCompressionPercentage; + @Builder.Default @JsonSetter(nulls = Nulls.SKIP) + private boolean convertToKepub = false; + @Builder.Default @JsonSetter(nulls = Nulls.SKIP) + private int conversionLimitInMb = 100; + @Builder.Default @JsonSetter(nulls = Nulls.SKIP) + private boolean convertCbxToEpub = false; + @Builder.Default @JsonSetter(nulls = Nulls.SKIP) + private int conversionLimitInMbForCbx = 100; + @Builder.Default @JsonSetter(nulls = Nulls.SKIP) + private boolean forceEnableHyphenation = false; + @Builder.Default @JsonSetter(nulls = Nulls.SKIP) + private int conversionImageCompressionPercentage = 85; } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataMatchWeights.java b/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataMatchWeights.java index f1f7a0277..83bdb8080 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataMatchWeights.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataMatchWeights.java @@ -60,6 +60,10 @@ public class MetadataMatchWeights { @Builder.Default @JsonSetter(nulls = Nulls.SKIP) private int ranobedbRating = 2; @Builder.Default @JsonSetter(nulls = Nulls.SKIP) + private int audibleRating = 2; + @Builder.Default @JsonSetter(nulls = Nulls.SKIP) + private int audibleReviewCount = 1; + @Builder.Default @JsonSetter(nulls = Nulls.SKIP) private int coverImage = 5; public int totalWeight() { @@ -67,6 +71,7 @@ public class MetadataMatchWeights { seriesName + seriesNumber + seriesTotal + isbn13 + isbn10 + language + pageCount + categories + amazonRating + amazonReviewCount + goodreadsRating + goodreadsReviewCount + hardcoverRating + - hardcoverReviewCount + ranobedbRating + coverImage; + hardcoverReviewCount + doubanRating + doubanReviewCount + + ranobedbRating + audibleRating + audibleReviewCount + coverImage; } } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataProviderSpecificFields.java b/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataProviderSpecificFields.java index 20db3e703..a6456eca7 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataProviderSpecificFields.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataProviderSpecificFields.java @@ -22,4 +22,7 @@ public class MetadataProviderSpecificFields { private Boolean lubimyczytacRating; private Boolean ranobedbId; private Boolean ranobedbRating; + private Boolean audibleId; + private Boolean audibleRating; + private Boolean audibleReviewCount; } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/CbxProcessor.java index f2c3ad738..9b61befee 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/CbxProcessor.java @@ -19,6 +19,7 @@ import org.booklore.util.ArchiveUtils; import org.booklore.util.BookCoverUtils; import org.booklore.util.FileService; import org.booklore.util.FileUtils; +import org.booklore.util.UnrarHelper; import com.github.junrar.Archive; import com.github.junrar.rarfile.FileHeader; import lombok.extern.slf4j.Slf4j; @@ -210,11 +211,37 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce } } } catch (Exception e) { + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage()); + return extractFirstImageFromRarViaCli(file); + } log.error("Error extracting RAR: {}", e.getMessage()); } return Optional.empty(); } + private Optional extractFirstImageFromRarViaCli(File file) { + try { + List entries = UnrarHelper.listEntries(file.toPath()); + List imageEntries = entries.stream() + .filter(name -> IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN.matcher(name).matches()) + .sorted() + .toList(); + for (String entry : imageEntries) { + try { + byte[] bytes = UnrarHelper.extractEntryBytes(file.toPath(), entry); + BufferedImage image = FileService.readImage(new ByteArrayInputStream(bytes)); + if (image != null) return Optional.of(image); + } catch (Exception ex) { + log.warn("Error reading RAR entry via CLI {}: {}", entry, ex.getMessage()); + } + } + } catch (Exception e) { + log.error("unrar CLI fallback also failed for {}: {}", file.getName(), e.getMessage()); + } + return Optional.empty(); + } + private void extractAndSetMetadata(BookEntity bookEntity) { try { BookMetadata extracted = cbxMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity))); diff --git a/booklore-api/src/main/java/org/booklore/service/kobo/CbxConversionService.java b/booklore-api/src/main/java/org/booklore/service/kobo/CbxConversionService.java index 9574d50eb..993c97533 100644 --- a/booklore-api/src/main/java/org/booklore/service/kobo/CbxConversionService.java +++ b/booklore-api/src/main/java/org/booklore/service/kobo/CbxConversionService.java @@ -6,6 +6,7 @@ import org.booklore.model.entity.CategoryEntity; import org.booklore.model.entity.TagEntity; import org.booklore.util.ArchiveUtils; import org.booklore.util.FileService; +import org.booklore.util.UnrarHelper; import com.github.junrar.Archive; import com.github.junrar.exception.RarException; import com.github.junrar.rarfile.FileHeader; @@ -263,6 +264,14 @@ public class CbxConversionService { log.warn("Error extracting image {}: {}", fileHeader.getFileName(), e.getMessage()); } } + } catch (Exception e) { + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI: {}", cbrFile.getName(), e.getMessage()); + return extractImagesFromRarViaCli(cbrFile, extractedImagesDir); + } + if (e instanceof IOException ioe) throw ioe; + if (e instanceof RarException re) throw re; + throw new IOException("Failed to read RAR archive: " + e.getMessage(), e); } log.debug("Found {} image entries in CBR file", imagePaths.size()); @@ -270,6 +279,26 @@ public class CbxConversionService { return imagePaths; } + private List extractImagesFromRarViaCli(File cbrFile, Path extractedImagesDir) throws IOException { + List imagePaths = new ArrayList<>(); + List entries = UnrarHelper.listEntries(cbrFile.toPath()); + for (String entryName : entries) { + if (!isImageFile(entryName)) continue; + try { + byte[] bytes = UnrarHelper.extractEntryBytes(cbrFile.toPath(), entryName); + validateImageSize(entryName, bytes.length); + Path outputPath = extractedImagesDir.resolve(extractFileName(entryName)); + Files.write(outputPath, bytes); + imagePaths.add(outputPath); + } catch (Exception e) { + log.warn("Error extracting image via CLI {}: {}", entryName, e.getMessage()); + } + } + log.debug("Found {} image entries in CBR file (via unrar CLI)", imagePaths.size()); + imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase())); + return imagePaths; + } + private List extractImagesFrom7z(File cb7File, Path extractedImagesDir) throws IOException { List imagePaths = new ArrayList<>(); diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java index 22228209a..84eb155fb 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java @@ -109,22 +109,25 @@ public class LibraryFileHelper { boolean hasNonAudioBooks = dirHasNonAudioBooks.getOrDefault(dir, false); if (audioFiles != null && audioFiles.size() >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBooks) { - // This is a folder-based audiobook: contains 2+ audio files and no ebook files // Don't treat library root as audiobook folder if (!dir.equals(libraryPath)) { - log.info("Detected folder-based audiobook: {} ({} audio files)", dir.getFileName(), audioFiles.size()); + if (FileUtils.isSeriesFolder(audioFiles)) { + log.info("Detected series folder: {} ({} audio files with distinct titles)", dir.getFileName(), audioFiles.size()); + addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles); + } else { + log.info("Detected folder-based audiobook: {} ({} audio files)", dir.getFileName(), audioFiles.size()); - processedAsFolderAudiobook.add(dir); + processedAsFolderAudiobook.add(dir); - // Add a single LibraryFile representing the folder - libraryFiles.add(LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(pathEntity) - .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir)) - .fileName(dir.getFileName().toString()) - .bookFileType(BookFileType.AUDIOBOOK) - .folderBased(true) - .build()); + libraryFiles.add(LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir)) + .fileName(dir.getFileName().toString()) + .bookFileType(BookFileType.AUDIOBOOK) + .folderBased(true) + .build()); + } } else { // Library root - add individual audio files addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/CbxMetadataExtractor.java b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/CbxMetadataExtractor.java index 774fb3817..b8ba01dff 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/CbxMetadataExtractor.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/CbxMetadataExtractor.java @@ -9,6 +9,7 @@ import org.apache.commons.io.FilenameUtils; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.ComicMetadata; import org.booklore.util.ArchiveUtils; +import org.booklore.util.UnrarHelper; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.w3c.dom.NodeList; @@ -22,6 +23,7 @@ import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; +import java.nio.file.Path; import java.time.LocalDate; import java.util.*; import java.util.List; @@ -108,7 +110,15 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { log.warn("Failed to extract metadata from CBR", e); return BookMetadata.builder().title(baseName).build(); } - } catch (Exception ignore) { + } catch (Exception e) { + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage()); + try { + return extractMetadataFromRarViaCli(file.toPath(), baseName); + } catch (Exception ex) { + log.warn("unrar CLI fallback also failed for {}", file.getName(), ex); + } + } } } return BookMetadata.builder().title(baseName).build(); @@ -749,7 +759,16 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { log.warn("Failed to extract cover image from CBR", e); return generatePlaceholderCover(250, 350); } - } catch (Exception ignore) { + } catch (Exception e) { + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI for cover: {}", file.getName(), e.getMessage()); + try { + byte[] coverBytes = extractCoverFromRarViaCli(file.toPath()); + if (coverBytes != null) return coverBytes; + } catch (Exception ex) { + log.warn("unrar CLI cover fallback also failed for {}", file.getName(), ex); + } + } } } @@ -1127,4 +1146,63 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { String lower = n.toLowerCase(); return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml"); } + + private BookMetadata extractMetadataFromRarViaCli(Path rarPath, String baseName) throws Exception { + List entries = UnrarHelper.listEntries(rarPath); + String comicInfoEntry = entries.stream() + .filter(CbxMetadataExtractor::isComicInfoName) + .findFirst() + .orElse(null); + if (comicInfoEntry == null) { + return BookMetadata.builder().title(baseName).build(); + } + byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry); + if (xmlBytes == null || xmlBytes.length == 0) { + return BookMetadata.builder().title(baseName).build(); + } + try (InputStream is = new ByteArrayInputStream(xmlBytes)) { + Document document = buildSecureDocument(is); + return mapDocumentToMetadata(document, baseName); + } + } + + private byte[] extractCoverFromRarViaCli(Path rarPath) throws Exception { + List entries = UnrarHelper.listEntries(rarPath); + + String comicInfoEntry = entries.stream() + .filter(CbxMetadataExtractor::isComicInfoName) + .findFirst() + .orElse(null); + if (comicInfoEntry != null) { + byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry); + if (xmlBytes != null && xmlBytes.length > 0) { + try (InputStream is = new ByteArrayInputStream(xmlBytes)) { + Document document = buildSecureDocument(is); + String imageName = findFrontCoverImageName(document); + if (imageName != null) { + String match = entries.stream() + .filter(e -> e.equalsIgnoreCase(imageName) || baseName(e).equalsIgnoreCase(baseName(imageName))) + .findFirst() + .orElse(null); + if (match != null) { + byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, match); + if (canDecode(bytes)) return bytes; + } + } + } + } + } + + List imageEntries = entries.stream() + .filter(this::isImageEntry) + .sorted(this::naturalCompare) + .toList(); + List sorted = new ArrayList<>(imageEntries); + sorted.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a)), !likelyCoverName(baseName(b)))); + for (String entry : sorted) { + byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, entry); + if (canDecode(bytes)) return bytes; + } + return null; + } } diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/Fb2MetadataExtractor.java b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/Fb2MetadataExtractor.java index eb8b87ce8..0356cb5c9 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/Fb2MetadataExtractor.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/Fb2MetadataExtractor.java @@ -1,6 +1,7 @@ package org.booklore.service.metadata.extractor; import org.booklore.model.dto.BookMetadata; +import org.booklore.util.SecureXmlUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; @@ -9,7 +10,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; @@ -37,9 +37,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor { @Override public byte[] extractCover(File file) { try (InputStream inputStream = getInputStream(file)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(inputStream); @@ -93,9 +91,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor { @Override public BookMetadata extractMetadata(File file) { try (InputStream inputStream = getInputStream(file)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(inputStream); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/writer/CbxMetadataWriter.java b/booklore-api/src/main/java/org/booklore/service/metadata/writer/CbxMetadataWriter.java index dd99559af..15db26dce 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/writer/CbxMetadataWriter.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/writer/CbxMetadataWriter.java @@ -5,6 +5,12 @@ import com.github.junrar.rarfile.FileHeader; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.Unmarshaller; +import jakarta.xml.bind.ValidationEvent; +import javax.xml.XMLConstants; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.sax.SAXSource; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; @@ -16,6 +22,7 @@ import org.booklore.model.enums.BookFileType; import org.booklore.model.enums.ComicCreatorRole; import org.booklore.service.appsettings.AppSettingService; import org.booklore.util.ArchiveUtils; +import org.booklore.util.UnrarHelper; import org.jsoup.Jsoup; import org.jsoup.safety.Safelist; import org.springframework.stereotype.Component; @@ -47,10 +54,6 @@ public class CbxMetadataWriter implements MetadataWriter { private static final JAXBContext JAXB_CONTEXT; static { - // XXE protection: Disable external DTD and Schema access for security - System.setProperty("javax.xml.accessExternalDTD", ""); - System.setProperty("javax.xml.accessExternalSchema", ""); - try { JAXB_CONTEXT = JAXBContext.newInstance(ComicInfo.class); } catch (jakarta.xml.bind.JAXBException e) { @@ -194,9 +197,32 @@ public class CbxMetadataWriter implements MetadataWriter { } } return new ComicInfo(); + } catch (Exception e) { + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage()); + return loadFromRarViaCli(file.toPath()); + } + throw e; } } + private ComicInfo loadFromRarViaCli(Path rarPath) throws Exception { + java.util.List entries = UnrarHelper.listEntries(rarPath); + String comicInfoEntry = entries.stream() + .filter(CbxMetadataWriter::isComicInfoXml) + .findFirst() + .orElse(null); + if (comicInfoEntry != null) { + byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry); + if (xmlBytes != null && xmlBytes.length > 0) { + try (InputStream stream = new ByteArrayInputStream(xmlBytes)) { + return parseComicInfo(stream); + } + } + } + return new ComicInfo(); + } + private void applyMetadataChanges(ComicInfo info, BookMetadataEntity metadata, MetadataClearFlags clearFlags) { MetadataCopyHelper helper = new MetadataCopyHelper(metadata); @@ -447,20 +473,32 @@ public class CbxMetadataWriter implements MetadataWriter { } private ComicInfo parseComicInfo(InputStream xmlStream) throws Exception { + // Use a SAXSource with an explicitly secured XMLReader to prevent XXE injection. + // This is more robust than System.setProperty() because it is per-instance and + // cannot be inadvertently disabled by other code running in the same JVM. + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + spf.setFeature("http://xml.org/sax/features/external-general-entities", false); + spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + SAXSource saxSource = new SAXSource(xmlReader, new InputSource(xmlStream)); + Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); unmarshaller.setEventHandler(event -> { - if (event.getSeverity() == jakarta.xml.bind.ValidationEvent.WARNING || - event.getSeverity() == jakarta.xml.bind.ValidationEvent.ERROR) { - log.warn("JAXB Parsing Issue: {} [Line: {}, Col: {}]", - event.getMessage(), - event.getLocator().getLineNumber(), + if (event.getSeverity() == ValidationEvent.WARNING || + event.getSeverity() == ValidationEvent.ERROR) { + log.warn("JAXB Parsing Issue: {} [Line: {}, Col: {}]", + event.getMessage(), + event.getLocator().getLineNumber(), event.getLocator().getColumnNumber()); } return true; // Continue processing }); - ComicInfo result = (ComicInfo) unmarshaller.unmarshal(xmlStream); - log.debug("CbxMetadataWriter: Parsed ComicInfo - Title: {}, Summary length: {}", - result.getTitle(), + ComicInfo result = (ComicInfo) unmarshaller.unmarshal(saxSource); + log.debug("CbxMetadataWriter: Parsed ComicInfo - Title: {}, Summary length: {}", + result.getTitle(), result.getSummary() != null ? result.getSummary().length() : 0); return result; } @@ -590,6 +628,13 @@ public class CbxMetadataWriter implements MetadataWriter { } } } + } catch (Exception e) { + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI extractAll: {}", rarFile.getName(), e.getMessage()); + UnrarHelper.extractAll(rarFile.toPath(), targetDir); + return; + } + throw e; } } @@ -617,6 +662,13 @@ public class CbxMetadataWriter implements MetadataWriter { zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml")); zipOutput.write(xmlContent); zipOutput.closeEntry(); + } catch (Exception e) { + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI for RAR-to-ZIP: {}", rarFile.getName(), e.getMessage()); + convertRarToZipViaCli(rarFile.toPath(), tempZip, xmlContent); + } else { + throw e; + } } Path targetPath = rarFile.toPath().resolveSibling(removeFileExtension(rarFile.getName()) + ".cbz"); @@ -630,6 +682,26 @@ public class CbxMetadataWriter implements MetadataWriter { return null; } + private void convertRarToZipViaCli(Path rarPath, Path tempZip, byte[] xmlContent) throws Exception { + java.util.List entries = UnrarHelper.listEntries(rarPath); + try (ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(tempZip))) { + for (String entryName : entries) { + if (isComicInfoXml(entryName)) continue; + if (!isPathSafe(entryName)) { + log.warn("Skipping unsafe RAR entry name: {}", entryName); + continue; + } + byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, entryName); + zipOutput.putNextEntry(new ZipEntry(entryName)); + zipOutput.write(bytes); + zipOutput.closeEntry(); + } + zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml")); + zipOutput.write(xmlContent); + zipOutput.closeEntry(); + } + } + private void restoreOriginalFile(Path backupPath, File targetFile) { try { if (backupPath != null) { @@ -703,8 +775,12 @@ public class CbxMetadataWriter implements MetadataWriter { if (entryName == null || entryName.isBlank()) return false; String normalized = entryName.replace('\\', '/'); if (normalized.startsWith("/")) return false; - if (normalized.contains("../")) return false; if (normalized.contains("\0")) return false; + // Check each path component for ".." traversal. Splitting with -1 limit catches + // trailing separators and avoids missing ".." at the end of a path (e.g. "foo/.."). + for (String component : normalized.split("/", -1)) { + if ("..".equals(component)) return false; + } return true; } diff --git a/booklore-api/src/main/java/org/booklore/service/opds/OpdsFeedService.java b/booklore-api/src/main/java/org/booklore/service/opds/OpdsFeedService.java index 335895952..af146f9e6 100644 --- a/booklore-api/src/main/java/org/booklore/service/opds/OpdsFeedService.java +++ b/booklore-api/src/main/java/org/booklore/service/opds/OpdsFeedService.java @@ -16,6 +16,7 @@ import org.springframework.stereotype.Service; import java.io.File; import java.time.format.DateTimeFormatter; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -472,7 +473,7 @@ public class OpdsFeedService { String queryString = request.getQueryString(); if (queryString != null) { - java.util.Arrays.stream(queryString.split("&")) + Arrays.stream(queryString.split("&")) .filter(param -> !param.startsWith("page=") && !param.startsWith("size=")) .forEach(param -> result.append(param).append("&")); } diff --git a/booklore-api/src/main/java/org/booklore/service/progress/ReadingProgressService.java b/booklore-api/src/main/java/org/booklore/service/progress/ReadingProgressService.java index bd42f98c1..89e0b72c5 100644 --- a/booklore-api/src/main/java/org/booklore/service/progress/ReadingProgressService.java +++ b/booklore-api/src/main/java/org/booklore/service/progress/ReadingProgressService.java @@ -209,36 +209,45 @@ public class ReadingProgressService { progress.setBook(book); progress.setLastReadTime(now); - Float percentage; + Float percentage = null; - if (request.getFileProgress() != null) { - BookFileProgress fileProgress = request.getFileProgress(); - percentage = fileProgress.progressPercent(); + boolean hasProgressData = request.getFileProgress() != null + || request.getEpubProgress() != null + || request.getPdfProgress() != null + || request.getCbxProgress() != null + || request.getAudiobookProgress() != null; - saveToUserBookFileProgress(userEntity, fileProgress, now); + if (hasProgressData) { + if (request.getFileProgress() != null) { + BookFileProgress fileProgress = request.getFileProgress(); + percentage = fileProgress.progressPercent(); - BookFileEntity bookFile = bookFileRepository.findById(fileProgress.bookFileId()) - .orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Book file not found")); - updateProgressFromFileProgress(progress, bookFile.getBookType(), fileProgress); - } else { - BookFileEntity primaryFile = book.getPrimaryBookFile(); - if (primaryFile == null) { - throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(); + saveToUserBookFileProgress(userEntity, fileProgress, now); + + BookFileEntity bookFile = bookFileRepository.findById(fileProgress.bookFileId()) + .orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Book file not found")); + updateProgressFromFileProgress(progress, bookFile.getBookType(), fileProgress); + } else { + BookFileEntity primaryFile = book.getPrimaryBookFile(); + if (primaryFile == null) { + throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(); + } + percentage = updateProgressByBookType(progress, primaryFile.getBookType(), request); + + if (percentage != null) { + saveToUserBookFileProgressFromLegacy(userEntity, primaryFile, progress, now); + } } - percentage = updateProgressByBookType(progress, primaryFile.getBookType(), request); if (percentage != null) { - saveToUserBookFileProgressFromLegacy(userEntity, primaryFile, progress, now); + progress.setReadStatus(calculateReadStatus(percentage, progress.getReadStatus())); + BookFileEntity primaryFile = book.getPrimaryBookFile(); + if (primaryFile != null) { + setProgressPercent(progress, primaryFile.getBookType(), percentage); + } } } - if (percentage != null) { - progress.setReadStatus(calculateReadStatus(percentage, progress.getReadStatus())); - BookFileEntity primaryFile = book.getPrimaryBookFile(); - if (primaryFile != null) { - setProgressPercent(progress, primaryFile.getBookType(), percentage); - } - } if (request.getDateFinished() != null) { progress.setDateFinished(request.getDateFinished()); } diff --git a/booklore-api/src/main/java/org/booklore/service/reader/CbxReaderService.java b/booklore-api/src/main/java/org/booklore/service/reader/CbxReaderService.java index 81afb03cf..81efe80c6 100644 --- a/booklore-api/src/main/java/org/booklore/service/reader/CbxReaderService.java +++ b/booklore-api/src/main/java/org/booklore/service/reader/CbxReaderService.java @@ -15,6 +15,7 @@ import org.booklore.model.entity.BookFileEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookRepository; import org.booklore.util.FileUtils; +import org.booklore.util.UnrarHelper; import org.springframework.stereotype.Service; import java.io.FileNotFoundException; @@ -396,7 +397,14 @@ public class CbxReaderService { } } } catch (Exception e) { - throw new IOException("Failed to read RAR archive: " + e.getMessage(), e); + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI: {}", cbxPath.getFileName(), e.getMessage()); + entries = UnrarHelper.listEntries(cbxPath).stream() + .filter(this::isImageFile) + .collect(Collectors.toCollection(ArrayList::new)); + } else { + throw new IOException("Failed to read RAR archive: " + e.getMessage(), e); + } } sortNaturally(entries); return entries; @@ -411,6 +419,11 @@ public class CbxReaderService { } } } catch (Exception e) { + if (UnrarHelper.isAvailable()) { + log.info("junrar failed for {}, falling back to unrar CLI: {}", cbxPath.getFileName(), e.getMessage()); + UnrarHelper.extractEntry(cbxPath, entryName, outputStream); + return; + } throw new IOException("Failed to extract from RAR archive: " + e.getMessage(), e); } throw new FileNotFoundException("Entry not found in RAR archive: " + entryName); @@ -437,6 +450,13 @@ public class CbxReaderService { if (normalized.startsWith("__MACOSX/") || normalized.contains("/__MACOSX/")) { return false; } + // Prevent path traversal: reject any entry whose path contains ".." as a component. + // Checks split-by-/ to catch "foo/..", ".." alone, and not just "../" (with trailing slash). + for (String component : normalized.split("/", -1)) { + if ("..".equals(component)) { + return false; + } + } String baseName = baseName(normalized).toLowerCase(); if (baseName.startsWith("._") || baseName.startsWith(".")) { return false; diff --git a/booklore-api/src/main/java/org/booklore/service/reader/EpubReaderService.java b/booklore-api/src/main/java/org/booklore/service/reader/EpubReaderService.java index 298c20593..365835721 100644 --- a/booklore-api/src/main/java/org/booklore/service/reader/EpubReaderService.java +++ b/booklore-api/src/main/java/org/booklore/service/reader/EpubReaderService.java @@ -20,11 +20,13 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.pdfbox.io.IOUtils; +import org.booklore.util.SecureXmlUtils; import org.springframework.stereotype.Service; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -63,12 +65,7 @@ public class EpubReaderService { private static final ThreadLocal DOCUMENT_BUILDER = ThreadLocal.withInitial(() -> { try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); - factory.setFeature("http://xml.org/sax/features/external-general-entities", false); - factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - return factory.newDocumentBuilder(); + return SecureXmlUtils.createSecureDocumentBuilder(true); } catch (ParserConfigurationException e) { throw new RuntimeException("Failed to create DocumentBuilder", e); } diff --git a/booklore-api/src/main/java/org/booklore/service/upload/FileUploadService.java b/booklore-api/src/main/java/org/booklore/service/upload/FileUploadService.java index 93c765cfc..603faadef 100644 --- a/booklore-api/src/main/java/org/booklore/service/upload/FileUploadService.java +++ b/booklore-api/src/main/java/org/booklore/service/upload/FileUploadService.java @@ -1,5 +1,6 @@ package org.booklore.service.upload; +import lombok.RequiredArgsConstructor; import org.booklore.config.AppProperties; import org.booklore.exception.ApiError; import org.booklore.mapper.AdditionalFileMapper; @@ -21,7 +22,7 @@ import org.booklore.service.file.FileMovingHelper; import org.booklore.service.monitoring.MonitoringRegistrationService; import org.booklore.service.metadata.extractor.MetadataExtractorFactory; import org.booklore.util.PathPatternResolver; -import lombok.RequiredArgsConstructor; +import org.springframework.util.StringUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -262,7 +263,13 @@ public class FileUploadService { if (originalFileName == null) { throw new IllegalArgumentException("File must have a name"); } - return originalFileName; + // Prevent Path Traversal by extracting only the base file name + String cleanPath = StringUtils.cleanPath(originalFileName); + String baseFileName = StringUtils.getFilename(cleanPath); + if (baseFileName == null || baseFileName.isEmpty() || baseFileName.equals("..")) { + throw new IllegalArgumentException("Invalid filename"); + } + return baseFileName; } private BookFileExtension getFileExtension(String fileName) { diff --git a/booklore-api/src/main/java/org/booklore/service/watcher/LibraryFileEventProcessor.java b/booklore-api/src/main/java/org/booklore/service/watcher/LibraryFileEventProcessor.java index eec59384f..bfb3af80d 100644 --- a/booklore-api/src/main/java/org/booklore/service/watcher/LibraryFileEventProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/watcher/LibraryFileEventProcessor.java @@ -18,6 +18,8 @@ import org.springframework.stereotype.Service; import java.io.IOException; import java.nio.file.*; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.*; @@ -252,7 +254,7 @@ public class LibraryFileEventProcessor { } private FolderAnalysis analyzeFolderForAudiobook(Path folderPath) { - int audioFileCount = 0; + List audioFiles = new ArrayList<>(); boolean hasNonAudioBook = false; try (var stream = Files.walk(folderPath)) { @@ -263,7 +265,7 @@ public class LibraryFileEventProcessor { var ext = BookFileExtension.fromFileName(fileName); if (ext.isPresent()) { if (ext.get().getType() == BookFileType.AUDIOBOOK) { - audioFileCount++; + audioFiles.add(file); } else { hasNonAudioBook = true; } @@ -273,12 +275,15 @@ public class LibraryFileEventProcessor { log.warn("[ERROR] Analyzing folder '{}': {}", folderPath, e.getMessage()); } - return new FolderAnalysis(audioFileCount, hasNonAudioBook); + boolean isSeriesFolder = audioFiles.size() >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK + && FileUtils.isSeriesFolder(audioFiles); + + return new FolderAnalysis(audioFiles.size(), hasNonAudioBook, isSeriesFolder); } - private record FolderAnalysis(int audioFileCount, boolean hasNonAudioBook) { + private record FolderAnalysis(int audioFileCount, boolean hasNonAudioBook, boolean isSeriesFolder) { boolean isFolderBasedAudiobook() { - return audioFileCount >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBook; + return audioFileCount >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBook && !isSeriesFolder; } } diff --git a/booklore-api/src/main/java/org/booklore/util/BookFileGroupingUtils.java b/booklore-api/src/main/java/org/booklore/util/BookFileGroupingUtils.java index d349d53a6..c9faad6b9 100644 --- a/booklore-api/src/main/java/org/booklore/util/BookFileGroupingUtils.java +++ b/booklore-api/src/main/java/org/booklore/util/BookFileGroupingUtils.java @@ -44,6 +44,23 @@ public class BookFileGroupingUtils { "[\\s_-]?(\\d{1,3})\\s*$" ); + // Part/disc indicators: "(part 1)", "[pt 2]", "- disc 1", "cd 3", etc. + // "part" requires brackets or dash prefix to avoid conflict with series labels ("Part 1" = series entry). + // "pt", "disc", "disk", "cd" are unambiguous and can be matched bare. + private static final Pattern PART_INDICATOR_PATTERN = Pattern.compile( + "\\s*(?:" + + "[\\(\\[]\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+\\s*[\\)\\]]" + + "|-\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+" + + "|(?:pt|dis[ck]|cd)\\s*\\d+" + + ")\\s*$", + Pattern.CASE_INSENSITIVE + ); + + // Bare-number prefix: "1. Title", "01 - Title" (NOT "101 Dalmatians" or "1984") + private static final Pattern BARE_NUMBER_PREFIX_PATTERN = Pattern.compile( + "^(\\d{1,3})(?:\\.|\\s*-)\\s+(.+)$" + ); + // Edition/version patterns that should NOT prevent grouping // Includes format indicators (audiobook, ebook) and edition descriptors private static final Pattern EDITION_PATTERN = Pattern.compile( @@ -86,6 +103,9 @@ public class BookFileGroupingUtils { baseName = FORMAT_INDICATOR_PATTERN.matcher(baseName).replaceAll(""); + // Strip part/disc indicators (e.g., "(part 1)", "[cd 2]") + baseName = PART_INDICATOR_PATTERN.matcher(baseName).replaceAll(""); + // Strip trailing author names (after dash) baseName = TRAILING_AUTHOR_PATTERN.matcher(baseName).replaceAll(""); @@ -318,6 +338,18 @@ public class BookFileGroupingUtils { } } } + + // Fallback: bare-number prefix like "1. title" or "01 - title" + Matcher bareMatcher = BARE_NUMBER_PREFIX_PATTERN.matcher(key); + if (bareMatcher.matches()) { + String number = bareMatcher.group(1); + String baseTitle = bareMatcher.group(2).trim(); + baseTitle = WHITESPACE_PATTERN.matcher(baseTitle).replaceAll(" ").trim(); + if (baseTitle.length() >= 3) { + return new SeriesInfo(baseTitle, number); + } + } + return null; } diff --git a/booklore-api/src/main/java/org/booklore/util/FileService.java b/booklore-api/src/main/java/org/booklore/util/FileService.java index 844962001..11cb99eb1 100644 --- a/booklore-api/src/main/java/org/booklore/util/FileService.java +++ b/booklore-api/src/main/java/org/booklore/util/FileService.java @@ -11,22 +11,30 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; +import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.URI; +import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.Comparator; +import java.util.Iterator; import java.util.Set; import java.util.stream.Stream; @@ -35,9 +43,32 @@ import java.util.stream.Stream; @Service public class FileService { + private static final ThreadLocal TARGET_HOST_THREAD_LOCAL = new ThreadLocal<>(); + + public static String getTargetHost() { + return TARGET_HOST_THREAD_LOCAL.get(); + } + + public static void setTargetHost(String host) { + TARGET_HOST_THREAD_LOCAL.set(host); + } + + public static void clearTargetHost() { + TARGET_HOST_THREAD_LOCAL.remove(); + } + + static { + // Enable restricted headers to allow 'Host' header override for DNS rebinding protection + System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); + } + private final AppProperties appProperties; private final RestTemplate restTemplate; private final AppSettingService appSettingService; + private final RestTemplate noRedirectRestTemplate; + + private static final int MAX_REDIRECTS = 5; + private static final double TARGET_COVER_ASPECT_RATIO = 1.5; private static final int SMART_CROP_COLOR_TOLERANCE = 30; @@ -58,6 +89,8 @@ public class FileService { private static final String JPEG_MIME_TYPE = "image/jpeg"; private static final String PNG_MIME_TYPE = "image/png"; private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; + // 20 MP covers legitimate book covers and author photos with a comfortable safety margin. + private static final long MAX_IMAGE_PIXELS = 20_000_000L; private static final int THUMBNAIL_WIDTH = 250; private static final int THUMBNAIL_HEIGHT = 350; private static final int SQUARE_THUMBNAIL_SIZE = 250; @@ -137,6 +170,7 @@ public class FileService { return Paths.get(appProperties.getPathConfig(), "tools", "kepubify").toString(); } + // ======================================== // VALIDATION // ======================================== @@ -170,18 +204,34 @@ public class FileService { if (imageData == null || imageData.length == 0) { throw new IOException("Image data is null or empty"); } - try (InputStream is = new ByteArrayInputStream(imageData)) { - BufferedImage image = ImageIO.read(is); - if (image != null) { - return image; + + try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageData))) { + Iterator readers = ImageIO.getImageReaders(iis); + if (readers.hasNext()) { + ImageReader reader = readers.next(); + try { + reader.setInput(iis); + int width = reader.getWidth(0); + int height = reader.getHeight(0); + + long pixelCount = (long) width * height; + if (pixelCount > MAX_IMAGE_PIXELS) { + throw new IOException(String.format("Rejected image: dimensions %dx%d (%d pixels) exceed limit %d — possible decompression bomb", + width, height, pixelCount, MAX_IMAGE_PIXELS)); + } + + return reader.read(0); + } finally { + reader.dispose(); + } } + } catch (IOException e) { + throw e; } catch (Exception e) { - log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage()); - return null; + throw new IOException("ImageIO decode failed (possibly unsupported format): " + e.getMessage(), e); } - log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)"); - return null; + throw new IOException("Unable to decode image, likely unsupported format"); } public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) { @@ -217,31 +267,138 @@ public class FileService { public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException { try { - HttpHeaders headers = new HttpHeaders(); - headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)"); - headers.set(HttpHeaders.ACCEPT, "image/*"); - - HttpEntity entity = new HttpEntity<>(headers); - - ResponseEntity response = restTemplate.exchange( - imageUrl, - HttpMethod.GET, - entity, - byte[].class - ); - - // Validate and convert - if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) { - return readImage(response.getBody()); - } else { - throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode()); - } + return downloadImageFromUrlInternal(imageUrl); } catch (Exception e) { - log.error("Failed to download image from URL: {} - {}", imageUrl, e.getMessage()); - throw new IOException("Failed to download image from URL: " + imageUrl + " - " + e.getMessage(), e); + log.warn("Failed to download image from {}: {}", imageUrl, e.getMessage()); + if (e instanceof IOException ioException) { + throw ioException; + } + throw new IOException("Failed to download image from " + imageUrl + ": " + e.getMessage(), e); } } + private BufferedImage downloadImageFromUrlInternal(String imageUrl) throws IOException { + String currentUrl = imageUrl; + int redirectCount = 0; + + try { + while (redirectCount <= MAX_REDIRECTS) { + URI uri = URI.create(currentUrl); + // Protocol validation + if (!"http".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(uri.getScheme())) { + throw new IOException("Only HTTP and HTTPS protocols are allowed"); + } + + String host = uri.getHost(); + if (host == null) { + throw new IOException("Invalid URL: no host found in " + currentUrl); + } + + // Resolve host to IP to prevent DNS rebinding (TOCTOU) + InetAddress[] inetAddresses = InetAddress.getAllByName(host); + if (inetAddresses.length == 0) { + throw new IOException("Could not resolve host: " + host); + } + for (InetAddress inetAddress : inetAddresses) { + if (isInternalAddress(inetAddress)) { + throw new SecurityException("URL points to a local or private internal network address: " + host + " (" + inetAddress.getHostAddress() + ")"); + } + } + String ipAddress = inetAddresses[0].getHostAddress(); + + // Set target host for SNI / Hostname verification in RestTemplate/SSLSocketFactory + setTargetHost(host); + + // Build request URL with IP address to ensure we connect to the validated address. + // We keep the original URI's path and query. + String portSuffix = (uri.getPort() != -1) ? ":" + uri.getPort() : ""; + String path = uri.getRawPath(); + if (path == null || path.isEmpty()) path = "/"; + String query = uri.getRawQuery(); + + // Handle IPv6 address formatting in URL + String hostInUrl = ipAddress; + if (ipAddress.contains(":")) { + hostInUrl = "[" + ipAddress + "]"; + } + String requestUrl = uri.getScheme() + "://" + hostInUrl + portSuffix + path + (query != null ? "?" + query : ""); + + HttpHeaders headers = new HttpHeaders(); + // Set original 'Host' header for server-side virtual hosting + headers.set(HttpHeaders.HOST, host); + headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)"); + headers.set(HttpHeaders.ACCEPT, "image/*"); + + HttpEntity entity = new HttpEntity<>(headers); + + log.debug("Downloading image via IP-based URL: {} (Original host: {})", requestUrl, host); + + ResponseEntity response = noRedirectRestTemplate.exchange( + requestUrl, + HttpMethod.GET, + entity, + byte[].class + ); + + if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) { + return readImage(response.getBody()); + } else if (response.getStatusCode().is3xxRedirection()) { + String location = response.getHeaders().getFirst(HttpHeaders.LOCATION); + if (location == null) { + throw new IOException("Redirection response without Location header"); + } + // Resolve location against CURRENT URL (which has the hostname) + currentUrl = uri.resolve(location).toString(); + redirectCount++; + } else { + throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode()); + } + } + } finally { + // Ensure thread-local is cleared to prevent leakage to subsequent requests (container thread reuse) + clearTargetHost(); + } + + throw new IOException("Too many redirects (max " + MAX_REDIRECTS + ")"); + } + + private boolean isInternalAddress(InetAddress address) { + if (address.isLoopbackAddress() || address.isLinkLocalAddress() || + address.isSiteLocalAddress() || address.isAnyLocalAddress()) { + return true; + } + + byte[] addr = address.getAddress(); + // Check for IPv6 Unique Local Address (fc00::/7) + if (addr.length == 16) { + if ((addr[0] & 0xFE) == (byte) 0xFC) { + return true; + } + } + + // Handle IPv4-mapped IPv6 addresses (::ffff:127.0.0.1) + if (isIpv4MappedAddress(addr)) { + try { + byte[] ipv4Bytes = new byte[4]; + System.arraycopy(addr, 12, ipv4Bytes, 0, 4); + InetAddress ipv4Addr = InetAddress.getByAddress(ipv4Bytes); + return isInternalAddress(ipv4Addr); + } catch (java.net.UnknownHostException e) { + return false; + } + } + + return false; + } + + private boolean isIpv4MappedAddress(byte[] addr) { + if (addr.length != 16) return false; + for (int i = 0; i < 10; i++) { + if (addr[i] != 0) return false; + } + return (addr[10] == (byte) 0xFF) && (addr[11] == (byte) 0xFF); + } + // ======================================== // COVER OPERATIONS // ======================================== diff --git a/booklore-api/src/main/java/org/booklore/util/FileUtils.java b/booklore-api/src/main/java/org/booklore/util/FileUtils.java index 3d20f7254..a234eea7b 100644 --- a/booklore-api/src/main/java/org/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/org/booklore/util/FileUtils.java @@ -12,8 +12,11 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Comparator; +import java.util.HashSet; import java.util.List; import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; @UtilityClass @Slf4j @@ -147,6 +150,43 @@ public class FileUtils { } } + private static final Pattern LEADING_NUMBER_PREFIX = Pattern.compile("^\\d{1,3}(?:\\.|\\s*-)\\s*"); + private static final Pattern PART_DISC_INDICATOR = Pattern.compile( + "\\s*[\\(\\[\\-]?\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+\\s*[\\)\\]]?\\s*$", + Pattern.CASE_INSENSITIVE + ); + private static final Pattern TRAILING_NUMBERS = Pattern.compile("\\s*\\d+\\s*$"); + private static final Set GENERIC_AUDIO_TITLES = Set.of( + "chapter", "track", "part", "disc", "disk", "cd", "side", "intro", "epilogue", "prologue", "outro" + ); + + /** + * Determines if a list of audio files represents a series folder (each file is a separate book) + * rather than a multi-file audiobook (chapter files for one book). + * + * Extracts a "base title" from each file by stripping numbering, part indicators, and extensions, + * then counts distinct non-generic titles. If more than one distinct title exists, it's a series folder. + */ + public boolean isSeriesFolder(List audioFiles) { + Set distinctTitles = new HashSet<>(); + for (Path file : audioFiles) { + String title = extractBaseTitle(file.getFileName().toString()); + if (!title.isEmpty() && !GENERIC_AUDIO_TITLES.contains(title)) { + distinctTitles.add(title); + } + } + return distinctTitles.size() > 1; + } + + private String extractBaseTitle(String fileName) { + int lastDot = fileName.lastIndexOf('.'); + String baseName = lastDot > 0 ? fileName.substring(0, lastDot) : fileName; + baseName = LEADING_NUMBER_PREFIX.matcher(baseName).replaceFirst(""); + baseName = PART_DISC_INDICATOR.matcher(baseName).replaceAll(""); + baseName = TRAILING_NUMBERS.matcher(baseName).replaceAll(""); + return baseName.toLowerCase().trim(); + } + public void deleteDirectoryRecursively(Path path) throws IOException { if (!Files.exists(path)) return; diff --git a/booklore-api/src/main/java/org/booklore/util/SecureXmlUtils.java b/booklore-api/src/main/java/org/booklore/util/SecureXmlUtils.java index f5fba2dad..45e3f48a5 100644 --- a/booklore-api/src/main/java/org/booklore/util/SecureXmlUtils.java +++ b/booklore-api/src/main/java/org/booklore/util/SecureXmlUtils.java @@ -12,7 +12,7 @@ import javax.xml.parsers.ParserConfigurationException; @UtilityClass public class SecureXmlUtils { - public static DocumentBuilderFactory createSecureDocumentBuilderFactory(boolean namespaceAware) { + public static DocumentBuilderFactory createSecureDocumentBuilderFactory(boolean namespaceAware) throws ParserConfigurationException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(namespaceAware); @@ -27,10 +27,8 @@ public class SecureXmlUtils { return factory; } catch (ParserConfigurationException e) { - log.warn("Failed to configure secure XML parser, using defaults: {}", e.getMessage()); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(namespaceAware); - return factory; + log.error("CRITICAL: Failed to configure secure XML parser: {}", e.getMessage()); + throw e; } } diff --git a/booklore-api/src/main/java/org/booklore/util/UnrarHelper.java b/booklore-api/src/main/java/org/booklore/util/UnrarHelper.java new file mode 100644 index 000000000..6d656d937 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/util/UnrarHelper.java @@ -0,0 +1,134 @@ +package org.booklore.util; + +import lombok.experimental.UtilityClass; +import lombok.extern.slf4j.Slf4j; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +@Slf4j +@UtilityClass +public class UnrarHelper { + + private static final String UNRAR_BIN_ENV = "BOOKLORE_UNRAR_BIN"; + private static final String DEFAULT_UNRAR_BIN = "unrar"; + private static final int PROCESS_TIMEOUT_SECONDS = 120; + private static volatile Boolean cachedAvailability; + + public static boolean isAvailable() { + if (cachedAvailability != null) { + return cachedAvailability; + } + synchronized (UnrarHelper.class) { + if (cachedAvailability != null) { + return cachedAvailability; + } + try { + Process process = new ProcessBuilder(getUnrarBin()) + .redirectErrorStream(true) + .start(); + try (InputStream is = process.getInputStream()) { + is.readAllBytes(); + } + boolean finished = process.waitFor(5, TimeUnit.SECONDS); + cachedAvailability = finished; + } catch (Exception e) { + log.debug("unrar binary not available: {}", e.getMessage()); + cachedAvailability = false; + } + if (cachedAvailability) { + log.info("unrar CLI detected, RAR5 fallback enabled"); + } + return cachedAvailability; + } + } + + public static List listEntries(Path rarPath) throws IOException { + ProcessBuilder pb = new ProcessBuilder(getUnrarBin(), "lb", rarPath.toAbsolutePath().toString()); + pb.redirectErrorStream(true); + Process process = pb.start(); + String output; + try (InputStream is = process.getInputStream()) { + output = new String(is.readAllBytes()); + } + try { + if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IOException("unrar list timed out for: " + rarPath); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("unrar list interrupted", e); + } + if (process.exitValue() != 0) { + throw new IOException("unrar list failed (exit " + process.exitValue() + ") for: " + rarPath); + } + return Arrays.stream(output.split("\n")) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .toList(); + } + + public static void extractEntry(Path rarPath, String entryName, OutputStream out) throws IOException { + ProcessBuilder pb = new ProcessBuilder( + getUnrarBin(), "p", "-inul", rarPath.toAbsolutePath().toString(), entryName + ); + pb.redirectErrorStream(false); + Process process = pb.start(); + try (InputStream is = process.getInputStream()) { + is.transferTo(out); + } + try { + if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IOException("unrar extract timed out for entry: " + entryName); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("unrar extract interrupted", e); + } + if (process.exitValue() != 0) { + throw new IOException("unrar extract failed (exit " + process.exitValue() + ") for entry: " + entryName); + } + } + + public static byte[] extractEntryBytes(Path rarPath, String entryName) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + extractEntry(rarPath, entryName, baos); + return baos.toByteArray(); + } + + public static void extractAll(Path rarPath, Path targetDir) throws IOException { + ProcessBuilder pb = new ProcessBuilder( + getUnrarBin(), "x", "-o+", rarPath.toAbsolutePath().toString(), targetDir.toAbsolutePath() + "/" + ); + pb.redirectErrorStream(true); + Process process = pb.start(); + try (InputStream is = process.getInputStream()) { + is.readAllBytes(); + } + try { + if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IOException("unrar extractAll timed out for: " + rarPath); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("unrar extractAll interrupted", e); + } + if (process.exitValue() != 0) { + throw new IOException("unrar extractAll failed (exit " + process.exitValue() + ") for: " + rarPath); + } + } + + private static String getUnrarBin() { + String env = System.getenv(UNRAR_BIN_ENV); + return (env != null && !env.isBlank()) ? env : DEFAULT_UNRAR_BIN; + } +} diff --git a/booklore-api/src/main/java/org/booklore/util/kobo/KoboUrlBuilder.java b/booklore-api/src/main/java/org/booklore/util/kobo/KoboUrlBuilder.java index ade824517..a7bdc630a 100644 --- a/booklore-api/src/main/java/org/booklore/util/kobo/KoboUrlBuilder.java +++ b/booklore-api/src/main/java/org/booklore/util/kobo/KoboUrlBuilder.java @@ -1,9 +1,12 @@ package org.booklore.util.kobo; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.booklore.util.RequestUtils; import org.springframework.stereotype.Component; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; @Component @@ -17,10 +20,30 @@ public class KoboUrlBuilder { .replacePath("") .replaceQuery(null); + UriComponents built = builder.build(); + if (built.getPort() == -1 && !hasForwardedHeaders()) { + int localPort = RequestUtils.getCurrentRequest().getLocalPort(); + if (!isDefaultPort(built.getScheme(), localPort)) { + builder.port(localPort); + } + } + log.debug("Final base URL: {}", builder.build().toUriString()); return builder; } + private boolean hasForwardedHeaders() { + HttpServletRequest request = RequestUtils.getCurrentRequest(); + return request.getHeader("X-Forwarded-Host") != null + || request.getHeader("X-Forwarded-Port") != null + || request.getHeader("X-Forwarded-Proto") != null + || request.getHeader("Forwarded") != null; + } + + private boolean isDefaultPort(String scheme, int port) { + return ("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443); + } + public String downloadUrl(String token, Long bookId) { return baseBuilder() .pathSegment("api", "kobo", token, "v1", "books", "{bookId}", "download") diff --git a/booklore-api/src/main/resources/application.yaml b/booklore-api/src/main/resources/application.yaml index 8a9c56b6e..61639be4b 100644 --- a/booklore-api/src/main/resources/application.yaml +++ b/booklore-api/src/main/resources/application.yaml @@ -2,6 +2,13 @@ app: path-config: '/app/data' bookdrop-folder: '/bookdrop' version: 'development' + + cors: + # Comma-separated list of allowed CORS origins. + # Leave empty (default) to allow same-origin requests only. + # Example: ALLOWED_ORIGINS=https://app.example.com,https://mobile.example.com + allowed-origins: ${ALLOWED_ORIGINS:*} + remote-auth: enabled: ${REMOTE_AUTH_ENABLED:false} create-new-users: ${REMOTE_AUTH_CREATE_NEW_USERS:true} @@ -28,6 +35,9 @@ server: relaxed-query-chars: '[,],%,{,},|' spring: + jackson: + deserialization: + fail-on-null-for-primitives: false servlet: multipart: enabled: false diff --git a/booklore-api/src/test/java/org/booklore/service/Rar5FallbackIntegrationTest.java b/booklore-api/src/test/java/org/booklore/service/Rar5FallbackIntegrationTest.java new file mode 100644 index 000000000..57cab3fe7 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/Rar5FallbackIntegrationTest.java @@ -0,0 +1,186 @@ +package org.booklore.service; + +import org.booklore.model.dto.BookMetadata; +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookMetadataEntity; +import org.booklore.service.kobo.CbxConversionService; +import org.booklore.service.metadata.extractor.CbxMetadataExtractor; +import org.booklore.service.metadata.writer.CbxMetadataWriter; +import org.booklore.service.reader.CbxReaderService; +import org.booklore.repository.BookRepository; +import org.booklore.service.appsettings.AppSettingService; +import org.booklore.util.UnrarHelper; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assumptions.assumeThat; + +/** + * Integration tests that feed a real RAR5 archive into the service layer + * and verify junrar fails then the unrar CLI fallback kicks in. + */ +@ExtendWith(MockitoExtension.class) +class Rar5FallbackIntegrationTest { + + private static final Path RAR5_CBR = Path.of("src/test/resources/cbx/test-rar5.cbr"); + + @BeforeAll + static void checkUnrarAvailable() { + assumeThat(UnrarHelper.isAvailable()) + .as("unrar binary must be on PATH to run these tests") + .isTrue(); + } + + // -- CbxMetadataExtractor: extractMetadata fallback -- + + @Test + void metadataExtractor_extractsComicInfoFromRar5(@TempDir Path tempDir) throws Exception { + Path cbrCopy = tempDir.resolve("test.cbr"); + Files.copy(RAR5_CBR, cbrCopy); + + CbxMetadataExtractor extractor = new CbxMetadataExtractor(); + BookMetadata metadata = extractor.extractMetadata(cbrCopy.toFile()); + + assertThat(metadata.getTitle()).isEqualTo("Test RAR5 Comic"); + assertThat(metadata.getSeriesName()).isEqualTo("RAR5 Test Series"); + assertThat(metadata.getSeriesNumber()).isEqualTo(1.0f); + assertThat(metadata.getAuthors()).contains("Test Author"); + } + + // -- CbxReaderService: getImageEntriesFromRar + streamEntryFromRar fallback -- + + @Test + void readerService_listsImagePagesFromRar5(@TempDir Path tempDir) throws Exception { + Path cbrCopy = tempDir.resolve("test.cbr"); + Files.copy(RAR5_CBR, cbrCopy); + + BookEntity book = new BookEntity(); + book.setId(99L); + BookRepository mockRepo = org.mockito.Mockito.mock(BookRepository.class); + org.mockito.Mockito.when(mockRepo.findById(99L)).thenReturn(java.util.Optional.of(book)); + + try (var fileUtilsStatic = org.mockito.Mockito.mockStatic(org.booklore.util.FileUtils.class)) { + fileUtilsStatic.when(() -> org.booklore.util.FileUtils.getBookFullPath(book)) + .thenReturn(cbrCopy.toString()); + + CbxReaderService readerService = new CbxReaderService(mockRepo); + List pages = readerService.getAvailablePages(99L); + + assertThat(pages).hasSize(3); + assertThat(pages).containsExactly(1, 2, 3); + } + } + + @Test + void readerService_streamsImageFromRar5(@TempDir Path tempDir) throws Exception { + Path cbrCopy = tempDir.resolve("test.cbr"); + Files.copy(RAR5_CBR, cbrCopy); + + BookEntity book = new BookEntity(); + book.setId(99L); + BookRepository mockRepo = org.mockito.Mockito.mock(BookRepository.class); + org.mockito.Mockito.when(mockRepo.findById(99L)).thenReturn(java.util.Optional.of(book)); + + try (var fileUtilsStatic = org.mockito.Mockito.mockStatic(org.booklore.util.FileUtils.class)) { + fileUtilsStatic.when(() -> org.booklore.util.FileUtils.getBookFullPath(book)) + .thenReturn(cbrCopy.toString()); + + CbxReaderService readerService = new CbxReaderService(mockRepo); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + readerService.streamPageImage(99L, 1, out); + + byte[] imageBytes = out.toByteArray(); + assertThat(imageBytes).hasSizeGreaterThan(0); + assertThat(imageBytes[0]).isEqualTo((byte) 0xFF); + assertThat(imageBytes[1]).isEqualTo((byte) 0xD8); + } + } + + // -- CbxConversionService: extractImagesFromRar fallback -- + + @Test + void conversionService_extractsImagesFromRar5(@TempDir Path tempDir) throws Exception { + Path cbrCopy = tempDir.resolve("test.cbr"); + Files.copy(RAR5_CBR, cbrCopy); + + BookEntity book = new BookEntity(); + book.setId(99L); + BookMetadataEntity meta = new BookMetadataEntity(); + meta.setTitle("Test RAR5 Comic"); + book.setMetadata(meta); + + CbxConversionService conversionService = new CbxConversionService(); + File epub = conversionService.convertCbxToEpub(cbrCopy.toFile(), tempDir.toFile(), book, 85); + + assertThat(epub).exists(); + assertThat(epub.length()).isGreaterThan(0); + + try (ZipFile epubZip = new ZipFile(epub)) { + ZipEntry mimetype = epubZip.getEntry("mimetype"); + assertThat(mimetype).isNotNull(); + + List imageEntries = epubZip.stream() + .map(ZipEntry::getName) + .filter(name -> name.startsWith("OEBPS/Images/page-")) + .toList(); + assertThat(imageEntries).hasSize(3); + } + } + + // -- CbxMetadataWriter: loadFromRar + convertRarToZipArchive fallback -- + + @Test + void metadataWriter_convertsRar5ToCbzViaFallback(@TempDir Path tempDir) throws Exception { + Path cbrCopy = tempDir.resolve("test.cbr"); + Files.copy(RAR5_CBR, cbrCopy); + + AppSettingService mockSettings = org.mockito.Mockito.mock(AppSettingService.class); + var appSettings = new org.booklore.model.dto.settings.AppSettings(); + var persistenceSettings = new org.booklore.model.dto.settings.MetadataPersistenceSettings(); + var saveToFile = new org.booklore.model.dto.settings.MetadataPersistenceSettings.SaveToOriginalFile(); + var cbxSettings = new org.booklore.model.dto.settings.MetadataPersistenceSettings.FormatSettings(); + cbxSettings.setEnabled(true); + cbxSettings.setMaxFileSizeInMb(500); + saveToFile.setCbx(cbxSettings); + persistenceSettings.setSaveToOriginalFile(saveToFile); + appSettings.setMetadataPersistenceSettings(persistenceSettings); + org.mockito.Mockito.when(mockSettings.getAppSettings()).thenReturn(appSettings); + + CbxMetadataWriter writer = new CbxMetadataWriter(mockSettings); + + BookMetadataEntity metadata = new BookMetadataEntity(); + metadata.setTitle("Updated RAR5 Title"); + + writer.saveMetadataToFile(cbrCopy.toFile(), metadata, null, null); + + Path cbzPath = tempDir.resolve("test.cbz"); + assertThat(cbzPath).exists(); + + try (ZipFile resultZip = new ZipFile(cbzPath.toFile())) { + ZipEntry comicInfo = resultZip.getEntry("ComicInfo.xml"); + assertThat(comicInfo).isNotNull(); + + String xml = new String(resultZip.getInputStream(comicInfo).readAllBytes()); + assertThat(xml).contains("Updated RAR5 Title"); + + long imageCount = resultZip.stream() + .map(ZipEntry::getName) + .filter(name -> name.endsWith(".jpg")) + .count(); + assertThat(imageCount).isEqualTo(3); + } + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/MetadataMatchServiceTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/MetadataMatchServiceTest.java index 964a96771..9f1851a85 100644 --- a/booklore-api/src/test/java/org/booklore/service/metadata/MetadataMatchServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/metadata/MetadataMatchServiceTest.java @@ -114,6 +114,7 @@ class MetadataMatchServiceTest { .isbn13(0).isbn10(0).language(0).pageCount(0).categories(0) .amazonRating(0).amazonReviewCount(0).goodreadsRating(0) .goodreadsReviewCount(0).hardcoverRating(0).hardcoverReviewCount(0) - .doubanRating(0).doubanReviewCount(0).ranobedbRating(0).coverImage(0); + .doubanRating(0).doubanReviewCount(0).ranobedbRating(0) + .audibleRating(0).audibleReviewCount(0).coverImage(0); } } diff --git a/booklore-api/src/test/java/org/booklore/util/BookFileGroupingUtilsTest.java b/booklore-api/src/test/java/org/booklore/util/BookFileGroupingUtilsTest.java index 07748909a..be80466fb 100644 --- a/booklore-api/src/test/java/org/booklore/util/BookFileGroupingUtilsTest.java +++ b/booklore-api/src/test/java/org/booklore/util/BookFileGroupingUtilsTest.java @@ -510,6 +510,152 @@ class BookFileGroupingUtilsTest { assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(basic, withAuthor); } + // ========== Part Indicator Stripping Tests ========== + + @Test + void extractGroupingKey_shouldStripPartIndicators() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (part 1).m4b")).isEqualTo("the lost hero"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (pt 2).m4b")).isEqualTo("the lost hero"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (disc 1).m4b")).isEqualTo("the lost hero"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero [cd 3].m4b")).isEqualTo("the lost hero"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero - part 1.m4b")).isEqualTo("the lost hero"); + } + + @Test + void extractGroupingKey_shouldPreserveNonPartParenthetical() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (Extended Edition).epub")) + .isEqualTo("the hobbit (extended edition)"); + } + + @Test + void extractGroupingKey_shouldProduceSameKeyForMultiPartFiles() { + String key1 = BookFileGroupingUtils.extractGroupingKey("1. The Lost Hero (part 1).m4b"); + String key2 = BookFileGroupingUtils.extractGroupingKey("1. The Lost Hero (part 2).m4b"); + assertThat(key1).isEqualTo(key2); + } + + // ========== Bare-Number Series Detection Tests ========== + + @Test + void extractGroupingKey_shouldNotStripBarePartAsSeriesLabel() { + // "Part 1" without brackets/dash is a series label, not a multi-file indicator + assertThat(BookFileGroupingUtils.extractGroupingKey("Harry Potter Part 1.epub")) + .isEqualTo("harry potter part 1"); + assertThat(BookFileGroupingUtils.extractGroupingKey("Harry Potter Part 2.epub")) + .isEqualTo("harry potter part 2"); + } + + @Test + void groupByBaseName_shouldKeepBarePartSeriesEntriesSeparate() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile part1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Harry Potter") + .fileName("Harry Potter Part 1.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile part2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Harry Potter") + .fileName("Harry Potter Part 2.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(part1, part2)); + + assertThat(groups).hasSize(2); + } + + @Test + void groupByBaseName_shouldSeparateBareNumberedSeriesFiles() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile file1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Percy Jackson") + .fileName("1. The Lightning Thief.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile file2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Percy Jackson") + .fileName("2. The Sea of Monsters.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2)); + + assertThat(groups).hasSize(2); + } + + @Test + void groupByBaseName_shouldGroupMultiPartFilesOfSameBook() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile part1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus") + .fileName("1. The Lost Hero (part 1).m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile part2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus") + .fileName("1. The Lost Hero (part 2).m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(part1, part2)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(part1, part2); + } + + @Test + void groupByBaseName_shouldHandleMixedPartsAndSeparateBooks() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile lostHeroPt1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus") + .fileName("1. The Lost Hero (part 1).m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile lostHeroPt2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus") + .fileName("1. The Lost Hero (part 2).m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile sonOfNeptune = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus") + .fileName("2. The Son of Neptune.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(lostHeroPt1, lostHeroPt2, sonOfNeptune)); + + assertThat(groups).hasSize(2); + boolean foundLostHeroGroup = groups.values().stream() + .anyMatch(list -> list.size() == 2 && list.containsAll(List.of(lostHeroPt1, lostHeroPt2))); + assertThat(foundLostHeroGroup).isTrue(); + } + @Test void groupByBaseName_shouldHandleFolderBasedAudiobook() { // Folder-based audiobook (MP3 folder) with ebook files @@ -637,6 +783,453 @@ class BookFileGroupingUtilsTest { assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, audiobook1); } + // ========== Part Indicator Pattern Edge Cases ========== + + @Test + void extractGroupingKey_shouldStripBareDiscAndCdAndPt() { + // pt, disc, disk, cd are unambiguous and stripped even without brackets/dash + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit disc 1.m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit disk 2.m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit cd 3.m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit pt 1.m4b")).isEqualTo("the hobbit"); + } + + @Test + void extractGroupingKey_shouldStripPartInSquareBrackets() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [part 1].m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [Part 2].m4b")).isEqualTo("the hobbit"); + } + + @Test + void extractGroupingKey_shouldStripPartCaseInsensitive() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (PART 1).m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (Part 1).m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit - PART 1.m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit DISC 1.m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit CD 3.m4b")).isEqualTo("the hobbit"); + } + + @Test + void extractGroupingKey_shouldNotStripPartWithoutNumber() { + // "part" keyword without a trailing number should not be stripped + assertThat(BookFileGroupingUtils.extractGroupingKey("The Best Part.epub")).isEqualTo("the best part"); + assertThat(BookFileGroupingUtils.extractGroupingKey("Disc Jockey.m4b")).isEqualTo("disc jockey"); + } + + @Test + void extractGroupingKey_shouldStripAudioFormatIndicators() { + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (m4b).m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (mp3).mp3")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [audiobook].m4b")).isEqualTo("the hobbit"); + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (audio).m4b")).isEqualTo("the hobbit"); + } + + @Test + void extractGroupingKey_shouldStripFormatThenPartIndicator() { + // Both format indicator and part indicator present + assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (mp3) (part 1).mp3")).isEqualTo("the hobbit"); + } + + // ========== Bare-Number Prefix Edge Cases ========== + + @Test + void extractGroupingKey_shouldPreserveBareNumberDotPrefix() { + // "N. Title" prefix is preserved in the grouping key (series detection handles it separately) + assertThat(BookFileGroupingUtils.extractGroupingKey("01. The Lightning Thief.m4b")).isEqualTo("01. the lightning thief"); + assertThat(BookFileGroupingUtils.extractGroupingKey("100. War and Peace.epub")).isEqualTo("100. war and peace"); + } + + @Test + void extractGroupingKey_shouldStripDashPrefixViaAuthorPattern() { + // "01 - The Lightning Thief" looks like "number - Author Name" to the trailing author pattern, + // so the author pattern strips it. This is expected existing behavior. + assertThat(BookFileGroupingUtils.extractGroupingKey("01 - The Lightning Thief.m4b")).isEqualTo("01"); + } + + @Test + void extractGroupingKey_shouldNotTreatFourDigitNumberAsPrefix() { + // 4-digit numbers should not be treated as series prefixes + assertThat(BookFileGroupingUtils.extractGroupingKey("1984.epub")).isEqualTo("1984"); + } + + @Test + void extractGroupingKey_shouldNotTreatNumberWithoutSeparatorAsPrefix() { + // "101 Dalmatians" has no dot or dash after the number + assertThat(BookFileGroupingUtils.extractGroupingKey("101 Dalmatians.epub")).isEqualTo("101 dalmatians"); + } + + @Test + void groupByBaseName_shouldSeparateFiveBookSeriesWithBareNumbers() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + List files = new java.util.ArrayList<>(); + String[] titles = { + "1. The Lightning Thief.m4b", + "2. The Sea of Monsters.m4b", + "3. The Titans Curse.m4b", + "4. The Battle of the Labyrinth.m4b", + "5. The Last Olympian.m4b" + }; + for (String title : titles) { + files.add(LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Percy Jackson") + .fileName(title) + .bookFileType(BookFileType.AUDIOBOOK) + .build()); + } + + Map> groups = BookFileGroupingUtils.groupByBaseName(files); + + assertThat(groups).hasSize(5); + } + + @Test + void groupByBaseName_shouldGroupSameBareNumberInMultipleFormats() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile epub = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Percy Jackson") + .fileName("1. The Lightning Thief.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile m4b = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Percy Jackson") + .fileName("1. The Lightning Thief.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile epub2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Percy Jackson") + .fileName("2. The Sea of Monsters.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, m4b, epub2)); + + // Book 1 in 2 formats = 1 group, Book 2 = 1 group + assertThat(groups).hasSize(2); + boolean foundBook1Group = groups.values().stream() + .anyMatch(list -> list.size() == 2 && list.containsAll(List.of(epub, m4b))); + assertThat(foundBook1Group).isTrue(); + } + + @Test + void groupByBaseName_shouldSeparateDashPrefixedSeriesFiles() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile file1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Rick Riordan") + .fileName("01 - The Lightning Thief.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile file2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Rick Riordan") + .fileName("02 - The Sea of Monsters.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2)); + + assertThat(groups).hasSize(2); + } + + @Test + void groupByBaseName_shouldHandleRootLevelBareNumberedFiles() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile file1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath(null) + .fileName("1. The Lightning Thief.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile file2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath(null) + .fileName("2. The Sea of Monsters.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2)); + + // Root-level uses exact key matching, different keys = separate groups + assertThat(groups).hasSize(2); + } + + // ========== Series Detection with Various Keywords ========== + + @Test + void groupByBaseName_shouldSeparateEpisodeSeriesEntries() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile ep1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("The Podcast") + .fileName("The Podcast Episode 1.mp3") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile ep2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("The Podcast") + .fileName("The Podcast Episode 2.mp3") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(ep1, ep2)); + + assertThat(groups).hasSize(2); + } + + @Test + void groupByBaseName_shouldSeparateHashNumberedSeries() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile n1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Discworld") + .fileName("Discworld #1.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile n2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Discworld") + .fileName("Discworld #2.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(n1, n2)); + + assertThat(groups).hasSize(2); + } + + // ========== Multi-Part Grouping Edge Cases ========== + + @Test + void groupByBaseName_shouldGroupBracketedPartsAtRootLevel() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile pt1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath(null) + .fileName("The Lost Hero (part 1).m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile pt2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath(null) + .fileName("The Lost Hero (part 2).m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(pt1, pt2)); + + // Root-level exact key matching: both produce "the lost hero" → same group + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(pt1, pt2); + } + + @Test + void groupByBaseName_shouldGroupDiscVariantsOfSameBook() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile d1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("War and Peace") + .fileName("War and Peace disc 1.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile d2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("War and Peace") + .fileName("War and Peace disc 2.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile d3 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("War and Peace") + .fileName("War and Peace disc 3.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(d1, d2, d3)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(d1, d2, d3); + } + + @Test + void groupByBaseName_shouldGroupCdVariantsOfSameBook() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile cd1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Moby Dick") + .fileName("Moby Dick cd 1.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + LibraryFile cd2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Moby Dick") + .fileName("Moby Dick cd 2.m4b") + .bookFileType(BookFileType.AUDIOBOOK) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(cd1, cd2)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(cd1, cd2); + } + + // ========== Grouping Boundary / Misc Edge Cases ========== + + @Test + void groupByBaseName_shouldHandleEmptyList() { + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of()); + assertThat(groups).isEmpty(); + } + + @Test + void groupByBaseName_shouldHandleSingleFileInFolder() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile file = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Some Folder") + .fileName("Lonely Book.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(file)); + + assertThat(groups).hasSize(1); + assertThat(groups.values().iterator().next()).containsExactly(file); + } + + @Test + void groupByBaseName_shouldHandleEmptySubPath() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile file1 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("Book.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile file2 = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("Book.pdf") + .bookFileType(BookFileType.PDF) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2)); + + // Empty subPath treated as root level + assertThat(groups).hasSize(1); + } + + @Test + void groupByBaseName_shouldSeparateCompletelyUnrelatedFilesInFolder() { + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile war = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Random") + .fileName("War and Peace.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile moby = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Random") + .fileName("Moby Dick.epub") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile pride = LibraryFile.builder() + .libraryPathEntity(pathEntity) + .fileSubPath("Random") + .fileName("Pride and Prejudice.pdf") + .bookFileType(BookFileType.PDF) + .build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(war, moby, pride)); + + assertThat(groups).hasSize(3); + } + + @Test + void groupByBaseName_shouldHandleFullHeroesOfOlympusScenario() { + // Realistic 5-book series with multi-part splits for some books + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(1L); + pathEntity.setPath("/library"); + + LibraryFile lh1 = LibraryFile.builder().libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus").fileName("1. The Lost Hero (part 1).m4b").bookFileType(BookFileType.AUDIOBOOK).build(); + LibraryFile lh2 = LibraryFile.builder().libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus").fileName("1. The Lost Hero (part 2).m4b").bookFileType(BookFileType.AUDIOBOOK).build(); + LibraryFile son = LibraryFile.builder().libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus").fileName("2. The Son of Neptune.m4b").bookFileType(BookFileType.AUDIOBOOK).build(); + LibraryFile moa1 = LibraryFile.builder().libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus").fileName("3. The Mark of Athena (part 1).m4b").bookFileType(BookFileType.AUDIOBOOK).build(); + LibraryFile moa2 = LibraryFile.builder().libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus").fileName("3. The Mark of Athena (part 2).m4b").bookFileType(BookFileType.AUDIOBOOK).build(); + LibraryFile hoh = LibraryFile.builder().libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus").fileName("4. The House of Hades.m4b").bookFileType(BookFileType.AUDIOBOOK).build(); + LibraryFile boo = LibraryFile.builder().libraryPathEntity(pathEntity) + .fileSubPath("Heroes of Olympus").fileName("5. The Blood of Olympus.m4b").bookFileType(BookFileType.AUDIOBOOK).build(); + + Map> groups = BookFileGroupingUtils.groupByBaseName(List.of(lh1, lh2, son, moa1, moa2, hoh, boo)); + + // 5 books: Lost Hero (2 parts grouped), Son of Neptune, Mark of Athena (2 parts grouped), House of Hades, Blood of Olympus + assertThat(groups).hasSize(5); + boolean lhGrouped = groups.values().stream().anyMatch(l -> l.size() == 2 && l.containsAll(List.of(lh1, lh2))); + boolean moaGrouped = groups.values().stream().anyMatch(l -> l.size() == 2 && l.containsAll(List.of(moa1, moa2))); + assertThat(lhGrouped).isTrue(); + assertThat(moaGrouped).isTrue(); + } + @Test void groupByBaseName_shouldGroupFolderWithDotInName() { // Folder-based audiobook with dot in name like "1. American Gods - Neil Gaiman (2011)" diff --git a/booklore-api/src/test/java/org/booklore/util/FileServiceTest.java b/booklore-api/src/test/java/org/booklore/util/FileServiceTest.java index df3212699..c14b355e1 100644 --- a/booklore-api/src/test/java/org/booklore/util/FileServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/util/FileServiceTest.java @@ -18,6 +18,7 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.RestTemplate; import javax.imageio.ImageIO; @@ -61,7 +62,9 @@ class FileServiceTest { .build(); lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings); - fileService = new FileService(appProperties, mock(RestTemplate.class), appSettingService); + RestTemplate mockRestTemplate = mock(RestTemplate.class); + RestTemplate mockNoRedirectRestTemplate = mock(RestTemplate.class); + fileService = new FileService(appProperties, mockRestTemplate, appSettingService, mockNoRedirectRestTemplate); } @Nested @@ -374,9 +377,9 @@ class FileServiceTest { } @Test - void invalidData_returnsNull() throws IOException { + void invalidData_throwsException() { byte[] invalidData = "not an image".getBytes(); - assertNull(FileService.readImage(invalidData)); + assertThrows(IOException.class, () -> FileService.readImage(invalidData)); } } @@ -485,11 +488,11 @@ class FileServiceTest { } @Test - void invalidImageData_skipsSave() { + void invalidImageData_throwsException() { byte[] invalidData = "not an image".getBytes(); Path outputPath = tempDir.resolve("invalid.jpg"); - assertDoesNotThrow(() -> + assertThrows(IOException.class, () -> FileService.saveImage(invalidData, outputPath.toString())); assertFalse(Files.exists(outputPath)); } @@ -913,12 +916,11 @@ class FileServiceTest { } @Test - void invalidImageBytes_skipsThumbnail() { + void invalidImageBytes_throwsException() { byte[] invalidData = "not an image".getBytes(); - assertDoesNotThrow(() -> + assertThrows(RuntimeException.class, () -> fileService.createThumbnailFromBytes(16L, invalidData)); - assertFalse(Files.exists(Path.of(fileService.getCoverFile(16L)))); } @Test @@ -1031,15 +1033,14 @@ class FileServiceTest { } @Test - void corruptImageData_skipsThumbnail() { + void corruptImageData_throwsException() { // Valid MIME type but corrupt image data byte[] corruptData = ("not an image but has jpeg mime type").getBytes(); MockMultipartFile corruptFile = new MockMultipartFile( "file", "corrupt.jpg", "image/jpeg", corruptData); - assertDoesNotThrow(() -> + assertThrows(RuntimeException.class, () -> fileService.createThumbnailFromFile(12L, corruptFile)); - assertFalse(Files.exists(Path.of(fileService.getCoverFile(12L)))); } @Test @@ -1176,7 +1177,7 @@ class FileServiceTest { .build(); lenient().when(appSettingServiceForNetwork.getAppSettings()).thenReturn(appSettings); - fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork); + fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork, restTemplate); } @Nested @@ -1187,17 +1188,17 @@ class FileServiceTest { @DisplayName("downloads and returns valid image") @Timeout(5) void downloadImageFromUrl_validImage_returnsBufferedImage() throws IOException { - String imageUrl = "http://example.com/image.jpg"; + String imageUrl = "http://1.1.1.1/image.jpg"; BufferedImage testImage = createTestImage(100, 100); byte[] imageBytes = imageToBytes(testImage); RestTemplate mockRestTemplate = mock(RestTemplate.class); AppSettingService mockAppSettingService = mock(AppSettingService.class); - FileService testFileService = new FileService(appProperties, mockRestTemplate, mockAppSettingService); + FileService testFileService = new FileService(appProperties, mockRestTemplate, mockAppSettingService, mockRestTemplate); ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); when(mockRestTemplate.exchange( - eq(imageUrl), + anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) @@ -1214,10 +1215,10 @@ class FileServiceTest { @DisplayName("throws exception when response body is null") @Timeout(5) void downloadImageFromUrl_nullBody_throwsException() { - String imageUrl = "http://example.com/image.jpg"; + String imageUrl = "http://1.1.1.1/image.jpg"; ResponseEntity responseEntity = ResponseEntity.ok(null); when(restTemplate.exchange( - eq(imageUrl), + anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) @@ -1228,31 +1229,38 @@ class FileServiceTest { } @Test - @DisplayName("returns null when ImageIO cannot read bytes") + @DisplayName("throws IOException when ImageIO cannot read bytes") @Timeout(5) - void downloadImageFromUrl_invalidImageData_returnsNull() throws IOException { - String imageUrl = "http://example.com/image.jpg"; + void downloadImageFromUrl_invalidImageData_throwsException() throws IOException { + String imageUrl = "http://1.1.1.1/image.jpg"; byte[] invalidBytes = "not an image".getBytes(); ResponseEntity responseEntity = ResponseEntity.ok(invalidBytes); - when(restTemplate.exchange( - eq(imageUrl), + // Note: using ReflectionTestUtils to get the private mock if needed, + // but wait, setup() already created fileService with mocks. + // We just need to know which mock to use. + // The setup() creates and injects mockNoRedirectRestTemplate. + + // Let's use ReflectionTestUtils to mock the correct one since the field in test class is 'restTemplate' + RestTemplate noRedirectMock = (RestTemplate) ReflectionTestUtils.getField(fileService, "noRedirectRestTemplate"); + + when(noRedirectMock.exchange( + anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) )).thenReturn(responseEntity); - BufferedImage result = fileService.downloadImageFromUrl(imageUrl); - assertNull(result); + assertThrows(IOException.class, () -> fileService.downloadImageFromUrl(imageUrl)); } @Test @DisplayName("throws exception on HTTP error status") @Timeout(5) void downloadImageFromUrl_httpError_throwsException() { - String imageUrl = "http://example.com/image.jpg"; + String imageUrl = "http://1.1.1.1/image.jpg"; ResponseEntity responseEntity = ResponseEntity.notFound().build(); when(restTemplate.exchange( - eq(imageUrl), + anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) @@ -1271,14 +1279,14 @@ class FileServiceTest { @DisplayName("downloads and saves cover images successfully") @Timeout(5) void createThumbnailFromUrl_validImage_createsCoverAndThumbnail() throws IOException { - String imageUrl = "http://example.com/cover.jpg"; + String imageUrl = "http://1.1.1.1/cover.jpg"; long bookId = 42L; BufferedImage testImage = createTestImage(800, 1200); // Portrait image byte[] imageBytes = imageToBytes(testImage); ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); when(restTemplate.exchange( - eq(imageUrl), + anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) @@ -1304,7 +1312,7 @@ class FileServiceTest { long bookId = 42L; when(restTemplate.exchange( - eq(imageUrl), + anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) diff --git a/booklore-api/src/test/java/org/booklore/util/FileUtilsTest.java b/booklore-api/src/test/java/org/booklore/util/FileUtilsTest.java index 9b73ace1e..7197bdec2 100644 --- a/booklore-api/src/test/java/org/booklore/util/FileUtilsTest.java +++ b/booklore-api/src/test/java/org/booklore/util/FileUtilsTest.java @@ -189,9 +189,251 @@ class FileUtilsTest { void testGetFileSizeInKb_validFile_returnsSize() throws IOException { Path file = tempDir.resolve("test.txt"); Files.write(file, "test".getBytes()); - + Long size = FileUtils.getFileSizeInKb(file); assertNotNull(size, "File size should not be null for existing file"); assertTrue(size >= 0, "File size should be non-negative"); } + + // ========== isSeriesFolder Tests ========== + + @Test + void testIsSeriesFolder_distinctTitles_returnsTrue() { + List files = List.of( + Path.of("1. The Lightning Thief.m4b"), + Path.of("2. The Sea of Monsters.m4b"), + Path.of("3. The Titans Curse.m4b") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_chapterFiles_returnsFalse() { + List files = List.of( + Path.of("Chapter 01.mp3"), + Path.of("Chapter 02.mp3"), + Path.of("Chapter 03.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_bareNumberedTracks_returnsFalse() { + List files = List.of( + Path.of("01.mp3"), + Path.of("02.mp3"), + Path.of("03.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_trackFiles_returnsFalse() { + List files = List.of( + Path.of("Track 01.mp3"), + Path.of("Track 02.mp3"), + Path.of("Track 03.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_mixedWithParts_returnsTrue() { + List files = List.of( + Path.of("1. The Lost Hero (part 1).m4b"), + Path.of("1. The Lost Hero (part 2).m4b"), + Path.of("2. The Son of Neptune.m4b") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_singleFile_returnsFalse() { + List files = List.of(Path.of("The Lightning Thief.m4b")); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_dashSeparatedNumbers_returnsTrue() { + List files = List.of( + Path.of("01 - The Lightning Thief.m4b"), + Path.of("02 - The Sea of Monsters.m4b") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_emptyList_returnsFalse() { + assertFalse(FileUtils.isSeriesFolder(List.of())); + } + + @Test + void testIsSeriesFolder_allSameTitle_returnsFalse() { + // Same book split across multiple files (no number prefix) + List files = List.of( + Path.of("The Lightning Thief.m4b"), + Path.of("The Lightning Thief.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_sameTitleWithParts_returnsFalse() { + // Same book split into parts: after stripping part indicators, all produce same title + List files = List.of( + Path.of("The Lightning Thief (part 1).m4b"), + Path.of("The Lightning Thief (part 2).m4b"), + Path.of("The Lightning Thief (part 3).m4b") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_genericPartTitles_returnsFalse() { + // "Part" is in the generic list, so "Part 1", "Part 2" → stripped to "part" → generic + List files = List.of( + Path.of("Part 1.mp3"), + Path.of("Part 2.mp3"), + Path.of("Part 3.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_genericDiscTitles_returnsFalse() { + List files = List.of( + Path.of("Disc 1.mp3"), + Path.of("Disc 2.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_genericSideTitles_returnsFalse() { + List files = List.of( + Path.of("Side 1.mp3"), + Path.of("Side 2.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_genericIntroEpilogue_returnsFalse() { + List files = List.of( + Path.of("Intro.mp3"), + Path.of("Epilogue.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_genericOutro_returnsFalse() { + List files = List.of( + Path.of("Intro.mp3"), + Path.of("Outro.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_mixedGenericAndRealTitles_returnsFalse() { + // Only one non-generic title → not > 1 distinct → not a series + List files = List.of( + Path.of("Intro.mp3"), + Path.of("Chapter 01.mp3"), + Path.of("The Lightning Thief.m4b") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_mixedCaseFileNames_returnsTrue() { + List files = List.of( + Path.of("1. THE LIGHTNING THIEF.M4B"), + Path.of("2. the Sea of Monsters.m4b") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_noExtension_returnsTrue() { + // Files without dots in the name (no extension confusion) + List files = List.of( + Path.of("The Lightning Thief"), + Path.of("The Sea of Monsters") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_zeroPaddedNumbers_returnsTrue() { + List files = List.of( + Path.of("001. A Game of Thrones.m4b"), + Path.of("002. A Clash of Kings.m4b"), + Path.of("003. A Storm of Swords.m4b") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_numberedPartsOfSameBook_returnsFalse() { + // Same book number but different parts → single distinct title after stripping + List files = List.of( + Path.of("1. The Lost Hero (part 1).m4b"), + Path.of("1. The Lost Hero (part 2).m4b"), + Path.of("1. The Lost Hero (part 3).m4b") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_twoDistinctAmongManyParts_returnsTrue() { + List files = List.of( + Path.of("1. The Lost Hero (part 1).m4b"), + Path.of("1. The Lost Hero (part 2).m4b"), + Path.of("1. The Lost Hero (part 3).m4b"), + Path.of("2. The Son of Neptune (part 1).m4b"), + Path.of("2. The Son of Neptune (part 2).m4b") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_titlesWithSpecialCharacters_returnsTrue() { + List files = List.of( + Path.of("1. The Lion, the Witch & the Wardrobe.m4b"), + Path.of("2. Prince Caspian.m4b") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_prologueAndChapters_returnsFalse() { + // All generic: prologue, chapter, epilogue + List files = List.of( + Path.of("Prologue.mp3"), + Path.of("Chapter 01.mp3"), + Path.of("Chapter 02.mp3"), + Path.of("Chapter 03.mp3"), + Path.of("Epilogue.mp3") + ); + assertFalse(FileUtils.isSeriesFolder(files)); + } + + @Test + void testIsSeriesFolder_largeSeriesFolder_returnsTrue() { + List files = List.of( + Path.of("01. The Colour of Magic.m4b"), + Path.of("02. The Light Fantastic.m4b"), + Path.of("03. Equal Rites.m4b"), + Path.of("04. Mort.m4b"), + Path.of("05. Sourcery.m4b"), + Path.of("06. Wyrd Sisters.m4b"), + Path.of("07. Pyramids.m4b"), + Path.of("08. Guards Guards.m4b"), + Path.of("09. Eric.m4b"), + Path.of("10. Moving Pictures.m4b") + ); + assertTrue(FileUtils.isSeriesFolder(files)); + } } diff --git a/booklore-api/src/test/java/org/booklore/util/UnrarHelperIntegrationTest.java b/booklore-api/src/test/java/org/booklore/util/UnrarHelperIntegrationTest.java new file mode 100644 index 000000000..7bf209323 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/util/UnrarHelperIntegrationTest.java @@ -0,0 +1,89 @@ +package org.booklore.util; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assumptions.assumeThat; + +class UnrarHelperIntegrationTest { + + private static final Path RAR5_CBR = Path.of("src/test/resources/cbx/test-rar5.cbr"); + + @BeforeAll + static void checkUnrarAvailable() { + assumeThat(UnrarHelper.isAvailable()) + .as("unrar binary must be on PATH to run these tests") + .isTrue(); + } + + @Test + void listEntries_returnsAllEntriesFromRar5Archive() throws IOException { + List entries = UnrarHelper.listEntries(RAR5_CBR); + + assertThat(entries).containsExactly( + "ComicInfo.xml", + "page_001.jpg", + "page_002.jpg", + "page_003.jpg" + ); + } + + @Test + void extractEntryBytes_extractsComicInfoXml() throws IOException { + byte[] bytes = UnrarHelper.extractEntryBytes(RAR5_CBR, "ComicInfo.xml"); + String xml = new String(bytes); + + assertThat(xml).contains("Test RAR5 Comic"); + assertThat(xml).contains("RAR5 Test Series"); + assertThat(xml).contains("Test Author"); + } + + @Test + void extractEntry_streamsImageToOutputStream() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnrarHelper.extractEntry(RAR5_CBR, "page_001.jpg", out); + + byte[] imageBytes = out.toByteArray(); + assertThat(imageBytes).hasSizeGreaterThan(0); + assertThat(imageBytes[0]).isEqualTo((byte) 0xFF); + assertThat(imageBytes[1]).isEqualTo((byte) 0xD8); + } + + @Test + void extractAll_extractsAllFilesToDirectory(@TempDir Path tempDir) throws IOException { + UnrarHelper.extractAll(RAR5_CBR, tempDir); + + assertThat(tempDir.resolve("ComicInfo.xml")).exists(); + assertThat(tempDir.resolve("page_001.jpg")).exists(); + assertThat(tempDir.resolve("page_002.jpg")).exists(); + assertThat(tempDir.resolve("page_003.jpg")).exists(); + + String xml = Files.readString(tempDir.resolve("ComicInfo.xml")); + assertThat(xml).contains("Test RAR5 Comic"); + } + + @Test + void listEntries_throwsForNonExistentFile() { + Path bogus = Path.of("/tmp/does-not-exist.cbr"); + + assertThatThrownBy(() -> UnrarHelper.listEntries(bogus)) + .isInstanceOf(IOException.class) + .hasMessageContaining("unrar list failed"); + } + + @Test + void extractEntryBytes_throwsForNonExistentEntry() { + assertThatThrownBy(() -> UnrarHelper.extractEntryBytes(RAR5_CBR, "no-such-file.jpg")) + .isInstanceOf(IOException.class) + .hasMessageContaining("unrar extract failed"); + } +} diff --git a/booklore-api/src/test/java/org/booklore/util/kobo/KoboUrlBuilderTest.java b/booklore-api/src/test/java/org/booklore/util/kobo/KoboUrlBuilderTest.java index a47b5d8ef..846c9201e 100644 --- a/booklore-api/src/test/java/org/booklore/util/kobo/KoboUrlBuilderTest.java +++ b/booklore-api/src/test/java/org/booklore/util/kobo/KoboUrlBuilderTest.java @@ -119,6 +119,127 @@ class KoboUrlBuilderTest { String result = koboUrlBuilder.downloadUrl(token, bookId); assertTrue(result.startsWith("https://books.example.com")); + assertFalse(result.contains(":443")); assertTrue(result.contains("/api/kobo/" + token + "/v1/books/" + bookId + "/download")); } + + @Test + void testHostHeaderWithoutPort_restoresLocalPort() { + // Kobo devices send "Host: 192.168.1.100" without port. + // Tomcat resolves missing port to 80 (HTTP default), which Spring strips. + // The fix should restore the actual listening port from request.getLocalPort(). + mockRequest.setServerName("192.168.1.100"); + mockRequest.setServerPort(80); + mockRequest.setLocalPort(6060); + + String result = koboUrlBuilder.downloadUrl("testToken", 123L); + + assertTrue(result.startsWith("http://192.168.1.100:6060/")); + assertTrue(result.contains("/api/kobo/testToken/v1/books/123/download")); + } + + @Test + void testHostHeaderWithoutPort_imageUrls() { + mockRequest.setServerName("192.168.1.100"); + mockRequest.setServerPort(80); + mockRequest.setLocalPort(6060); + + assertTrue(koboUrlBuilder.imageUrlTemplate("t").startsWith("http://192.168.1.100:6060/")); + assertTrue(koboUrlBuilder.imageUrlQualityTemplate("t").startsWith("http://192.168.1.100:6060/")); + assertTrue(koboUrlBuilder.librarySyncUrl("t").startsWith("http://192.168.1.100:6060/")); + } + + @Test + void testReverseProxy_xForwardedProto_doesNotOverridePort() { + mockRequest.setScheme("https"); + mockRequest.setServerName("books.example.com"); + mockRequest.setServerPort(443); + mockRequest.setLocalPort(6060); + mockRequest.addHeader("X-Forwarded-Proto", "https"); + + String result = koboUrlBuilder.downloadUrl("testToken", 123L); + + assertTrue(result.startsWith("https://books.example.com/")); + assertFalse(result.contains(":6060")); + } + + @Test + void testReverseProxy_xForwardedHost_doesNotOverridePort() { + mockRequest.setScheme("https"); + mockRequest.setServerName("books.example.com"); + mockRequest.setServerPort(443); + mockRequest.setLocalPort(6060); + mockRequest.addHeader("X-Forwarded-Host", "books.example.com"); + + String result = koboUrlBuilder.downloadUrl("testToken", 123L); + + assertTrue(result.startsWith("https://books.example.com/")); + assertFalse(result.contains(":6060")); + } + + @Test + void testReverseProxy_xForwardedPort_doesNotOverridePort() { + mockRequest.setScheme("https"); + mockRequest.setServerName("books.example.com"); + mockRequest.setServerPort(443); + mockRequest.setLocalPort(6060); + mockRequest.addHeader("X-Forwarded-Port", "443"); + + String result = koboUrlBuilder.downloadUrl("testToken", 123L); + + assertTrue(result.startsWith("https://books.example.com/")); + assertFalse(result.contains(":6060")); + } + + @Test + void testReverseProxy_forwardedHeader_doesNotOverridePort() { + mockRequest.setScheme("https"); + mockRequest.setServerName("books.example.com"); + mockRequest.setServerPort(443); + mockRequest.setLocalPort(6060); + mockRequest.addHeader("Forwarded", "proto=https;host=books.example.com"); + + String result = koboUrlBuilder.downloadUrl("testToken", 123L); + + assertTrue(result.startsWith("https://books.example.com/")); + assertFalse(result.contains(":6060")); + } + + @Test + void testReverseProxy_nonStandardPort_preserved() { + mockRequest.setScheme("https"); + mockRequest.setServerName("books.example.com"); + mockRequest.setServerPort(8443); + mockRequest.setLocalPort(6060); + mockRequest.addHeader("X-Forwarded-Port", "8443"); + + String result = koboUrlBuilder.downloadUrl("testToken", 123L); + + assertTrue(result.startsWith("https://books.example.com:8443/")); + } + + @Test + void testServerOnPort80_noPortAdded() { + mockRequest.setServerName("192.168.1.100"); + mockRequest.setServerPort(80); + mockRequest.setLocalPort(80); + + String result = koboUrlBuilder.downloadUrl("testToken", 123L); + + assertTrue(result.startsWith("http://192.168.1.100/")); + assertFalse(result.contains(":80")); + } + + @Test + void testServerOnPort443_noPortAdded() { + mockRequest.setScheme("https"); + mockRequest.setServerName("192.168.1.100"); + mockRequest.setServerPort(443); + mockRequest.setLocalPort(443); + + String result = koboUrlBuilder.downloadUrl("testToken", 123L); + + assertTrue(result.startsWith("https://192.168.1.100/")); + assertFalse(result.contains(":443")); + } } diff --git a/booklore-api/src/test/resources/cbx/test-rar5.cbr b/booklore-api/src/test/resources/cbx/test-rar5.cbr new file mode 100644 index 000000000..8ae68a762 Binary files /dev/null and b/booklore-api/src/test/resources/cbx/test-rar5.cbr differ diff --git a/booklore-ui/package-lock.json b/booklore-ui/package-lock.json index f7e0bb0b7..2119c71b8 100644 --- a/booklore-ui/package-lock.json +++ b/booklore-ui/package-lock.json @@ -20,7 +20,7 @@ "@angular/service-worker": "^21.1.5", "@iharbeck/ngx-virtual-scroller": "^20.0.0", "@jsverse/transloco": "^8.2.1", - "@primeng/themes": "^21.0.3", + "@primeuix/themes": "^2.0.3", "@stomp/rx-stomp": "^2.3.0", "@stomp/stompjs": "^7.3.0", "@tweenjs/tween.js": "^25.0.0", @@ -29,6 +29,7 @@ "chartjs-chart-matrix": "^3.0.0", "chartjs-plugin-datalabels": "^2.2.0", "date-fns": "^4.1.0", + "dompurify": "^3.3.1", "jwt-decode": "^4.0.0", "ng-lazyload-image": "^9.1.3", "ng2-charts": "^8.0.0", @@ -40,25 +41,25 @@ "rxjs": "^7.8.2", "showdown": "^2.1.0", "tslib": "^2.8.1", - "uuid": "^13.0.0", + "uuid": "^11.0.0", "ws": "^8.19.0", "zone.js": "^0.16.1" }, "devDependencies": { "@analogjs/vite-plugin-angular": "^2.2.3", "@analogjs/vitest-angular": "^2.2.3", - "@angular/build": "^21.1.4", - "@angular/cli": "^21.1.4", + "@angular/build": "^21.1.5", + "@angular/cli": "^21.1.5", "@angular/compiler-cli": "^21.1.5", + "@types/dompurify": "^3.0.5", "@types/node": "^25.3.0", "@types/showdown": "^2.0.6", - "@types/uuid": "^11.0.0", "@vitest/coverage-v8": "^4.0.17", "angular-eslint": "^21.2.0", - "eslint": "^10.0.0", + "eslint": "^9.39.3", "jsdom": "^28.1.0", "typescript": "~5.9.3", - "typescript-eslint": "^8.56.0", + "typescript-eslint": "^8.56.1", "vitest": "^4.0.17" } }, @@ -335,13 +336,13 @@ } }, "node_modules/@angular-devkit/architect": { - "version": "0.2101.4", - "resolved": "https://registry.npmjs.org/@angular-devkit/architect/-/architect-0.2101.4.tgz", - "integrity": "sha512-3yyebORk+ovtO+LfDjIGbGCZhCMDAsyn9vkCljARj3sSshS4blOQBar0g+V3kYAweLT5Gf+rTKbN5jneOkBAFQ==", + "version": "0.2101.5", + "resolved": "https://registry.npmjs.org/@angular-devkit/architect/-/architect-0.2101.5.tgz", + "integrity": "sha512-eTo6wWzUW5AyBBLTbaUTpBHhGbZhzteErtNGklWkhjicCr/soNH+2mVtvg8bqA8sNreYffK1VXKFsq5NyMh5qg==", "dev": true, "license": "MIT", "dependencies": { - "@angular-devkit/core": "21.1.4", + "@angular-devkit/core": "21.1.5", "rxjs": "7.8.2" }, "bin": { @@ -354,13 +355,13 @@ } }, "node_modules/@angular-devkit/core": { - "version": "21.1.4", - "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-21.1.4.tgz", - "integrity": "sha512-ObPTI5gYCB1jGxTRhcqZ6oQVUBFVJ8GH4LksVuAiz0nFX7xxpzARWvlhq943EtnlovVlUd9I8fM3RQqjfGVVAQ==", + "version": "21.1.5", + "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-21.1.5.tgz", + "integrity": "sha512-KUKbllHvHefkAbTBjWNpRPyrpBqecW+6HBBAR+XNbKBuFTHkG+gxtuwMXNsvO5KECKwQphvQt5h3g05Xtaf0LQ==", "dev": true, "license": "MIT", "dependencies": { - "ajv": "8.17.1", + "ajv": "8.18.0", "ajv-formats": "3.0.1", "jsonc-parser": "3.3.1", "picomatch": "4.0.3", @@ -382,13 +383,13 @@ } }, "node_modules/@angular-devkit/schematics": { - "version": "21.1.4", - "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-21.1.4.tgz", - "integrity": "sha512-Nqq0ioCUxrbEX+L4KOarETcZZJNnJ1mAJ0ubO4VM91qnn8RBBM9SnQ91590TfC34Szk/wh+3+Uj6KUvTJNuegQ==", + "version": "21.1.5", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-21.1.5.tgz", + "integrity": "sha512-CGmoorQL5+mVCJEHwHWOrhSd1hFxB3h66i9wUDizJAEQUM3mSml5SiglHArpWY/G4GmFwi6XVe+Jm3U8J/mcFg==", "dev": true, "license": "MIT", "dependencies": { - "@angular-devkit/core": "21.1.4", + "@angular-devkit/core": "21.1.5", "jsonc-parser": "3.3.1", "magic-string": "0.30.21", "ora": "9.0.0", @@ -525,14 +526,14 @@ } }, "node_modules/@angular/build": { - "version": "21.1.4", - "resolved": "https://registry.npmjs.org/@angular/build/-/build-21.1.4.tgz", - "integrity": "sha512-7CAAQPWFMMqod40ox5MOVB/CnoBXFDehyQhs0hls6lu7bOy/M0EDy0v6bERkyNGRz1mihWWBiCV8XzEinrlq1A==", + "version": "21.1.5", + "resolved": "https://registry.npmjs.org/@angular/build/-/build-21.1.5.tgz", + "integrity": "sha512-v2eDinWKlSKuk5pyMMY8j5TMFW8HA9B1l13TrDDpxsRGAAzekg7TFNyuh1x9Y6Rq4Vn+8/8pCjMUPZigzWbMhQ==", "dev": true, "license": "MIT", "dependencies": { "@ampproject/remapping": "2.3.0", - "@angular-devkit/architect": "0.2101.4", + "@angular-devkit/architect": "0.2101.5", "@babel/core": "7.28.5", "@babel/helper-annotate-as-pure": "7.27.3", "@babel/helper-split-export-declaration": "7.24.7", @@ -575,7 +576,7 @@ "@angular/platform-browser": "^21.0.0", "@angular/platform-server": "^21.0.0", "@angular/service-worker": "^21.0.0", - "@angular/ssr": "^21.1.4", + "@angular/ssr": "^21.1.5", "karma": "^6.4.0", "less": "^4.2.0", "ng-packagr": "^21.0.0", @@ -641,19 +642,19 @@ } }, "node_modules/@angular/cli": { - "version": "21.1.4", - "resolved": "https://registry.npmjs.org/@angular/cli/-/cli-21.1.4.tgz", - "integrity": "sha512-XsMHgxTvHGiXXrhYZz3zMZYhYU0gHdpoHKGiEKXwcx+S1KoYbIssyg6oF2Kq49ZaE0OYCTKjnvgDce6ZqdkJ/A==", + "version": "21.1.5", + "resolved": "https://registry.npmjs.org/@angular/cli/-/cli-21.1.5.tgz", + "integrity": "sha512-ljqvAzSk8FKMaYW/aZhR+SXjudbQViYYkMlJvJUClGpokjDM9KfJWPX+QZfr2J+piW5yaaHmFaIMddO9QxkUDQ==", "dev": true, "license": "MIT", "dependencies": { - "@angular-devkit/architect": "0.2101.4", - "@angular-devkit/core": "21.1.4", - "@angular-devkit/schematics": "21.1.4", + "@angular-devkit/architect": "0.2101.5", + "@angular-devkit/core": "21.1.5", + "@angular-devkit/schematics": "21.1.5", "@inquirer/prompts": "7.10.1", "@listr2/prompt-adapter-inquirer": "3.0.5", "@modelcontextprotocol/sdk": "1.26.0", - "@schematics/angular": "21.1.4", + "@schematics/angular": "21.1.5", "@yarnpkg/lockfile": "1.1.0", "algoliasearch": "5.46.2", "ini": "6.0.0", @@ -1865,110 +1866,139 @@ } }, "node_modules/@eslint/config-array": { - "version": "0.23.1", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.1.tgz", - "integrity": "sha512-uVSdg/V4dfQmTjJzR0szNczjOH/J+FyUMMjYtr07xFRXR7EDf9i1qdxrD0VusZH9knj1/ecxzCQQxyic5NzAiA==", + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.1.tgz", + "integrity": "sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@eslint/object-schema": "^3.0.1", + "@eslint/object-schema": "^2.1.7", "debug": "^4.3.1", - "minimatch": "^10.1.1" + "minimatch": "^3.1.2" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/config-array/node_modules/balanced-match": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.2.tgz", - "integrity": "sha512-x0K50QvKQ97fdEz2kPehIerj+YTeptKF9hyYkKf6egnwmMWAkADiO0QCzSp0R5xN8FTZgYaBfSaue46Ej62nMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "jackspeak": "^4.2.3" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/@eslint/config-array/node_modules/brace-expansion": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.2.tgz", - "integrity": "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/@eslint/config-array/node_modules/minimatch": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.0.tgz", - "integrity": "sha512-ugkC31VaVg9cF0DFVoADH12k6061zNZkZON+aX8AWsR9GhPcErkcMBceb6znR8wLERM2AkkOxy2nWRLpT9Jq5w==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.2" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/@eslint/config-helpers": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.5.2.tgz", - "integrity": "sha512-a5MxrdDXEvqnIq+LisyCX6tQMPF/dSJpCfBgBauY+pNZ28yCtSsTvyTYrMhaI+LK26bVyCJfJkT0u8KIj2i1dQ==", + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@eslint/core": "^1.1.0" + "@eslint/core": "^0.17.0" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/@eslint/core": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.1.0.tgz", - "integrity": "sha512-/nr9K9wkr3P1EzFTdFdMoLuo1PmIxjmwvPozwoSodjNBdefGujXQUF93u1DDZpEaTuDvMsIQddsd35BwtrW9Xw==", + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", "dev": true, "license": "Apache-2.0", "dependencies": { "@types/json-schema": "^7.0.15" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.4.tgz", + "integrity": "sha512-4h4MVF8pmBsncB60r0wSJiIeUKTSD4m7FmTFThG8RHlsg9ajqckLm9OraguFGZE4vVdpiI1Q4+hFnisopmG6gQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.3", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/js": { + "version": "9.39.3", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.3.tgz", + "integrity": "sha512-1B1VkCq6FuUNlQvlBYb+1jDu/gV297TIs/OeiaSR9l1H27SVW55ONE1e1Vp16NqP683+xEGzxYtv4XCiDPaQiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" } }, "node_modules/@eslint/object-schema": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.1.tgz", - "integrity": "sha512-P9cq2dpr+LU8j3qbLygLcSZrl2/ds/pUpfnHNNuk5HW7mnngHs+6WSq5C9mO3rqRX8A1poxqLTC9cu0KOyJlBg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", "dev": true, "license": "Apache-2.0", "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/@eslint/plugin-kit": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.6.0.tgz", - "integrity": "sha512-bIZEUzOI1jkhviX2cp5vNyXQc6olzb2ohewQubuYlMXZ2Q/XjBO0x0XhGPvc9fjSIiUN0vw+0hq53BJ4eQSJKQ==", + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@eslint/core": "^1.1.0", + "@eslint/core": "^0.17.0", "levn": "^0.4.1" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/@exodus/bytes": { @@ -2416,16 +2446,6 @@ } } }, - "node_modules/@isaacs/cliui": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz", - "integrity": "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/@isaacs/fs-minipass": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", @@ -3720,17 +3740,6 @@ "license": "MIT", "optional": true }, - "node_modules/@primeng/themes": { - "version": "21.0.4", - "resolved": "https://registry.npmjs.org/@primeng/themes/-/themes-21.0.4.tgz", - "integrity": "sha512-WDF8pj91K3ItGmUJB91T1mRj6ut3dCMz4/5rb1sZR6sjxP7jX06PT/uXkKF8sz60ewEEBbh3yK98Js/mKxev3A==", - "deprecated": "Deprecated. This package is no longer maintained. Please migrate to @primeuix/themes: https://www.npmjs.com/package/@primeuix/themes", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@primeuix/styled": "^0.7.4", - "@primeuix/themes": "^2.0.2" - } - }, "node_modules/@primeuix/motion": { "version": "0.0.10", "resolved": "https://registry.npmjs.org/@primeuix/motion/-/motion-0.0.10.tgz", @@ -4361,14 +4370,14 @@ ] }, "node_modules/@schematics/angular": { - "version": "21.1.4", - "resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-21.1.4.tgz", - "integrity": "sha512-I1zdSNzdbrVCWpeE2NsZQmIoa9m0nlw4INgdGIkqUH6FgwvoGKC0RoOxKAmm6HHVJ48FE/sPI13dwAeK89ow5A==", + "version": "21.1.5", + "resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-21.1.5.tgz", + "integrity": "sha512-AndJ17ePYUoqJqiIF9VaXbGAFfOqDcHuAxhwozsQlWDzwgQSOUC/WWeG9hKVCgMD6tE02Sxr2ova9DiBKsLQNg==", "dev": true, "license": "MIT", "dependencies": { - "@angular-devkit/core": "21.1.4", - "@angular-devkit/schematics": "21.1.4", + "@angular-devkit/core": "21.1.5", + "@angular-devkit/schematics": "21.1.5", "jsonc-parser": "3.3.1" }, "engines": { @@ -4517,48 +4526,6 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@tufjs/models/node_modules/balanced-match": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.2.tgz", - "integrity": "sha512-x0K50QvKQ97fdEz2kPehIerj+YTeptKF9hyYkKf6egnwmMWAkADiO0QCzSp0R5xN8FTZgYaBfSaue46Ej62nMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "jackspeak": "^4.2.3" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/@tufjs/models/node_modules/brace-expansion": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.2.tgz", - "integrity": "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/@tufjs/models/node_modules/minimatch": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.0.tgz", - "integrity": "sha512-ugkC31VaVg9cF0DFVoADH12k6061zNZkZON+aX8AWsR9GhPcErkcMBceb6znR8wLERM2AkkOxy2nWRLpT9Jq5w==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.2" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/@tweenjs/tween.js": { "version": "25.0.0", "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz", @@ -4594,6 +4561,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/dompurify": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/dompurify/-/dompurify-3.0.5.tgz", + "integrity": "sha512-1Wg0g3BtQF7sSb27fJQAKck1HECM6zV1EB66j8JH9i3LCjYabJa0FSdiSgsD5K/RbrsR0SiraKacLB+T8ZVYAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/trusted-types": "*" + } + }, "node_modules/@types/esrecurse": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", @@ -4632,29 +4609,25 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/uuid": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-11.0.0.tgz", - "integrity": "sha512-HVyk8nj2m+jcFRNazzqyVKiZezyhDKrGUA3jlEcg/nZ6Ms+qHwocba1Y/AaVaznJTAM9xpdFSh+ptbNrhOGvZA==", - "deprecated": "This is a stub types definition. uuid provides its own type definitions, so you do not need this installed.", - "dev": true, - "license": "MIT", - "dependencies": { - "uuid": "*" - } + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "devOptional": true, + "license": "MIT" }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.56.0.tgz", - "integrity": "sha512-lRyPDLzNCuae71A3t9NEINBiTn7swyOhvUj3MyUOxb8x6g6vPEFoOU+ZRmGMusNC3X3YMhqMIX7i8ShqhT74Pw==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.56.1.tgz", + "integrity": "sha512-Jz9ZztpB37dNC+HU2HI28Bs9QXpzCz+y/twHOwhyrIRdbuVDxSytJNDl6z/aAKlaRIwC7y8wJdkBv7FxYGgi0A==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.56.0", - "@typescript-eslint/type-utils": "8.56.0", - "@typescript-eslint/utils": "8.56.0", - "@typescript-eslint/visitor-keys": "8.56.0", + "@typescript-eslint/scope-manager": "8.56.1", + "@typescript-eslint/type-utils": "8.56.1", + "@typescript-eslint/utils": "8.56.1", + "@typescript-eslint/visitor-keys": "8.56.1", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.4.0" @@ -4667,22 +4640,22 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.56.0", + "@typescript-eslint/parser": "^8.56.1", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "node_modules/@typescript-eslint/parser": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.56.0.tgz", - "integrity": "sha512-IgSWvLobTDOjnaxAfDTIHaECbkNlAlKv2j5SjpB2v7QHKv1FIfjwMy8FsDbVfDX/KjmCmYICcw7uGaXLhtsLNg==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.56.1.tgz", + "integrity": "sha512-klQbnPAAiGYFyI02+znpBRLyjL4/BrBd0nyWkdC0s/6xFLkXYQ8OoRrSkqacS1ddVxf/LDyODIKbQ5TgKAf/Fg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.56.0", - "@typescript-eslint/types": "8.56.0", - "@typescript-eslint/typescript-estree": "8.56.0", - "@typescript-eslint/visitor-keys": "8.56.0", + "@typescript-eslint/scope-manager": "8.56.1", + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/typescript-estree": "8.56.1", + "@typescript-eslint/visitor-keys": "8.56.1", "debug": "^4.4.3" }, "engines": { @@ -4698,14 +4671,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.56.0.tgz", - "integrity": "sha512-M3rnyL1vIQOMeWxTWIW096/TtVP+8W3p/XnaFflhmcFp+U4zlxUxWj4XwNs6HbDeTtN4yun0GNTTDBw/SvufKg==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.56.1.tgz", + "integrity": "sha512-TAdqQTzHNNvlVFfR+hu2PDJrURiwKsUvxFn1M0h95BB8ah5jejas08jUWG4dBA68jDMI988IvtfdAI53JzEHOQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.56.0", - "@typescript-eslint/types": "^8.56.0", + "@typescript-eslint/tsconfig-utils": "^8.56.1", + "@typescript-eslint/types": "^8.56.1", "debug": "^4.4.3" }, "engines": { @@ -4720,14 +4693,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.56.0.tgz", - "integrity": "sha512-7UiO/XwMHquH+ZzfVCfUNkIXlp/yQjjnlYUyYz7pfvlK3/EyyN6BK+emDmGNyQLBtLGaYrTAI6KOw8tFucWL2w==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.56.1.tgz", + "integrity": "sha512-YAi4VDKcIZp0O4tz/haYKhmIDZFEUPOreKbfdAN3SzUDMcPhJ8QI99xQXqX+HoUVq8cs85eRKnD+rne2UAnj2w==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.56.0", - "@typescript-eslint/visitor-keys": "8.56.0" + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/visitor-keys": "8.56.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4738,9 +4711,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.56.0.tgz", - "integrity": "sha512-bSJoIIt4o3lKXD3xmDh9chZcjCz5Lk8xS7Rxn+6l5/pKrDpkCwtQNQQwZ2qRPk7TkUYhrq3WPIHXOXlbXP0itg==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.56.1.tgz", + "integrity": "sha512-qOtCYzKEeyr3aR9f28mPJqBty7+DBqsdd63eO0yyDwc6vgThj2UjWfJIcsFeSucYydqcuudMOprZ+x1SpF3ZuQ==", "dev": true, "license": "MIT", "engines": { @@ -4755,15 +4728,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.56.0.tgz", - "integrity": "sha512-qX2L3HWOU2nuDs6GzglBeuFXviDODreS58tLY/BALPC7iu3Fa+J7EOTwnX9PdNBxUI7Uh0ntP0YWGnxCkXzmfA==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.56.1.tgz", + "integrity": "sha512-yB/7dxi7MgTtGhZdaHCemf7PuwrHMenHjmzgUW1aJpO+bBU43OycnM3Wn+DdvDO/8zzA9HlhaJ0AUGuvri4oGg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.56.0", - "@typescript-eslint/typescript-estree": "8.56.0", - "@typescript-eslint/utils": "8.56.0", + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/typescript-estree": "8.56.1", + "@typescript-eslint/utils": "8.56.1", "debug": "^4.4.3", "ts-api-utils": "^2.4.0" }, @@ -4780,9 +4753,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.56.0.tgz", - "integrity": "sha512-DBsLPs3GsWhX5HylbP9HNG15U0bnwut55Lx12bHB9MpXxQ+R5GC8MwQe+N1UFXxAeQDvEsEDY6ZYwX03K7Z6HQ==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.56.1.tgz", + "integrity": "sha512-dbMkdIUkIkchgGDIv7KLUpa0Mda4IYjo4IAMJUZ+3xNoUXxMsk9YtKpTHSChRS85o+H9ftm51gsK1dZReY9CVw==", "dev": true, "license": "MIT", "engines": { @@ -4794,18 +4767,18 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.56.0.tgz", - "integrity": "sha512-ex1nTUMWrseMltXUHmR2GAQ4d+WjkZCT4f+4bVsps8QEdh0vlBsaCokKTPlnqBFqqGaxilDNJG7b8dolW2m43Q==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.56.1.tgz", + "integrity": "sha512-qzUL1qgalIvKWAf9C1HpvBjif+Vm6rcT5wZd4VoMb9+Km3iS3Cv9DY6dMRMDtPnwRAFyAi7YXJpTIEXLvdfPxg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.56.0", - "@typescript-eslint/tsconfig-utils": "8.56.0", - "@typescript-eslint/types": "8.56.0", - "@typescript-eslint/visitor-keys": "8.56.0", + "@typescript-eslint/project-service": "8.56.1", + "@typescript-eslint/tsconfig-utils": "8.56.1", + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/visitor-keys": "8.56.1", "debug": "^4.4.3", - "minimatch": "^9.0.5", + "minimatch": "^10.2.2", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.4.0" @@ -4822,16 +4795,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.56.0.tgz", - "integrity": "sha512-RZ3Qsmi2nFGsS+n+kjLAYDPVlrzf7UhTffrDIKr+h2yzAlYP/y5ZulU0yeDEPItos2Ph46JAL5P/On3pe7kDIQ==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.56.1.tgz", + "integrity": "sha512-HPAVNIME3tABJ61siYlHzSWCGtOoeP2RTIaHXFMPqjrQKCGB9OgUVdiNgH7TJS2JNIQ5qQ4RsAUDuGaGme/KOA==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.56.0", - "@typescript-eslint/types": "8.56.0", - "@typescript-eslint/typescript-estree": "8.56.0" + "@typescript-eslint/scope-manager": "8.56.1", + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/typescript-estree": "8.56.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4846,13 +4819,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.56.0.tgz", - "integrity": "sha512-q+SL+b+05Ud6LbEE35qe4A99P+htKTKVbyiNEe45eCbJFyh/HVK9QXwlrbz+Q4L8SOW4roxSVwXYj4DMBT7Ieg==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.56.1.tgz", + "integrity": "sha512-KiROIzYdEV85YygXw6BI/Dx4fnBlFQu6Mq4QE4MOH9fFnhohw6wX/OAvDY2/C+ut0I3RSPKenvZJIVYqJNkhEw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.56.0", + "@typescript-eslint/types": "8.56.1", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -4864,9 +4837,9 @@ } }, "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.0.tgz", - "integrity": "sha512-A0XeIi7CXU7nPlfHS9loMYEKxUaONu/hTEzHTGba9Huu94Cq1hPivf+DE5erJozZOky0LfvXAyrV/tcswpLI0Q==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", "dev": true, "license": "Apache-2.0", "engines": { @@ -5063,9 +5036,9 @@ } }, "node_modules/acorn": { - "version": "8.15.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", - "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "dev": true, "license": "MIT", "bin": { @@ -5096,9 +5069,9 @@ } }, "node_modules/ajv": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", - "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", "dev": true, "license": "MIT", "dependencies": { @@ -5291,11 +5264,14 @@ } }, "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } }, "node_modules/baseline-browser-mapping": { "version": "2.9.19", @@ -5370,13 +5346,16 @@ "license": "ISC" }, "node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.3.tgz", + "integrity": "sha512-fy6KJm2RawA5RcHkLa1z/ScpBeA762UF9KmZQxwIbDtRJrgLzM10depAiEQ+CXYcoiqW1/m96OAAoke2nE9EeA==", "dev": true, "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0" + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" } }, "node_modules/braces": { @@ -6074,6 +6053,15 @@ "url": "https://github.com/fb55/domhandler?sponsor=1" } }, + "node_modules/dompurify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.1.tgz", + "integrity": "sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/domutils": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", @@ -6325,30 +6313,33 @@ } }, "node_modules/eslint": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.0.0.tgz", - "integrity": "sha512-O0piBKY36YSJhlFSG8p9VUdPV/SxxS4FYDWVpr/9GJuMaepzwlf4J8I4ov1b+ySQfDTPhc3DtLaxcT1fN0yqCg==", + "version": "9.39.3", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.3.tgz", + "integrity": "sha512-VmQ+sifHUbI/IcSopBCF/HO3YiHQx/AVd3UVyYL6weuwW+HvON9VYn5l6Zl1WZzPWXPNZrSQpxwkkZ/VuvJZzg==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", - "@eslint-community/regexpp": "^4.12.2", - "@eslint/config-array": "^0.23.0", - "@eslint/config-helpers": "^0.5.2", - "@eslint/core": "^1.1.0", - "@eslint/plugin-kit": "^0.6.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.1", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.39.3", + "@eslint/plugin-kit": "^0.4.1", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.12.4", + "chalk": "^4.0.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^9.1.0", - "eslint-visitor-keys": "^5.0.0", - "espree": "^11.1.0", - "esquery": "^1.7.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", @@ -6358,7 +6349,8 @@ "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "minimatch": "^10.1.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, @@ -6366,7 +6358,7 @@ "eslint": "bin/eslint.js" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://eslint.org/donate" @@ -6413,9 +6405,9 @@ } }, "node_modules/eslint/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", "dev": true, "license": "MIT", "dependencies": { @@ -6429,40 +6421,64 @@ "url": "https://github.com/sponsors/epoberezkin" } }, - "node_modules/eslint/node_modules/balanced-match": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.2.tgz", - "integrity": "sha512-x0K50QvKQ97fdEz2kPehIerj+YTeptKF9hyYkKf6egnwmMWAkADiO0QCzSp0R5xN8FTZgYaBfSaue46Ej62nMg==", + "node_modules/eslint/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "license": "MIT", "dependencies": { - "jackspeak": "^4.2.3" + "color-convert": "^2.0.1" }, "engines": { - "node": "20 || >=22" + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/eslint/node_modules/brace-expansion": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.2.tgz", - "integrity": "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw==", + "node_modules/eslint/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "license": "MIT", "dependencies": { - "balanced-match": "^4.0.2" + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" }, "engines": { - "node": "20 || >=22" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/eslint/node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, "node_modules/eslint/node_modules/eslint-visitor-keys": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.0.tgz", - "integrity": "sha512-A0XeIi7CXU7nPlfHS9loMYEKxUaONu/hTEzHTGba9Huu94Cq1hPivf+DE5erJozZOky0LfvXAyrV/tcswpLI0Q==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", "dev": true, "license": "Apache-2.0", "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -6485,48 +6501,32 @@ "dev": true, "license": "MIT" }, - "node_modules/eslint/node_modules/minimatch": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.0.tgz", - "integrity": "sha512-ugkC31VaVg9cF0DFVoADH12k6061zNZkZON+aX8AWsR9GhPcErkcMBceb6znR8wLERM2AkkOxy2nWRLpT9Jq5w==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.2" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/espree": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-11.1.0.tgz", - "integrity": "sha512-WFWYhO1fV4iYkqOOvq8FbqIhr2pYfoDY0kCotMkDeNtGpiGGkZ1iov2u8ydjtgM8yF8rzK7oaTbw2NAzbAbehw==", + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", "dev": true, "license": "BSD-2-Clause", "dependencies": { "acorn": "^8.15.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^5.0.0" + "eslint-visitor-keys": "^4.2.1" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" } }, "node_modules/espree/node_modules/eslint-visitor-keys": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.0.tgz", - "integrity": "sha512-A0XeIi7CXU7nPlfHS9loMYEKxUaONu/hTEzHTGba9Huu94Cq1hPivf+DE5erJozZOky0LfvXAyrV/tcswpLI0Q==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", "dev": true, "license": "Apache-2.0", "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -7058,46 +7058,17 @@ "dev": true, "license": "BSD-2-Clause" }, - "node_modules/glob/node_modules/balanced-match": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.2.tgz", - "integrity": "sha512-x0K50QvKQ97fdEz2kPehIerj+YTeptKF9hyYkKf6egnwmMWAkADiO0QCzSp0R5xN8FTZgYaBfSaue46Ej62nMg==", + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", "dev": true, "license": "MIT", - "dependencies": { - "jackspeak": "^4.2.3" - }, "engines": { - "node": "20 || >=22" - } - }, - "node_modules/glob/node_modules/brace-expansion": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.2.tgz", - "integrity": "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/glob/node_modules/minimatch": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.0.tgz", - "integrity": "sha512-ugkC31VaVg9cF0DFVoADH12k6061zNZkZON+aX8AWsR9GhPcErkcMBceb6znR8wLERM2AkkOxy2nWRLpT9Jq5w==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.2" - }, - "engines": { - "node": "20 || >=22" + "node": ">=18" }, "funding": { - "url": "https://github.com/sponsors/isaacs" + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/gopd": { @@ -7157,9 +7128,9 @@ } }, "node_modules/hono": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.0.tgz", - "integrity": "sha512-NekXntS5M94pUfiVZ8oXXK/kkri+5WpX2/Ik+LVsl+uvw+soj4roXIsPqO+XsWrAw20mOzaXOZf3Q7PfB9A/IA==", + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.2.tgz", + "integrity": "sha512-gJnaDHXKDayjt8ue0n8Gs0A007yKXj4Xzb8+cNjZeYsSzzwKc0Lr+OZgYwVfB0pHfUs17EPoLvrOsEaJ9mj+Tg==", "dev": true, "license": "MIT", "engines": { @@ -7338,48 +7309,6 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/ignore-walk/node_modules/balanced-match": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.2.tgz", - "integrity": "sha512-x0K50QvKQ97fdEz2kPehIerj+YTeptKF9hyYkKf6egnwmMWAkADiO0QCzSp0R5xN8FTZgYaBfSaue46Ej62nMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "jackspeak": "^4.2.3" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/ignore-walk/node_modules/brace-expansion": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.2.tgz", - "integrity": "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/ignore-walk/node_modules/minimatch": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.0.tgz", - "integrity": "sha512-ugkC31VaVg9cF0DFVoADH12k6061zNZkZON+aX8AWsR9GhPcErkcMBceb6znR8wLERM2AkkOxy2nWRLpT9Jq5w==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.2" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/immutable": { "version": "5.1.4", "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.4.tgz", @@ -7624,22 +7553,6 @@ "node": ">=8" } }, - "node_modules/jackspeak": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz", - "integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/cliui": "^9.0.0" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/jose": { "version": "6.1.3", "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz", @@ -7943,6 +7856,13 @@ "integrity": "sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==", "license": "MIT" }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, "node_modules/log-symbols": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-7.0.1.tgz", @@ -8205,16 +8125,16 @@ } }, "node_modules/minimatch": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", - "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.2.tgz", + "integrity": "sha512-+G4CpNBxa5MprY+04MbgOw1v7So6n5JY166pFi9KfYwT78fxScCeSNQSNzp6dpPSW2rONOps6Ocam1wFhCgoVw==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^2.0.1" + "brace-expansion": "^5.0.2" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -10392,16 +10312,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.56.0.tgz", - "integrity": "sha512-c7toRLrotJ9oixgdW7liukZpsnq5CZ7PuKztubGYlNppuTqhIoWfhgHo/7EU0v06gS2l/x0i2NEFK1qMIf0rIg==", + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.56.1.tgz", + "integrity": "sha512-U4lM6pjmBX7J5wk4szltF7I1cGBHXZopnAXCMXb3+fZ3B/0Z3hq3wS/CCUB2NZBNAExK92mCU2tEohWuwVMsDQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.56.0", - "@typescript-eslint/parser": "8.56.0", - "@typescript-eslint/typescript-estree": "8.56.0", - "@typescript-eslint/utils": "8.56.0" + "@typescript-eslint/eslint-plugin": "8.56.1", + "@typescript-eslint/parser": "8.56.1", + "@typescript-eslint/typescript-estree": "8.56.1", + "@typescript-eslint/utils": "8.56.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -10510,16 +10430,16 @@ } }, "node_modules/uuid": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz", - "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", "funding": [ "https://github.com/sponsors/broofa", "https://github.com/sponsors/ctavan" ], "license": "MIT", "bin": { - "uuid": "dist-node/bin/uuid" + "uuid": "dist/esm/bin/uuid" } }, "node_modules/validate-npm-package-license": { diff --git a/booklore-ui/package.json b/booklore-ui/package.json index c09913950..f4fd6d46e 100644 --- a/booklore-ui/package.json +++ b/booklore-ui/package.json @@ -24,7 +24,7 @@ "@angular/service-worker": "^21.1.5", "@iharbeck/ngx-virtual-scroller": "^20.0.0", "@jsverse/transloco": "^8.2.1", - "@primeng/themes": "^21.0.3", + "@primeuix/themes": "^2.0.3", "@stomp/rx-stomp": "^2.3.0", "@stomp/stompjs": "^7.3.0", "@tweenjs/tween.js": "^25.0.0", @@ -33,6 +33,7 @@ "chartjs-chart-matrix": "^3.0.0", "chartjs-plugin-datalabels": "^2.2.0", "date-fns": "^4.1.0", + "dompurify": "^3.3.1", "jwt-decode": "^4.0.0", "ng-lazyload-image": "^9.1.3", "ng2-charts": "^8.0.0", @@ -44,25 +45,32 @@ "rxjs": "^7.8.2", "showdown": "^2.1.0", "tslib": "^2.8.1", - "uuid": "^13.0.0", + "uuid": "^11.0.0", "ws": "^8.19.0", "zone.js": "^0.16.1" }, "devDependencies": { "@analogjs/vite-plugin-angular": "^2.2.3", "@analogjs/vitest-angular": "^2.2.3", - "@angular/build": "^21.1.4", - "@angular/cli": "^21.1.4", + "@angular/build": "^21.1.5", + "@angular/cli": "^21.1.5", "@angular/compiler-cli": "^21.1.5", + "@types/dompurify": "^3.0.5", "@types/node": "^25.3.0", "@types/showdown": "^2.0.6", - "@types/uuid": "^11.0.0", "@vitest/coverage-v8": "^4.0.17", "angular-eslint": "^21.2.0", - "eslint": "^10.0.0", + "eslint": "^9.39.3", "jsdom": "^28.1.0", "typescript": "~5.9.3", - "typescript-eslint": "^8.56.0", + "typescript-eslint": "^8.56.1", "vitest": "^4.0.17" + }, + "overrides": { + "minimatch": "^10.2.1", + "ajv": "^8.18.0", + "eslint": { + "ajv": "^6.14.0" + } } } diff --git a/booklore-ui/src/app/core/config/transloco-loader.ts b/booklore-ui/src/app/core/config/transloco-loader.ts index 8b97a045c..8e2812fc7 100644 --- a/booklore-ui/src/app/core/config/transloco-loader.ts +++ b/booklore-ui/src/app/core/config/transloco-loader.ts @@ -51,7 +51,7 @@ function deepMerge(base: Record, override: Record): Re if (override[key] && typeof override[key] === 'object' && !Array.isArray(override[key]) && base[key] && typeof base[key] === 'object' && !Array.isArray(base[key])) { result[key] = deepMerge(base[key], override[key]); - } else { + } else if (override[key] !== '') { result[key] = override[key]; } } diff --git a/booklore-ui/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.html b/booklore-ui/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.html index 741c1da51..00d14279d 100644 --- a/booklore-ui/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.html +++ b/booklore-ui/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.html @@ -23,6 +23,7 @@ @@ -123,8 +124,13 @@

{{ t('dragDropText') }}

- -
+ @if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) { + +
+ } @else { + {{ t('supplementaryAllFormats') }} +
+ } {{ t('maxFileSize', { size: maxFileSizeDisplay }) }}

diff --git a/booklore-ui/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.ts b/booklore-ui/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.ts index eed6abd90..a39a55471 100644 --- a/booklore-ui/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.ts +++ b/booklore-ui/src/app/features/book/components/additional-file-uploader/additional-file-uploader.component.ts @@ -1,4 +1,4 @@ -import {ChangeDetectorRef, Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {ChangeDetectorRef, Component, inject, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; @@ -48,11 +48,14 @@ export class AdditionalFileUploaderComponent implements OnInit, OnDestroy { files: UploadingFile[] = []; fileType: AdditionalFileType = AdditionalFileType.ALTERNATIVE_FORMAT; isUploading = false; + readonly AdditionalFileType = AdditionalFileType; + private static readonly BOOK_FORMAT_ACCEPT = '.pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3,.m4b,.m4a,.mp3'; maxFileSizeBytes?: number; maxFileSizeDisplay: string = '100 MB'; fileTypeOptions: FileTypeOption[] = []; + @ViewChild(FileUpload) private fileUpload!: FileUpload; private destroy$ = new Subject(); constructor( @@ -89,6 +92,19 @@ export class AdditionalFileUploaderComponent implements OnInit, OnDestroy { this.destroy$.complete(); } + onFileTypeChange(): void { + this.files = []; + if (this.fileUpload) { + this.fileUpload.clear(); + } + } + + get acceptedFormats(): string { + return this.fileType === AdditionalFileType.ALTERNATIVE_FORMAT + ? AdditionalFileUploaderComponent.BOOK_FORMAT_ACCEPT + : ''; + } + hasPendingFiles(): boolean { return this.files.some(f => f.status === 'Pending'); } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html index 889cf997f..669dc6cdf 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html @@ -312,6 +312,7 @@ [isSeriesCollapsed]="seriesCollapseFilter.isSeriesCollapsed" (checkboxClick)="onCheckboxClicked($event)" [isSelected]="selectedBooks.has(book.id)" + [useSquareCovers]="isAudiobookOnlyLibrary" [overlayPreferenceService]="bookCardOverlayPreferenceService"> diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index defe0ced8..61df836ee 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -196,7 +196,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy { const totalGaps = (columns - 1) * this.MOBILE_GAP; const availableWidth = this.screenWidth - totalGaps - this.MOBILE_PADDING; const cardWidth = Math.floor(availableWidth / columns); - const coverHeight = Math.floor(cardWidth * this.CARD_ASPECT_RATIO); + const coverHeight = this.isAudiobookOnlyLibrary ? cardWidth : Math.floor(cardWidth * this.CARD_ASPECT_RATIO); const cardHeight = coverHeight + this.MOBILE_TITLE_BAR_HEIGHT; return {width: cardWidth, height: cardHeight}; } @@ -209,23 +209,31 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy { if (this.isMobile) { return this.mobileCardSize; } - return this.coverScalePreferenceService.currentCardSize; + const base = this.coverScalePreferenceService.currentCardSize; + if (this.isAudiobookOnlyLibrary) { + const squareSide = Math.round(base.width * 1.1); + return { width: squareSide, height: squareSide + 31 }; + } + return base; } get gridColumnMinWidth(): string { if (this.isMobile) { return `${this.mobileCardSize.width}px`; } + if (this.isAudiobookOnlyLibrary) { + return `${this.currentCardSize.width}px`; + } return this.coverScalePreferenceService.gridColumnMinWidth; } getCardHeight(_book: Book): number { - // Use uniform height for all book types to ensure smooth virtual scrolling. - // Mixed heights cause choppy/jumpy scrolling because the virtual scroller - // cannot accurately estimate positions when item heights vary. if (this.isMobile) { return this.mobileCardSize.height; } + if (this.isAudiobookOnlyLibrary) { + return this.currentCardSize.height; + } return this.coverScalePreferenceService.getCardHeight(_book); } @@ -267,6 +275,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy { : filterSummary; } + get isAudiobookOnlyLibrary(): boolean { + if (!this.entity || this.entityType !== EntityType.LIBRARY) return false; + const library = this.entity as Library; + return !!library.allowedFormats && library.allowedFormats.length === 1 && library.allowedFormats[0] === 'AUDIOBOOK'; + } + get seriesViewEnabled(): boolean { return Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView); } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html index 7df34472d..63076d2de 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html @@ -2,12 +2,12 @@ [class.selected]="isSelected" (click)="onCardClick($event)"> -
+
; @@ -138,7 +139,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { } ngOnChanges(changes: SimpleChanges): void { - if (changes['book'] || changes['forceEbookMode']) { + if (changes['book'] || changes['forceEbookMode'] || changes['useSquareCovers']) { this.computeAllMemoizedValues(); if (changes['book'] && !changes['book'].firstChange && this.menuInitialized) { this.additionalFilesLoaded = false; diff --git a/booklore-ui/src/app/features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.ts b/booklore-ui/src/app/features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.ts index cc5241c39..bcb0be017 100644 --- a/booklore-ui/src/app/features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.ts +++ b/booklore-ui/src/app/features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component.ts @@ -426,6 +426,7 @@ export class BookdropFileReviewComponent implements OnInit { severity: 'success', outlined: true }, + acceptIcon: 'pi pi-check', accept: () => this.finalizeImport(), }); } diff --git a/booklore-ui/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.ts b/booklore-ui/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.ts index 2432137a9..d8678c248 100644 --- a/booklore-ui/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.ts +++ b/booklore-ui/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.ts @@ -35,6 +35,10 @@ export class MetadataProviderFieldSelectorComponent implements OnInit { label: 'Hardcover', fields: ['hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount'] }, + { + label: 'Audible', + fields: ['audibleId', 'audibleRating', 'audibleReviewCount'] + }, { label: 'Comicvine', fields: ['comicvineId'] @@ -46,10 +50,6 @@ export class MetadataProviderFieldSelectorComponent implements OnInit { { label: 'Ranobedb', fields: ['ranobedbId', 'ranobedbRating'] - }, - { - label: 'Audible', - fields: ['audibleId', 'audibleRating', 'audibleReviewCount'] } ]; diff --git a/booklore-ui/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.ts b/booklore-ui/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.ts index 832619595..167900083 100644 --- a/booklore-ui/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.ts +++ b/booklore-ui/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.ts @@ -34,19 +34,22 @@ export class MetadataMatchWeightsComponent implements OnInit { coverImage: 'Cover Image', seriesName: 'Series Name', seriesNumber: 'Series Number', + seriesTotal: 'Series Total', language: 'Language', isbn13: 'ISBN-13', isbn10: 'ISBN-10', pageCount: 'Page Count', amazonRating: 'Amazon Rating', - amazonReviewCount: 'Amazon Rating # ', + amazonReviewCount: 'Amazon Rating #', goodreadsRating: 'Goodreads Rating', goodreadsReviewCount: 'Goodreads Rating #', hardcoverRating: 'Hardcover Rating', hardcoverReviewCount: 'Hardcover Rating #', - ranobedbRating: 'Ranobedb Rating', audibleRating: 'Audible Rating', audibleReviewCount: 'Audible Rating #', + doubanRating: 'Douban Rating', + doubanReviewCount: 'Douban Rating #', + ranobedbRating: 'Ranobedb Rating', }; form!: FormGroup; @@ -72,6 +75,7 @@ export class MetadataMatchWeightsComponent implements OnInit { categories: [0, [Validators.required, Validators.min(0)]], seriesName: [0, [Validators.required, Validators.min(0)]], seriesNumber: [0, [Validators.required, Validators.min(0)]], + seriesTotal: [0, [Validators.required, Validators.min(0)]], isbn13: [0, [Validators.required, Validators.min(0)]], isbn10: [0, [Validators.required, Validators.min(0)]], pageCount: [0, [Validators.required, Validators.min(0)]], @@ -82,6 +86,8 @@ export class MetadataMatchWeightsComponent implements OnInit { goodreadsReviewCount: [0, [Validators.required, Validators.min(0)]], hardcoverRating: [0, [Validators.required, Validators.min(0)]], hardcoverReviewCount: [0, [Validators.required, Validators.min(0)]], + doubanRating: [0, [Validators.required, Validators.min(0)]], + doubanReviewCount: [0, [Validators.required, Validators.min(0)]], ranobedbRating: [0, [Validators.required, Validators.min(0)]], audibleRating: [0, [Validators.required, Validators.min(0)]], audibleReviewCount: [0, [Validators.required, Validators.min(0)]], diff --git a/booklore-ui/src/app/shared/layout/component/theme-palette-extend.ts b/booklore-ui/src/app/shared/layout/component/theme-palette-extend.ts index 110ed5f72..ed400beb6 100644 --- a/booklore-ui/src/app/shared/layout/component/theme-palette-extend.ts +++ b/booklore-ui/src/app/shared/layout/component/theme-palette-extend.ts @@ -1,4 +1,4 @@ -import Aura from '@primeng/themes/aura'; +import Aura from '@primeuix/themes/aura'; type ColorPalette = Record; diff --git a/booklore-ui/src/app/shared/model/app-settings.model.ts b/booklore-ui/src/app/shared/model/app-settings.model.ts index 324b231f4..40e112dab 100644 --- a/booklore-ui/src/app/shared/model/app-settings.model.ts +++ b/booklore-ui/src/app/shared/model/app-settings.model.ts @@ -25,6 +25,8 @@ export interface MetadataMatchWeights { doubanReviewCount: number; lubimyczytacRating: number; ranobedbRating: number; + audibleRating: number; + audibleReviewCount: number; coverImage: number; } diff --git a/booklore-ui/src/app/shared/service/app-config.service.ts b/booklore-ui/src/app/shared/service/app-config.service.ts index 6dc1a957e..1ecf0df53 100644 --- a/booklore-ui/src/app/shared/service/app-config.service.ts +++ b/booklore-ui/src/app/shared/service/app-config.service.ts @@ -1,8 +1,8 @@ -import {DOCUMENT, isPlatformBrowser} from '@angular/common'; -import {effect, inject, Injectable, PLATFORM_ID, signal} from '@angular/core'; -import {$t, updatePreset, updateSurfacePalette} from '@primeng/themes'; -import Aura from '@primeng/themes/aura'; -import {AppState} from '../model/app-state.model'; +import { DOCUMENT, isPlatformBrowser } from '@angular/common'; +import { effect, inject, Injectable, PLATFORM_ID, signal } from '@angular/core'; +import { $t, updatePreset, updateSurfacePalette } from '@primeuix/themes'; +import Aura from '@primeuix/themes/aura'; +import { AppState } from '../model/app-state.model'; type ColorPalette = Record; @@ -332,7 +332,7 @@ export class AppConfigService { constructor() { const initialState = this.loadAppState(); - this.appState.set({...initialState}); + this.appState.set({ ...initialState }); this.document.documentElement.classList.add('p-dark'); if (isPlatformBrowser(this.platformId)) { @@ -383,7 +383,7 @@ export class AppConfigService { if (primaryName === 'noir') { return { semantic: { - primary: {...surfacePalette}, + primary: { ...surfacePalette }, colorScheme: { dark: { primary: { @@ -430,6 +430,6 @@ export class AppConfigService { onPresetChange(): void { const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral'); const preset = this.getPresetExt(); - $t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({useDefaultOptions: true}); + $t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({ useDefaultOptions: true }); } } diff --git a/booklore-ui/src/app/shared/services/icon.service.ts b/booklore-ui/src/app/shared/services/icon.service.ts index 53bd9d2d8..f42504058 100644 --- a/booklore-ui/src/app/shared/services/icon.service.ts +++ b/booklore-ui/src/app/shared/services/icon.service.ts @@ -1,10 +1,11 @@ -import {inject, Injectable} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; -import {Observable, of} from 'rxjs'; -import {finalize, map, shareReplay, tap} from 'rxjs/operators'; -import {API_CONFIG} from '../../core/config/api-config'; -import {IconCacheService} from './icon-cache.service'; -import {DomSanitizer, SafeHtml} from '@angular/platform-browser'; +import { inject, Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable, of } from 'rxjs'; +import { finalize, map, shareReplay, tap } from 'rxjs/operators'; +import { API_CONFIG } from '../../core/config/api-config'; +import { IconCacheService } from './icon-cache.service'; +import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; +import DOMPurify from 'dompurify'; interface SvgIconData { svgName: string; @@ -25,7 +26,6 @@ interface SvgIconBatchResponse { } type IconContentMap = Record; - @Injectable({ providedIn: 'root' }) @@ -39,6 +39,16 @@ export class IconService { private iconCache = inject(IconCacheService); private sanitizer = inject(DomSanitizer); + /** + * Sanitizes SVG content using DOMPurify. + */ + private sanitizeSvgContent(content: string): string { + return DOMPurify.sanitize(content, { + USE_PROFILES: { svg: true }, + FORBID_TAGS: ['script', 'style', 'foreignObject'] + }); + } + preloadAllIcons(): Observable { if (this.preloadCache$) { return this.preloadCache$; @@ -47,12 +57,12 @@ export class IconService { this.preloadCache$ = this.http.get(`${this.baseUrl}/all/content`).pipe( tap((iconsMap) => { Object.entries(iconsMap).forEach(([iconName, content]) => { - const sanitized = this.sanitizer.bypassSecurityTrustHtml(content); + const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(content)); this.iconCache.cacheIcon(iconName, content, sanitized); }); }), map(() => void 0), - shareReplay({bufferSize: 1, refCount: false}), + shareReplay({ bufferSize: 1, refCount: false }), finalize(() => this.preloadCache$ = null) ); @@ -70,10 +80,10 @@ export class IconService { responseType: 'text' }).pipe( tap(content => { - const sanitized = this.sanitizer.bypassSecurityTrustHtml(content); + const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(content)); this.iconCache.cacheIcon(iconName, content, sanitized); }), - shareReplay({bufferSize: 1, refCount: true}), + shareReplay({ bufferSize: 1, refCount: true }), finalize(() => this.requestCache.delete(iconName)) ); @@ -113,13 +123,13 @@ export class IconService { } saveBatchSvgIcons(icons: SvgIconData[]): Observable { - return this.http.post(`${this.baseUrl}/batch`, {icons}).pipe( + return this.http.post(`${this.baseUrl}/batch`, { icons }).pipe( tap((response) => { response.results.forEach(result => { if (result.success) { const iconData = icons.find(icon => icon.svgName === result.iconName); if (iconData) { - const sanitized = this.sanitizer.bypassSecurityTrustHtml(iconData.svgData); + const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(iconData.svgData)); this.iconCache.cacheIcon(iconData.svgName, iconData.svgData, sanitized); } } diff --git a/booklore-ui/src/i18n/en/book.json b/booklore-ui/src/i18n/en/book.json index d8647ecd5..aeab370c4 100644 --- a/booklore-ui/src/i18n/en/book.json +++ b/booklore-ui/src/i18n/en/book.json @@ -445,6 +445,7 @@ "statusFailed": "Failed", "dragDropText": "Drag and drop a file here to upload.", "supportedFormats": "Supported formats: .pdf, .epub, .cbz, .cbr, .cb7, .fb2, .mobi, .azw3, .m4b, .mp3", + "supplementaryAllFormats": "All file formats are supported for supplementary files.", "maxFileSize": "Maximum file size: {{ size }} per file", "uploadForBook": "Upload an additional file for {{ title }}.", "thisBook": "this book", diff --git a/booklore-ui/src/i18n/es/book.json b/booklore-ui/src/i18n/es/book.json index bec8db2a6..1d26d4cac 100644 --- a/booklore-ui/src/i18n/es/book.json +++ b/booklore-ui/src/i18n/es/book.json @@ -445,6 +445,7 @@ "statusFailed": "Fallido", "dragDropText": "Arrastre y suelte un archivo aquí para subir.", "supportedFormats": "Formatos compatibles: .pdf, .epub, .cbz, .cbr, .cb7, .fb2, .mobi, .azw3, .m4b, .mp3", + "supplementaryAllFormats": "Todos los formatos de archivo son compatibles con archivos complementarios.", "maxFileSize": "Tamaño máximo de archivo: {{ size }} por archivo", "uploadForBook": "Subir un archivo adicional para {{ title }}.", "thisBook": "este libro", diff --git a/booklore-ui/src/main.ts b/booklore-ui/src/main.ts index b365ab329..613522427 100644 --- a/booklore-ui/src/main.ts +++ b/booklore-ui/src/main.ts @@ -1,28 +1,28 @@ -import {provideHttpClient, withInterceptors} from '@angular/common/http'; -import {DialogService} from 'primeng/dynamicdialog'; -import {ConfirmationService, MessageService} from 'primeng/api'; -import {RxStompService} from './app/shared/websocket/rx-stomp.service'; -import {rxStompServiceFactory} from './app/shared/websocket/rx-stomp-service-factory'; -import {provideRouter, RouteReuseStrategy} from '@angular/router'; -import {CustomReuseStrategy} from './app/core/custom-reuse-strategy'; -import {provideAnimationsAsync} from '@angular/platform-browser/animations/async'; -import {providePrimeNG} from 'primeng/config'; -import {bootstrapApplication} from '@angular/platform-browser'; -import {AppComponent} from './app/app.component'; -import Aura from '@primeng/themes/aura'; -import {routes} from './app/app.routes'; -import {AuthInterceptorService} from './app/core/security/auth-interceptor.service'; -import {AuthService, websocketInitializer} from './app/shared/service/auth.service'; -import {OAuthStorage, provideOAuthClient} from 'angular-oauth2-oidc'; -import {inject, isDevMode, provideAppInitializer, provideZoneChangeDetection} from '@angular/core'; -import {initializeAuthFactory} from './app/core/security/auth-initializer'; -import {StartupService} from './app/shared/service/startup.service'; -import {provideCharts, withDefaultRegisterables} from 'ng2-charts'; +import { provideHttpClient, withInterceptors } from '@angular/common/http'; +import { DialogService } from 'primeng/dynamicdialog'; +import { ConfirmationService, MessageService } from 'primeng/api'; +import { RxStompService } from './app/shared/websocket/rx-stomp.service'; +import { rxStompServiceFactory } from './app/shared/websocket/rx-stomp-service-factory'; +import { provideRouter, RouteReuseStrategy } from '@angular/router'; +import { CustomReuseStrategy } from './app/core/custom-reuse-strategy'; +import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; +import { providePrimeNG } from 'primeng/config'; +import { bootstrapApplication } from '@angular/platform-browser'; +import { AppComponent } from './app/app.component'; +import Aura from '@primeuix/themes/aura'; +import { routes } from './app/app.routes'; +import { AuthInterceptorService } from './app/core/security/auth-interceptor.service'; +import { AuthService, websocketInitializer } from './app/shared/service/auth.service'; +import { OAuthStorage, provideOAuthClient } from 'angular-oauth2-oidc'; +import { inject, isDevMode, provideAppInitializer, provideZoneChangeDetection } from '@angular/core'; +import { initializeAuthFactory } from './app/core/security/auth-initializer'; +import { StartupService } from './app/shared/service/startup.service'; +import { provideCharts, withDefaultRegisterables } from 'ng2-charts'; import ChartDataLabels from 'chartjs-plugin-datalabels'; -import {provideServiceWorker} from '@angular/service-worker'; -import {provideTransloco} from '@jsverse/transloco'; -import {AVAILABLE_LANGS, TranslocoInlineLoader} from './app/core/config/transloco-loader'; -import {initializeLanguage} from './app/core/config/language-initializer'; +import { provideServiceWorker } from '@angular/service-worker'; +import { provideTransloco } from '@jsverse/transloco'; +import { AVAILABLE_LANGS, TranslocoInlineLoader } from './app/core/config/transloco-loader'; +import { initializeLanguage } from './app/core/config/language-initializer'; export function storageFactory(): OAuthStorage { return localStorage; diff --git a/dev.docker-compose.yml b/dev.docker-compose.yml index 796b9f455..d185991a7 100644 --- a/dev.docker-compose.yml +++ b/dev.docker-compose.yml @@ -4,12 +4,13 @@ services: command: sh -c "cd /booklore-api && ./gradlew bootRun" ports: - "${BACKEND_PORT:-6060}:6060" - - "${REMOTE_DEBUG_PORT:-5005}:5005" + - "127.0.0.1:${REMOTE_DEBUG_PORT:-5005}:5005" environment: - DATABASE_URL=jdbc:mariadb://backend_db:3306/booklore - DATABASE_USERNAME=booklore - DATABASE_PASSWORD=booklore - REMOTE_DEBUG_ENABLED=true + - ALLOWED_ORIGINS=http://localhost:4200 stdin_open: true tty: true restart: unless-stopped diff --git a/docker/unrar/unrar-amd64 b/docker/unrar/unrar-amd64 new file mode 100755 index 000000000..313790a4a Binary files /dev/null and b/docker/unrar/unrar-amd64 differ diff --git a/docker/unrar/unrar-arm64 b/docker/unrar/unrar-arm64 new file mode 100755 index 000000000..feee4c65c Binary files /dev/null and b/docker/unrar/unrar-arm64 differ diff --git a/example-docker/docker-compose.yml b/example-docker/docker-compose.yml index b7aabbda1..d7334bbc8 100644 --- a/example-docker/docker-compose.yml +++ b/example-docker/docker-compose.yml @@ -14,6 +14,7 @@ services: - DATABASE_PASSWORD=your_secure_password # Use a strong password; must match MYSQL_PASSWORD defined in the mariadb container - SWAGGER_ENABLED=false # Enable or disable Swagger UI (API docs). Set to 'true' to allow access; 'false' to block access (recommended for production). - FORCE_DISABLE_OIDC=false # Set to 'true' to force-disable OIDC and allow internal login, regardless of UI config + # ALLOWED_ORIGINS= # Comma-separated list of allowed cross-origin URLs for CORS (e.g. https://app.example.com). Defaults to '*' (allow all) if unset. Leave empty to restrict to same-origin. depends_on: mariadb: condition: service_healthy