#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add a first-run setup wizard for self-hosted servers (#8500)
EthanHealy01028784a1f56f
diff --git a/.github/workflows/PR-Auto-Deploy-V2.yml b/.github/workflows/PR-Auto-Deploy-V2.ymlindex b28057c854..c3dd7df044 100644--- a/.github/workflows/PR-Auto-Deploy-V2.yml+++ b/.github/workflows/PR-Auto-Deploy-V2.yml@@ -320,6 +320,8 @@ jobs:STIRLING_BILLING_ACCOUNT_LINK_METERING_ENABLED: "false"# Browser connection state belongs to the origin advertised in the preview link.SYSTEM_FRONTENDURL: "http://${NEW_VPS_HOST}:${V2_PORT}"+ # Previews are throwaway demos; the first-run setup wizard would greet every reviewer.+ SYSTEM_SETUPCOMPLETED: "true"SECURITY_ENABLELOGIN: "true"SECURITY_INITIALLOGIN_USERNAME: "${TEST_LOGIN_USERNAME}"SECURITY_INITIALLOGIN_PASSWORD: "${TEST_LOGIN_PASSWORD}"diff --git a/.github/workflows/build-enterprise.yml b/.github/workflows/build-enterprise.ymlindex 521937f2d5..451fef111c 100644--- a/.github/workflows/build-enterprise.yml+++ b/.github/workflows/build-enterprise.yml@@ -164,6 +164,8 @@ jobs:exit 1- name: Boot Stirling-PDF (frontend baked in, OAuth env)env:+ # A fresh server signs in as the default admin and hides the SSO buttons.+ SYSTEM_SETUPCOMPLETED: "true"SECURITY_ENABLELOGIN: "true"SECURITY_LOGINMETHOD: "all"SECURITY_OAUTH2_ENABLED: "true"@@ -231,6 +233,8 @@ jobs:echo "✓ SAML certs prepared"- name: Boot Stirling-PDF (frontend baked in, SAML env)env:+ # A fresh server signs in as the default admin and hides the SSO buttons.+ SYSTEM_SETUPCOMPLETED: "true"SECURITY_ENABLELOGIN: "true"SECURITY_LOGINMETHOD: "all"SECURITY_SAML2_ENABLED: "true"diff --git a/.taskfiles/e2e.yml b/.taskfiles/e2e.ymlindex eb8e12aca6..fa619c5553 100644--- a/.taskfiles/e2e.yml+++ b/.taskfiles/e2e.yml@@ -57,17 +57,10 @@ tasks:# Off by default to keep local dev runs uninstrumented; CI flips it.env:STIRLING_BASE_PATH: '{{.BASE_DIR}}'- # Suppress the analytics opt-in modal that fires on first admin login.- # It renders a Mantine overlay that intercepts pointer events and blocks- # FirstLoginSlide from rendering, so the bootstrap spec times out waiting- # for the password-change prompt.+ # Otherwise the analytics opt-in modal covers every admin page and live specs time out.SYSTEM_ENABLEANALYTICS: "false"- # NOTE: SECURITY_INITIALLOGIN_USERNAME/PASSWORD are intentionally NOT set.- # The live-setup project's bootstrap spec performs the real first-login- # flow against the backend's default admin/stirling user, exercising the- # forced-password-change UI and leaving the DB at admin/adminadmin for- # the rest of the live suite. This is both real coverage of the first-- # login flow and a stronger seed than env-var-driven user creation.+ # INITIALLOGIN is left unset on purpose: the live-setup bootstrap runs real first-run setup+ # on admin/stirling and leaves admin/adminadmin for the rest of the suite.cmds:# Wrapped in `bash -c` because Task's embedded shell (mvdan/sh) doesn't# support `&` + `$!` + `wait` reliably (gradle was never actuallydiff --git a/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java b/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.javaindex 13d5410630..cadf4d7968 100644--- a/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java+++ b/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java@@ -82,10 +82,13 @@ public class ConfigInitializer {migrateProFeaturesKeyCasing(settingsFile, settingsTemplateFile);boolean ssoAutoLoginMigrated =migrateSsoAutoLoginToSecurity(settingsFile, settingsTemplateFile);+ boolean setupCompletedMigrated =+ markExistingServerSetUp(settingsFile, settingsTemplateFile);boolean changesMade =settingsTemplateFile.updateValuesFromYaml(settingsFile, settingsTemplateFile)- || ssoAutoLoginMigrated;+ || ssoAutoLoginMigrated+ || setupCompletedMigrated;if (changesMade) {settingsTemplateFile.save(destPath);log.info("Settings file updated based on template changes.");@@ -171,4 +174,12 @@ public class ConfigInitializer {}return false;}++ /** A settings file from before the wizard lacks setupCompleted: that server is set up. */+ boolean markExistingServerSetUp(YamlHelper yaml, YamlHelper template) {+ if (yaml.getValueByExactKeyPath("system", "setupCompleted") != null) {+ return false;+ }+ return template.updateValue(List.of("system", "setupCompleted"), true);+ }}diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex e241399bc2..a7b110491c 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -1329,6 +1329,8 @@ public class ApplicationProperties {private String tessdataDir;private boolean enableAlphaFunctionality;private Boolean enableAnalytics;+ // True when absent: older and read-only settings files belong to servers already set up.+ private boolean setupCompleted = true;private Boolean enablePosthog;private Boolean enableScarf;private Boolean enableDesktopInstallSlide = true;diff --git a/app/common/src/test/java/stirling/software/common/configuration/ConfigInitializerTest.java b/app/common/src/test/java/stirling/software/common/configuration/ConfigInitializerTest.javaindex 775c1f7c6b..371b552f09 100644--- a/app/common/src/test/java/stirling/software/common/configuration/ConfigInitializerTest.java+++ b/app/common/src/test/java/stirling/software/common/configuration/ConfigInitializerTest.java@@ -87,4 +87,46 @@ class ConfigInitializerTest {template.getValueByExactKeyPath("premium", "proFeatures", "customMetadata", "author"));}++ private static final String SETUP_TEMPLATE =+ """+ system:+ setupCompleted: false+ defaultLocale: ""+ """;++ @Test+ void markExistingServerSetUp_upgradedSettingsMergeAsSetUp() {+ YamlHelper template = new YamlHelper(LOAD_SETTINGS, SETUP_TEMPLATE);+ YamlHelper existing =+ new YamlHelper(+ LOAD_SETTINGS,+ """+ system:+ defaultLocale: de-DE+ """);++ assertTrue(new ConfigInitializer().markExistingServerSetUp(existing, template));+ template.updateValuesFromYaml(existing, template);++ assertEquals("true", template.getValueByExactKeyPath("system", "setupCompleted"));+ assertEquals("de-DE", template.getValueByExactKeyPath("system", "defaultLocale"));+ }++ @Test+ void markExistingServerSetUp_keepsAnUnfinishedSetup() {+ YamlHelper template = new YamlHelper(LOAD_SETTINGS, SETUP_TEMPLATE);+ YamlHelper existing =+ new YamlHelper(+ LOAD_SETTINGS,+ """+ system:+ setupCompleted: false+ """);++ assertFalse(new ConfigInitializer().markExistingServerSetUp(existing, template));+ template.updateValuesFromYaml(existing, template);++ assertEquals("false", template.getValueByExactKeyPath("system", "setupCompleted"));+ }}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.javaindex 3d86667b65..31e09834f4 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java@@ -312,6 +312,7 @@ public class ConfigController {// Check if this is a new server (version was 0.0.0 before initialization)configData.put("isNewServer", InitialSetup.isNewServer());+ configData.put("setupCompleted", applicationProperties.getSystem().isSetupCompleted());// Check if the current user is a first-time userboolean isNewUser =diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex ee78cd760e..63d337527e 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -181,6 +181,7 @@ system:customHTMLFiles: false # enable to have files placed in /customFiles/templates override the existing template HTML filestessdataDir: "" # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored.enableAnalytics: null # Master toggle for analytics: set to 'true' to enable all analytics, 'false' to disable all analytics, or leave as 'null' to prompt admin on first launch+ setupCompleted: false # 'true' once an admin has finished or skipped the first-run setup wizard. An existing settings file without this key is marked 'true' on upgrade, so the wizard only appears on new serversenableDesktopInstallSlide: true # Set to 'false' to hide the desktop app installation slide in the onboarding flowenableEasterEggs: true # Set to 'false' to remove the app's hidden novelty featuresenableFeedback: true # Set to 'false' to disable ability to send feedback to Stirling from the appdiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.javaindex 06354d66cb..6a8d3d0cf3 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java@@ -188,6 +188,8 @@ public class ProprietaryUIDataController {data.setFirstTimeSetup(isFirstTimeSetup);data.setShowDefaultCredentials(showDefaultCredentials);+ data.setDefaultSignIn(+ showDefaultCredentials && !applicationProperties.getSystem().isSetupCompleted());OAUTH2 oauth = securityProps.getOauth2();@@ -662,6 +664,10 @@ public class ProprietaryUIDataController {private boolean altLogin;private boolean firstTimeSetup;private boolean showDefaultCredentials;++ /** Login may sign in as the default admin: only before setup, while that login works. */+ private boolean defaultSignIn;+private List<String> languages;private String defaultLocale;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/mcp/security/LazyIssuerJwtDecoder.java b/app/proprietary/src/main/java/stirling/software/proprietary/mcp/security/LazyIssuerJwtDecoder.javanew file mode 100644index 0000000000..e0ccc6b8be--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/mcp/security/LazyIssuerJwtDecoder.java@@ -0,0 +1,72 @@+package stirling.software.proprietary.mcp.security;++import java.time.Clock;+import java.time.Duration;+import java.time.Instant;+import java.util.concurrent.locks.ReentrantLock;+import java.util.function.Supplier;++import org.springframework.security.oauth2.jwt.BadJwtException;+import org.springframework.security.oauth2.jwt.Jwt;+import org.springframework.security.oauth2.jwt.JwtDecoder;+import org.springframework.security.oauth2.jwt.JwtException;++import lombok.extern.slf4j.Slf4j;++/** Builds the issuer decoder on first use, so an unreachable issuer stops MCP sign-in, not boot. */+@Slf4j+final class LazyIssuerJwtDecoder implements JwtDecoder {++ static final Duration RETRY_AFTER = Duration.ofSeconds(30);++ private final Supplier<JwtDecoder> build;+ private final Clock clock;+ private final ReentrantLock building = new ReentrantLock();+ private volatile JwtDecoder delegate;+ private volatile Instant retryAt = Instant.MIN;++ LazyIssuerJwtDecoder(Supplier<JwtDecoder> build) {+ this(build, Clock.systemUTC());+ }++ LazyIssuerJwtDecoder(Supplier<JwtDecoder> build, Clock clock) {+ this.build = build;+ this.clock = clock;+ }++ @Override+ public Jwt decode(String token) throws JwtException {+ JwtDecoder ready = delegate;+ return (ready != null ? ready : resolve()).decode(token);+ }++ // Fails as BadJwtException, a 401 (SupplierJwtDecoder's error is a 500). One lookup at a time;+ // requests meanwhile are rejected, not queued, and a failed lookup waits RETRY_AFTER.+ private JwtDecoder resolve() {+ if (!building.tryLock()) {+ throw new BadJwtException("MCP issuer discovery is still in progress");+ }+ try {+ if (delegate != null) {+ return delegate;+ }+ Instant now = clock.instant();+ if (now.isBefore(retryAt)) {+ throw new BadJwtException("MCP issuer is unavailable");+ }+ try {+ delegate = build.get();+ return delegate;+ } catch (RuntimeException e) {+ retryAt = now.plus(RETRY_AFTER);+ log.warn(+ "MCP issuer discovery failed; rejecting tokens for {}s before retrying: {}",+ RETRY_AFTER.toSeconds(),+ e.getMessage());+ throw new BadJwtException("MCP issuer discovery failed", e);+ }+ } finally {+ building.unlock();+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/mcp/security/McpSecurityConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/mcp/security/McpSecurityConfig.javaindex 0380c44f20..e7d7ee7a1a 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/mcp/security/McpSecurityConfig.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/mcp/security/McpSecurityConfig.java@@ -234,6 +234,10 @@ public class McpSecurityConfig {"mcp.auth.issuer-uri is not configured");};}+ return new LazyIssuerJwtDecoder(() -> buildIssuerDecoder(auth));+ }++ private NimbusJwtDecoder buildIssuerDecoder(ApplicationProperties.Mcp.Auth auth) {String jwksUri = auth.getJwksUri();NimbusJwtDecoder decoder =jwksUri.isBlank()diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/InitialSecuritySetup.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/InitialSecuritySetup.javaindex a53c53770c..5c08c05994 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/InitialSecuritySetup.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/InitialSecuritySetup.java@@ -1,5 +1,6 @@package stirling.software.proprietary.security;+import java.io.IOException;import java.sql.SQLException;import java.util.Arrays;import java.util.List;@@ -19,6 +20,7 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.model.enumeration.Role;import stirling.software.common.model.exception.UnsupportedProviderException;+import stirling.software.common.util.GeneralUtils;import stirling.software.proprietary.model.Team;import stirling.software.proprietary.security.model.User;import stirling.software.proprietary.security.service.DatabaseServiceInterface;@@ -103,6 +105,7 @@ public class InitialSecuritySetup {configureJWTSettings();initializeInternalApiUser();+ markProvisionedServerSetUp();if (isSaas()) {log.info("SaaS profile active - skipping self-host user-table bootstrap"@@ -113,6 +116,22 @@ public class InitialSecuritySetup {}}+ // An admin with their own password means the server was set up some other way (initialLogin, or+ // a database that outlived settings.yml). In memory first, so a read-only file still counts.+ private void markProvisionedServerSetUp() {+ if (applicationProperties.getSystem().isSetupCompleted()+ || !userService.hasAdminPastFirstLogin()) {+ return;+ }+ applicationProperties.getSystem().setSetupCompleted(true);+ log.info("An admin already has their own password; first-run setup is not needed.");+ try {+ GeneralUtils.saveKeyToSettings("system.setupCompleted", true);+ } catch (IOException e) {+ log.debug("Could not record setup as complete in the settings file", e);+ }+ }+private void initializeUserLicenseSettings() {licenseSettingsService.initializeGrandfatheredCount();licenseSettingsService.updateLicenseMaxUsers();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminSettingsController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminSettingsController.javaindex c8997b2301..5e75bfd5b7 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminSettingsController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminSettingsController.java@@ -46,6 +46,7 @@ import stirling.software.common.util.RegexPatternUtils;import stirling.software.proprietary.security.model.api.admin.SettingValueResponse;import stirling.software.proprietary.security.model.api.admin.UpdateSettingValueRequest;import stirling.software.proprietary.security.model.api.admin.UpdateSettingsRequest;+import stirling.software.proprietary.security.service.IssuerDiscoveryProbe;import stirling.software.proprietary.service.AiEngineConfigSync;import tools.jackson.core.type.TypeReference;@@ -61,6 +62,7 @@ public class AdminSettingsController {private final ObjectMapper objectMapper;private final ApplicationContext applicationContext;private final AiEngineConfigSync aiEngineConfigSync;+ private final IssuerDiscoveryProbe issuerDiscoveryProbe;// Track settings that have been modified but not yet applied (require restart)private static final ConcurrentHashMap<String, Object> pendingChanges =@@ -531,6 +533,63 @@ public class AdminSettingsController {}}+ @PostMapping("/check-issuer")+ @Operation(+ summary = "Check an OpenID Connect issuer answers discovery",+ description =+ "Fetches <issuer>/.well-known/openid-configuration so a mistyped or"+ + " unreachable issuer is caught before it is saved. Admin access"+ + " required.")+ @ApiResponses(+ value = {+ @ApiResponse(responseCode = "200", description = "Check completed"),+ @ApiResponse(+ responseCode = "403",+ description = "Access denied - Admin role required")+ })+ public ResponseEntity<Map<String, Object>> checkIssuer(+ @RequestBody Map<String, String> request) {+ String issuer = request.get("issuer");+ return ResponseEntity.ok(+ Map.of("reachable", issuerDiscoveryProbe.answersDiscovery(issuer)));+ }++ @PostMapping("/setup-complete")+ @Operation(+ summary = "Mark first-run setup as complete",+ description =+ "Records that an admin has finished the first-run setup wizard, so it is not"+ + " shown again. Applies immediately, without a restart. Admin access"+ + " required. The response says whether it also reached the settings"+ + " file; when it did not, setup is complete until the next restart.")+ @ApiResponses(+ value = {+ @ApiResponse(responseCode = "200", description = "Setup marked complete"),+ @ApiResponse(+ responseCode = "403",+ description = "Access denied - Admin role required")+ })+ public ResponseEntity<Map<String, Object>> completeSetup() {+ // In memory first: the wizard must not come back because the settings file is+ // read-only or the follow-up restart fails. The file only decides the next boot.+ applicationProperties.getSystem().setSetupCompleted(true);+ try {+ GeneralUtils.saveKeyToSettings("system.setupCompleted", true);+ } catch (IOException e) {+ log.warn(+ "Setup is complete for this run but could not be recorded in the settings"+ + " file: {}",+ e.getMessage());+ return ResponseEntity.ok(+ Map.of(+ "message",+ "Setup marked complete until the next restart.",+ "persisted",+ false));+ }+ return ResponseEntity.ok(Map.of("message", "Setup marked complete.", "persisted", true));+ }+@PostMapping("/restart")@Operation(summary = "Restart the application",diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.javaindex 5688cd8a85..9d50795260 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java@@ -336,6 +336,11 @@ public class UserController {.body(Map.of("error", "incorrectPassword", "message", "Incorrect password"));}userService.changePassword(user, newPassword);+ // The login page signs in with the default login until first login ends; left set, every+ // visit would count a failed attempt until this account locked.+ if (Boolean.TRUE.equals(user.getIsFirstLogin())) {+ userService.changeFirstUse(user, false);+ }// Logout using Spring's utilitynew SecurityContextLogoutHandler().logout(request, response, null);return ResponseEntity.ok(diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/IssuerDiscoveryProbe.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/IssuerDiscoveryProbe.javanew file mode 100644index 0000000000..bf2b1a18af--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/IssuerDiscoveryProbe.java@@ -0,0 +1,134 @@+package stirling.software.proprietary.security.service;++import java.io.IOException;+import java.io.InputStream;+import java.net.InetAddress;+import java.net.URI;+import java.net.UnknownHostException;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.time.Duration;+import java.util.Locale;+import java.util.Set;++import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.stereotype.Service;++import lombok.extern.slf4j.Slf4j;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;++/** Whether an OpenID Connect issuer answers discovery; setup checks one before saving it. */+@Service+@Slf4j+public class IssuerDiscoveryProbe {++ private static final Duration TIMEOUT = Duration.ofSeconds(5);+ private static final String DISCOVERY_PATH = "/.well-known/openid-configuration";+ private static final int MAX_DOCUMENT_BYTES = 256 * 1024; // real documents are a few KB+ private static final Set<InetAddress> METADATA_ADDRESSES = metadataAddresses();++ private final HttpClient httpClient;+ private final ObjectMapper objectMapper;++ @Autowired+ public IssuerDiscoveryProbe(ObjectMapper objectMapper) {+ this(+ HttpClient.newBuilder()+ .connectTimeout(TIMEOUT)+ .followRedirects(HttpClient.Redirect.NEVER)+ .build(),+ objectMapper);+ }++ IssuerDiscoveryProbe(HttpClient httpClient, ObjectMapper objectMapper) {+ this.httpClient = httpClient;+ this.objectMapper = objectMapper;+ }++ /** True when the issuer's discovery document names it exactly, as Spring does. Never throws. */+ public boolean answersDiscovery(String issuer) {+ if (issuer == null) {+ return false;+ }+ String expectedIssuer = issuer.trim();+ URI discovery;+ try {+ URI base = URI.create(withoutTrailingSlashes(expectedIssuer));+ String scheme =+ base.getScheme() == null ? "" : base.getScheme().toLowerCase(Locale.ROOT);+ if (!scheme.equals("http") && !scheme.equals("https") || base.getHost() == null) {+ return false;+ }+ if (resolvesToRefusedAddress(base.getHost())) {+ return false;+ }+ discovery = URI.create(base + DISCOVERY_PATH);+ } catch (IllegalArgumentException | UnknownHostException e) {+ return false;+ }+ try {+ HttpResponse<InputStream> response =+ httpClient.send(+ HttpRequest.newBuilder(discovery).timeout(TIMEOUT).GET().build(),+ HttpResponse.BodyHandlers.ofInputStream());+ try (InputStream body = response.body()) {+ if (response.statusCode() != 200) {+ return false;+ }+ byte[] document = body.readNBytes(MAX_DOCUMENT_BYTES + 1);+ if (document.length > MAX_DOCUMENT_BYTES) {+ log.debug("Issuer discovery document too large for {}", discovery);+ return false;+ }+ JsonNode advertisedIssuer = objectMapper.readTree(document).get("issuer");+ return advertisedIssuer != null+ && advertisedIssuer.isString()+ && expectedIssuer.equals(advertisedIssuer.stringValue());+ }+ } catch (IOException e) {+ log.debug("Issuer discovery failed for {}: {}", discovery, e.getMessage());+ return false;+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return false;+ } catch (RuntimeException e) {+ log.debug("Issuer discovery returned an unreadable document for {}", discovery);+ return false;+ }+ }++ // A loop rather than replaceAll("/+$"), which backtracks on long runs of slashes.+ private static String withoutTrailingSlashes(String value) {+ int end = value.length();+ while (end > 0 && value.charAt(end - 1) == '/') {+ end--;+ }+ return value.substring(0, end);+ }++ private static boolean resolvesToRefusedAddress(String host) throws UnknownHostException {+ for (InetAddress address : InetAddress.getAllByName(host)) {+ if (address.isLinkLocalAddress()+ || address.isAnyLocalAddress()+ || address.isMulticastAddress()+ || METADATA_ADDRESSES.contains(address)) {+ return true;+ }+ }+ return false;+ }++ /** Metadata services that are not link-local, so the address-class checks miss them. */+ private static Set<InetAddress> metadataAddresses() {+ try {+ return Set.of(+ InetAddress.getByName("100.100.100.200"), // Alibaba Cloud+ InetAddress.getByName("fd00:ec2::254")); // AWS IMDS over IPv6+ } catch (UnknownHostException e) {+ throw new IllegalStateException("IP literals do not resolve", e);+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.javaindex 08f6148be4..078dbac03b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java@@ -372,6 +372,12 @@ public class UserService implements UserServiceInterface {return userRepository.existsByUsernameIgnoreCaseAndIdNot(username, userId);}+ /** True when an enabled admin is not waiting on a first-login password change. */+ public boolean hasAdminPastFirstLogin() {+ return userRepository.findEnabledAdminsByIdAsc().stream()+ .anyMatch(user -> !user.isFirstLogin());+ }+public boolean hasUsers() {long userCount = userRepository.count();if (findByUsernameIgnoreCase(Role.INTERNAL_API_USER.getRoleId()).isPresent()) {diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerMoreTest.javaindex 46ac79c33c..a4fedf3502 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerMoreTest.java@@ -148,6 +148,7 @@ class ProprietaryUIDataControllerMoreTest {void singleAdminFirstLogin() {User admin = normalUser(1L, "admin");admin.setFirstLogin(true);+ applicationProperties.getSystem().setSetupCompleted(false);when(userRepository.countByUsernameNot(Role.INTERNAL_API_USER.getRoleId())).thenReturn(1L);when(userRepository.findByUsernameIgnoreCase("admin")).thenReturn(Optional.of(admin));@@ -157,6 +158,38 @@ class ProprietaryUIDataControllerMoreTest {LoginData data = response.getBody();assertThat(data.isFirstTimeSetup()).isTrue();assertThat(data.isShowDefaultCredentials()).isTrue();+ assertThat(data.isDefaultSignIn()).isTrue();+ }++ @Test+ @DisplayName("never signs in by itself once setup is complete")+ void noDefaultSignInAfterSetup() {+ User admin = normalUser(1L, "admin");+ admin.setFirstLogin(true);+ applicationProperties.getSystem().setSetupCompleted(true);+ when(userRepository.countByUsernameNot(Role.INTERNAL_API_USER.getRoleId()))+ .thenReturn(1L);+ when(userRepository.findByUsernameIgnoreCase("admin")).thenReturn(Optional.of(admin));++ LoginData data = controller.getLoginData().getBody();++ assertThat(data.isShowDefaultCredentials()).isTrue();+ assertThat(data.isDefaultSignIn()).isFalse();+ }++ @Test+ @DisplayName("never signs in by itself once the admin has set a password")+ void noDefaultSignInAfterPasswordSet() {+ User admin = normalUser(1L, "admin");+ admin.setFirstLogin(false);+ when(userRepository.countByUsernameNot(Role.INTERNAL_API_USER.getRoleId()))+ .thenReturn(1L);+ when(userRepository.findByUsernameIgnoreCase("admin")).thenReturn(Optional.of(admin));++ LoginData data = controller.getLoginData().getBody();++ assertThat(data.isShowDefaultCredentials()).isFalse();+ assertThat(data.isDefaultSignIn()).isFalse();}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/mcp/security/LazyIssuerJwtDecoderTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/mcp/security/LazyIssuerJwtDecoderTest.javanew file mode 100644index 0000000000..eb6dcac2b4--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/mcp/security/LazyIssuerJwtDecoderTest.java@@ -0,0 +1,100 @@+package stirling.software.proprietary.mcp.security;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.time.Clock;+import java.time.Instant;+import java.time.ZoneId;+import java.time.ZoneOffset;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.function.Supplier;++import org.junit.jupiter.api.Test;+import org.springframework.security.oauth2.jwt.BadJwtException;+import org.springframework.security.oauth2.jwt.Jwt;+import org.springframework.security.oauth2.jwt.JwtDecoder;++class LazyIssuerJwtDecoderTest {++ private final SettableClock clock = new SettableClock(Instant.parse("2026-01-01T00:00:00Z"));+ private final AtomicInteger attempts = new AtomicInteger();++ private Supplier<JwtDecoder> failing() {+ return () -> {+ attempts.incrementAndGet();+ throw new IllegalStateException("issuer down");+ };+ }++ @Test+ void aFailedDiscoveryRejectsTheTokenAsBad() {+ LazyIssuerJwtDecoder decoder = new LazyIssuerJwtDecoder(failing(), clock);++ assertThatThrownBy(() -> decoder.decode("a.b.c"))+ .isInstanceOf(BadJwtException.class)+ .hasCauseInstanceOf(IllegalStateException.class);+ }++ @Test+ void aFailedDiscoveryIsNotRetriedUntilTheCooldownPasses() {+ LazyIssuerJwtDecoder decoder = new LazyIssuerJwtDecoder(failing(), clock);++ assertThatThrownBy(() -> decoder.decode("a.b.c")).isInstanceOf(BadJwtException.class);+ assertThatThrownBy(() -> decoder.decode("a.b.c")).isInstanceOf(BadJwtException.class);+ assertThat(attempts).hasValue(1);++ clock.advance(LazyIssuerJwtDecoder.RETRY_AFTER);+ assertThatThrownBy(() -> decoder.decode("a.b.c")).isInstanceOf(BadJwtException.class);+ assertThat(attempts).hasValue(2);+ }++ @Test+ void aSuccessfulDiscoveryIsBuiltOnceAndThenDecodes() {+ JwtDecoder delegate = mock(JwtDecoder.class);+ Jwt jwt = mock(Jwt.class);+ when(delegate.decode("a.b.c")).thenReturn(jwt);+ LazyIssuerJwtDecoder decoder =+ new LazyIssuerJwtDecoder(+ () -> {+ attempts.incrementAndGet();+ return delegate;+ },+ clock);++ assertThat(decoder.decode("a.b.c")).isSameAs(jwt);+ assertThat(decoder.decode("a.b.c")).isSameAs(jwt);+ assertThat(attempts).hasValue(1);+ }+}++/** A clock the test moves by hand. */+class SettableClock extends Clock {++ private Instant now;++ SettableClock(Instant now) {+ this.now = now;+ }++ void advance(java.time.Duration by) {+ now = now.plus(by);+ }++ @Override+ public ZoneId getZone() {+ return ZoneOffset.UTC;+ }++ @Override+ public Clock withZone(ZoneId zone) {+ return this;+ }++ @Override+ public Instant instant() {+ return now;+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/mcp/security/McpJwtDecoderTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/mcp/security/McpJwtDecoderTest.javanew file mode 100644index 0000000000..1aa930f406--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/mcp/security/McpJwtDecoderTest.java@@ -0,0 +1,40 @@+package stirling.software.proprietary.mcp.security;++import static org.assertj.core.api.Assertions.assertThatCode;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.Mockito.mock;++import org.junit.jupiter.api.Test;+import org.springframework.beans.factory.ObjectProvider;+import org.springframework.security.oauth2.jwt.BadJwtException;+import org.springframework.security.oauth2.jwt.JwtDecoder;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.service.UserService;++class McpJwtDecoderTest {++ @SuppressWarnings("unchecked")+ private JwtDecoder decoderFor(String issuerUri) {+ ApplicationProperties properties = new ApplicationProperties();+ properties.getMcp().getAuth().setIssuerUri(issuerUri);+ McpSecurityConfig config =+ new McpSecurityConfig(+ properties, mock(UserService.class), mock(ObjectProvider.class));+ return config.mcpJwtDecoder();+ }++ @Test+ void anUnreachableIssuerDoesNotStopStartup() {+ // Port 1 refuses connections, so discovery would fail if it ran eagerly.+ assertThatCode(() -> decoderFor("http://127.0.0.1:1/issuer")).doesNotThrowAnyException();+ }++ @Test+ void anUnreachableIssuerRejectsTokensInstead() {+ JwtDecoder decoder = decoderFor("http://127.0.0.1:1/issuer");++ // BadJwtException is what the resource server answers with a 401.+ assertThatThrownBy(() -> decoder.decode("a.b.c")).isInstanceOf(BadJwtException.class);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/InitialSecuritySetupTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/InitialSecuritySetupTest.javaindex 61575e9891..d54427a035 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/InitialSecuritySetupTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/InitialSecuritySetupTest.java@@ -1,13 +1,17 @@package stirling.software.proprietary.security;import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mockStatic;import static org.mockito.Mockito.never;import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.io.IOException;import java.sql.SQLException;import java.util.Collections;import java.util.Optional;@@ -17,6 +21,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.ArgumentCaptor;import org.mockito.Mock;+import org.mockito.MockedStatic;import org.mockito.junit.jupiter.MockitoExtension;import org.springframework.core.env.Environment;import org.springframework.dao.DataIntegrityViolationException;@@ -25,6 +30,7 @@ import org.springframework.test.util.ReflectionTestUtils;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.model.enumeration.Role;import stirling.software.common.model.exception.UnsupportedProviderException;+import stirling.software.common.util.GeneralUtils;import stirling.software.proprietary.model.Team;import stirling.software.proprietary.security.model.User;import stirling.software.proprietary.security.service.DatabaseServiceInterface;@@ -143,4 +149,38 @@ class InitialSecuritySetupTest {assertThat(applicationProperties.getSecurity().getJwt().isEnableKeyCleanup()).isFalse();}++ /** An existing server's startup, as far as the setup check, with the admin stubbed in. */+ private void startExistingServer(boolean adminPastFirstLogin) {+ applicationProperties.getSystem().setSetupCompleted(false);+ when(userService.hasUsers()).thenReturn(true);+ when(userService.getUsersWithoutTeam()).thenReturn(Collections.emptyList());+ when(userService.usernameExistsIgnoreCase(Role.INTERNAL_API_USER.getRoleId()))+ .thenReturn(true);+ when(userService.hasAdminPastFirstLogin()).thenReturn(adminPastFirstLogin);+ }++ @Test+ void initMarksAServerWhoseAdminHasTheirOwnPasswordAsSetUp() {+ startExistingServer(true);+ try (MockedStatic<GeneralUtils> settings = mockStatic(GeneralUtils.class)) {+ settings.when(() -> GeneralUtils.saveKeyToSettings("system.setupCompleted", true))+ .thenThrow(new IOException("read-only file system"));++ initialSecuritySetup.init();++ assertTrue(applicationProperties.getSystem().isSetupCompleted());+ }+ }++ @Test+ void initLeavesANewServerToFirstRunSetup() {+ startExistingServer(false);+ try (MockedStatic<GeneralUtils> settings = mockStatic(GeneralUtils.class)) {+ initialSecuritySetup.init();++ assertFalse(applicationProperties.getSystem().isSetupCompleted());+ settings.verifyNoInteractions();+ }+ }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminSettingsControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminSettingsControllerTest.javaindex 6c618b1729..8f2d41e7f1 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminSettingsControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminSettingsControllerTest.java@@ -31,6 +31,7 @@ import stirling.software.common.util.GeneralUtils;import stirling.software.proprietary.security.model.api.admin.SettingValueResponse;import stirling.software.proprietary.security.model.api.admin.UpdateSettingValueRequest;import stirling.software.proprietary.security.model.api.admin.UpdateSettingsRequest;+import stirling.software.proprietary.security.service.IssuerDiscoveryProbe;import stirling.software.proprietary.service.AiEngineConfigSync;import tools.jackson.databind.ObjectMapper;@@ -44,6 +45,7 @@ class AdminSettingsControllerTest {private ObjectMapper objectMapper;private ApplicationContext applicationContext;private AiEngineConfigSync aiEngineConfigSync;+ private IssuerDiscoveryProbe issuerDiscoveryProbe;private AdminSettingsController controller;@@ -53,12 +55,14 @@ class AdminSettingsControllerTest {objectMapper = JsonMapper.builder().build();applicationContext = org.mockito.Mockito.mock(ApplicationContext.class);aiEngineConfigSync = org.mockito.Mockito.mock(AiEngineConfigSync.class);+ issuerDiscoveryProbe = org.mockito.Mockito.mock(IssuerDiscoveryProbe.class);controller =new AdminSettingsController(applicationProperties,objectMapper,applicationContext,- aiEngineConfigSync);+ aiEngineConfigSync,+ issuerDiscoveryProbe);clearPendingChanges();}@@ -729,4 +733,57 @@ class AdminSettingsControllerTest {}}}++ @Nested+ @DisplayName("POST /setup-complete")+ class CompleteSetup {++ @Test+ @DisplayName("persists the flag and applies it without a restart")+ void marksComplete() {+ applicationProperties.getSystem().setSetupCompleted(false);+ try (MockedStatic<GeneralUtils> mocked = mockStatic(GeneralUtils.class)) {+ ResponseEntity<Map<String, Object>> response = controller.completeSetup();++ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);+ assertThat(response.getBody()).containsEntry("persisted", true);+ assertThat(applicationProperties.getSystem().isSetupCompleted()).isTrue();+ mocked.verify(() -> GeneralUtils.saveKeyToSettings("system.setupCompleted", true));+ }+ }++ @Test+ @DisplayName("applies the flag in memory even when the settings file cannot be written")+ void saveFails() {+ applicationProperties.getSystem().setSetupCompleted(false);+ try (MockedStatic<GeneralUtils> mocked = mockStatic(GeneralUtils.class)) {+ mocked.when(() -> GeneralUtils.saveKeyToSettings("system.setupCompleted", true))+ .thenThrow(new IOException("read-only file system"));++ ResponseEntity<Map<String, Object>> response = controller.completeSetup();++ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);+ assertThat(response.getBody()).containsEntry("persisted", false);+ assertThat(applicationProperties.getSystem().isSetupCompleted()).isTrue();+ }+ }+ }++ @Nested+ @DisplayName("POST /check-issuer")+ class CheckIssuer {++ @Test+ @DisplayName("reports whether the issuer answers discovery")+ void reportsReachability() {+ org.mockito.Mockito.when(+ issuerDiscoveryProbe.answersDiscovery("https://id.example.com"))+ .thenReturn(true);++ ResponseEntity<Map<String, Object>> response =+ controller.checkIssuer(Map.of("issuer", "https://id.example.com"));++ assertThat(response.getBody()).containsEntry("reachable", true);+ }+ }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.javaindex 6838ff683a..6881baa88e 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java@@ -163,6 +163,26 @@ class UserControllerTest {.andExpect(jsonPath("$.error").value("User not found."));}+ @Test+ void changingThePasswordEndsTheFirstLogin() throws Exception {+ User admin = new User();+ admin.setUsername("admin");+ admin.setFirstLogin(true);+ Authentication authentication = new UsernamePasswordAuthenticationToken("admin", "pw");+ when(userService.findByUsernameIgnoreCase("admin")).thenReturn(Optional.of(admin));+ when(userService.isPasswordCorrect(admin, "stirling")).thenReturn(true);++ mockMvc.perform(+ post("/api/v1/user/change-password")+ .param("currentPassword", "stirling")+ .param("newPassword", "a-new-pass")+ .principal(authentication))+ .andExpect(status().isOk());++ verify(userService).changePassword(admin, "a-new-pass");+ verify(userService).changeFirstUse(admin, false);+ }+@Testvoid updateLoginLandingViewStoresTheOptIn() throws Exception {UpdateLoginLandingView payload = new UpdateLoginLandingView();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/IssuerDiscoveryProbeTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/IssuerDiscoveryProbeTest.javanew file mode 100644index 0000000000..2bfb433c5d--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/IssuerDiscoveryProbeTest.java@@ -0,0 +1,157 @@+package stirling.software.proprietary.security.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verifyNoInteractions;++import java.io.IOException;+import java.io.OutputStream;+import java.net.InetSocketAddress;+import java.net.http.HttpClient;+import java.nio.charset.StandardCharsets;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import com.sun.net.httpserver.HttpServer;++import tools.jackson.databind.json.JsonMapper;++class IssuerDiscoveryProbeTest {++ private HttpServer server;+ private String base;+ private final IssuerDiscoveryProbe probe =+ new IssuerDiscoveryProbe(JsonMapper.builder().build());++ @BeforeEach+ void startServer() throws IOException {+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ server.createContext(+ "/good/.well-known/openid-configuration",+ exchange -> respond(exchange, 200, "{\"issuer\":\"" + base + "/good\"}"));+ server.createContext(+ "/elsewhere/.well-known/openid-configuration",+ exchange -> respond(exchange, 200, "{\"issuer\":\"" + base + "/good\"}"));+ server.createContext(+ "/slashed/.well-known/openid-configuration",+ exchange -> respond(exchange, 200, "{\"issuer\":\"" + base + "/slashed/\"}"));+ server.createContext(+ "/huge/.well-known/openid-configuration",+ exchange ->+ respond(+ exchange,+ 200,+ "{\"issuer\":\""+ + base+ + "/huge\",\"pad\":\""+ + "x".repeat(300 * 1024)+ + "\"}"));+ server.createContext(+ "/numeric/.well-known/openid-configuration",+ exchange -> respond(exchange, 200, "{\"issuer\":1}"));+ server.createContext(+ "/empty/.well-known/openid-configuration",+ exchange -> respond(exchange, 200, "{}"));+ server.createContext(+ "/moved/.well-known/openid-configuration",+ exchange -> {+ exchange.getResponseHeaders()+ .add("Location", base + "/good/.well-known/openid-configuration");+ exchange.sendResponseHeaders(302, -1);+ exchange.close();+ });+ server.start();+ base = "http://127.0.0.1:" + server.getAddress().getPort();+ }++ @AfterEach+ void stopServer() {+ server.stop(0);+ }++ private static void respond(+ com.sun.net.httpserver.HttpExchange exchange, int status, String body)+ throws IOException {+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);+ exchange.sendResponseHeaders(status, bytes.length);+ try (OutputStream out = exchange.getResponseBody()) {+ out.write(bytes);+ }+ }++ @Test+ void anIssuerThatAnswersDiscovery() {+ assertThat(probe.answersDiscovery(" " + base + "/good ")).isTrue();+ }++ @Test+ void anIssuerIsMatchedExactly() {+ // Auth0 advertises its issuer with a trailing slash, so one entered with it must pass+ // and one entered without must not: Spring compares them the same way on boot.+ assertThat(probe.answersDiscovery(base + "/slashed/")).isTrue();+ assertThat(probe.answersDiscovery(base + "/slashed")).isFalse();+ assertThat(probe.answersDiscovery(base + "/good/")).isFalse();+ }++ @Test+ void anOversizedDocument() {+ assertThat(probe.answersDiscovery(base + "/huge")).isFalse();+ }++ @Test+ void aDocumentWithoutAnIssuer() {+ assertThat(probe.answersDiscovery(base + "/empty")).isFalse();+ }++ @Test+ void aDocumentNamingAnotherIssuer() {+ assertThat(probe.answersDiscovery(base + "/elsewhere")).isFalse();+ }++ @Test+ void aDocumentWhoseIssuerIsNotText() {+ assertThat(probe.answersDiscovery(base + "/numeric")).isFalse();+ }++ @Test+ void aMissingDiscoveryDocument() {+ assertThat(probe.answersDiscovery(base + "/missing")).isFalse();+ }++ @Test+ void anUnreachableOrInvalidIssuer() {+ assertThat(probe.answersDiscovery("http://127.0.0.1:1/issuer")).isFalse();+ assertThat(probe.answersDiscovery("ftp://example.com")).isFalse();+ assertThat(probe.answersDiscovery("not a url")).isFalse();+ }++ @Test+ void anIssuerWithManyTrailingSlashesIsAnsweredPromptly() {+ assertThat(probe.answersDiscovery(base + "/good" + "/".repeat(10_000))).isFalse();+ }++ @Test+ void noIssuerAtAll() {+ assertThat(probe.answersDiscovery(null)).isFalse();+ }++ @Test+ void aMetadataServiceIsNeverRequested() {+ HttpClient client = mock(HttpClient.class);+ IssuerDiscoveryProbe guarded =+ new IssuerDiscoveryProbe(client, JsonMapper.builder().build());++ assertThat(guarded.answersDiscovery("http://169.254.169.254/latest")).isFalse();+ assertThat(guarded.answersDiscovery("http://[fe80::1]/issuer")).isFalse();+ assertThat(guarded.answersDiscovery("http://100.100.100.200/latest")).isFalse();+ assertThat(guarded.answersDiscovery("http://[fd00:ec2::254]/latest")).isFalse();+ verifyNoInteractions(client);+ }++ @Test+ void aRedirectIsNotFollowed() {+ assertThat(probe.answersDiscovery(base + "/moved")).isFalse();+ }+}diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 8f3f81a622..4030005db2 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -12125,6 +12125,162 @@ showTools = "View unavailable tools ▾"title = "Your Stirling-PDF server is unreachable"toolNotAvailableLocally = "Your Stirling-PDF server is offline and \"{{endpoint}}\" is not available on the local backend."+[serverSetup]+back = "Back"+collapse = "Hide {{setting}} settings"+configured = "Configured"+continue = "Continue"+dialogLabel = "Server setup"+expand = "Show {{setting}} settings"+finishSetup = "Finish setup"+loadErrorSubtitle = "Setup needs the server's current settings to start."+loadErrorTitle = "Couldn't load your settings"+off = "Off"+on = "On"+save = "Save"+stepCount = "{{current}} of {{total}}"++[serverSetup.account]+failed = "Couldn't save your details. Check the server is reachable and try again."+save = "Save and continue"+signIn = "Sign in"+signInAgainSubtitle = "Sign in again with your new username and password to carry on."+signInAgainTitle = "Your details are saved"+subtitle = "Choose how you'll sign in from now on."+title = "Set up your account"+updating = "Updating"+updatingSubtitle = "One moment."+updatingTitle = "Updating your details"+username = "Username"+usernameHelp = "What you'll sign in with. An email address works too."++[serverSetup.addresses]+backendUrl = "Server address"+backendUrlHelp = "Where sign-in providers send people back. Usually the same as the web address."+frontendUrl = "Web address"+frontendUrlHelp = "Where people open Stirling PDF. Used in emails, share links and QR codes."+subtitle = "How people and sign-in providers reach this server."+title = "Addresses"++[serverSetup.ai]+apiKey = "API key"+apiKeyHelp = "Leave empty to use the key the AI engine already has."+baseUrl = "Base URL"+engineUrl = "AI engine address"+fastModel = "Fast model"+label = "Self-hosted AI"+provider = "Model provider"+providerCustom = "OpenAI-compatible"+smartModel = "Full model"+stirling = "Stirling AI"+subtitle = "Document questions, automated edits and AI agents."+title = "AI"++[serverSetup.analytics]+accept = "Accept and continue"+acceptFinish = "Accept and finish"+changeLater = "You can change this at any time in {{path}}."+decline = "Decline and continue"+declineFinish = "Decline and finish"+learnMore = "What we collect"+note = "Share usage data from this server with us to help us improve Stirling PDF. We never collect files or their contents."+title = "Server analytics"++[serverSetup.documents]+label = "Document questions"+model = "Embedding model"+provider = "Embedding provider"+providerHelp = "Turns document text into the search index that answers questions."++[serverSetup.email]+from = "From address"+host = "SMTP host"+label = "Send email"+password = "Password"+port = "Port"+subtitle = "For invites, signing requests and shares."+title = "Email"+username = "Username"++[serverSetup.error]+email = "Enter an email address"+issuerUnreachable = "Couldn't reach this issuer. Check the address, and that this server can reach it."+passwordIncorrect = "Incorrect password"+passwordLength = "Use at least 8 characters"+passwordMismatch = "Passwords don't match"+passwordRejected = "The server didn't accept this password. Try another."+passwordUnchanged = "Choose a password different from the current one"+port = "Enter a port from 1 to 65535"+providerName = "Use letters, numbers, dashes or underscores only"+required = "Required"+url = "Enter a full address, starting with http:// or https://"+username = "Use 3 to 50 letters, numbers or . _ + - @, or an email address"+usernameTaken = "That username is taken"++[serverSetup.files]+sharing = "File sharing"+sharingOffWarning = "With sharing off, existing share links stop working."+storage = "Store files"+storageOffWarning = "With storage off, files people saved on the server can no longer be opened."+subtitle = "Manage file storage and sharing."+title = "Files"++[serverSetup.finish]+errorNote = "Check the server is reachable and that you're still signed in as an admin."+errorSubtitle = "Nothing was restarted."+errorTitle = "Couldn't save your settings"+manualSubtitle = "This server can't restart itself. Restart its container or service to apply them."+manualTitle = "Settings saved"+restartFailedSubtitle = "The server didn't restart. Restart its container or service to apply them."+restartingSubtitle = "This page reloads when it's back, usually within a minute."+restartingTitle = "Restarting your server"+retry = "Try again"+saving = "Saving"+savingSubtitle = "One moment."+savingTitle = "Saving your settings"++[serverSetup.language]+auto = "Match each browser"+label = "Default language"+subtitle = "What new visitors see first."+title = "Language"++[serverSetup.mcp]+label = "MCP server"++[serverSetup.password]+confirm = "Confirm new password"+current = "Current password"+new = "New password"++[serverSetup.signIn]+clientId = "Client ID"+clientSecret = "Client secret"+issuer = "Issuer URL"+label = "Sign in with"+oidc = "Other OpenID Connect"+password = "Username and password"+providerName = "Provider name"+providerNameHelp = "Shown on the sign-in button, for example okta or entra."+redirectNote = "Add this redirect URI in your provider:"+subtitle = "How your team signs in."+title = "Sign-in"++[serverSetup.signingIn]+button = "Signing in"+title = "Signing in with default credentials"++[serverSetup.start]+custom = "Custom"+quick = "Quick start"+setupLabel = "Setup"+subtitle = "Set it up for your team in a few steps."+title = "Your server is up"++[serverSetup.summary]+subtitle = "Check the essentials. Everything else keeps its default."+title = "Quick start"+[session]expired = "Your session has expired. Please refresh the page and try again."diff --git a/frontend/src/editor/core/components/layout/AppRoot.test.tsx b/frontend/src/editor/core/components/layout/AppRoot.test.tsxnew file mode 100644index 0000000000..20fb27068f--- /dev/null+++ b/frontend/src/editor/core/components/layout/AppRoot.test.tsx@@ -0,0 +1,42 @@+import { render, screen } from "@testing-library/react";+import { MemoryRouter } from "react-router-dom";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { AppRoot } from "@editor/components/layout/AppRoot";++const setup = vi.hoisted(() => ({ pending: false }));+vi.mock("@editor/components/startup/ServerSetupGate", () => ({+ useServerSetupPending: () => setup.pending,+}));+vi.mock("@editor/components/startup/StartupPrompts", () => ({+ StartupPrompts: () => <div>Setup</div>,+}));+vi.mock("@editor/pages/HomePage", () => ({ default: () => <div>Editor</div> }));+vi.mock("@editor/hooks/usePdfEngineWarmUp", () => ({+ usePdfEngineWarmUp: () => {},+}));++function renderRoot() {+ render(+ <MemoryRouter>+ <AppRoot />+ </MemoryRouter>,+ );+}++describe("AppRoot", () => {+ beforeEach(() => {+ setup.pending = false;+ });++ it("shows the editor once setup is done", () => {+ renderRoot();+ expect(screen.getByText("Editor")).toBeInTheDocument();+ });++ it("keeps the editor out of the page while setup is pending", () => {+ setup.pending = true;+ renderRoot();+ expect(screen.getByText("Setup")).toBeInTheDocument();+ expect(screen.queryByText("Editor")).toBeNull();+ });+});diff --git a/frontend/src/editor/core/components/layout/AppRoot.tsx b/frontend/src/editor/core/components/layout/AppRoot.tsxindex 258fe9a21e..a9b24d9fc9 100644--- a/frontend/src/editor/core/components/layout/AppRoot.tsx+++ b/frontend/src/editor/core/components/layout/AppRoot.tsx@@ -5,6 +5,7 @@ import { LoadingFallback } from "@editor/components/shared/LoadingFallback";import { stripBasePath } from "@editor/constants/app";import { DOCS_PATH, HAS_DOCS } from "@editor/routes/docsRoute";import { StartupPrompts } from "@editor/components/startup/StartupPrompts";+import { useServerSetupPending } from "@editor/components/startup/ServerSetupGate";import { usePdfEngineWarmUp } from "@editor/hooks/usePdfEngineWarmUp";// Their own chunks: the settings tree (admin sections, account, licence flows)@@ -38,10 +39,13 @@ function AppContent() {/** The editor's authenticated or login-disabled routes, including catch-all entries. */export function AppRoot() {usePdfEngineWarmUp();+ // Unmounted, not just covered: under setup's overlay the editor could still+ // take keyboard focus and be used before the default password is replaced.+ const setupPending = useServerSetupPending();return (<><StartupPrompts />- <AppContent />+ {!setupPending && <AppContent />}</>);}diff --git a/frontend/src/editor/core/components/startup/ServerSetupGate.tsx b/frontend/src/editor/core/components/startup/ServerSetupGate.tsxnew file mode 100644index 0000000000..6332e2c3e0--- /dev/null+++ b/frontend/src/editor/core/components/startup/ServerSetupGate.tsx@@ -0,0 +1,25 @@+import type { ReactNode } from "react";++/** Whether first-run server setup is waiting on the current user. */+export function useServerSetupPending(): boolean {+ return false;+}++export interface ServerSetupGateProps {+ children: ReactNode;+ /** The account must replace its password; setup then opens on that card. */+ passwordChange?: { usingDefaultCredentials: boolean };+ /** Called once setup has set the new password. */+ onPasswordChanged?: () => void;+}++/** Shown while startup checks load; a build whose login hands over to setup+ * keeps that hand-off's screen up. */+export function ServerSetupLoading() {+ return null;+}++/** Shows first-run server setup in place of the app while it is pending. */+export function ServerSetupGate({ children }: ServerSetupGateProps) {+ return <>{children}</>;+}diff --git a/frontend/src/editor/core/components/startup/StartupSetup.tsx b/frontend/src/editor/core/components/startup/StartupSetup.tsxindex 7dc8ee2848..aeef3902d2 100644--- a/frontend/src/editor/core/components/startup/StartupSetup.tsx+++ b/frontend/src/editor/core/components/startup/StartupSetup.tsx@@ -16,6 +16,11 @@ import { DEFAULT_RUNTIME_STATE } from "@editor/components/onboarding/orchestratoimport StaticOnboardingSlide from "@editor/components/onboarding/StaticOnboardingSlide";import { Button } from "@editor/ui/Button";import { Z_INDEX_ONBOARDING_CARD } from "@editor/styles/zIndex";+import {+ ServerSetupGate,+ ServerSetupLoading,+ useServerSetupPending,+} from "@editor/components/startup/ServerSetupGate";function requiresMfaSetup(account: AccountData): boolean {if (account.mfaEnabled) return false;@@ -44,6 +49,8 @@ export function StartupSetup({ children }: { children: ReactNode }) {const [analyticsLoading, setAnalyticsLoading] = useState(false);const [analyticsConfigured, setAnalyticsConfigured] = useState(false);const [mfaCompleted, setMfaCompleted] = useState(false);+ const [passwordChangedInSetup, setPasswordChangedInSetup] = useState(false);+ const serverSetupPending = useServerSetupPending();const loginEnabled = config?.enableLogin === true;const requirements = useQuery({@@ -90,7 +97,9 @@ export function StartupSetup({ children }: { children: ReactNode }) {});};- if (requirements.isPending || requirements.isFetching) return null;+ if (requirements.isPending || requirements.isFetching) {+ return <ServerSetupLoading />;+ }if (requirements.isError) {return (@@ -115,7 +124,9 @@ export function StartupSetup({ children }: { children: ReactNode }) {}const runtimeState = DEFAULT_RUNTIME_STATE;+ // Server setup asks the analytics question itself, after the password change.if (+ !serverSetupPending &&!analyticsConfigured &&effectiveIsAdmin &&config?.enableAnalytics == null@@ -138,7 +149,10 @@ export function StartupSetup({ children }: { children: ReactNode }) {}const { account, login } = requirements.data ?? {};- if (account?.changeCredsFlag) {+ const mustChangePassword =+ account?.changeCredsFlag === true && !passwordChangedInSetup;+ // Server setup ends by setting the password, so it replaces this screen.+ if (mustChangePassword && !serverSetupPending) {return (<StaticOnboardingSlidekey="first-login"@@ -170,5 +184,16 @@ export function StartupSetup({ children }: { children: ReactNode }) {);}- return <>{children}</>;+ return (+ <ServerSetupGate+ passwordChange={+ mustChangePassword+ ? { usingDefaultCredentials: login?.showDefaultCredentials === true }+ : undefined+ }+ onPasswordChanged={() => setPasswordChangedInSetup(true)}+ >+ {children}+ </ServerSetupGate>+ );}diff --git a/frontend/src/editor/core/tests/helpers/login.ts b/frontend/src/editor/core/tests/helpers/login.tsindex 9fc60eaaaf..daefe15dcd 100644--- a/frontend/src/editor/core/tests/helpers/login.ts+++ b/frontend/src/editor/core/tests/helpers/login.ts@@ -34,15 +34,8 @@ export async function skipOnboarding(page: Page): Promise<void> {});}-/**- * Shared login helper for Stirling-PDF E2E tests.- * Logs in with the given credentials and waits for the dashboard to load.- *- * Default credentials are `admin / adminadmin` — set by the live-setup- * bootstrap spec, which performs the real first-login password change from- * the backend's default `admin / stirling` (min 8 chars per- * FirstLoginSlide validation).- */+/** The live suite's admin: the bootstrap spec sets this password on setup's+ * account card, replacing the backend's default admin/stirling. */export const DEFAULT_TEST_USERNAME = "admin";export const DEFAULT_TEST_PASSWORD = "adminadmin";diff --git a/frontend/src/editor/core/tests/live-setup/bootstrap.setup.ts b/frontend/src/editor/core/tests/live-setup/bootstrap.setup.tsindex bbf4aeda05..affd636be8 100644--- a/frontend/src/editor/core/tests/live-setup/bootstrap.setup.ts+++ b/frontend/src/editor/core/tests/live-setup/bootstrap.setup.ts@@ -6,30 +6,12 @@ import {DEFAULT_TEST_PASSWORD,} from "@editor/tests/helpers/login";-/**- * Live-suite bootstrap. Two responsibilities:- *- * 1. **Pristine CI path** — log in as the backend's default- * `admin / stirling` user (created with firstLogin=true), exercise- * the FirstLoginSlide UI, change to `admin / adminadmin`, verify- * the post-change toast. Real coverage of the forced-first-login- * flow.- *- * 2. **Already-seeded path** — for local dev where `admin / adminadmin`- * already exists (e.g. the developer's settings.yml provisions it- * directly), the bootstrap is a no-op pass. We detect this by- * attempting the API login first; if it returns 200 we skip the- * UI flow.- *- * Configured as a Playwright `setup` project; the `live` project- * depends on it so it runs once before every other live spec.- */+/** Runs once before the live suite: sets admin/adminadmin on a fresh server's+ * account card (or reuses a seeded one), then marks setup complete. */-const DEFAULT_BACKEND_PASSWORD = "stirling";--async function adminAdminadminAlreadyExists(+async function signInSeededAdmin(request: import("@playwright/test").APIRequestContext,-): Promise<boolean> {+): Promise<string | null> {const res = await request.post("/api/v1/auth/login", {data: {@@ -38,22 +20,28 @@ async function adminAdminadminAlreadyExists(},}).catch(() => null);- return res?.ok() ?? false;+ if (!res?.ok()) return null;+ const body = await res.json();+ return body?.session?.access_token ?? null;}test.describe("Live-suite bootstrap", () => {- test("first-login: change default admin/stirling to admin/adminadmin", async ({+ test("first-run setup: change default admin/stirling to admin/adminadmin", async ({page,request,}) => {test.setTimeout(60_000);- // Already-seeded local case — skip the UI flow.- if (await adminAdminadminAlreadyExists(request)) {+ const seededToken = await signInSeededAdmin(request);+ if (seededToken) {+ const done = await request.post("/api/v1/admin/settings/setup-complete", {+ headers: { Authorization: `Bearer ${seededToken}` },+ });+ expect(done.ok()).toBeTruthy();test.info().annotations.push({type: "bootstrap",description:- "admin/adminadmin already provisioned (local-dev path); skipping forced-first-login UI flow",+ "admin/adminadmin already provisioned (local-dev path); skipping first-run setup UI flow",});return;}@@ -62,43 +50,36 @@ test.describe("Live-suite bootstrap", () => {await skipOnboarding(page);await page.goto("/login", { waitUntil: "domcontentloaded" });- await page.locator("#email").waitFor({ state: "visible", timeout: 15_000 });-- await page.locator("#email").fill(DEFAULT_TEST_USERNAME);- await page.locator("#password").fill(DEFAULT_BACKEND_PASSWORD);- await page.locator('button[type="submit"]').click();- await expect(- page.getByText(/must change your password|set your password/i).first(),- ).toBeVisible({ timeout: 15_000 });+ await expect(page.getByText("Set up your account").first()).toBeVisible({+ timeout: 20_000,+ });- // Mantine's PasswordInput label association doesn't match getByLabel- // cleanly across builds — use the placeholder which is stable.await page- .getByPlaceholder(/enter new password.*characters/i)+ .getByRole("textbox", { name: "Username", exact: true })+ .fill(DEFAULT_TEST_USERNAME);+ await page+ .getByRole("textbox", { name: "New password", exact: true }).fill(DEFAULT_TEST_PASSWORD);await page- .getByPlaceholder(/re-enter new password/i)+ .getByRole("textbox", { name: "Confirm new password", exact: true }).fill(DEFAULT_TEST_PASSWORD);+ await page.getByRole("button", { name: "Save and continue" }).click();- const submitBtn = page.getByRole("button", { name: /change password/i });- await expect(submitBtn).toBeEnabled();- await submitBtn.click();-- await expect(- page.getByText(/password changed successfully/i).first(),- ).toBeVisible({ timeout: 10_000 });+ await expect(page.getByText("Your server is up").first()).toBeVisible({+ timeout: 15_000,+ });- // After success the user is signed out; expect redirect back to /login- await page.waitForURL(/\/login(\?.*)?$/, { timeout: 15_000 });+ const token = await signInSeededAdmin(request);+ expect(token).not.toBeNull();+ const done = await request.post("/api/v1/admin/settings/setup-complete", {+ headers: { Authorization: `Bearer ${token}` },+ });+ expect(done.ok()).toBeTruthy();- // Confirm the new credentials work via the API- const verify = await request.post("/api/v1/auth/login", {- data: {- username: DEFAULT_TEST_USERNAME,- password: DEFAULT_TEST_PASSWORD,- },+ await page.reload({ waitUntil: "domcontentloaded" });+ await expect(page.getByText("Your server is up")).toHaveCount(0, {+ timeout: 15_000,});- expect(verify.ok()).toBeTruthy();});});diff --git a/frontend/src/editor/core/types/appConfig.ts b/frontend/src/editor/core/types/appConfig.tsindex 0760174a77..cbf07f2817 100644--- a/frontend/src/editor/core/types/appConfig.ts+++ b/frontend/src/editor/core/types/appConfig.ts@@ -55,6 +55,8 @@ export interface AppConfig {dependenciesReady?: boolean;error?: string;isNewServer?: boolean;+ /** False until an admin finishes or skips first-run server setup. */+ setupCompleted?: boolean;isNewUser?: boolean;/** Server tool-panel default; a stored user preference takes precedence. */defaultToolPanelMode?: "sidebar" | "fullscreen";diff --git a/frontend/src/editor/core/ui/FormField.tsx b/frontend/src/editor/core/ui/FormField.tsxindex 61beee8ad7..d829817541 100644--- a/frontend/src/editor/core/ui/FormField.tsx+++ b/frontend/src/editor/core/ui/FormField.tsx@@ -17,6 +17,10 @@ export interface FormFieldProps {* instead of taking up permanent space under the control like `helperText`.*/info?: ReactNode;+ /** Puts the (i) before the label instead of after it. */+ infoBeforeLabel?: boolean;+ /** For a field shown over a layer above the default tooltip layer. */+ infoZIndex?: number;/** Error string. Causes the control + helper region to swap to the error tone. */error?: ReactNode;required?: boolean;@@ -39,6 +43,8 @@ export function FormField({label,helperText,info,+ infoBeforeLabel = false,+ infoZIndex,error,required,children,@@ -66,6 +72,9 @@ export function FormField({>{(label || info) && (<div className="sui-field__label-row">+ {info && infoBeforeLabel && (+ <InfoTooltip label={info} zIndex={infoZIndex} />+ )}{label && (<label htmlFor={controlId} className="sui-field__label">{label}@@ -77,7 +86,9 @@ export function FormField({)}</label>)}- {info && <InfoTooltip label={info} />}+ {info && !infoBeforeLabel && (+ <InfoTooltip label={info} zIndex={infoZIndex} />+ )}</div>)}<div className="sui-field__control">{child}</div>diff --git a/frontend/src/editor/core/ui/InfoTooltip.tsx b/frontend/src/editor/core/ui/InfoTooltip.tsxindex dff757842f..ce16a98577 100644--- a/frontend/src/editor/core/ui/InfoTooltip.tsx+++ b/frontend/src/editor/core/ui/InfoTooltip.tsx@@ -11,6 +11,8 @@ export interface InfoTooltipProps {ariaLabel?: string;/** Which side the tooltip opens on. Default "top". */position?: FloatingPosition;+ /** For use over a layer that sits above the default tooltip layer. */+ zIndex?: number;}/**@@ -22,6 +24,7 @@ export function InfoTooltip({label,ariaLabel,position = "top",+ zIndex,}: InfoTooltipProps) {const { t } = useTranslation();return (@@ -31,6 +34,7 @@ export function InfoTooltip({w={260}withArrowposition={position}+ zIndex={zIndex}events={{ hover: true, focus: true, touch: true }}><buttondiff --git a/frontend/src/editor/desktop/components/serverSetup/setupAddressPrefill.test.ts b/frontend/src/editor/desktop/components/serverSetup/setupAddressPrefill.test.tsnew file mode 100644index 0000000000..b2d96c40cb--- /dev/null+++ b/frontend/src/editor/desktop/components/serverSetup/setupAddressPrefill.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it, vi } from "vitest";+import { setupAddressPrefill } from "@editor/components/serverSetup/setupAddressPrefill";++const connection = vi.hoisted(() => ({+ serverConfig: null as { url: string } | null,+}));+vi.mock("@editor/services/connectionModeService", () => ({+ connectionModeService: {+ getCachedServerConfig: () => connection.serverConfig,+ },+}));++describe("setupAddressPrefill", () => {+ it("offers the server the app is signed in to, not the webview's origin", () => {+ connection.serverConfig = { url: "https://pdf.example.com/" };+ expect(setupAddressPrefill()).toBe("https://pdf.example.com");+ });++ it("offers nothing without a server address", () => {+ connection.serverConfig = null;+ expect(setupAddressPrefill()).toBe("");+ connection.serverConfig = { url: "" };+ expect(setupAddressPrefill()).toBe("");+ });+});diff --git a/frontend/src/editor/desktop/components/serverSetup/setupAddressPrefill.ts b/frontend/src/editor/desktop/components/serverSetup/setupAddressPrefill.tsnew file mode 100644index 0000000000..2b8b5f6f1d--- /dev/null+++ b/frontend/src/editor/desktop/components/serverSetup/setupAddressPrefill.ts@@ -0,0 +1,8 @@+import { connectionModeService } from "@editor/services/connectionModeService";++/** The self-hosted server this app is signed in to; the webview's own origin+ * (http://tauri.localhost on Windows) is the app, never the server. */+export function setupAddressPrefill(): string {+ const url = connectionModeService.getCachedServerConfig()?.url ?? "";+ return /^https?:\/\//.test(url) ? url.replace(/\/+$/, "") : "";+}diff --git a/frontend/src/editor/proprietary/auth/defaultCredentials.ts b/frontend/src/editor/proprietary/auth/defaultCredentials.tsnew file mode 100644index 0000000000..fbf643fde9--- /dev/null+++ b/frontend/src/editor/proprietary/auth/defaultCredentials.ts@@ -0,0 +1,5 @@+/** The admin a fresh server creates; must match InitialSecuritySetup. */+export const DEFAULT_ADMIN_CREDENTIALS = {+ username: "admin",+ password: "stirling",+} as const;diff --git a/frontend/src/editor/proprietary/auth/spring/springAuthClient.ts b/frontend/src/editor/proprietary/auth/spring/springAuthClient.tsindex f576b478b4..fd5cc22b8d 100644--- a/frontend/src/editor/proprietary/auth/spring/springAuthClient.ts+++ b/frontend/src/editor/proprietary/auth/spring/springAuthClient.ts@@ -437,7 +437,16 @@ class SpringAuthClient {return { user: data.user, session, error: null };} catch (error: unknown) {- console.error("[SpringAuth] signInWithPassword error:", error);+ // Never the error itself: an Axios error carries the request body, which+ // holds the password.+ console.error(+ "[SpringAuth] signInWithPassword error:",+ error instanceof AxiosError+ ? `${error.response?.status ?? "no response"} ${error.message}`+ : error instanceof Error+ ? error.message+ : "unknown error",+ );if (error instanceof AxiosError) {const errorCode = error.response?.data?.error as string | undefined;const errorMessage =diff --git a/frontend/src/editor/proprietary/auth/ui/AuthDefaultCredentials.tsx b/frontend/src/editor/proprietary/auth/ui/AuthDefaultCredentials.tsxindex 9f1a6dd3f4..c45ecd9ef6 100644--- a/frontend/src/editor/proprietary/auth/ui/AuthDefaultCredentials.tsx+++ b/frontend/src/editor/proprietary/auth/ui/AuthDefaultCredentials.tsx@@ -1,5 +1,6 @@import { Alert, Stack, Text } from "@mantine/core";import { useTranslation } from "react-i18next";+import { DEFAULT_ADMIN_CREDENTIALS } from "@editor/auth/defaultCredentials";/*** First-time-setup notice showing the default admin credentials. Rendered@@ -17,13 +18,13 @@ export default function AuthDefaultCredentials() {<Text component="span" fw={600} style={{ color: "var(--c-text)" }}>{t("login.username", "Username")}:</Text>{" "}- admin+ {DEFAULT_ADMIN_CREDENTIALS.username}</Text><Text size="sm" ta="center" style={{ color: "var(--c-text)" }}><Text component="span" fw={600} style={{ color: "var(--c-text)" }}>{t("login.password", "Password")}:</Text>{" "}- stirling+ {DEFAULT_ADMIN_CREDENTIALS.password}</Text><Textsize="xs"diff --git a/frontend/src/editor/proprietary/auth/ui/AuthShell.module.css b/frontend/src/editor/proprietary/auth/ui/AuthShell.module.cssindex 4477d64acc..18a25fb781 100644--- a/frontend/src/editor/proprietary/auth/ui/AuthShell.module.css+++ b/frontend/src/editor/proprietary/auth/ui/AuthShell.module.css@@ -23,22 +23,34 @@box-shadow: 0 1.25rem 3.75rem rgba(0, 0, 0, 0.12);overflow-y: auto;overflow-x: hidden;- transition: width var(--motion-slow);+ transition:+ width var(--motion-slow),+ padding var(--motion-slow);}@media (prefers-reduced-motion: reduce) {- .authCard {+ .authCard,+ .authContent {transition: none;}}+.authCardMedium {+ width: min(28rem, 96vw);+}++.authCardMedium .authContent {+ max-width: 24rem; /* 28rem card minus 2rem padding each side */+}+.authCardWide {width: min(36rem, 96vw);padding: 2.5rem;}+/* A width, not none, so it can transition with the card's width. */.authCardWide .authContent {- max-width: none;+ max-width: 31rem; /* 36rem card minus 2.5rem padding each side */}.authCard::-webkit-scrollbar {@@ -48,4 +60,5 @@.authContent {max-width: 22rem; /* 352px */width: 100%;+ transition: max-width var(--motion-slow);}diff --git a/frontend/src/editor/proprietary/auth/ui/AuthShell.tsx b/frontend/src/editor/proprietary/auth/ui/AuthShell.tsxindex b5dd89623a..ce68cd7d28 100644--- a/frontend/src/editor/proprietary/auth/ui/AuthShell.tsx+++ b/frontend/src/editor/proprietary/auth/ui/AuthShell.tsx@@ -5,8 +5,9 @@ export interface AuthShellProps {children: ReactNode;/** Optional fixed footer slot (the editor passes its legal/cookie footer). */footer?: ReactNode;- /** `wide` fits content with code samples or side-by-side rows. Default `narrow`. */- size?: "narrow" | "wide";+ /** `medium` fits a setting's label beside its control; `wide` fits code+ * samples or side-by-side rows. Default `narrow`. */+ size?: "narrow" | "medium" | "wide";}/**@@ -14,6 +15,12 @@ export interface AuthShellProps {* card centered on the screen. Purely presentational - callers provide the* form (children) and an optional footer.*/+const SIZE_CLASS: Record<NonNullable<AuthShellProps["size"]>, string> = {+ narrow: "",+ medium: styles.authCardMedium,+ wide: styles.authCardWide,+};+export function AuthShell({children,footer,@@ -22,7 +29,7 @@ export function AuthShell({return (<div className={styles.authContainer}><div- className={[styles.authCard, size === "wide" ? styles.authCardWide : ""]+ className={[styles.authCard, SIZE_CLASS[size]].filter(Boolean).join(" ")}>diff --git a/frontend/src/editor/proprietary/auth/ui/useSpringLogin.ts b/frontend/src/editor/proprietary/auth/ui/useSpringLogin.tsindex 67ec0521f9..a7f44270bb 100644--- a/frontend/src/editor/proprietary/auth/ui/useSpringLogin.ts+++ b/frontend/src/editor/proprietary/auth/ui/useSpringLogin.ts@@ -16,6 +16,8 @@ export interface SpringLoginUiData {ssoAutoLogin?: boolean;firstTimeSetup?: boolean;showDefaultCredentials?: boolean;+ /** The server allows signing in with the default admin login by itself. */+ defaultSignIn?: boolean;languages?: string[] | null;defaultLocale?: string | null;}diff --git a/frontend/src/editor/proprietary/components/serverSetup/ServerSetupWizard.tsx b/frontend/src/editor/proprietary/components/serverSetup/ServerSetupWizard.tsxnew file mode 100644index 0000000000..36c94d08c4--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/ServerSetupWizard.tsx@@ -0,0 +1,592 @@+import {+ useEffect,+ useRef,+ useState,+ type ComponentProps,+ type ComponentType,+} from "react";+import { useQuery } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { SegmentedControl } from "@editor/ui/SegmentedControl";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";+import {+ SettingRow,+ SetupNote,+ initialOpenSection,+ nextOpenSection,+ sectionsConfiguredOnServer,+ sectionForField,+ type ExpandableSection,+ type SetupStepProps,+} from "@editor/components/serverSetup/SetupFields";+import { SetupStepFrame } from "@editor/components/serverSetup/SetupStepFrame";+import {+ SetupScreen,+ SetupSignInScreen,+} from "@editor/components/serverSetup/SetupScreen";+import {+ clearSetupSignIn,+ isSetupSignInPending,+} from "@editor/components/serverSetup/setupSignInHandoff";+import {+ PasswordChangeError,+ SignInAgainError,+ UsernameChangeError,+ useSetupFinish,+} from "@editor/components/serverSetup/useSetupFinish";+import { useAuth } from "@editor/auth/UseSession";+import { DEFAULT_ADMIN_CREDENTIALS } from "@editor/auth/defaultCredentials";+import {+ checkIssuer,+ fetchServerSettings,+} from "@editor/components/serverSetup/serverSetupApi";+import {+ draftFromSettings,+ draftToSave,+ issuersToCheck,+ prefillAddresses,+ stepsConfiguredOnServer,+ stepsFor,+ validateStep,+ type ServerSetupDraft,+ type SetupMode,+ type SetupStepId,+ type StepErrors,+} from "@editor/components/serverSetup/serverSetupDraft";+import { AddressesStep } from "@editor/components/serverSetup/steps/AddressesStep";+import { LanguageStep } from "@editor/components/serverSetup/steps/LanguageStep";+import { SignInStep } from "@editor/components/serverSetup/steps/SignInStep";+import { EmailStep } from "@editor/components/serverSetup/steps/EmailStep";+import { FilesStep } from "@editor/components/serverSetup/steps/FilesStep";+import { AiStep } from "@editor/components/serverSetup/steps/AiStep";+import { AnalyticsStep } from "@editor/components/serverSetup/steps/AnalyticsStep";+import { PasswordStep } from "@editor/components/serverSetup/steps/PasswordStep";+import { QuickSummaryStep } from "@editor/components/serverSetup/steps/QuickSummaryStep";+import { useStepCopy } from "@editor/components/serverSetup/useStepCopy";+import { setupAddressPrefill } from "@editor/components/serverSetup/setupAddressPrefill";++const STEP_COMPONENTS: Record<SetupStepId, ComponentType<SetupStepProps>> = {+ addresses: AddressesStep,+ language: LanguageStep,+ signIn: SignInStep,+ email: EmailStep,+ files: FilesStep,+ ai: AiStep,+ analytics: AnalyticsStep,+ password: PasswordStep,+ summary: QuickSummaryStep,+};++/** Where each server password error belongs on the Password step. */+function passwordErrors(error: PasswordChangeError): StepErrors {+ switch (error.code) {+ case "incorrectPassword":+ return { currentPassword: "passwordIncorrect" };+ case "passwordUnchanged":+ return { newPassword: "passwordUnchanged" };+ case "passwordMismatch":+ return { confirmPassword: "passwordMismatch" };+ default:+ return { newPassword: "passwordRejected" };+ }+}++function usernameErrors(error: UsernameChangeError): StepErrors {+ return {+ adminUsername:+ error.code === "usernameExists" ? "usernameTaken" : "username",+ };+}++/** The account card's progress; "updating" holds the card while the details save. */+type AccountState = "editing" | "updating" | "failed" | "signInAgain";++type FrameProps = ComponentProps<typeof SetupStepFrame>;++type Phase =+ | { kind: "password" }+ | { kind: "start" }+ | { kind: "step"; index: number }+ | { kind: "finish" };++interface ServerSetupWizardProps {+ onDone: () => void;+ passwordChange?: { usingDefaultCredentials: boolean };+ onPasswordChanged?: () => void;+}++function ServerSetupFlow({+ settings,+ onDone,+ passwordChange,+ onPasswordChanged,+}: ServerSetupWizardProps & { settings: Record<string, unknown> }) {+ // Setup's own card is up, so the sign-in card has done its job.+ useEffect(() => clearSetupSignIn(), []);+ const { t } = useTranslation();+ const stepCopy = useStepCopy();+ const [initial] = useState(() => draftFromSettings(settings));+ // Fixed when the wizard opens, so a step switched on here stays on screen.+ const [configuredSteps] = useState(() => stepsConfiguredOnServer(initial));+ const usingDefaultCredentials =+ passwordChange?.usingDefaultCredentials === true;+ const [draft, setDraft] = useState<ServerSetupDraft>(() => ({+ ...prefillAddresses(initial, setupAddressPrefill()),+ currentPassword: usingDefaultCredentials+ ? DEFAULT_ADMIN_CREDENTIALS.password+ : "",+ }));+ const [mode, setMode] = useState<SetupMode>("quick");+ // Owed account details come first, so the default login stops working+ // before the admin spends any time on settings.+ const [phase, setPhase] = useState<Phase>(+ passwordChange ? { kind: "password" } : { kind: "start" },+ );+ const [accountState, setAccountState] = useState<AccountState>("editing");+ const { signOut } = useAuth();+ const [errors, setErrors] = useState<StepErrors>({});+ const [openSection, setOpenSectionState] = useState<ExpandableSection | null>(+ null,+ );+ const [configured, setConfigured] = useState(() =>+ sectionsConfiguredOnServer(initial),+ );+ // A section reads Configured from the first time it is shut after being open.+ const setOpenSection = (next: ExpandableSection | null) => {+ if (openSection && openSection !== next) {+ setConfigured((current) => new Set(current).add(openSection));+ }+ setOpenSectionState(next);+ };+ const steps = stepsFor(mode, configuredSteps);+ const {+ state: finishState,+ finish,+ saveAccount,+ complete,+ reset,+ } = useSetupFinish({ onDone, onPasswordChanged });++ // Custom's AI card starts with AI on, so its fields are there to fill+ // in; only the first visit applies it, so switching AI off sticks.+ const aiDefaulted = useRef(false);+ // True while that default is in the draft, so a switch to Quick start can undo it.+ const aiAutoSet = useRef(false);++ const goTo = (next: Phase) => {+ setErrors({});+ setPhase(next);+ if (next.kind !== "step") return;+ const step = steps[next.index];+ let target = draft;+ if (step === "ai" && mode === "custom" && !aiDefaulted.current) {+ aiDefaulted.current = true;+ if (draft.ai === "off") {+ target = { ...draft, ai: "custom" };+ setDraft(target);+ aiAutoSet.current = true;+ }+ }+ setOpenSection(initialOpenSection(step, target, configuredSteps));+ };++ /** Errors `step` has in `section`'s fields. */+ const sectionErrors = (+ step: SetupStepId,+ section: ExpandableSection,+ ): StepErrors =>+ Object.fromEntries(+ Object.entries(validateStep(step, draft, mode)).filter(+ ([field]) =>+ sectionForField(field as keyof ServerSetupDraft) === section,+ ),+ );++ const saveSection = (section: ExpandableSection) => {+ if (phase.kind !== "step") return;+ const step = steps[phase.index];+ const found = sectionErrors(step, section);+ if (Object.keys(found).length > 0) {+ showErrors(found);+ return;+ }+ setErrors({});+ setOpenSection(nextOpenSection(step, draft, section, configuredSteps));+ };++ const stepProps: SetupStepProps = {+ draft,+ initial,+ update: (patch) => setDraft((current) => ({ ...current, ...patch })),+ errors,+ mode,+ usingDefaultCredentials,+ openSection,+ setOpenSection,+ configured,+ configuredSteps,+ saveSection,+ };++ /** Shows `stepErrors`, opening the section the first is in and focusing it. */+ const showErrors = (stepErrors: StepErrors) => {+ setErrors(stepErrors);+ const [first] = Object.keys(stepErrors) as (keyof ServerSetupDraft)[];+ const section = first ? sectionForField(first) : null;+ if (section) setOpenSection(section);+ if (first) {+ // After the render that opens its section and marks the field invalid.+ requestAnimationFrame(() =>+ document.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus(),+ );+ }+ };++ const [checkingIssuers, setCheckingIssuers] = useState(false);++ /** Errors for issuers this step would save that the server cannot reach. */+ const unreachableIssuers = async (step: SetupStepId): Promise<StepErrors> => {+ const fields = issuersToCheck(step, draft, initial);+ if (fields.length === 0) return {};+ setCheckingIssuers(true);+ try {+ const reachable = await Promise.all(+ fields.map((field) => checkIssuer(draft[field]).catch(() => false)),+ );+ return Object.fromEntries(+ fields+ .filter((_, i) => !reachable[i])+ .map((field) => [field, "issuerUnreachable"]),+ );+ } finally {+ setCheckingIssuers(false);+ }+ };++ const startFinish = (finalDraft: ServerSetupDraft = draft) => {+ goTo({ kind: "finish" });+ finish(initial, draftToSave(finalDraft, initial, mode));+ };++ const submitAccount = () => {+ if (accountState === "updating") return;+ const stepErrors = validateStep("password", draft, mode);+ showErrors(stepErrors);+ if (Object.keys(stepErrors).length > 0) return;+ setAccountState("updating");+ saveAccount(draft)+ .then(() => {+ // Nothing needs the passwords after this, so they leave memory now.+ setDraft((current) => ({+ ...current,+ currentPassword: "",+ newPassword: "",+ confirmPassword: "",+ }));+ setAccountState("editing");+ goTo({ kind: "start" });+ })+ .catch((error: unknown) => {+ if (error instanceof SignInAgainError) {+ setAccountState("signInAgain");+ return;+ }+ if (error instanceof PasswordChangeError) {+ setAccountState("editing");+ showErrors(passwordErrors(error));+ } else if (error instanceof UsernameChangeError) {+ setAccountState("editing");+ showErrors(usernameErrors(error));+ } else {+ setAccountState("failed");+ }+ });+ };++ const accountFrame = (): FrameProps => {+ switch (accountState) {+ case "updating":+ return {+ title: t(+ "serverSetup.account.updatingTitle",+ "Updating your details",+ ),+ subtitle: t("serverSetup.account.updatingSubtitle", "One moment."),+ primaryLabel: t("serverSetup.account.updating", "Updating"),+ onPrimary: () => {},+ primaryLoading: true,+ };+ case "signInAgain":+ return {+ title: t(+ "serverSetup.account.signInAgainTitle",+ "Your details are saved",+ ),+ subtitle: t(+ "serverSetup.account.signInAgainSubtitle",+ "Sign in again with your new username and password to carry on.",+ ),+ primaryLabel: t("serverSetup.account.signIn", "Sign in"),+ onPrimary: () => void signOut(),+ };+ default:+ return {+ ...stepCopy("password"),+ primaryLabel: t("serverSetup.account.save", "Save and continue"),+ onPrimary: submitAccount,+ children: (+ <>+ <PasswordStep {...stepProps} />+ {accountState === "failed" && (+ <SetupNote tone="warning">+ <p className={styles.noteText}>+ {t(+ "serverSetup.account.failed",+ "Couldn't save your details. Check the server is reachable and try again.",+ )}+ </p>+ </SetupNote>+ )}+ </>+ ),+ };+ }+ };++ const finishOrContinue = (isLast: boolean) =>+ isLast+ ? t("serverSetup.finishSetup", "Finish setup")+ : t("serverSetup.continue", "Continue");++ const analyticsLabel = (accept: boolean, isLast: boolean) => {+ if (accept) {+ return isLast+ ? t("serverSetup.analytics.acceptFinish", "Accept and finish")+ : t("serverSetup.analytics.accept", "Accept and continue");+ }+ return isLast+ ? t("serverSetup.analytics.declineFinish", "Decline and finish")+ : t("serverSetup.analytics.decline", "Decline and continue");+ };++ const startFrame = (): FrameProps => {+ const setupLabel = t("serverSetup.start.setupLabel", "Setup");+ return {+ title: t("serverSetup.start.title", "Your server is up"),+ subtitle: t(+ "serverSetup.start.subtitle",+ "Set it up for your team in a few steps.",+ ),+ primaryLabel: finishOrContinue(steps.length === 0),+ onPrimary: () =>+ steps.length === 0 ? startFinish() : goTo({ kind: "step", index: 0 }),+ children: (+ <SettingRow label={setupLabel}>+ {() => (+ <SegmentedControl+ fullWidth+ ariaLabel={setupLabel}+ value={mode}+ onChange={(next) => {+ setMode(next);+ if (next === "quick" && aiAutoSet.current) {+ aiAutoSet.current = false;+ aiDefaulted.current = false;+ setDraft((current) => ({ ...current, ai: initial.ai }));+ }+ }}+ options={[+ {+ value: "quick",+ label: t("serverSetup.start.quick", "Quick start"),+ },+ {+ value: "custom",+ label: t("serverSetup.start.custom", "Custom"),+ },+ ]}+ />+ )}+ </SettingRow>+ ),+ };+ };++ const answerAnalytics = (accept: boolean, index: number) => {+ const answered = { ...draft, analytics: accept };+ setDraft(answered);+ if (index === steps.length - 1) startFinish(answered);+ else goTo({ kind: "step", index: index + 1 });+ };++ const stepFrame = (index: number): FrameProps => {+ const step = steps[index];+ const Step = STEP_COMPONENTS[step];+ const isLast = index === steps.length - 1;+ const card = {+ ...stepCopy(step),+ progress: { current: index + 1, total: steps.length },+ onBack: () =>+ goTo(+ index === 0 ? { kind: "start" } : { kind: "step", index: index - 1 },+ ),+ children: <Step {...stepProps} />,+ };+ if (step === "analytics") {+ return {+ ...card,+ primaryLabel: analyticsLabel(true, isLast),+ onPrimary: () => answerAnalytics(true, index),+ secondaryLabel: analyticsLabel(false, isLast),+ onSecondary: () => answerAnalytics(false, index),+ };+ }+ return {+ ...card,+ primaryLabel: finishOrContinue(isLast),+ primaryLoading: checkingIssuers,+ onPrimary: () => {+ if (checkingIssuers) return;+ const stepErrors = validateStep(step, draft, mode);+ showErrors(stepErrors);+ if (Object.keys(stepErrors).length > 0) return;+ const advance = () =>+ isLast ? startFinish() : goTo({ kind: "step", index: index + 1 });+ if (issuersToCheck(step, draft, initial).length === 0) {+ advance();+ return;+ }+ void unreachableIssuers(step).then((issuerErrors) => {+ if (Object.keys(issuerErrors).length > 0) showErrors(issuerErrors);+ else advance();+ });+ },+ };+ };++ const finishFrame = (): FrameProps => {+ switch (finishState) {+ case "restarting":+ return {+ title: t(+ "serverSetup.finish.restartingTitle",+ "Restarting your server",+ ),+ subtitle: t(+ "serverSetup.finish.restartingSubtitle",+ "This page reloads when it's back, usually within a minute.",+ ),+ };+ case "manualRestart":+ case "restartFailed":+ return {+ title: t("serverSetup.finish.manualTitle", "Settings saved"),+ subtitle:+ finishState === "manualRestart"+ ? t(+ "serverSetup.finish.manualSubtitle",+ "This server can't restart itself. Restart its container or service to apply them.",+ )+ : t(+ "serverSetup.finish.restartFailedSubtitle",+ "The server didn't restart. Restart its container or service to apply them.",+ ),+ primaryLabel: t("serverSetup.continue", "Continue"),+ onPrimary: complete,+ };+ case "error":+ return {+ title: t(+ "serverSetup.finish.errorTitle",+ "Couldn't save your settings",+ ),+ subtitle: t(+ "serverSetup.finish.errorSubtitle",+ "Nothing was restarted.",+ ),+ onBack: () => {+ reset();+ goTo({ kind: "step", index: steps.length - 1 });+ },+ primaryLabel: t("serverSetup.finish.retry", "Try again"),+ onPrimary: startFinish,+ children: (+ <SetupNote tone="warning">+ <p className={styles.noteText}>+ {t(+ "serverSetup.finish.errorNote",+ "Check the server is reachable and that you're still signed in as an admin.",+ )}+ </p>+ </SetupNote>+ ),+ };+ default:+ return {+ title: t("serverSetup.finish.savingTitle", "Saving your settings"),+ subtitle: t("serverSetup.finish.savingSubtitle", "One moment."),+ primaryLabel: t("serverSetup.finish.saving", "Saving"),+ onPrimary: () => {},+ primaryLoading: true,+ };+ }+ };++ const frame =+ phase.kind === "password"+ ? accountFrame()+ : phase.kind === "start"+ ? startFrame()+ : phase.kind === "finish"+ ? finishFrame()+ : stepFrame(phase.index);++ // One frame for every phase, so its height animates between them.+ return (+ <SetupScreen>+ <SetupStepFrame {...frame} />+ </SetupScreen>+ );+}++/** First-run settings for a new self-hosted server, shown once to its first admin. */+export function ServerSetupWizard({+ onDone,+ passwordChange,+ onPasswordChanged,+}: ServerSetupWizardProps) {+ const { t } = useTranslation();+ const settings = useQuery({+ queryKey: ["serverSetup", "settings"],+ queryFn: fetchServerSettings,+ staleTime: Infinity,+ retry: false,+ });++ if (settings.isPending) {+ return isSetupSignInPending() ? <SetupSignInScreen /> : null;+ }+ if (settings.isError) {+ return (+ <SetupScreen>+ <SetupStepFrame+ title={t("serverSetup.loadErrorTitle", "Couldn't load your settings")}+ subtitle={t(+ "serverSetup.loadErrorSubtitle",+ "Setup needs the server's current settings to start.",+ )}+ primaryLabel={t("serverSetup.finish.retry", "Try again")}+ onPrimary={() => void settings.refetch()}+ />+ </SetupScreen>+ );+ }+ return (+ <ServerSetupFlow+ settings={settings.data}+ onDone={onDone}+ passwordChange={passwordChange}+ onPasswordChanged={onPasswordChanged}+ />+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/SetupFields.tsx b/frontend/src/editor/proprietary/components/serverSetup/SetupFields.tsxnew file mode 100644index 0000000000..0157be31cd--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/SetupFields.tsx@@ -0,0 +1,528 @@+import {+ useEffect,+ useId,+ useRef,+ type KeyboardEvent,+ type MouseEvent,+ type ReactNode,+ type TransitionEvent,+} from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@editor/ui/Button";+import { FormField } from "@editor/ui/FormField";+import { Icon } from "@editor/ui/Icon";+import { Input } from "@editor/ui/Input";+import {+ SegmentedControl,+ type SegmentedOption,+} from "@editor/ui/SegmentedControl";+import type {+ SetupStepId,+ ErrorCode,+ ServerSetupDraft,+ SetupMode,+ StepErrors,+} from "@editor/components/serverSetup/serverSetupDraft";+import { Z_INDEX_ONBOARDING_CARD } from "@editor/styles/zIndex";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++/** Select dropdowns portal to the body, so they must sit above the setup screen. */+export const SETUP_DROPDOWN = { zIndex: Z_INDEX_ONBOARDING_CARD + 1 };++/** Settings that open more fields when switched on; one is open at a time. */+export type ExpandableSection = "signIn" | "email" | "ai" | "documents";++/** Each card's expandable settings, top to bottom. */+const SECTIONS_BY_STEP: Partial<Record<SetupStepId, ExpandableSection[]>> = {+ summary: ["signIn", "email", "ai", "documents"],+ signIn: ["signIn"],+ email: ["email"],+ ai: ["ai", "documents"],+};++function isSectionOn(+ draft: ServerSetupDraft,+): Record<ExpandableSection, boolean> {+ return {+ signIn: draft.login !== "password",+ email: draft.emailEnabled,+ ai: draft.ai === "custom",+ documents: draft.ai === "custom" && draft.documentQuestions,+ };+}++/** The step whose card holds each section. */+const STEP_OF_SECTION: Record<ExpandableSection, SetupStepId> = {+ signIn: "signIn",+ email: "email",+ ai: "ai",+ documents: "ai",+};++/** The sections on `step` that are shown and switched on, and so have fields+ * to fill in; a configured step's sections are not on the card at all. */+function sectionsOn(+ step: SetupStepId,+ draft: ServerSetupDraft,+ configuredSteps: ReadonlySet<SetupStepId>,+): ExpandableSection[] {+ const isOn = isSectionOn(draft);+ return (SECTIONS_BY_STEP[step] ?? []).filter(+ (section) =>+ isOn[section] && !configuredSteps.has(STEP_OF_SECTION[section]),+ );+}++/** Sections the server already has switched on, so already configured. */+export function sectionsConfiguredOnServer(+ initial: ServerSetupDraft,+): Set<ExpandableSection> {+ const isOn = isSectionOn(initial);+ return new Set(+ (Object.keys(isOn) as ExpandableSection[]).filter(+ (section) => isOn[section],+ ),+ );+}++/** The section to open when a card first shows: its first one switched on. */+export function initialOpenSection(+ step: SetupStepId,+ draft: ServerSetupDraft,+ configuredSteps: ReadonlySet<SetupStepId> = new Set(),+): ExpandableSection | null {+ return sectionsOn(step, draft, configuredSteps)[0] ?? null;+}++/** The section Save moves on to: the next one switched on below `current`, if any. */+export function nextOpenSection(+ step: SetupStepId,+ draft: ServerSetupDraft,+ current: ExpandableSection,+ configuredSteps: ReadonlySet<SetupStepId> = new Set(),+): ExpandableSection | null {+ const order = SECTIONS_BY_STEP[step] ?? [];+ return (+ sectionsOn(step, draft, configuredSteps).find(+ (section) => order.indexOf(section) > order.indexOf(current),+ ) ?? null+ );+}++/** The section that holds a field, so an error there can open it. */+export function sectionForField(+ field: keyof ServerSetupDraft,+): ExpandableSection | null {+ if (field.startsWith("oauth")) return "signIn";+ if (field.startsWith("smtp")) return "email";+ if (field.startsWith("embedding")) return "documents";+ if (field.startsWith("ai")) return "ai";+ return null;+}++export interface SetupStepProps {+ draft: ServerSetupDraft;+ /** The server's values when the wizard opened. */+ initial: ServerSetupDraft;+ update: (patch: Partial<ServerSetupDraft>) => void;+ errors: StepErrors;+ mode: SetupMode;+ /** The admin signed in with the default password, so it need not be asked for. */+ usingDefaultCredentials: boolean;+ openSection: ExpandableSection | null;+ setOpenSection: (section: ExpandableSection | null) => void;+ /** Sections the server had on, or that were shut while on; they read Configured. */+ configured: ReadonlySet<ExpandableSection>;+ /** Steps the server already has settings for; their fields are not shown. */+ configuredSteps: ReadonlySet<SetupStepId>;+ /** Checks `section`'s fields; when they pass, opens the next section switched on. */+ saveSection: (section: ExpandableSection) => void;+}++const prefersReducedMotion = () =>+ window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;++/** Scrolls the card just enough to show `group` (or its top, if taller) below+ * the sticky bar holding Back and the step count. */+function revealInCard(group: HTMLElement) {+ const scroller = group.closest<HTMLElement>(`.${styles.frameScroll}`);+ if (!scroller) return;+ const sticky =+ scroller.querySelector<HTMLElement>(`.${styles.topBar}`)?.offsetHeight ?? 0;+ const view = scroller.getBoundingClientRect();+ const box = group.getBoundingClientRect();+ const belowView = box.bottom - view.bottom;+ const aboveView = box.top - (view.top + sticky);+ const delta =+ aboveView < 0 ? aboveView : Math.min(Math.max(belowView, 0), aboveView);+ if (delta === 0) return;+ scroller.scrollBy({+ top: delta,+ behavior: prefersReducedMotion() ? "auto" : "smooth",+ });+}++/** A setting's label and control, plus any `details` it opens in an animated+ * panel; boxed whenever it has `details`, so those fields read as its own. */+export function SettingRow({+ label,+ children,+ expand,+ chevron = false,+ details,+}: {+ label: string;+ children: (labelId: string) => ReactNode;+ /** Shows `details` with a Save button while open. The control opens and+ * shuts it, unless `chevron`. */+ expand?: SectionExpand;+ /** Adds a chevron that opens and shuts `details`, for a control that cannot. */+ chevron?: boolean;+ details?: ReactNode;+}) {+ const { t } = useTranslation();+ const labelId = useId();+ const detailsId = useId();+ const open = expand?.open === true;+ const groupRef = useRef<HTMLDivElement>(null);+ const wasOpen = useRef(open);++ // Scrolled once fully open (at once without motion), when the card has grown;+ // not on mount, where a card that opens with it showing is at its top.+ useEffect(() => {+ const opened = open && !wasOpen.current;+ wasOpen.current = open;+ if (opened && prefersReducedMotion() && groupRef.current) {+ revealInCard(groupRef.current);+ }+ }, [open]);+ const revealWhenOpened = (event: TransitionEvent<HTMLDivElement>) => {+ if (open && event.target === event.currentTarget && groupRef.current) {+ revealInCard(groupRef.current);+ }+ };++ return (+ <div+ ref={groupRef}+ className={styles.group}+ data-expandable={details !== undefined}+ role="group"+ aria-labelledby={labelId}+ >+ <div className={styles.groupRow}>+ <span className={styles.settingLabel} id={labelId}>+ {label}+ </span>+ <div className={styles.settingControl}>{children(labelId)}</div>+ {expand && chevron && (+ <button+ type="button"+ className={styles.expandToggle}+ data-open={expand.open}+ aria-expanded={expand.open}+ aria-controls={details ? detailsId : undefined}+ aria-label={+ expand.open+ ? t("serverSetup.collapse", "Hide {{setting}} settings", {+ setting: label,+ })+ : t("serverSetup.expand", "Show {{setting}} settings", {+ setting: label,+ })+ }+ onClick={expand.onToggle}+ >+ <Icon name="chevron-down" size={16} />+ </button>+ )}+ </div>+ {details && (+ <div+ id={detailsId}+ className={styles.groupDetails}+ data-open={open}+ inert={!open}+ onTransitionEnd={revealWhenOpened}+ >+ <div className={styles.groupDetailsClip}>+ <div className={styles.groupDetailsBody}>+ {details}+ {expand && (+ <div className={styles.groupDetailsActions}>+ <Button variant="secondary" size="sm" onClick={expand.onSave}>+ {t("serverSetup.save", "Save")}+ </Button>+ </div>+ )}+ </div>+ </div>+ </div>+ )}+ </div>+ );+}++/** A set of fields with no controlling setting, such as the addresses. */+export function FieldGroup({ children }: { children: ReactNode }) {+ return (+ <div className={styles.group}>+ <div className={styles.groupFields}>{children}</div>+ </div>+ );+}++export interface SectionExpand {+ open: boolean;+ configured: boolean;+ onToggle: () => void;+ onSave: () => void;+}++/** The `expand` prop for a SettingRow whose fields live in `section`. */+export function sectionToggle(+ props: Pick<+ SetupStepProps,+ "openSection" | "setOpenSection" | "saveSection" | "configured"+ >,+ section: ExpandableSection,+): SectionExpand {+ const open = props.openSection === section;+ return {+ open,+ configured: props.configured.has(section),+ onToggle: () => props.setOpenSection(open ? null : section),+ onSave: () => props.saveSection(section),+ };+}++/** A segmented choice whose `expandValue` segment also opens and shuts the+ * setting's fields; it reads Configured once they have been shut. */+export function SetupChoice<T extends string>({+ options,+ value,+ onChange,+ ariaLabel,+ expand,+ expandValue,+}: {+ options: SegmentedOption<T>[];+ value: T;+ onChange: (value: T) => void;+ ariaLabel: string;+ expand?: SectionExpand;+ expandValue?: T;+}) {+ const { t } = useTranslation();+ const toggles = expand !== undefined && value === expandValue;+ const isExpandRadio = (target: EventTarget) =>+ toggles &&+ target instanceof HTMLInputElement &&+ target.value === expandValue;+ // A click on the label reaches the radio as a click too, so handling the+ // radio's alone toggles once. A chosen radio gets no click from the keyboard.+ const toggleOnClick = (event: MouseEvent<HTMLDivElement>) => {+ if (isExpandRadio(event.target)) expand?.onToggle();+ };+ const toggleOnKey = (event: KeyboardEvent<HTMLDivElement>) => {+ if (+ (event.key === " " || event.key === "Enter") &&+ isExpandRadio(event.target)+ ) {+ event.preventDefault();+ expand?.onToggle();+ }+ };+ const shown = options.map((option) =>+ toggles && option.value === expandValue+ ? {+ ...option,+ label: (+ <span className={styles.expandLabel}>+ <span className={styles.expandLabelText}>+ {expand.open && !expand.configured+ ? option.label+ : t("serverSetup.configured", "Configured")}+ </span>+ <Icon+ name={expand.open ? "chevron-up" : "chevron-down"}+ size={14}+ />+ </span>+ ),+ }+ : option,+ );+ return (+ <div+ className={styles.setupChoice}+ onClick={toggleOnClick}+ onKeyDown={toggleOnKey}+ >+ <SegmentedControl+ fullWidth+ ariaLabel={ariaLabel}+ value={value}+ onChange={onChange}+ options={shown}+ />+ </div>+ );+}++export function OnOffControl({+ value,+ onChange,+ ariaLabel,+ expand,+}: {+ value: boolean;+ onChange: (value: boolean) => void;+ ariaLabel: string;+ expand?: SectionExpand;+}) {+ const { t } = useTranslation();+ return (+ <SetupChoice+ ariaLabel={ariaLabel}+ value={value ? "on" : "off"}+ onChange={(next) => onChange(next === "on")}+ expand={expand}+ expandValue="on"+ options={[+ { value: "off", label: t("serverSetup.off", "Off") },+ { value: "on", label: t("serverSetup.on", "On") },+ ]}+ />+ );+}++function useErrorText() {+ const { t } = useTranslation();+ return (code: ErrorCode | undefined) => {+ switch (code) {+ case "required":+ return t("serverSetup.error.required", "Required");+ case "url":+ return t(+ "serverSetup.error.url",+ "Enter a full address, starting with http:// or https://",+ );+ case "port":+ return t("serverSetup.error.port", "Enter a port from 1 to 65535");+ case "email":+ return t("serverSetup.error.email", "Enter an email address");+ case "passwordLength":+ return t(+ "serverSetup.error.passwordLength",+ "Use at least 8 characters",+ );+ case "passwordMismatch":+ return t("serverSetup.error.passwordMismatch", "Passwords don't match");+ case "passwordUnchanged":+ return t(+ "serverSetup.error.passwordUnchanged",+ "Choose a password different from the current one",+ );+ case "passwordIncorrect":+ return t("serverSetup.error.passwordIncorrect", "Incorrect password");+ case "issuerUnreachable":+ return t(+ "serverSetup.error.issuerUnreachable",+ "Couldn't reach this issuer. Check the address, and that this server can reach it.",+ );+ case "providerName":+ return t(+ "serverSetup.error.providerName",+ "Use letters, numbers, dashes or underscores only",+ );+ case "username":+ return t(+ "serverSetup.error.username",+ "Use 3 to 50 letters, numbers or . _ + - @, or an email address",+ );+ case "usernameTaken":+ return t("serverSetup.error.usernameTaken", "That username is taken");+ case "passwordRejected":+ return t(+ "serverSetup.error.passwordRejected",+ "The server didn't accept this password. Try another.",+ );+ default:+ return undefined;+ }+ };+}++export function TextField({+ label,+ value,+ onChange,+ error,+ info,+ type = "text",+ placeholder,+ required,+ autoComplete = "off",+ initialFocus,+}: {+ label: ReactNode;+ value: string;+ onChange: (value: string) => void;+ error?: ErrorCode;+ /** Explanation behind an (i) beside the label. */+ info?: string;+ type?: "text" | "password" | "url" | "email";+ autoComplete?: string;+ placeholder?: string;+ required?: boolean;+ /** Takes focus when the dialog opens; otherwise it focuses the first+ * focusable, which may be an (i) whose tooltip opens on focus. */+ initialFocus?: boolean;+}) {+ const errorText = useErrorText();+ return (+ <FormField+ label={label}+ info={info}+ infoBeforeLabel+ infoZIndex={SETUP_DROPDOWN.zIndex}+ error={errorText(error)}+ required={required}+ >+ <Input+ type={type}+ value={value}+ placeholder={placeholder}+ autoComplete={autoComplete}+ spellCheck={false}+ data-autofocus={initialFocus || undefined}+ onChange={(event) => onChange(event.target.value)}+ />+ </FormField>+ );+}++export function SetupNote({+ children,+ tone = "info",+}: {+ children: ReactNode;+ tone?: "info" | "warning";+}) {+ return (+ <div+ className={[styles.note, tone === "warning" ? styles.noteWarning : ""]+ .filter(Boolean)+ .join(" ")}+ role={tone === "warning" ? "alert" : undefined}+ >+ <Icon+ name={tone === "warning" ? "triangle-alert" : "info"}+ size={16}+ className={styles.noteIcon}+ />+ <div className={styles.noteBody}>{children}</div>+ </div>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/SetupScreen.tsx b/frontend/src/editor/proprietary/components/serverSetup/SetupScreen.tsxnew file mode 100644index 0000000000..6ef7b1570f--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/SetupScreen.tsx@@ -0,0 +1,46 @@+import type { ReactNode } from "react";+import { FocusTrap } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { AuthShell } from "@editor/auth/ui/AuthShell";+import { Z_INDEX_ONBOARDING_CARD } from "@editor/styles/zIndex";+import { SetupStepFrame } from "@editor/components/serverSetup/SetupStepFrame";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++/** Covers the app as a modal: focus stays inside, and the app shell around it+ * (banners, toasts) is out of reach until setup closes. */+export function SetupScreen({ children }: { children: ReactNode }) {+ const { t } = useTranslation();+ return (+ <div className={styles.screen} style={{ zIndex: Z_INDEX_ONBOARDING_CARD }}>+ <FocusTrap active>+ <div+ role="dialog"+ aria-modal="true"+ aria-label={t("serverSetup.dialogLabel", "Server setup")}+ >+ {/* Medium: a default OAuth redirect URI and the longest sign-in method fit on one line. */}+ <AuthShell size="medium">{children}</AuthShell>+ </div>+ </FocusTrap>+ </div>+ );+}++/** The card from the automatic first sign-in until setup's first card is+ * ready; each load along the way renders it, so it reads as one card. */+export function SetupSignInScreen() {+ const { t } = useTranslation();+ return (+ <SetupScreen>+ <SetupStepFrame+ title={t(+ "serverSetup.signingIn.title",+ "Signing in with default credentials",+ )}+ primaryLabel={t("serverSetup.signingIn.button", "Signing in")}+ onPrimary={() => {}}+ primaryLoading+ />+ </SetupScreen>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/SetupStepFrame.tsx b/frontend/src/editor/proprietary/components/serverSetup/SetupStepFrame.tsxnew file mode 100644index 0000000000..f4627f634a--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/SetupStepFrame.tsx@@ -0,0 +1,112 @@+import { useEffect, useRef, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@editor/ui/Button";+import { Icon } from "@editor/ui/Icon";+import { AnimatedHeight } from "@editor/components/shared/setupCard/AnimatedHeight";+import { SetupCardLayout } from "@editor/components/shared/setupCard/SetupCardLayout";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++interface SetupStepFrameProps {+ /** Shown top right, as "current of total". */+ progress?: { current: number; total: number };+ /** Shows a Back button top left. */+ onBack?: () => void;+ title: ReactNode;+ subtitle?: ReactNode;+ children?: ReactNode;+ /** Omit both to show no actions, as while the server restarts. */+ primaryLabel?: ReactNode;+ onPrimary?: () => void;+ primaryLoading?: boolean;+ /** With `onSecondary`, a two-way choice: this button left, the primary+ * right, neither focused when it appears. */+ secondaryLabel?: ReactNode;+ onSecondary?: () => void;+}++/** One wizard card; keep it mounted across steps so the actions ride its edge+ * as it resizes. Past its max height the header and body scroll. */+export function SetupStepFrame({+ progress,+ onBack,+ title,+ subtitle,+ children,+ primaryLabel,+ onPrimary,+ primaryLoading,+ secondaryLabel,+ onSecondary,+}: SetupStepFrameProps) {+ const { t } = useTranslation();+ const frameRef = useRef<HTMLDivElement>(null);+ const isChoice = Boolean(secondaryLabel && onSecondary);++ // The card stays mounted, so focus left on the previous step's button would+ // land on one of the answers, and Enter would choose it unread.+ useEffect(() => {+ if (isChoice) frameRef.current?.focus();+ }, [isChoice]);++ return (+ <div ref={frameRef} className={styles.frame} tabIndex={-1}>+ <AnimatedHeight className={styles.frameScroll}>+ {(onBack || progress) && (+ <div className={styles.topBar}>+ {onBack ? (+ <Button+ variant="quiet"+ size="sm"+ leftSection={<Icon name="arrow-left" size={14} />}+ onClick={onBack}+ >+ {t("serverSetup.back", "Back")}+ </Button>+ ) : (+ <span />+ )}+ {progress && (+ <span className={styles.progress}>+ {t("serverSetup.stepCount", "{{current}} of {{total}}", {+ current: progress.current,+ total: progress.total,+ })}+ </span>+ )}+ </div>+ )}+ <SetupCardLayout title={title} subtitle={subtitle}>+ {children}+ </SetupCardLayout>+ </AnimatedHeight>+ {primaryLabel && onPrimary && (+ <div+ className={styles.actions}+ data-choice={isChoice ? "true" : undefined}+ >+ {isChoice && (+ <Button+ key="secondary"+ variant="secondary"+ fat+ fullWidth+ onClick={onSecondary}+ >+ {secondaryLabel}+ </Button>+ )}+ <Button+ key="primary"+ variant="primary"+ fat+ fullWidth+ loading={primaryLoading}+ onClick={onPrimary}+ >+ {primaryLabel}+ </Button>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/serverSetupApi.ts b/frontend/src/editor/proprietary/components/serverSetup/serverSetupApi.tsnew file mode 100644index 0000000000..2246c10304--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/serverSetupApi.ts@@ -0,0 +1,120 @@+import apiClient from "@editor/services/apiClient";+import { putAdminSettings } from "@editor/api/adminSettings";++const RESTART_POLL_MS = 1500;+const RESTART_GIVE_UP_MS = 120_000;++/** The server's current settings, secrets masked. */+export async function fetchServerSettings(): Promise<Record<string, unknown>> {+ const response = await apiClient.get<Record<string, unknown>>(+ "/api/v1/admin/settings",+ );+ return response.data ?? {};+}++/** Writes dotted settings keys to settings.yml; they apply on the next restart. */+export async function saveServerSettings(+ settings: Record<string, unknown>,+): Promise<void> {+ if (Object.keys(settings).length === 0) return;+ await putAdminSettings(settings);+}++/** Answers the first-launch analytics question. It applies at once, so that+ * prompt doesn't return if the restart afterwards fails. */+export async function answerAnalytics(enabled: boolean): Promise<void> {+ const formData = new FormData();+ formData.append("enabled", String(enabled));+ await apiClient.post("/api/v1/settings/update-enable-analytics", formData);+}++/** Whether the server can reach an OpenID Connect issuer's discovery document. */+export async function checkIssuer(issuer: string): Promise<boolean> {+ const response = await apiClient.post<{ reachable?: boolean }>(+ "/api/v1/admin/settings/check-issuer",+ { issuer },+ { suppressErrorToast: true },+ );+ return response.data?.reachable === true;+}++/** Records that setup is done; applies at once, so the wizard never reappears. */+export async function markSetupComplete(): Promise<void> {+ await apiClient.post("/api/v1/admin/settings/setup-complete");+}++/** Replaces the signed-in admin's default password. Errors reach the caller,+ * not a toast, since setup shows them on its account card. */+export async function changeAdminPassword(+ currentPassword: string,+ newPassword: string,+): Promise<void> {+ const formData = new FormData();+ formData.append("currentPassword", currentPassword);+ formData.append("newPassword", newPassword);+ formData.append("confirmPassword", newPassword);+ await apiClient.post("/api/v1/user/change-password-on-login", formData, {+ suppressErrorToast: true,+ });+}++/** Renames the signed-in admin. Tokens name the old username, so the caller+ * must sign in again. */+export async function changeAdminUsername(+ currentPassword: string,+ newUsername: string,+): Promise<void> {+ const formData = new FormData();+ formData.append("currentPasswordChangeUsername", currentPassword);+ formData.append("newUsername", newUsername);+ await apiClient.post("/api/v1/user/change-username", formData, {+ suppressErrorToast: true,+ });+}++/** The HTTP status of a failed request, when the server answered at all. */+export function httpStatus(error: unknown): number | undefined {+ const status = (error as { response?: { status?: unknown } }).response+ ?.status;+ return typeof status === "number" ? status : undefined;+}++/** Asks the server to restart: "unsupported" is its 503 when it can't restart+ * itself (outside a packaged JAR); "failed" is anything else. */+export async function requestRestart(): Promise<+ "restarting" | "unsupported" | "failed"+> {+ try {+ await apiClient.post("/api/v1/admin/settings/restart", undefined, {+ suppressErrorToast: true,+ });+ return "restarting";+ } catch (error) {+ return httpStatus(error) === 503 ? "unsupported" : "failed";+ }+}++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function serverAnswers(): Promise<boolean> {+ try {+ await apiClient.get("/api/v1/info/status", { suppressErrorToast: true });+ return true;+ } catch {+ return false;+ }+}++/** Resolves once the server has gone down and come back, so the reload never+ * hits the old process; gives up after two minutes. */+export async function waitForServer(): Promise<void> {+ const giveUpAt = Date.now() + RESTART_GIVE_UP_MS;+ while (Date.now() < giveUpAt && (await serverAnswers())) {+ await delay(RESTART_POLL_MS);+ }+ while (Date.now() < giveUpAt && !(await serverAnswers())) {+ await delay(RESTART_POLL_MS);+ }+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/serverSetupDraft.test.ts b/frontend/src/editor/proprietary/components/serverSetup/serverSetupDraft.test.tsnew file mode 100644index 0000000000..f8ef46eea8--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/serverSetupDraft.test.ts@@ -0,0 +1,442 @@+import { describe, expect, it } from "vitest";+import {+ aiProviderChange,+ asksForModels,+ draftFromSettings,+ embeddingProviderChange,+ isValidUsername,+ issuersToCheck,+ loginChange,+ draftToSave,+ oauthRedirectUri,+ prefillAddresses,+ revertStep,+ settingsDelta,+ stepsConfiguredOnServer,+ stepsFor,+ validateStep,+} from "@editor/components/serverSetup/serverSetupDraft";++const SETTINGS = {+ system: {+ frontendUrl: "",+ backendUrl: "",+ defaultLocale: "",+ enableAnalytics: null,+ },+ security: {+ oauth2: {+ enabled: false,+ provider: "google",+ client: { google: { clientId: "" }, github: {}, keycloak: {} },+ },+ },+ mail: {+ enabled: false,+ host: "smtp.example.com",+ port: 587,+ password: "********",+ },+ storage: { enabled: true, sharing: { enabled: false } },+ aiEngine: {+ enabled: false,+ mode: "SELF_HOSTED",+ url: "http://localhost:5001",+ models: {+ provider: "anthropic",+ fastModel: "claude-haiku-4-5",+ smartModel: "claude-haiku-4-5",+ apiKey: "",+ },+ rag: {+ embeddingProvider: "voyageai",+ embeddingModel: "voyage-4",+ embeddingApiKey: "********",+ embeddingBaseUrl: "",+ },+ features: { documentQuestions: true },+ },+ mcp: { enabled: false, auth: { mode: "oauth" } },+};++const ORIGIN = "https://pdf.example.com";++describe("draftFromSettings", () => {+ it("leaves addresses as the server has them", () => {+ expect(draftFromSettings(SETTINGS).frontendUrl).toBe("");+ });++ it("reads an unanswered analytics question as null", () => {+ expect(draftFromSettings(SETTINGS).analytics).toBeNull();+ });++ it("reads Stirling AI from cloud mode", () => {+ const draft = draftFromSettings({+ ...SETTINGS,+ aiEngine: { ...SETTINGS.aiEngine, enabled: true, mode: "CLOUD" },+ });+ expect(draft.ai).toBe("stirling");+ });+});++describe("settingsDelta", () => {+ it("saves prefilled addresses and nothing the admin left alone", () => {+ const initial = draftFromSettings(SETTINGS);+ const draft = prefillAddresses(initial, ORIGIN);+ const delta = settingsDelta(initial, { ...draft, analytics: true });+ expect(delta).toEqual({+ "system.frontendUrl": ORIGIN,+ "system.backendUrl": ORIGIN,+ "system.enableAnalytics": true,+ });+ });++ it("writes the provider's client and switches OAuth on", () => {+ const initial = draftFromSettings(SETTINGS);+ const delta = settingsDelta(initial, {+ ...initial,+ login: "keycloak",+ oauthIssuer: "https://id.example.com/realms/main/",+ oauthClientId: "stirling",+ oauthClientSecret: "s3cret",+ });+ expect(delta).toMatchObject({+ "security.oauth2.enabled": true,+ "security.oauth2.client.keycloak.issuer":+ "https://id.example.com/realms/main/",+ "security.oauth2.client.keycloak.clientId": "stirling",+ "security.oauth2.client.keycloak.clientSecret": "s3cret",+ });+ expect(delta).not.toHaveProperty("security.ssoAutoLogin");+ });++ it("never writes a masked secret the admin left alone", () => {+ const initial = draftFromSettings(SETTINGS);+ const delta = settingsDelta(initial, {+ ...initial,+ emailEnabled: true,+ smtpFrom: "[email protected]",+ });+ expect(delta).toMatchObject({ "mail.enabled": true, "mail.port": 587 });+ expect(delta).not.toHaveProperty("mail.password");+ });+});++describe("revertStep", () => {+ it("restores only the skipped step's fields", () => {+ const initial = draftFromSettings(SETTINGS);+ const edited = { ...initial, emailEnabled: true, mcpEnabled: true };+ const reverted = revertStep(edited, initial, "email");+ expect(reverted.emailEnabled).toBe(false);+ expect(reverted.mcpEnabled).toBe(true);+ });+});++describe("validateStep", () => {+ const initial = prefillAddresses(draftFromSettings(SETTINGS), ORIGIN);++ it("requires full http(s) addresses", () => {+ expect(+ validateStep(+ "addresses",+ { ...initial, frontendUrl: "pdf.example.com" },+ "quick",+ ),+ ).toEqual({ frontendUrl: "url" });+ });++ it("requires credentials once an OAuth provider is picked", () => {+ expect(+ validateStep("signIn", { ...initial, login: "oidc" }, "quick"),+ ).toEqual({+ oauthClientId: "required",+ oauthClientSecret: "required",+ oauthIssuer: "required",+ oauthProviderName: "required",+ });+ });++ it("asks for model names in either mode", () => {+ const draft = { ...initial, ai: "custom" as const, aiFastModel: "" };+ expect(validateStep("ai", draft, "quick")).toEqual({+ aiFastModel: "required",+ });+ expect(validateStep("ai", draft, "custom")).toEqual({+ aiFastModel: "required",+ });+ });+});++describe("oauthRedirectUri", () => {+ it("uses the provider name as the registration id for generic OIDC", () => {+ const draft = prefillAddresses(draftFromSettings(SETTINGS), ORIGIN);+ expect(+ oauthRedirectUri({ ...draft, login: "oidc", oauthProviderName: "okta" }),+ ).toBe(`${ORIGIN}/login/oauth2/code/okta`);+ });+});++describe("draftToSave", () => {+ it("drops answers to Custom-only steps when Quick start is chosen", () => {+ const initial = draftFromSettings(SETTINGS);+ const edited = {+ ...initial,+ ai: "custom" as const,+ storageEnabled: false,+ mcpEnabled: true,+ emailEnabled: true,+ };+ const quick = draftToSave(edited, initial, "quick");+ expect(quick.storageEnabled).toBe(true);+ expect(quick.mcpEnabled).toBe(true);+ expect(quick.emailEnabled).toBe(true);+ expect(draftToSave(edited, initial, "custom")).toEqual({+ ...edited,+ mcpAuthMode: "apikey",+ });+ });++ it("keeps MCP on when AI is switched off", () => {+ const initial = {+ ...draftFromSettings(SETTINGS),+ ai: "custom" as const,+ mcpEnabled: true,+ };+ const draft = { ...initial, ai: "off" as const };+ expect(draftToSave(draft, initial, "custom").mcpEnabled).toBe(true);+ });+});++describe("MCP", () => {+ const initial = draftFromSettings(SETTINGS);++ it("turns on with API keys, which need no identity provider", () => {+ const saved = draftToSave(+ { ...initial, mcpEnabled: true },+ initial,+ "quick",+ );+ expect(settingsDelta(initial, saved)).toEqual({+ "mcp.enabled": true,+ "mcp.auth.mode": "apikey",+ });+ });++ it("keeps the sign-in mode of a server that already runs it", () => {+ const running = { ...initial, mcpEnabled: true };+ expect(draftToSave(running, running, "custom").mcpAuthMode).toBe("oauth");+ });+});++describe("document questions", () => {+ const initial = prefillAddresses(draftFromSettings(SETTINGS), ORIGIN);+ const custom = {+ ...initial,+ ai: "custom" as const,+ aiFastModel: "fast",+ aiSmartModel: "smart",+ };++ it("saves the embedding setup with AI, leaving a masked key alone", () => {+ const delta = settingsDelta(initial, custom);+ expect(delta).toMatchObject({+ "aiEngine.features.documentQuestions": true,+ "aiEngine.rag.embeddingProvider": "voyageai",+ "aiEngine.rag.embeddingModel": "voyage-4",+ });+ expect(delta).not.toHaveProperty("aiEngine.rag.embeddingApiKey");+ });++ it("needs a model, and a base URL for local providers", () => {+ const draft = {+ ...custom,+ ...embeddingProviderChange("ollama", initial),+ embeddingModel: "",+ };+ expect(validateStep("ai", draft, "custom")).toEqual({+ embeddingModel: "required",+ embeddingBaseUrl: "required",+ });+ });++ it("starts a new provider on its own model, without the old key", () => {+ expect(embeddingProviderChange("openai", initial)).toMatchObject({+ embeddingModel: "text-embedding-3-small",+ embeddingApiKey: "",+ });+ expect(embeddingProviderChange("voyageai", initial)).toMatchObject({+ embeddingModel: "voyage-4",+ embeddingApiKey: "********",+ });+ });+});++describe("switching provider", () => {+ const initial = {+ ...draftFromSettings(SETTINGS),+ login: "google" as const,+ oauthClientId: "google-id",+ oauthClientSecret: "********",+ aiProvider: "anthropic" as const,+ aiApiKey: "********",+ aiFastModel: "claude-haiku-4-5",+ aiSmartModel: "claude-haiku-4-5",+ };++ it("never carries one provider's model names to another", () => {+ expect(aiProviderChange("openai", initial)).toMatchObject({+ aiFastModel: "",+ aiSmartModel: "",+ });+ expect(aiProviderChange("anthropic", initial)).toMatchObject({+ aiFastModel: "claude-haiku-4-5",+ aiSmartModel: "claude-haiku-4-5",+ });+ });++ it("has Quick start ask for model names only once there are none to keep", () => {+ expect(asksForModels("quick", initial, initial)).toBe(false);+ const switched = { ...initial, ...aiProviderChange("ollama", initial) };+ expect(asksForModels("quick", switched, initial)).toBe(true);+ expect(asksForModels("custom", initial, initial)).toBe(true);+ const noModels = { ...initial, aiFastModel: "", aiSmartModel: "" };+ expect(asksForModels("quick", noModels, noModels)).toBe(true);+ });++ it("will not save Your own AI without model names, in either mode", () => {+ const switched = {+ ...prefillAddresses(initial, ORIGIN),+ ai: "custom" as const,+ aiEngineUrl: "http://localhost:5001",+ ...aiProviderChange("openai", initial),+ };+ expect(validateStep("summary", switched, "quick")).toMatchObject({+ aiFastModel: "required",+ aiSmartModel: "required",+ });+ });++ it("never hands one provider's secret to another", () => {+ expect(loginChange("keycloak", initial)).toMatchObject({+ oauthClientId: "",+ oauthClientSecret: "",+ });+ expect(aiProviderChange("openai", initial)).toMatchObject({ aiApiKey: "" });+ });++ it("restores the server's values on going back to its provider", () => {+ expect(loginChange("google", initial)).toMatchObject({+ oauthClientId: "google-id",+ oauthClientSecret: "********",+ });+ expect(aiProviderChange("anthropic", initial)).toMatchObject({+ aiApiKey: "********",+ });+ });+});++describe("issuersToCheck", () => {+ const initial = prefillAddresses(draftFromSettings(SETTINGS), ORIGIN);++ it("checks a new sign-in issuer on the steps that save it", () => {+ const draft = {+ ...initial,+ login: "oidc" as const,+ oauthIssuer: "https://id.example.com",+ };+ expect(issuersToCheck("summary", draft, initial)).toEqual(["oauthIssuer"]);+ expect(issuersToCheck("signIn", draft, initial)).toEqual(["oauthIssuer"]);+ expect(issuersToCheck("email", draft, initial)).toEqual([]);+ });++ it("skips an issuer the server already uses", () => {+ const using = {+ ...initial,+ login: "keycloak" as const,+ oauthIssuer: "https://id.example.com",+ };+ expect(issuersToCheck("signIn", { ...using }, using)).toEqual([]);+ });+});++describe("provider name", () => {+ it("must be safe as a redirect URI path segment", () => {+ const draft = {+ ...prefillAddresses(draftFromSettings(SETTINGS), ORIGIN),+ login: "oidc" as const,+ oauthIssuer: "https://id.example.com",+ oauthClientId: "id",+ oauthClientSecret: "secret",+ oauthProviderName: "my okta/",+ };+ expect(validateStep("signIn", draft, "quick")).toEqual({+ oauthProviderName: "providerName",+ });+ });+});++describe("isValidUsername", () => {+ it("takes what the server takes", () => {+ expect(isValidUsername("pdf-admin")).toBe(true);+ expect(isValidUsername("[email protected]")).toBe(true);+ });++ it("turns down what the server turns down", () => {+ expect(isValidUsername("ab")).toBe(false);+ expect(isValidUsername("-admin")).toBe(false);+ expect(isValidUsername("ad..min")).toBe(false);+ expect(isValidUsername("has space")).toBe(false);+ expect(isValidUsername("anonymousUser")).toBe(false);+ });+});++describe("settings the server already has", () => {+ const fresh = draftFromSettings(SETTINGS);+ const preconfigured = {+ ...fresh,+ frontendUrl: ORIGIN,+ backendUrl: ORIGIN,+ login: "keycloak" as const,+ oauthIssuer: "https://sso.example.com/realms/pdf",+ oauthClientId: "pdf",+ oauthClientSecret: "********",+ emailEnabled: true,+ smtpHost: "mail.example.com",+ smtpFrom: "[email protected]",+ analytics: false,+ };++ it("asks about everything on a fresh server", () => {+ expect(stepsConfiguredOnServer(fresh)).toEqual(new Set());+ expect(stepsFor("quick", stepsConfiguredOnServer(fresh))).toEqual([+ "summary",+ "analytics",+ ]);+ });++ it("leaves out each step the server already has", () => {+ const configured = stepsConfiguredOnServer(preconfigured);+ expect(configured).toEqual(+ new Set(["addresses", "signIn", "email", "analytics"]),+ );+ expect(stepsFor("custom", configured)).toEqual(["language", "files", "ai"]);+ expect(stepsFor("quick", configured)).toEqual(["summary"]);+ });++ it("keeps a step the server has switched on but not finished", () => {+ const halfSet = { ...fresh, frontendUrl: ORIGIN };+ expect(stepsConfiguredOnServer(halfSet).has("addresses")).toBe(false);+ const noSender = { ...preconfigured, smtpFrom: "" };+ expect(stepsConfiguredOnServer(noSender).has("email")).toBe(false);+ });++ it("drops the summary once it has nothing left to ask", () => {+ const allSet = {+ ...preconfigured,+ ai: "custom" as const,+ aiEngineUrl: "http://localhost:5001",+ documentQuestions: false,+ };+ expect(stepsFor("quick", stepsConfiguredOnServer(allSet))).toEqual([]);+ });+});diff --git a/frontend/src/editor/proprietary/components/serverSetup/serverSetupDraft.ts b/frontend/src/editor/proprietary/components/serverSetup/serverSetupDraft.tsnew file mode 100644index 0000000000..ca09125aea--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/serverSetupDraft.ts@@ -0,0 +1,738 @@+// The setup wizard's answers and their settings.yml keys. Only keys that differ+// from the server's are saved, so untouched fields keep the server's values.++import { EMBEDDING_MODEL_SUGGESTIONS } from "@editor/components/shared/config/configSections/aiEngineSettings";++export type SetupMode = "quick" | "custom";++export type SetupStepId =+ | "addresses"+ | "language"+ | "signIn"+ | "email"+ | "files"+ | "ai"+ | "analytics"+ | "password"+ | "summary";++/** The settings each mode asks about; anything else keeps the server's value. */+export const SETUP_STEPS: Record<SetupMode, SetupStepId[]> = {+ quick: ["addresses", "signIn", "email", "ai", "analytics"],+ custom: [+ "addresses",+ "language",+ "signIn",+ "email",+ "files",+ "ai",+ "analytics",+ ],+};++/** Quick start shows these together on one summary card. */+export const QUICK_SUMMARY_STEPS: SetupStepId[] = [+ "addresses",+ "signIn",+ "email",+ "ai",+];++/** Whether the server has each step's settings set at all. Only steps with+ * an unmistakable set state are here: a locale or a file switch reads the+ * same whether an admin chose it or never touched it. */+const SET_ON_SERVER: Partial<+ Record<SetupStepId, (draft: ServerSetupDraft) => boolean>+> = {+ addresses: (draft) =>+ Boolean(draft.frontendUrl.trim() || draft.backendUrl.trim()),+ signIn: (draft) => draft.login !== "password",+ email: (draft) => draft.emailEnabled,+ ai: (draft) => draft.ai !== "off",+ analytics: (draft) => draft.analytics !== null,+};++/** Steps the server already has set and complete, so setup leaves them out.+ * One set but incomplete stays in, so the admin can finish it. */+export function stepsConfiguredOnServer(+ initial: ServerSetupDraft,+): Set<SetupStepId> {+ return new Set(+ (Object.keys(SET_ON_SERVER) as SetupStepId[]).filter(+ (step) =>+ SET_ON_SERVER[step]?.(initial) === true &&+ Object.keys(validateStep(step, initial, "custom")).length === 0,+ ),+ );+}++/** The Quick start summary's settings the server doesn't already have. */+function summaryStepsFor(configured: ReadonlySet<SetupStepId>): SetupStepId[] {+ return QUICK_SUMMARY_STEPS.filter((step) => !configured.has(step));+}++/** The numbered cards after the mode choice, leaving out `configured` steps;+ * Quick start's settings share one summary card. An owed password has its+ * own card before these. */+export function stepsFor(+ mode: SetupMode,+ configured: ReadonlySet<SetupStepId> = new Set(),+): SetupStepId[] {+ const shown = (step: SetupStepId) => !configured.has(step);+ if (mode === "custom") return SETUP_STEPS.custom.filter(shown);+ const summary: SetupStepId[] =+ summaryStepsFor(configured).length > 0 ? ["summary"] : [];+ return [...summary, ...(["analytics"] as SetupStepId[]).filter(shown)];+}++/** Issuer fields `step` would save with a new value; each must answer OIDC+ * discovery first, since one the server can't reach stops sign-in. */+export function issuersToCheck(+ step: SetupStepId,+ draft: ServerSetupDraft,+ initial: ServerSetupDraft,+): "oauthIssuer"[] {+ const covers = step === "summary" ? QUICK_SUMMARY_STEPS : [step];+ return covers.includes("signIn") &&+ loginNeedsIssuer(draft.login) &&+ draft.oauthIssuer.trim() !== initial.oauthIssuer.trim()+ ? ["oauthIssuer"]+ : [];+}++/** Sign-in fields for switching to `login`: the server's own on its current+ * method, blank otherwise, so no provider is handed another's secret. */+export function loginChange(+ login: LoginMethod,+ initial: ServerSetupDraft,+): Partial<ServerSetupDraft> {+ if (login === initial.login) {+ return {+ login,+ oauthIssuer: initial.oauthIssuer,+ oauthClientId: initial.oauthClientId,+ oauthClientSecret: initial.oauthClientSecret,+ oauthProviderName: initial.oauthProviderName,+ };+ }+ return {+ login,+ oauthIssuer: "",+ oauthClientId: "",+ oauthClientSecret: "",+ oauthProviderName: "",+ };+}++/** The same for the AI provider, whose key, base URL and model names are its+ * own: another provider's model names would fail every AI call. */+export function aiProviderChange(+ provider: AiProvider,+ initial: ServerSetupDraft,+): Partial<ServerSetupDraft> {+ return provider === initial.aiProvider+ ? {+ aiProvider: provider,+ aiApiKey: initial.aiApiKey,+ aiBaseUrl: initial.aiBaseUrl,+ aiFastModel: initial.aiFastModel,+ aiSmartModel: initial.aiSmartModel,+ }+ : {+ aiProvider: provider,+ aiApiKey: "",+ aiBaseUrl: "",+ aiFastModel: "",+ aiSmartModel: "",+ };+}++/** Whether the AI card shows model names: Quick start keeps the server's and+ * asks only when there are none to keep (a new provider, or none set). */+export function asksForModels(+ mode: SetupMode,+ draft: ServerSetupDraft,+ initial: ServerSetupDraft,+): boolean {+ return (+ mode === "custom" ||+ draft.aiProvider !== initial.aiProvider ||+ !initial.aiFastModel.trim() ||+ !initial.aiSmartModel.trim()+ );+}++/** The same for the embedding provider: a new one starts on its first+ * suggested model, since the previous provider's means nothing to it. */+export function embeddingProviderChange(+ provider: EmbeddingProvider,+ initial: ServerSetupDraft,+): Partial<ServerSetupDraft> {+ return provider === initial.embeddingProvider+ ? {+ embeddingProvider: provider,+ embeddingModel: initial.embeddingModel,+ embeddingApiKey: initial.embeddingApiKey,+ embeddingBaseUrl: initial.embeddingBaseUrl,+ }+ : {+ embeddingProvider: provider,+ embeddingModel: EMBEDDING_MODEL_SUGGESTIONS[provider]?.[0] ?? "",+ embeddingApiKey: "",+ embeddingBaseUrl: "",+ };+}++/** Field errors across several steps, as one map (their fields never overlap). */+export function validateSteps(+ steps: SetupStepId[],+ draft: ServerSetupDraft,+ mode: SetupMode,+): StepErrors {+ return steps.reduce<StepErrors>(+ (all, step) => ({ ...all, ...validateStep(step, draft, mode) }),+ {},+ );+}++export type LoginMethod =+ | "password"+ | "google"+ | "github"+ | "keycloak"+ | "oidc";++/** "stirling" is only ever read back from a server already on Stirling AI. */+export type AiChoice = "off" | "custom" | "stirling";++export type AiProvider = "anthropic" | "openai" | "ollama" | "custom";++export type EmbeddingProvider = "voyageai" | "openai" | "ollama" | "custom";++/** How MCP clients sign in: OAuth needs an identity provider, so setup only turns on API keys. */+export type McpAuthMode = "oauth" | "apikey";++export interface ServerSetupDraft {+ frontendUrl: string;+ backendUrl: string;+ defaultLocale: string;+ login: LoginMethod;+ oauthIssuer: string;+ oauthClientId: string;+ oauthClientSecret: string;+ oauthProviderName: string;+ emailEnabled: boolean;+ smtpHost: string;+ smtpPort: string;+ smtpUsername: string;+ smtpPassword: string;+ smtpFrom: string;+ storageEnabled: boolean;+ sharingEnabled: boolean;+ ai: AiChoice;+ aiEngineUrl: string;+ aiProvider: AiProvider;+ aiApiKey: string;+ aiBaseUrl: string;+ aiFastModel: string;+ aiSmartModel: string;+ documentQuestions: boolean;+ embeddingProvider: EmbeddingProvider;+ embeddingModel: string;+ embeddingApiKey: string;+ embeddingBaseUrl: string;+ mcpEnabled: boolean;+ mcpAuthMode: McpAuthMode;+ analytics: boolean | null;+ adminUsername: string;+ currentPassword: string;+ newPassword: string;+ confirmPassword: string;+}++/** The draft fields each step edits; Skip restores these to the server's values. */+export const STEP_FIELDS: Record<SetupStepId, (keyof ServerSetupDraft)[]> = {+ addresses: ["frontendUrl", "backendUrl"],+ language: ["defaultLocale"],+ signIn: [+ "login",+ "oauthIssuer",+ "oauthClientId",+ "oauthClientSecret",+ "oauthProviderName",+ ],+ email: [+ "emailEnabled",+ "smtpHost",+ "smtpPort",+ "smtpUsername",+ "smtpPassword",+ "smtpFrom",+ ],+ files: ["storageEnabled", "sharingEnabled"],+ ai: [+ "ai",+ "aiEngineUrl",+ "aiProvider",+ "aiApiKey",+ "aiBaseUrl",+ "aiFastModel",+ "aiSmartModel",+ "documentQuestions",+ "embeddingProvider",+ "embeddingModel",+ "embeddingApiKey",+ "embeddingBaseUrl",+ "mcpEnabled",+ "mcpAuthMode",+ ],+ analytics: ["analytics"],+ password: [+ "adminUsername",+ "currentPassword",+ "newPassword",+ "confirmPassword",+ ],+ summary: [],+};++/** Providers whose models are reached through an OpenAI-compatible base URL. */+export function providerNeedsBaseUrl(+ provider: AiProvider | EmbeddingProvider,+): boolean {+ return provider === "ollama" || provider === "custom";+}++/** Ollama runs locally and takes no key. */+export function embeddingNeedsApiKey(provider: EmbeddingProvider): boolean {+ return provider !== "ollama";+}++export function loginNeedsIssuer(login: LoginMethod): boolean {+ return login === "keycloak" || login === "oidc";+}++/** The OAuth callback the provider must allow. Must match the backend's+ * OAuth2Configuration.REDIRECT_URI_PATH (provider key, or OIDC name). */+export function oauthRedirectUri(draft: ServerSetupDraft): string {+ const registrationId =+ draft.login === "oidc" ? draft.oauthProviderName.trim() : draft.login;+ return `${trimUrl(draft.backendUrl)}/login/oauth2/code/${registrationId}`;+}++type Settings = Record<string, unknown>;++function read(settings: Settings, path: string): unknown {+ let node: unknown = settings;+ for (const part of path.split(".")) {+ if (typeof node !== "object" || node === null) return undefined;+ node = (node as Settings)[part];+ }+ return node;+}++function readString(settings: Settings, path: string): string {+ const value = read(settings, path);+ return typeof value === "string" || typeof value === "number"+ ? String(value)+ : "";+}++function readBool(settings: Settings, path: string): boolean {+ return read(settings, path) === true;+}++function readLogin(settings: Settings): LoginMethod {+ if (!readBool(settings, "security.oauth2.enabled")) return "password";+ if (readString(settings, "security.oauth2.client.google.clientId"))+ return "google";+ if (readString(settings, "security.oauth2.client.github.clientId"))+ return "github";+ if (readString(settings, "security.oauth2.client.keycloak.clientId"))+ return "keycloak";+ return "oidc";+}++function oauthPrefix(login: LoginMethod): string {+ switch (login) {+ case "google":+ case "github":+ case "keycloak":+ return `security.oauth2.client.${login}`;+ default:+ return "security.oauth2";+ }+}++function readAi(settings: Settings): AiChoice {+ if (!readBool(settings, "aiEngine.enabled")) return "off";+ return read(settings, "aiEngine.mode") === "CLOUD" ? "stirling" : "custom";+}++function readProvider(settings: Settings): AiProvider {+ const value = readString(settings, "aiEngine.models.provider");+ return value === "openai" || value === "ollama" || value === "custom"+ ? value+ : "anthropic";+}++function readEmbeddingProvider(settings: Settings): EmbeddingProvider {+ const value = readString(settings, "aiEngine.rag.embeddingProvider");+ return value === "openai" || value === "ollama" || value === "custom"+ ? value+ : "voyageai";+}++/** How GET /api/v1/admin/settings returns a secret. */+const MASKED_SECRET = "********";++/** settings.yml.template's sample host; shown empty so it is never saved as real. */+const TEMPLATE_SMTP_HOST = "smtp.example.com";++/** The draft as the server stands, from GET /api/v1/admin/settings; masked+ * secrets left untouched are never written back. */+export function draftFromSettings(settings: Settings): ServerSetupDraft {+ const login = readLogin(settings);+ const prefix = oauthPrefix(login);+ const analytics = read(settings, "system.enableAnalytics");+ return {+ frontendUrl: readString(settings, "system.frontendUrl"),+ backendUrl: readString(settings, "system.backendUrl"),+ defaultLocale: readString(settings, "system.defaultLocale"),+ login,+ oauthIssuer:+ login === "password" ? "" : readString(settings, `${prefix}.issuer`),+ oauthClientId:+ login === "password" ? "" : readString(settings, `${prefix}.clientId`),+ oauthClientSecret:+ login === "password"+ ? ""+ : readString(settings, `${prefix}.clientSecret`),+ oauthProviderName:+ login === "oidc" ? readString(settings, "security.oauth2.provider") : "",+ emailEnabled: readBool(settings, "mail.enabled"),+ smtpHost:+ readString(settings, "mail.host") === TEMPLATE_SMTP_HOST+ ? ""+ : readString(settings, "mail.host"),+ smtpPort: readString(settings, "mail.port"),+ smtpUsername: readString(settings, "mail.username"),+ smtpPassword: readString(settings, "mail.password"),+ smtpFrom: readString(settings, "mail.from"),+ storageEnabled: readBool(settings, "storage.enabled"),+ sharingEnabled: readBool(settings, "storage.sharing.enabled"),+ ai: readAi(settings),+ aiEngineUrl: readString(settings, "aiEngine.url"),+ aiProvider: readProvider(settings),+ aiApiKey: readString(settings, "aiEngine.models.apiKey"),+ aiBaseUrl: readString(settings, "aiEngine.models.baseUrl"),+ aiFastModel: readString(settings, "aiEngine.models.fastModel"),+ aiSmartModel: readString(settings, "aiEngine.models.smartModel"),+ documentQuestions: readBool(+ settings,+ "aiEngine.features.documentQuestions",+ ),+ embeddingProvider: readEmbeddingProvider(settings),+ embeddingModel: readString(settings, "aiEngine.rag.embeddingModel"),+ embeddingApiKey: readString(settings, "aiEngine.rag.embeddingApiKey"),+ embeddingBaseUrl: readString(settings, "aiEngine.rag.embeddingBaseUrl"),+ mcpEnabled: readBool(settings, "mcp.enabled"),+ mcpAuthMode:+ readString(settings, "mcp.auth.mode") === "apikey" ? "apikey" : "oauth",+ analytics: typeof analytics === "boolean" ? analytics : null,+ adminUsername: "",+ currentPassword: "",+ newPassword: "",+ confirmPassword: "",+ };+}++/** Fills addresses the server hasn't set from `origin`; draft-only, so the+ * prefilled value counts as a change and is saved. */+export function prefillAddresses(+ draft: ServerSetupDraft,+ origin: string,+): ServerSetupDraft {+ const frontendUrl = draft.frontendUrl || origin;+ return {+ ...draft,+ frontendUrl,+ backendUrl: draft.backendUrl || frontendUrl,+ };+}++function trimUrl(url: string): string {+ return url.trim().replace(/\/+$/, "");+}++function loginSettings(draft: ServerSetupDraft): Settings {+ if (draft.login === "password") return { "security.oauth2.enabled": false };+ const prefix = oauthPrefix(draft.login);+ const settings: Settings = {+ "security.oauth2.enabled": true,+ [`${prefix}.clientId`]: draft.oauthClientId.trim(),+ [`${prefix}.clientSecret`]: draft.oauthClientSecret.trim(),+ };+ if (loginNeedsIssuer(draft.login)) {+ // As entered, slash and all: Spring matches it against the issuer the+ // discovery document advertises, and Auth0 advertises a trailing slash.+ settings[`${prefix}.issuer`] = draft.oauthIssuer.trim();+ }+ if (draft.login === "oidc") {+ settings["security.oauth2.provider"] = draft.oauthProviderName.trim();+ }+ return settings;+}++function emailSettings(draft: ServerSetupDraft): Settings {+ if (!draft.emailEnabled) return { "mail.enabled": false };+ const port = Number(draft.smtpPort);+ return {+ "mail.enabled": true,+ "mail.host": draft.smtpHost.trim(),+ "mail.port": Number.isInteger(port) ? port : draft.smtpPort,+ "mail.username": draft.smtpUsername.trim(),+ "mail.password": draft.smtpPassword,+ "mail.from": draft.smtpFrom.trim(),+ };+}++function aiSettings(draft: ServerSetupDraft): Settings {+ if (draft.ai === "off") return { "aiEngine.enabled": false };+ if (draft.ai === "stirling") return { "aiEngine.enabled": true };+ const settings: Settings = {+ "aiEngine.enabled": true,+ "aiEngine.mode": "SELF_HOSTED",+ "aiEngine.url": trimUrl(draft.aiEngineUrl),+ "aiEngine.models.provider": draft.aiProvider,+ "aiEngine.models.apiKey": draft.aiApiKey.trim(),+ "aiEngine.models.fastModel": draft.aiFastModel.trim(),+ "aiEngine.models.smartModel": draft.aiSmartModel.trim(),+ };+ if (providerNeedsBaseUrl(draft.aiProvider)) {+ settings["aiEngine.models.baseUrl"] = trimUrl(draft.aiBaseUrl);+ }+ return { ...settings, ...documentQuestionSettings(draft) };+}++/** Document questions search an embedding index, so they need an embedding model. */+function documentQuestionSettings(draft: ServerSetupDraft): Settings {+ if (!draft.documentQuestions) {+ return { "aiEngine.features.documentQuestions": false };+ }+ const settings: Settings = {+ "aiEngine.features.documentQuestions": true,+ "aiEngine.rag.embeddingProvider": draft.embeddingProvider,+ "aiEngine.rag.embeddingModel": draft.embeddingModel.trim(),+ };+ if (embeddingNeedsApiKey(draft.embeddingProvider)) {+ settings["aiEngine.rag.embeddingApiKey"] = draft.embeddingApiKey.trim();+ }+ if (providerNeedsBaseUrl(draft.embeddingProvider)) {+ settings["aiEngine.rag.embeddingBaseUrl"] = trimUrl(draft.embeddingBaseUrl);+ }+ return settings;+}++function toSettings(draft: ServerSetupDraft): Settings {+ return {+ "system.frontendUrl": trimUrl(draft.frontendUrl),+ "system.backendUrl": trimUrl(draft.backendUrl),+ "system.defaultLocale": draft.defaultLocale,+ ...loginSettings(draft),+ ...emailSettings(draft),+ "storage.enabled": draft.storageEnabled,+ "storage.sharing.enabled": draft.sharingEnabled,+ ...aiSettings(draft),+ "mcp.enabled": draft.mcpEnabled,+ ...(draft.mcpEnabled ? { "mcp.auth.mode": draft.mcpAuthMode } : {}),+ ...(draft.analytics === null+ ? {}+ : { "system.enableAnalytics": draft.analytics }),+ };+}++/** Dotted settings keys whose value in `draft` differs from `initial`. */+export function settingsDelta(+ initial: ServerSetupDraft,+ draft: ServerSetupDraft,+): Settings {+ const before = toSettings(initial);+ const after = toSettings(draft);+ return Object.fromEntries(+ Object.entries(after).filter(+ ([key, value]) => value !== MASKED_SECRET && before[key] !== value,+ ),+ );+}++/** The draft with every field `step` edits put back to the server's value. */+export function revertStep(+ draft: ServerSetupDraft,+ initial: ServerSetupDraft,+ step: SetupStepId,+): ServerSetupDraft {+ const next = { ...draft };+ for (const field of STEP_FIELDS[step]) {+ Object.assign(next, { [field]: initial[field] });+ }+ return next;+}++/** What Finish saves: steps outside the chosen mode revert to the server's.+ * MCP switched on here uses API keys; one already running keeps its mode. */+export function draftToSave(+ draft: ServerSetupDraft,+ initial: ServerSetupDraft,+ mode: SetupMode,+): ServerSetupDraft {+ const hidden = (Object.keys(STEP_FIELDS) as SetupStepId[]).filter(+ (step) => !SETUP_STEPS[mode].includes(step),+ );+ const saved = hidden.reduce(+ (next, step) => revertStep(next, initial, step),+ draft,+ );+ return saved.mcpEnabled && !initial.mcpEnabled+ ? { ...saved, mcpAuthMode: "apikey" }+ : saved;+}++function isHttpUrl(value: string): boolean {+ try {+ const url = new URL(value.trim());+ return url.protocol === "http:" || url.protocol === "https:";+ } catch {+ return false;+ }+}++export type ErrorCode =+ | "required"+ | "url"+ | "port"+ | "email"+ | "passwordLength"+ | "passwordMismatch"+ | "passwordUnchanged"+ | "passwordIncorrect"+ | "passwordRejected"+ | "issuerUnreachable"+ | "providerName"+ | "username"+ | "usernameTaken";++/** The provider name is the OAuth registration id and a redirect URI path segment. */+const PROVIDER_NAME = /^[A-Za-z0-9_-]+$/;++/** Mirrors RegexPatternUtils' username pattern; the server also takes an email address. */+const SIMPLE_USERNAME =+ /^[a-zA-Z0-9](?!.*[-@._+]{2,})[a-zA-Z0-9@._+-]{1,48}[a-zA-Z0-9]$/;+const EMAIL_USERNAME = /^[^\s@]{1,64}@[^\s@]{1,255}$/;++/** Names UserService.isUsernameValid turns down whatever their shape. */+const RESERVED_USERNAMES = ["all_users", "anonymoususer"];++/** A first check only; the server's answer is final. */+export function isValidUsername(value: string): boolean {+ const name = value.trim();+ return (+ (SIMPLE_USERNAME.test(name) || EMAIL_USERNAME.test(name)) &&+ !RESERVED_USERNAMES.includes(name.toLowerCase())+ );+}++/** Matches the first-login password screen's rule. */+const MIN_PASSWORD_LENGTH = 8;++export type StepErrors = Partial<Record<keyof ServerSetupDraft, ErrorCode>>;++/** Field errors for `step` as codes it translates; empty when it can go on. */+export function validateStep(+ step: SetupStepId,+ draft: ServerSetupDraft,+ mode: SetupMode,+): StepErrors {+ const errors: StepErrors = {};+ const require = (field: keyof ServerSetupDraft) => {+ if (!String(draft[field] ?? "").trim()) errors[field] = "required";+ };+ const requireUrl = (field: keyof ServerSetupDraft) => {+ require(field);+ if (!errors[field] && !isHttpUrl(String(draft[field])))+ errors[field] = "url";+ };++ switch (step) {+ case "addresses":+ requireUrl("frontendUrl");+ requireUrl("backendUrl");+ break;+ case "signIn":+ if (draft.login !== "password") {+ require("oauthClientId");+ require("oauthClientSecret");+ if (loginNeedsIssuer(draft.login)) requireUrl("oauthIssuer");+ if (draft.login === "oidc") {+ require("oauthProviderName");+ if (+ !errors.oauthProviderName &&+ !PROVIDER_NAME.test(draft.oauthProviderName.trim())+ ) {+ errors.oauthProviderName = "providerName";+ }+ }+ }+ break;+ case "email":+ if (draft.emailEnabled) {+ require("smtpHost");+ const port = Number(draft.smtpPort);+ if (!Number.isInteger(port) || port < 1 || port > 65535) {+ errors.smtpPort = "port";+ }+ require("smtpFrom");+ if (+ !errors.smtpFrom &&+ !/^[^\s@]+@[^\s@]+$/.test(draft.smtpFrom.trim())+ ) {+ errors.smtpFrom = "email";+ }+ }+ break;+ case "ai":+ if (draft.ai === "custom") {+ requireUrl("aiEngineUrl");+ if (providerNeedsBaseUrl(draft.aiProvider)) requireUrl("aiBaseUrl");+ require("aiFastModel");+ require("aiSmartModel");+ }+ if (draft.ai === "custom" && draft.documentQuestions) {+ require("embeddingModel");+ if (providerNeedsBaseUrl(draft.embeddingProvider)) {+ requireUrl("embeddingBaseUrl");+ }+ }+ break;+ case "summary":+ return validateSteps(QUICK_SUMMARY_STEPS, draft, mode);+ case "password":+ require("adminUsername");+ if (!errors.adminUsername && !isValidUsername(draft.adminUsername)) {+ errors.adminUsername = "username";+ }+ require("currentPassword");+ if (draft.newPassword.length < MIN_PASSWORD_LENGTH) {+ errors.newPassword = "passwordLength";+ } else if (draft.newPassword === draft.currentPassword) {+ errors.newPassword = "passwordUnchanged";+ }+ if (draft.confirmPassword !== draft.newPassword) {+ errors.confirmPassword = "passwordMismatch";+ }+ break;+ default:+ break;+ }+ return errors;+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/setupAddressPrefill.ts b/frontend/src/editor/proprietary/components/serverSetup/setupAddressPrefill.tsnew file mode 100644index 0000000000..6f90ba7fb6--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/setupAddressPrefill.ts@@ -0,0 +1,8 @@+import { withBasePath } from "@editor/constants/app";++/** The address setup offers for the server: this page's origin, or empty when+ * the page isn't served over http(s). */+export function setupAddressPrefill(): string {+ if (!/^https?:$/.test(window.location.protocol)) return "";+ return `${window.location.origin}${withBasePath("/")}`.replace(/\/+$/, "");+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/setupSignInHandoff.ts b/frontend/src/editor/proprietary/components/serverSetup/setupSignInHandoff.tsnew file mode 100644index 0000000000..9dada30dc1--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/setupSignInHandoff.ts@@ -0,0 +1,31 @@+// Set by the login page after its automatic default sign-in, so the app holds+// the sign-in card rather than flash the editor. Per tab; a display hint only.+const KEY = "stirling.setupSignInHandoff";++/** Past this the hint is stale, so the app is never held up for long. */+const MAX_HOLD_MS = 10_000;++export function markSetupSignIn(): void {+ try {+ sessionStorage.setItem(KEY, String(Date.now()));+ } catch {+ // Without storage the editor may show for a moment; nothing else changes.+ }+}++export function isSetupSignInPending(): boolean {+ try {+ const markedAt = Number(sessionStorage.getItem(KEY));+ return markedAt > 0 && Date.now() - markedAt < MAX_HOLD_MS;+ } catch {+ return false;+ }+}++export function clearSetupSignIn(): void {+ try {+ sessionStorage.removeItem(KEY);+ } catch {+ // Nothing to clear.+ }+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/AddressesStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/AddressesStep.tsxnew file mode 100644index 0000000000..19db9c4c13--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/AddressesStep.tsx@@ -0,0 +1,42 @@+import { useTranslation } from "react-i18next";+import {+ FieldGroup,+ TextField,+ type SetupStepProps,+} from "@editor/components/serverSetup/SetupFields";++export function AddressesStep({ draft, update, errors }: SetupStepProps) {+ const { t } = useTranslation();+ return (+ <>+ <FieldGroup>+ <TextField+ required+ type="url"+ label={t("serverSetup.addresses.frontendUrl", "Web address")}+ info={t(+ "serverSetup.addresses.frontendUrlHelp",+ "Where people open Stirling PDF. Used in emails, share links and QR codes.",+ )}+ placeholder="https://pdf.example.com"+ value={draft.frontendUrl}+ onChange={(frontendUrl) => update({ frontendUrl })}+ error={errors.frontendUrl}+ />+ <TextField+ required+ type="url"+ label={t("serverSetup.addresses.backendUrl", "Server address")}+ info={t(+ "serverSetup.addresses.backendUrlHelp",+ "Where sign-in providers send people back. Usually the same as the web address.",+ )}+ placeholder="https://pdf.example.com"+ value={draft.backendUrl}+ onChange={(backendUrl) => update({ backendUrl })}+ error={errors.backendUrl}+ />+ </FieldGroup>+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/AiStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/AiStep.tsxnew file mode 100644index 0000000000..ba000cd507--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/AiStep.tsx@@ -0,0 +1,244 @@+import { useTranslation } from "react-i18next";+import { FormField } from "@editor/ui/FormField";+import { Select } from "@editor/ui/Select";+import {+ OnOffControl,+ sectionToggle,+ SETUP_DROPDOWN,+ SettingRow,+ SetupChoice,+ TextField,+ type SetupStepProps,+} from "@editor/components/serverSetup/SetupFields";+import {+ aiProviderChange,+ asksForModels,+ embeddingNeedsApiKey,+ embeddingProviderChange,+ providerNeedsBaseUrl,+ type AiChoice,+ type AiProvider,+ type EmbeddingProvider,+} from "@editor/components/serverSetup/serverSetupDraft";++export function AiStep(props: SetupStepProps) {+ const { draft, initial, update, errors, mode, setOpenSection } = props;+ const { t } = useTranslation();+ const label = t("serverSetup.ai.label", "Self-hosted AI");+ const documentsLabel = t("serverSetup.documents.label", "Document questions");+ const mcpLabel = t("serverSetup.mcp.label", "MCP server");+ const choices: { value: AiChoice; label: string }[] = [+ { value: "off", label: t("serverSetup.off", "Off") },+ { value: "custom", label: t("serverSetup.on", "On") },+ ];+ // Stirling AI cannot be set up from here yet; keep it selectable only on a+ // server that already uses it, so the wizard never switches it off by accident.+ if (initial.ai === "stirling") {+ choices.push({+ value: "stirling",+ label: t("serverSetup.ai.stirling", "Stirling AI"),+ });+ }+ const embeddingProviders: { value: EmbeddingProvider; label: string }[] = [+ { value: "voyageai", label: "VoyageAI" },+ { value: "openai", label: "OpenAI" },+ { value: "ollama", label: "Ollama" },+ {+ value: "custom",+ label: t("serverSetup.ai.providerCustom", "OpenAI-compatible"),+ },+ ];+ const providers: { value: AiProvider; label: string }[] = [+ { value: "anthropic", label: "Anthropic" },+ { value: "openai", label: "OpenAI" },+ { value: "ollama", label: "Ollama" },+ {+ value: "custom",+ label: t("serverSetup.ai.providerCustom", "OpenAI-compatible"),+ },+ ];++ const aiExpand =+ draft.ai === "custom" ? sectionToggle(props, "ai") : undefined;+ const documentsExpand = draft.documentQuestions+ ? sectionToggle(props, "documents")+ : undefined;++ return (+ <>+ <SettingRow+ label={label}+ expand={aiExpand}+ details={+ <>+ <TextField+ required+ type="url"+ label={t("serverSetup.ai.engineUrl", "AI engine address")}+ placeholder="http://localhost:5001"+ value={draft.aiEngineUrl}+ onChange={(aiEngineUrl) => update({ aiEngineUrl })}+ error={errors.aiEngineUrl}+ />+ <FormField label={t("serverSetup.ai.provider", "Model provider")}>+ <Select+ comboboxProps={SETUP_DROPDOWN}+ options={providers}+ value={draft.aiProvider}+ onChange={(value) => {+ if (value)+ update(aiProviderChange(value as AiProvider, initial));+ }}+ />+ </FormField>+ {providerNeedsBaseUrl(draft.aiProvider) && (+ <TextField+ required+ type="url"+ label={t("serverSetup.ai.baseUrl", "Base URL")}+ placeholder="http://ollama:11434/v1"+ value={draft.aiBaseUrl}+ onChange={(aiBaseUrl) => update({ aiBaseUrl })}+ error={errors.aiBaseUrl}+ />+ )}+ <TextField+ type="password"+ label={t("serverSetup.ai.apiKey", "API key")}+ info={t(+ "serverSetup.ai.apiKeyHelp",+ "Leave empty to use the key the AI engine already has.",+ )}+ value={draft.aiApiKey}+ onChange={(aiApiKey) => update({ aiApiKey })}+ />+ {asksForModels(mode, draft, initial) && (+ <>+ <TextField+ required+ label={t("serverSetup.ai.fastModel", "Fast model")}+ value={draft.aiFastModel}+ onChange={(aiFastModel) => update({ aiFastModel })}+ error={errors.aiFastModel}+ />+ <TextField+ required+ label={t("serverSetup.ai.smartModel", "Full model")}+ value={draft.aiSmartModel}+ onChange={(aiSmartModel) => update({ aiSmartModel })}+ error={errors.aiSmartModel}+ />+ </>+ )}+ <FormField label={mcpLabel}>+ <OnOffControl+ ariaLabel={mcpLabel}+ value={draft.mcpEnabled}+ onChange={(mcpEnabled) => update({ mcpEnabled })}+ />+ </FormField>+ </>+ }+ >+ {() => (+ <SetupChoice+ ariaLabel={label}+ value={draft.ai}+ onChange={(ai) => {+ // MCP is only shown while AI is on, so switching AI off must+ // not leave a change to it that the admin can no longer see.+ update(+ ai === "custom"+ ? { ai }+ : { ai, mcpEnabled: initial.mcpEnabled },+ );+ if (ai === "custom") setOpenSection("ai");+ }}+ options={choices}+ expand={aiExpand}+ expandValue="custom"+ />+ )}+ </SettingRow>+ {draft.ai === "custom" && (+ <SettingRow+ label={documentsLabel}+ expand={documentsExpand}+ details={+ <>+ <FormField+ label={t(+ "serverSetup.documents.provider",+ "Embedding provider",+ )}+ info={t(+ "serverSetup.documents.providerHelp",+ "Turns document text into the search index that answers questions.",+ )}+ infoBeforeLabel+ infoZIndex={SETUP_DROPDOWN.zIndex}+ >+ <Select+ comboboxProps={SETUP_DROPDOWN}+ options={embeddingProviders}+ value={draft.embeddingProvider}+ onChange={(value) => {+ if (value)+ update(+ embeddingProviderChange(+ value as EmbeddingProvider,+ initial,+ ),+ );+ }}+ />+ </FormField>+ <TextField+ required+ label={t("serverSetup.documents.model", "Embedding model")}+ value={draft.embeddingModel}+ onChange={(embeddingModel) => update({ embeddingModel })}+ error={errors.embeddingModel}+ />+ {providerNeedsBaseUrl(draft.embeddingProvider) && (+ <TextField+ required+ type="url"+ label={t("serverSetup.ai.baseUrl", "Base URL")}+ placeholder="http://ollama:11434/v1"+ value={draft.embeddingBaseUrl}+ onChange={(embeddingBaseUrl) => update({ embeddingBaseUrl })}+ error={errors.embeddingBaseUrl}+ />+ )}+ {embeddingNeedsApiKey(draft.embeddingProvider) && (+ <TextField+ type="password"+ label={t("serverSetup.ai.apiKey", "API key")}+ info={t(+ "serverSetup.ai.apiKeyHelp",+ "Leave empty to use the key the AI engine already has.",+ )}+ value={draft.embeddingApiKey}+ onChange={(embeddingApiKey) => update({ embeddingApiKey })}+ />+ )}+ </>+ }+ >+ {() => (+ <OnOffControl+ ariaLabel={documentsLabel}+ value={draft.documentQuestions}+ expand={documentsExpand}+ onChange={(documentQuestions) => {+ update({ documentQuestions });+ if (documentQuestions) setOpenSection("documents");+ }}+ />+ )}+ </SettingRow>+ )}+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/AnalyticsStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/AnalyticsStep.tsxnew file mode 100644index 0000000000..082ec26bc7--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/AnalyticsStep.tsx@@ -0,0 +1,42 @@+import { useTranslation } from "react-i18next";+import { Icon } from "@editor/ui/Icon";+import { SetupNote } from "@editor/components/serverSetup/SetupFields";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++const ANALYTICS_DOCS =+ "https://docs.stirlingpdf.com/Server/Analytics-and-Telemetry/";++export function AnalyticsStep() {+ const { t } = useTranslation();+ const settingsPath = [+ t("settings.title", "Settings"),+ t("settings.server.title", "Server"),+ t("settings.policiesPrivacy.title", "Legal & privacy"),+ ].join(" → ");+ return (+ <SetupNote>+ <p className={styles.noteText}>+ {t(+ "serverSetup.analytics.note",+ "Share usage data from this server with us to help us improve Stirling PDF. We never collect files or their contents.",+ )}+ </p>+ <p className={styles.noteText}>+ {t(+ "serverSetup.analytics.changeLater",+ "You can change this at any time in {{path}}.",+ { path: settingsPath },+ )}+ </p>+ <a+ className={styles.noteLink}+ href={ANALYTICS_DOCS}+ target="_blank"+ rel="noopener noreferrer"+ >+ {t("serverSetup.analytics.learnMore", "What we collect")}+ <Icon name="external-link" size={14} />+ </a>+ </SetupNote>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/EmailStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/EmailStep.tsxnew file mode 100644index 0000000000..d7ff7acc7b--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/EmailStep.tsx@@ -0,0 +1,77 @@+import { useTranslation } from "react-i18next";+import {+ OnOffControl,+ sectionToggle,+ SettingRow,+ TextField,+ type SetupStepProps,+} from "@editor/components/serverSetup/SetupFields";++export function EmailStep(props: SetupStepProps) {+ const { draft, update, errors, setOpenSection } = props;+ const { t } = useTranslation();+ const label = t("serverSetup.email.label", "Send email");+ const emailExpand = draft.emailEnabled+ ? sectionToggle(props, "email")+ : undefined;+ return (+ <>+ <SettingRow+ label={label}+ expand={emailExpand}+ details={+ <>+ <TextField+ required+ label={t("serverSetup.email.host", "SMTP host")}+ placeholder="smtp.example.com"+ value={draft.smtpHost}+ onChange={(smtpHost) => update({ smtpHost })}+ error={errors.smtpHost}+ />+ <TextField+ required+ label={t("serverSetup.email.port", "Port")}+ placeholder="587"+ value={draft.smtpPort}+ onChange={(smtpPort) => update({ smtpPort })}+ error={errors.smtpPort}+ />+ <TextField+ label={t("serverSetup.email.username", "Username")}+ value={draft.smtpUsername}+ onChange={(smtpUsername) => update({ smtpUsername })}+ />+ <TextField+ type="password"+ label={t("serverSetup.email.password", "Password")}+ value={draft.smtpPassword}+ onChange={(smtpPassword) => update({ smtpPassword })}+ />+ <TextField+ required+ type="email"+ label={t("serverSetup.email.from", "From address")}+ placeholder="[email protected]"+ value={draft.smtpFrom}+ onChange={(smtpFrom) => update({ smtpFrom })}+ error={errors.smtpFrom}+ />+ </>+ }+ >+ {() => (+ <OnOffControl+ ariaLabel={label}+ value={draft.emailEnabled}+ expand={emailExpand}+ onChange={(emailEnabled) => {+ update({ emailEnabled });+ if (emailEnabled) setOpenSection("email");+ }}+ />+ )}+ </SettingRow>+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/FilesStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/FilesStep.tsxnew file mode 100644index 0000000000..942810473b--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/FilesStep.tsx@@ -0,0 +1,61 @@+import { useTranslation } from "react-i18next";+import {+ OnOffControl,+ SettingRow,+ SetupNote,+ type SetupStepProps,+} from "@editor/components/serverSetup/SetupFields";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++export function FilesStep({ draft, initial, update }: SetupStepProps) {+ const { t } = useTranslation();+ const storageLabel = t("serverSetup.files.storage", "Store files");+ const sharingLabel = t("serverSetup.files.sharing", "File sharing");+ const storageTurnedOff = initial.storageEnabled && !draft.storageEnabled;+ const sharingTurnedOff = initial.sharingEnabled && !draft.sharingEnabled;+ return (+ <>+ <SettingRow label={storageLabel}>+ {() => (+ <OnOffControl+ ariaLabel={storageLabel}+ value={draft.storageEnabled}+ onChange={(storageEnabled) =>+ update(+ storageEnabled+ ? { storageEnabled }+ : { storageEnabled, sharingEnabled: false },+ )+ }+ />+ )}+ </SettingRow>+ {draft.storageEnabled && (+ <SettingRow label={sharingLabel}>+ {() => (+ <OnOffControl+ ariaLabel={sharingLabel}+ value={draft.sharingEnabled}+ onChange={(sharingEnabled) => update({ sharingEnabled })}+ />+ )}+ </SettingRow>+ )}+ {(storageTurnedOff || sharingTurnedOff) && (+ <SetupNote tone="warning">+ <p className={styles.noteText}>+ {storageTurnedOff+ ? t(+ "serverSetup.files.storageOffWarning",+ "With storage off, files people saved on the server can no longer be opened.",+ )+ : t(+ "serverSetup.files.sharingOffWarning",+ "With sharing off, existing share links stop working.",+ )}+ </p>+ </SetupNote>+ )}+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/LanguageStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/LanguageStep.tsxnew file mode 100644index 0000000000..7b5bed86f0--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/LanguageStep.tsx@@ -0,0 +1,44 @@+import { useTranslation } from "react-i18next";+import { Select } from "@editor/ui/Select";+import { supportedLanguages } from "@editor/i18n/languages";+import {+ SETUP_DROPDOWN,+ SettingRow,+ type SetupStepProps,+} from "@editor/components/serverSetup/SetupFields";++const AUTO_DETECT = "auto";++export function LanguageStep({ draft, update }: SetupStepProps) {+ const { t } = useTranslation();+ const options = [+ {+ value: AUTO_DETECT,+ label: t("serverSetup.language.auto", "Match each browser"),+ },+ ...Object.entries(supportedLanguages).map(([value, label]) => ({+ value,+ label,+ })),+ ];+ return (+ <>+ <SettingRow label={t("serverSetup.language.label", "Default language")}>+ {(labelId) => (+ <Select+ comboboxProps={SETUP_DROPDOWN}+ searchable+ aria-labelledby={labelId}+ options={options}+ value={draft.defaultLocale || AUTO_DETECT}+ onChange={(value) =>+ update({+ defaultLocale: !value || value === AUTO_DETECT ? "" : value,+ })+ }+ />+ )}+ </SettingRow>+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/PasswordStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/PasswordStep.tsxnew file mode 100644index 0000000000..67c704207e--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/PasswordStep.tsx@@ -0,0 +1,63 @@+import { useTranslation } from "react-i18next";+import {+ FieldGroup,+ TextField,+ type SetupStepProps,+} from "@editor/components/serverSetup/SetupFields";++export function PasswordStep({+ draft,+ update,+ errors,+ usingDefaultCredentials,+}: SetupStepProps) {+ const { t } = useTranslation();+ return (+ <>+ <FieldGroup>+ <TextField+ required+ initialFocus+ autoComplete="username"+ label={t("serverSetup.account.username", "Username")}+ info={t(+ "serverSetup.account.usernameHelp",+ "What you'll sign in with. An email address works too.",+ )}+ value={draft.adminUsername}+ onChange={(adminUsername) => update({ adminUsername })}+ error={errors.adminUsername}+ />+ {(!usingDefaultCredentials || errors.currentPassword) && (+ <TextField+ required+ type="password"+ autoComplete="current-password"+ label={t("serverSetup.password.current", "Current password")}+ value={draft.currentPassword}+ onChange={(currentPassword) => update({ currentPassword })}+ error={errors.currentPassword}+ />+ )}+ <TextField+ required+ type="password"+ autoComplete="new-password"+ label={t("serverSetup.password.new", "New password")}+ value={draft.newPassword}+ onChange={(newPassword) => update({ newPassword })}+ error={errors.newPassword}+ />+ <TextField+ required+ type="password"+ autoComplete="new-password"+ label={t("serverSetup.password.confirm", "Confirm new password")}+ value={draft.confirmPassword}+ onChange={(confirmPassword) => update({ confirmPassword })}+ error={errors.confirmPassword}+ />+ </FieldGroup>+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/QuickSummaryStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/QuickSummaryStep.tsxnew file mode 100644index 0000000000..896a58a4ce--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/QuickSummaryStep.tsx@@ -0,0 +1,28 @@+import type { ComponentType } from "react";+import type { SetupStepProps } from "@editor/components/serverSetup/SetupFields";+import type { SetupStepId } from "@editor/components/serverSetup/serverSetupDraft";+import { AddressesStep } from "@editor/components/serverSetup/steps/AddressesStep";+import { SignInStep } from "@editor/components/serverSetup/steps/SignInStep";+import { EmailStep } from "@editor/components/serverSetup/steps/EmailStep";+import { AiStep } from "@editor/components/serverSetup/steps/AiStep";++/** Must match QUICK_SUMMARY_STEPS, in the same order. */+const SUMMARY_PARTS: [SetupStepId, ComponentType<SetupStepProps>][] = [+ ["addresses", AddressesStep],+ ["signIn", SignInStep],+ ["email", EmailStep],+ ["ai", AiStep],+];++/** Quick start's settings on one card, without those the server already has. */+export function QuickSummaryStep(props: SetupStepProps) {+ return (+ <>+ {SUMMARY_PARTS.filter(([id]) => !props.configuredSteps.has(id)).map(+ ([id, Part]) => (+ <Part key={id} {...props} />+ ),+ )}+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/SetupSteps.stories.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/SetupSteps.stories.tsxnew file mode 100644index 0000000000..91f1446c0a--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/SetupSteps.stories.tsx@@ -0,0 +1,272 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { expect, userEvent, waitFor, within } from "storybook/test";+import { http, HttpResponse } from "msw";+import { AuthProvider } from "@editor/auth/UseSession";+import { ServerSetupWizard } from "@editor/components/serverSetup/ServerSetupWizard";+import { SetupSignInScreen } from "@editor/components/serverSetup/SetupScreen";+import {+ stepsFor,+ type SetupMode,+ type SetupStepId,+} from "@editor/components/serverSetup/serverSetupDraft";+// The app loads the card's colours globally (App.tsx); a story has to load them itself.+import "@editor/auth/ui/auth-theme.css";++/** What a new server answers for its current settings. */+const NEW_SERVER_SETTINGS = {+ system: { frontendUrl: "", backendUrl: "", enableAnalytics: null },+ security: { oauth2: { enabled: false } },+ mail: { enabled: false },+ storage: { enabled: true, sharing: { enabled: false } },+ aiEngine: {+ enabled: false,+ url: "http://localhost:5001",+ models: {+ provider: "anthropic",+ fastModel: "claude-haiku-4-5",+ smartModel: "claude-haiku-4-5",+ },+ rag: { embeddingProvider: "voyageai", embeddingModel: "voyage-4" },+ features: { documentQuestions: true },+ },+ mcp: { enabled: false, auth: { mode: "oauth" } },+};++/** A new server that saves everything and, like Docker, cannot restart itself. */+const newServer = [+ http.get("*/api/v1/admin/settings", () =>+ HttpResponse.json(NEW_SERVER_SETTINGS),+ ),+ http.put("*/api/v1/admin/settings", () => HttpResponse.json({})),+ http.post("*/api/v1/settings/update-enable-analytics", () =>+ HttpResponse.json({}),+ ),+ http.post("*/api/v1/admin/settings/setup-complete", () =>+ HttpResponse.json({ persisted: true }),+ ),+ http.post("*/api/v1/admin/settings/restart", () =>+ HttpResponse.json({}, { status: 503 }),+ ),+];++interface WizardProps {+ /** The admin is still on the default password, so setup starts with the account. */+ owesPassword?: boolean;+}++/** The wizard as ServerSetupGate mounts it; only the server is mocked. */+function Wizard({ owesPassword = false }: WizardProps) {+ return (+ <AuthProvider>+ <ServerSetupWizard+ onDone={() => {}}+ passwordChange={+ owesPassword ? { usingDefaultCredentials: true } : undefined+ }+ />+ </AuthProvider>+ );+}++/** First-run setup, rendered by the real wizard against a mocked new server;+ * each story clicks through the flow to reach its card. */+const meta = {+ title: "Server Setup/Steps",+ component: Wizard,+ parameters: { layout: "fullscreen", msw: { handlers: newServer } },+} satisfies Meta<typeof Wizard>;+export default meta;+type Story = StoryObj<typeof meta>;++type Canvas = ReturnType<typeof within>;++const button = (canvas: Canvas, name: string) =>+ userEvent.click(canvas.getByRole("button", { name }));++/** Picks `option` on `setting`'s own control, ahead of any setting nested in its fields. */+const choose = (canvas: Canvas, setting: string, option: string) =>+ userEvent.click(+ within(canvas.getByRole("group", { name: setting })).getAllByText(option, {+ exact: true,+ })[0],+ );++/** From the first card, clicks Continue until `step`'s card is up. */+async function reach(canvas: Canvas, mode: SetupMode, step: SetupStepId) {+ await canvas.findByRole("heading", { name: "Your server is up" });+ if (mode === "custom") await userEvent.click(canvas.getByText("Custom"));+ const steps = stepsFor(mode);+ const target = steps.indexOf(step);+ for (let index = 0; index <= target; index++) {+ await button(canvas, "Continue");+ await canvas.findByText(`${index + 1} of ${steps.length}`);+ }+}++export const SigningIn: Story = {+ render: () => <SetupSignInScreen />,+};++export const Account: Story = {+ args: { owesPassword: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const username = await canvas.findByRole("textbox", { name: /^Username/ });+ await waitFor(() => expect(username).toHaveFocus());+ },+};++export const AccountMismatch: Story = {+ args: { owesPassword: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.type(+ await canvas.findByRole("textbox", { name: /^Username/ }),+ "admin",+ );+ await userEvent.type(canvas.getByLabelText(/^New password/), "adminadmin");+ await userEvent.type(+ canvas.getByLabelText(/^Confirm new password/),+ "adminadmi",+ );+ await button(canvas, "Save and continue");+ },+};++export const Start: Story = {};++export const StartCustom: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await canvas.findByRole("heading", { name: "Your server is up" });+ await userEvent.click(canvas.getByText("Custom"));+ },+};++export const QuickStart: Story = {+ play: ({ canvasElement }) => reach(within(canvasElement), "quick", "summary"),+};++export const QuickStartEmailOn: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await reach(canvas, "quick", "summary");+ await choose(canvas, "Send email", "On");+ },+};++export const Addresses: Story = {+ play: ({ canvasElement }) =>+ reach(within(canvasElement), "custom", "addresses"),+};++export const Language: Story = {+ play: ({ canvasElement }) =>+ reach(within(canvasElement), "custom", "language"),+};++export const SignIn: Story = {+ play: ({ canvasElement }) => reach(within(canvasElement), "custom", "signIn"),+};++async function chooseOpenIdConnect(canvas: Canvas) {+ await reach(canvas, "custom", "signIn");+ await userEvent.click(canvas.getByRole("textbox", { name: "Sign in with" }));+ await userEvent.click(+ await within(document.body).findByRole("option", {+ name: "Other OpenID Connect",+ }),+ );+}++export const SignInOpenIdConnect: Story = {+ play: ({ canvasElement }) => chooseOpenIdConnect(within(canvasElement)),+};++export const SignInMissingFields: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await chooseOpenIdConnect(canvas);+ await button(canvas, "Continue");+ },+};++export const Email: Story = {+ play: ({ canvasElement }) => reach(within(canvasElement), "custom", "email"),+};++export const EmailOn: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await reach(canvas, "custom", "email");+ await choose(canvas, "Send email", "On");+ },+};++export const Files: Story = {+ play: ({ canvasElement }) => reach(within(canvasElement), "custom", "files"),+};++export const FilesStorageTurnedOff: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await reach(canvas, "custom", "files");+ await choose(canvas, "Store files", "Off");+ },+};++export const AiOn: Story = {+ play: ({ canvasElement }) => reach(within(canvasElement), "custom", "ai"),+};++export const AiConfigured: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await reach(canvas, "custom", "ai");+ await choose(canvas, "Self-hosted AI", "On");+ await within(+ canvas.getByRole("group", { name: "Self-hosted AI" }),+ ).findByRole("radio", { name: "Configured" });+ },+};++export const AiOff: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await reach(canvas, "custom", "ai");+ await choose(canvas, "Self-hosted AI", "Off");+ },+};++export const Analytics: Story = {+ play: ({ canvasElement }) =>+ reach(within(canvasElement), "quick", "analytics"),+};++export const Saved: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await reach(canvas, "quick", "analytics");+ await button(canvas, "Accept and finish");+ await canvas.findByRole("heading", { name: "Settings saved" });+ },+};++export const SaveFailed: Story = {+ parameters: {+ msw: {+ handlers: [+ http.put("*/api/v1/admin/settings", () =>+ HttpResponse.json({}, { status: 500 }),+ ),+ ...newServer,+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await reach(canvas, "quick", "analytics");+ await button(canvas, "Accept and finish");+ await canvas.findByRole("heading", { name: "Couldn't save your settings" });+ },+};diff --git a/frontend/src/editor/proprietary/components/serverSetup/steps/SignInStep.tsx b/frontend/src/editor/proprietary/components/serverSetup/steps/SignInStep.tsxnew file mode 100644index 0000000000..ddcfcad7ce--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/steps/SignInStep.tsx@@ -0,0 +1,117 @@+import { useTranslation } from "react-i18next";+import { Select } from "@editor/ui/Select";+import {+ sectionToggle,+ SETUP_DROPDOWN,+ SettingRow,+ TextField,+ type SetupStepProps,+} from "@editor/components/serverSetup/SetupFields";+import {+ loginChange,+ loginNeedsIssuer,+ oauthRedirectUri,+ type LoginMethod,+} from "@editor/components/serverSetup/serverSetupDraft";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++export function SignInStep(props: SetupStepProps) {+ const { draft, update, errors, setOpenSection } = props;+ const { t } = useTranslation();+ const methods: { value: LoginMethod; label: string }[] = [+ {+ value: "password",+ label: t("serverSetup.signIn.password", "Username and password"),+ },+ { value: "google", label: "Google" },+ { value: "github", label: "GitHub" },+ { value: "keycloak", label: "Keycloak" },+ {+ value: "oidc",+ label: t("serverSetup.signIn.oidc", "Other OpenID Connect"),+ },+ ];+ const oauth = draft.login !== "password";++ return (+ <>+ <SettingRow+ label={t("serverSetup.signIn.label", "Sign in with")}+ expand={oauth ? sectionToggle(props, "signIn") : undefined}+ chevron+ details={+ oauth && (+ <>+ {draft.login === "oidc" && (+ <TextField+ required+ label={t("serverSetup.signIn.providerName", "Provider name")}+ info={t(+ "serverSetup.signIn.providerNameHelp",+ "Shown on the sign-in button, for example okta or entra.",+ )}+ value={draft.oauthProviderName}+ onChange={(oauthProviderName) =>+ update({ oauthProviderName })+ }+ error={errors.oauthProviderName}+ />+ )}+ {loginNeedsIssuer(draft.login) && (+ <TextField+ required+ type="url"+ label={t("serverSetup.signIn.issuer", "Issuer URL")}+ placeholder="https://id.example.com/realms/main"+ value={draft.oauthIssuer}+ onChange={(oauthIssuer) => update({ oauthIssuer })}+ error={errors.oauthIssuer}+ />+ )}+ <TextField+ required+ label={t("serverSetup.signIn.clientId", "Client ID")}+ value={draft.oauthClientId}+ onChange={(oauthClientId) => update({ oauthClientId })}+ error={errors.oauthClientId}+ />+ <TextField+ required+ type="password"+ label={t("serverSetup.signIn.clientSecret", "Client secret")}+ value={draft.oauthClientSecret}+ onChange={(oauthClientSecret) => update({ oauthClientSecret })}+ error={errors.oauthClientSecret}+ />+ <p className={styles.hint}>+ {t(+ "serverSetup.signIn.redirectNote",+ "Add this redirect URI in your provider:",+ )}{" "}+ <code+ className={`${styles.inlineCode} ${styles.inlineCodeWrap}`}+ >+ {oauthRedirectUri(draft)}+ </code>+ </p>+ </>+ )+ }+ >+ {(labelId) => (+ <Select+ comboboxProps={SETUP_DROPDOWN}+ aria-labelledby={labelId}+ options={methods}+ value={draft.login}+ onChange={(value) => {+ if (!value) return;+ update(loginChange(value as LoginMethod, props.initial));+ if (value !== "password") setOpenSection("signIn");+ }}+ />+ )}+ </SettingRow>+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/useSetupFinish.ts b/frontend/src/editor/proprietary/components/serverSetup/useSetupFinish.tsnew file mode 100644index 0000000000..2dbe067559--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/useSetupFinish.ts@@ -0,0 +1,174 @@+import { useCallback, useRef, useState } from "react";+import { useAuth } from "@editor/auth/UseSession";+import { springAuth } from "@editor/auth/spring/springAuthClient";+import {+ answerAnalytics,+ changeAdminPassword,+ changeAdminUsername,+ httpStatus,+ markSetupComplete,+ requestRestart,+ saveServerSettings,+ waitForServer,+} from "@editor/components/serverSetup/serverSetupApi";+import {+ settingsDelta,+ type ServerSetupDraft,+} from "@editor/components/serverSetup/serverSetupDraft";++export type FinishState =+ | "idle"+ | "saving"+ | "restarting"+ | "manualRestart"+ | "restartFailed"+ | "error";++/** The server turned the new password down; `code` is its error key, such as "incorrectPassword". */+export class PasswordChangeError extends Error {+ constructor(readonly code: string | undefined) {+ super("Password change failed");+ }+}++/** The server turned the new username down; `code` is its error key, such as "usernameExists". */+export class UsernameChangeError extends Error {+ constructor(readonly code: string | undefined) {+ super("Username change failed");+ }+}++/** The details saved, but signing in under the new username failed, so the+ * admin must sign in again. */+export class SignInAgainError extends Error {+ constructor() {+ super("Sign in again");+ }+}++/** Only a refusal with a reason belongs on a field; anything else is a failed save. */+function isRefusal(error: unknown): boolean {+ const status = httpStatus(error);+ return status !== undefined && status >= 400 && status < 500;+}++function serverErrorCode(error: unknown): string | undefined {+ const data = (error as { response?: { data?: { error?: unknown } } }).response+ ?.data;+ return typeof data?.error === "string" ? data.error : undefined;+}++/** Saves every answer in one write, records setup as done, then restarts once;+ * a server that can't restart itself gets a "restart it yourself" card. */+async function applySettings(+ initial: ServerSetupDraft,+ draft: ServerSetupDraft,+): Promise<"done" | "restarting" | "manualRestart" | "restartFailed"> {+ const delta = settingsDelta(initial, draft);+ const firstAnalyticsAnswer =+ initial.analytics === null && draft.analytics !== null+ ? draft.analytics+ : null;+ if (firstAnalyticsAnswer !== null) delete delta["system.enableAnalytics"];++ await saveServerSettings(delta);+ if (firstAnalyticsAnswer !== null)+ await answerAnalytics(firstAnalyticsAnswer);+ await markSetupComplete();++ if (Object.keys(delta).length === 0) return "done";+ const restart = await requestRestart();+ if (restart === "restarting") return "restarting";+ return restart === "unsupported" ? "manualRestart" : "restartFailed";+}++/** Saves the account (password, then any rename, with a fresh sign-in) and+ * settings. The token refreshes only on close: a refresh unmounts setup. */+export function useSetupFinish({+ onDone,+ onPasswordChanged,+}: {+ onDone: () => void;+ onPasswordChanged?: () => void;+}) {+ const { refreshSession, user } = useAuth();+ const [state, setState] = useState<FinishState>("idle");+ const passwordChanged = useRef(false);++ const changePassword = useCallback(+ async (draft: ServerSetupDraft) => {+ try {+ await changeAdminPassword(draft.currentPassword, draft.newPassword);+ } catch (error) {+ if (isRefusal(error)) {+ throw new PasswordChangeError(serverErrorCode(error));+ }+ throw error;+ }+ passwordChanged.current = true;+ onPasswordChanged?.();+ },+ [onPasswordChanged],+ );++ const rename = useCallback(async (username: string, password: string) => {+ try {+ await changeAdminUsername(password, username);+ } catch (error) {+ if (isRefusal(error)) {+ throw new UsernameChangeError(serverErrorCode(error));+ }+ throw error;+ }+ const { session, error } = await springAuth+ .signInWithPassword({ email: username, password })+ .catch(() => ({ session: null, error: true }));+ if (error || !session) throw new SignInAgainError();+ }, []);++ const saveAccount = useCallback(+ async (draft: ServerSetupDraft) => {+ if (!passwordChanged.current) await changePassword(draft);+ const username = draft.adminUsername.trim();+ // The server compares names exactly but rejects one taken in any case.+ if (username.toLowerCase() !== (user?.username ?? "").toLowerCase()) {+ await rename(username, draft.newPassword);+ }+ },+ [changePassword, rename, user?.username],+ );++ /** Leaves setup; rotates the token first when the password was changed. */+ const complete = useCallback(() => {+ onDone();+ if (passwordChanged.current) void refreshSession();+ }, [onDone, refreshSession]);++ const finish = useCallback(+ (initial: ServerSetupDraft, draft: ServerSetupDraft) => {+ setState("saving");+ applySettings(initial, draft)+ .then(async (result) => {+ if (result === "done") {+ complete();+ return;+ }+ setState(result);+ if (result === "restarting") {+ await waitForServer();+ window.location.reload();+ }+ })+ .catch(() => setState("error"));+ },+ [complete],+ );++ return {+ state,+ finish,+ saveAccount,+ complete,+ reset: () => setState("idle"),+ };+}diff --git a/frontend/src/editor/proprietary/components/serverSetup/useStepCopy.ts b/frontend/src/editor/proprietary/components/serverSetup/useStepCopy.tsnew file mode 100644index 0000000000..4fa60792d4--- /dev/null+++ b/frontend/src/editor/proprietary/components/serverSetup/useStepCopy.ts@@ -0,0 +1,76 @@+import { useTranslation } from "react-i18next";+import type { SetupStepId } from "@editor/components/serverSetup/serverSetupDraft";++/** Each setup card's title and subtitle, shared by the wizard and its stories. */+export function useStepCopy() {+ const { t } = useTranslation();+ return (step: SetupStepId) => {+ switch (step) {+ case "addresses":+ return {+ title: t("serverSetup.addresses.title", "Addresses"),+ subtitle: t(+ "serverSetup.addresses.subtitle",+ "How people and sign-in providers reach this server.",+ ),+ };+ case "language":+ return {+ title: t("serverSetup.language.title", "Language"),+ subtitle: t(+ "serverSetup.language.subtitle",+ "What new visitors see first.",+ ),+ };+ case "signIn":+ return {+ title: t("serverSetup.signIn.title", "Sign-in"),+ subtitle: t("serverSetup.signIn.subtitle", "How your team signs in."),+ };+ case "email":+ return {+ title: t("serverSetup.email.title", "Email"),+ subtitle: t(+ "serverSetup.email.subtitle",+ "For invites, signing requests and shares.",+ ),+ };+ case "files":+ return {+ title: t("serverSetup.files.title", "Files"),+ subtitle: t(+ "serverSetup.files.subtitle",+ "Manage file storage and sharing.",+ ),+ };+ case "ai":+ return {+ title: t("serverSetup.ai.title", "AI"),+ subtitle: t(+ "serverSetup.ai.subtitle",+ "Document questions, automated edits and AI agents.",+ ),+ };+ case "summary":+ return {+ title: t("serverSetup.summary.title", "Quick start"),+ subtitle: t(+ "serverSetup.summary.subtitle",+ "Check the essentials. Everything else keeps its default.",+ ),+ };+ case "password":+ return {+ title: t("serverSetup.account.title", "Set up your account"),+ subtitle: t(+ "serverSetup.account.subtitle",+ "Choose how you'll sign in from now on.",+ ),+ };+ case "analytics":+ return {+ title: t("serverSetup.analytics.title", "Server analytics"),+ };+ }+ };+}diff --git a/frontend/src/editor/proprietary/components/shared/setupCard/AnimatedHeight.test.tsx b/frontend/src/editor/proprietary/components/shared/setupCard/AnimatedHeight.test.tsxnew file mode 100644index 0000000000..727085d279--- /dev/null+++ b/frontend/src/editor/proprietary/components/shared/setupCard/AnimatedHeight.test.tsx@@ -0,0 +1,63 @@+import { act, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { AnimatedHeight } from "@editor/components/shared/setupCard/AnimatedHeight";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++let resize: () => void = () => {};+let contentHeight = 100;++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: () => void) {+ resize = callback;+ }+ observe() {}+ disconnect() {}+ },+ );+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(+ () => contentHeight,+ );+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++function stubReducedMotion(reduce: boolean) {+ vi.stubGlobal("matchMedia", () => ({ matches: reduce }));+}++/** Two resizes far enough apart to count as separate changes. */+async function resizeTo(height: number) {+ contentHeight = height;+ vi.spyOn(performance, "now").mockReturnValue(performance.now() + 1000);+ await act(async () => resize());+}++describe("AnimatedHeight", () => {+ it("clips while easing to a new height", async () => {+ stubReducedMotion(false);+ const { container } = render(<AnimatedHeight>content</AnimatedHeight>);+ const box = container.firstElementChild!;+ await resizeTo(100);+ await resizeTo(300);++ expect(box.className).toContain(styles.animating);+ expect((box as HTMLElement).style.height).toBe("300px");+ });++ it("never clips under reduced motion, where no transition ends it", async () => {+ stubReducedMotion(true);+ const { container } = render(<AnimatedHeight>content</AnimatedHeight>);+ const box = container.firstElementChild!;+ await resizeTo(100);+ await resizeTo(300);++ expect(box.className).not.toContain(styles.animating);+ expect((box as HTMLElement).style.height).toBe("300px");+ });+});diff --git a/frontend/src/editor/proprietary/components/shared/setupCard/AnimatedHeight.tsx b/frontend/src/editor/proprietary/components/shared/setupCard/AnimatedHeight.tsxnew file mode 100644index 0000000000..632202173e--- /dev/null+++ b/frontend/src/editor/proprietary/components/shared/setupCard/AnimatedHeight.tsx@@ -0,0 +1,74 @@+import { useLayoutEffect, useRef, useState, type ReactNode } from "react";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++/** Resizes closer together than this are one continuous change. */+const FOLLOW_WINDOW_MS = 100;++/** Eases its height to fit its content, which CSS can't do to `auto`; clips+ * only mid-transition, so focus rings show, and follows animating children. */+export function AnimatedHeight({+ children,+ className,+}: {+ children: ReactNode;+ className?: string;+}) {+ const contentRef = useRef<HTMLDivElement>(null);+ const [height, setHeight] = useState<number>();+ const [animating, setAnimating] = useState(false);+ const [following, setFollowing] = useState(false);+ const lastHeight = useRef<number | undefined>(undefined);+ const lastResize = useRef(0);++ useLayoutEffect(() => {+ const content = contentRef.current;+ if (!content) return;+ const reducedMotion = window.matchMedia?.(+ "(prefers-reduced-motion: reduce)",+ );+ const observer = new ResizeObserver(() => {+ const next = content.offsetHeight;+ const previous = lastHeight.current;+ lastHeight.current = next;+ if (previous === next) return;++ const now = performance.now();+ const continuous = now - lastResize.current < FOLLOW_WINDOW_MS;+ lastResize.current = now;+ setFollowing(continuous);+ setAnimating(+ previous !== undefined && !continuous && !reducedMotion?.matches,+ );+ setHeight(next);+ });+ observer.observe(content);+ return () => observer.disconnect();+ }, []);++ const stopAnimating = (event: {+ target: EventTarget;+ currentTarget: EventTarget;+ }) => {+ if (event.target === event.currentTarget) setAnimating(false);+ };++ return (+ <div+ className={[+ styles.animatedHeight,+ animating ? styles.animating : "",+ following ? styles.followResize : "",+ className ?? "",+ ]+ .filter(Boolean)+ .join(" ")}+ style={{ height }}+ onTransitionEnd={stopAnimating}+ onTransitionCancel={stopAnimating}+ >+ <div ref={contentRef} className={styles.animatedContent}>+ {children}+ </div>+ </div>+ );+}diff --git a/frontend/src/editor/proprietary/components/shared/setupCard/SetupCard.module.css b/frontend/src/editor/proprietary/components/shared/setupCard/SetupCard.module.cssnew file mode 100644index 0000000000..c9a6a7bfb3--- /dev/null+++ b/frontend/src/editor/proprietary/components/shared/setupCard/SetupCard.module.css@@ -0,0 +1,364 @@+.header {+ display: flex;+ align-items: center;+ gap: var(--space-4);+ margin-bottom: var(--space-6);+}++.headerText {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ min-width: 0;+}++.title {+ margin: 0;+ font-size: 1.25rem;+ font-weight: var(--font-weight-semibold);+ line-height: 1.3;+ color: var(--c-text);+}++.subtitle {+ margin: 0;+ font-size: 0.9375rem;+ line-height: 1.5;+ color: var(--c-text-muted);+}++.body {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+}++.settingRow {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-4);+ padding: var(--space-3) 0;+ border-top: 1px solid var(--c-border-subtle);+ border-bottom: 1px solid var(--c-border-subtle);+}++.settingLabel {+ font-size: 0.9375rem;+ font-weight: var(--font-weight-semibold);+ color: var(--c-text);+ white-space: nowrap;+}++.settingControl {+ flex: 0 1 13rem;+ min-width: 0;+}++.note {+ display: flex;+ align-items: flex-start;+ gap: var(--space-2);+ margin: 0;+ padding: var(--space-3) var(--space-4);+ border-radius: var(--radius-md);+ background: var(--c-surface-sunken);+ font-size: 0.875rem;+ line-height: 1.45;+ color: var(--c-text-muted);+}++.noteBody {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: var(--space-2);+ min-width: 0;+}++.noteText {+ margin: 0;+}++.inlineCode {+ padding: 0.0625rem 0.375rem;+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-sm);+ background: var(--c-surface);+ font-family: var(--font-mono);+ font-size: 0.8125rem;+ color: var(--c-text);+ white-space: nowrap;+}++.noteLink {+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ font-weight: var(--font-weight-medium);+ color: var(--c-accent-text);+ text-decoration: none;+}++.noteLink:hover {+ text-decoration: underline;+}++.noteIcon {+ flex: 0 0 auto;+ margin-top: 0.0625rem;+ color: var(--c-accent-fg, var(--c-primary));+}++.animatedHeight {+ transition: height var(--motion-slow);+}++/* A new formatting context, so child margins stay inside the measured height+ instead of collapsing through, and jumping, as the animation ends. */+.animatedContent {+ display: flow-root;+}++.animating {+ overflow: hidden;+}++@media (prefers-reduced-motion: reduce) {+ .animatedHeight {+ transition: none;+ }+}++.noteWarning {+ background: var(--c-danger-subtle);+}++.noteWarning .noteIcon {+ color: var(--c-danger);+}++/* Room above and below the settings, so they don't crowd the title or the button. */+.frame .body {+ padding-block: var(--space-2) var(--space-4);+}++.actions {+ margin-top: var(--space-4);+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-2);+}++/* Side by side, wrapping to a stack with the primary last on narrow cards. */+.actions[data-choice="true"] {+ flex-direction: row;+ flex-wrap: wrap;+}++.actions[data-choice="true"] > * {+ flex: 1 1 10rem;+ min-width: 0;+}++.screen {+ position: fixed;+ inset: 0;+ overflow-y: auto;+ background: var(--c-bg);+}++/* For URLs and other values longer than the card is wide. */+.inlineCodeWrap {+ white-space: normal;+ overflow-wrap: anywhere;+}++.topBar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ min-height: 1.75rem;+ margin-bottom: var(--space-3);+}++.progress {+ font-size: 0.8125rem;+ font-variant-numeric: tabular-nums;+ color: var(--c-text-subtle);+}++.hint {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--c-text-muted);+}++.expandToggle {+ flex: 0 0 auto;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ margin-left: calc(var(--space-2) * -1);+ padding: 0;+ border: 0;+ border-radius: var(--radius-sm);+ background: none;+ color: var(--c-text-muted);+ cursor: pointer;+ transition: transform var(--motion-fast);+}++.setupChoice {+ min-width: 0;+}++/* The chevron sits at the segment's right edge whatever the word beside it. */+.setupChoice :global(.mantine-SegmentedControl-innerLabel):has(.expandLabel) {+ width: 100%;+}++.expandLabel {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ width: 100%;+}++.expandLabelText {+ flex: 1 1 auto;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ text-align: center;+}++/* The details panel is the same grey as a segmented track, so a choice among+ its fields takes an input's well and a tinted pill instead. */+.groupDetailsBody :global(.sui-seg.mantine-SegmentedControl-root) {+ --sc-color: var(--c-active);+ background-color: var(--c-input-bg);+ box-shadow: inset 0 0 0 1px var(--c-border);+}++.expandToggle:hover {+ background: var(--c-hover);+}++.expandToggle[data-open="true"] {+ transform: rotate(180deg);+}++/* The card stops growing here; its header and body scroll, its actions stay. */+.frame {+ display: flex;+ flex-direction: column;+ max-height: min(42rem, calc(100vh - 8rem));+}++/* Focused only to take focus off a choice's buttons, not as a control. */+.frame:focus {+ outline: none;+}++/* The inline padding keeps a boxed setting's outward edge and inputs' focus+ rings clear of the scroll clip; it must exceed --setup-box-bleed. */+.frameScroll {+ /* A boxed row's padding and border. */+ --setup-box-bleed: calc(var(--space-4) + 1px);+ flex: 1 1 auto;+ min-height: 0;+ margin-inline: -1.5rem;+ padding-inline: 1.5rem;+ scrollbar-width: thin;+}++.frameScroll:not(.animating) {+ overflow-y: auto;+}++/* Back and the step count stay in reach while a long card scrolls under them. */+.frameScroll .topBar {+ position: sticky;+ top: 0;+ z-index: 5;+ margin-inline: -1.5rem;+ margin-bottom: 0;+ padding: 0 1.5rem var(--space-3);+ background: var(--auth-card-bg);+}++/* Only a setting that can open more fields is boxed. The box reaches out by its+ padding and border, so its contents line up with the settings around it. */+.group[data-expandable="true"] {+ margin-inline: calc(-1 * var(--setup-box-bleed));+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-lg);+ overflow: hidden;+}++.groupRow {+ display: flex;+ align-items: center;+ gap: var(--space-3);+}++.group[data-expandable="true"] .groupRow {+ padding: var(--space-3) var(--space-4);+}++.groupRow .settingLabel {+ flex: 1 1 auto;+}++.groupFields {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+}++/* Grid rows animate between 0fr and 1fr, which height cannot do to auto. */+.groupDetails {+ display: grid;+ grid-template-rows: 0fr;+ transition: grid-template-rows var(--motion-slow);+}++.groupDetails[data-open="true"] {+ grid-template-rows: 1fr;+}++.groupDetailsActions {+ display: flex;+ justify-content: flex-end;+}++.groupDetailsClip {+ min-height: 0;+ overflow: hidden;+}++.groupDetailsBody {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ padding: var(--space-4);+ border-top: 1px solid var(--c-border-subtle);+ background: var(--c-surface-sunken);+}++/* Tracks a resize that is itself animating, such as a group opening. */+.followResize {+ transition: none;+}++@media (prefers-reduced-motion: reduce) {+ .groupDetails,+ .expandToggle {+ transition: none;+ }+}diff --git a/frontend/src/editor/proprietary/components/shared/setupCard/SetupCardLayout.tsx b/frontend/src/editor/proprietary/components/shared/setupCard/SetupCardLayout.tsxnew file mode 100644index 0000000000..8d37ddf2dd--- /dev/null+++ b/frontend/src/editor/proprietary/components/shared/setupCard/SetupCardLayout.tsx@@ -0,0 +1,29 @@+import type { ReactNode } from "react";+import { Logo } from "@editor/ui/Logo";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";++interface SetupCardLayoutProps {+ title: ReactNode;+ subtitle?: ReactNode;+ children: ReactNode;+}++/** Header and body of a step in a centred setup card (AuthShell). */+export function SetupCardLayout({+ title,+ subtitle,+ children,+}: SetupCardLayoutProps) {+ return (+ <>+ <header className={styles.header}>+ <Logo variant="iconOnly" iconHeight="2.5rem" />+ <div className={styles.headerText}>+ <h1 className={styles.title}>{title}</h1>+ {subtitle && <p className={styles.subtitle}>{subtitle}</p>}+ </div>+ </header>+ <div className={styles.body}>{children}</div>+ </>+ );+}diff --git a/frontend/src/editor/proprietary/components/startup/ServerSetupGate.test.tsx b/frontend/src/editor/proprietary/components/startup/ServerSetupGate.test.tsxnew file mode 100644index 0000000000..355f1b6f2d--- /dev/null+++ b/frontend/src/editor/proprietary/components/startup/ServerSetupGate.test.tsx@@ -0,0 +1,783 @@+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ServerSetupGate } from "@editor/components/startup/ServerSetupGate";+import * as api from "@editor/components/serverSetup/serverSetupApi";+import { alert } from "@editor/components/toast";++/** A stand-in for the server's app-config: it reports setup done once marked so. */+const server = vi.hoisted(() => {+ const listeners = new Set<() => void>();+ const state = {+ config: {} as Record<string, unknown>,+ loading: false,+ setupMarkedComplete: false,+ subscribe(listener: () => void) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ notify() {+ listeners.forEach((listener) => listener());+ },+ refetch() {+ if (state.setupMarkedComplete) {+ state.config = { ...state.config, setupCompleted: true };+ listeners.forEach((listener) => listener());+ }+ return Promise.resolve();+ },+ };+ return state;+});+vi.mock("@editor/contexts/AppConfigContext", async () => {+ const { useSyncExternalStore } = await import("react");+ return {+ useAppConfig: () => ({+ config: useSyncExternalStore(server.subscribe, () => server.config),+ loading: useSyncExternalStore(server.subscribe, () => server.loading),+ refetch: server.refetch,+ }),+ };+});+vi.mock(+ "@editor/components/serverSetup/serverSetupApi",+ async (importOriginal) => ({+ httpStatus: (+ await importOriginal<+ typeof import("@editor/components/serverSetup/serverSetupApi")+ >()+ ).httpStatus,+ fetchServerSettings: vi.fn(),+ saveServerSettings: vi.fn(),+ answerAnalytics: vi.fn(),+ markSetupComplete: vi.fn(),+ requestRestart: vi.fn(),+ waitForServer: vi.fn(),+ checkIssuer: vi.fn(),+ changeAdminPassword: vi.fn(),+ changeAdminUsername: vi.fn(),+ }),+);+const auth = vi.hoisted(() => ({+ refreshSession: vi.fn(),+ signOut: vi.fn(),+ user: { username: "admin" },+}));+const signIn = vi.hoisted(() => vi.fn());+vi.mock("@editor/auth/spring/springAuthClient", () => ({+ springAuth: { signInWithPassword: signIn },+}));+vi.mock("@editor/auth/UseSession", () => ({ useAuth: () => auth }));+vi.mock("@editor/components/toast", () => ({ alert: vi.fn() }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (+ _key: string,+ fallback: string,+ options: Record<string, unknown> = {},+ ) =>+ fallback.replace(/\{\{(\w+)\}\}/g, (_, name: string) =>+ String(options[name]),+ ),+ }),+}));++const NEW_SERVER_SETTINGS = {+ system: { frontendUrl: "", backendUrl: "", enableAnalytics: null },+ security: { oauth2: { enabled: false } },+ mail: { enabled: false },+ storage: { enabled: true, sharing: { enabled: false } },+ aiEngine: {+ enabled: false,+ url: "http://localhost:5001",+ models: {+ provider: "anthropic",+ fastModel: "claude-haiku-4-5",+ smartModel: "claude-haiku-4-5",+ },+ rag: { embeddingProvider: "voyageai", embeddingModel: "voyage-4" },+ features: { documentQuestions: true },+ },+ mcp: { enabled: false, auth: { mode: "oauth" } },+};++function renderGate(+ passwordChange?: { usingDefaultCredentials: boolean },+ onPasswordChanged = vi.fn(),+) {+ return render(+ <QueryClientProvider client={new QueryClient()}>+ <MantineProvider>+ <ServerSetupGate+ passwordChange={passwordChange}+ onPasswordChanged={onPasswordChanged}+ >+ <div>The app</div>+ </ServerSetupGate>+ </MantineProvider>+ </QueryClientProvider>,+ );+}++const click = (name: string) =>+ fireEvent.click(screen.getByRole("button", { name }));++const acceptAnalytics = () => click("Accept and finish");++const group = (name: string) => screen.getByRole("group", { name });+const option = (setting: string, name: string) =>+ within(screen.getByRole("radiogroup", { name: setting })).getByRole("radio", {+ name,+ });+const turnAiOn = () => fireEvent.click(option("Self-hosted AI", "On"));++/** Collapsed fields stay mounted so they can animate; read their panel. */+const isShown = (name: RegExp) => {+ const panel = screen.getByRole("textbox", { name }).closest("[data-open]");+ return (+ panel?.getAttribute("data-open") === "true" && !panel.hasAttribute("inert")+ );+};++async function openQuickStart() {+ await screen.findByRole("heading", { name: "Your server is up" });+ click("Continue");+}++beforeEach(() => {+ vi.clearAllMocks();+ server.config = { enableLogin: true, isAdmin: true, setupCompleted: false };+ server.setupMarkedComplete = false;+ server.loading = false;+ sessionStorage.clear();+ vi.mocked(api.fetchServerSettings).mockResolvedValue(NEW_SERVER_SETTINGS);+ vi.mocked(api.requestRestart).mockResolvedValue("unsupported");+ vi.mocked(api.checkIssuer).mockResolvedValue(true);+ vi.mocked(api.markSetupComplete).mockImplementation(async () => {+ server.setupMarkedComplete = true;+ });+});++describe("ServerSetupGate", () => {+ it("shows the app once setup is done", () => {+ server.config.setupCompleted = true;+ renderGate();+ expect(screen.getByText("The app")).toBeInTheDocument();+ });++ it("holds the sign-in card, not the app, while the first config loads", async () => {+ sessionStorage.setItem("stirling.setupSignInHandoff", String(Date.now()));+ server.config = {};+ server.loading = true;+ renderGate();+ expect(+ screen.getByRole("heading", {+ name: "Signing in with default credentials",+ }),+ ).toBeInTheDocument();+ expect(screen.queryByText("The app")).not.toBeInTheDocument();++ act(() => {+ server.config = {+ enableLogin: true,+ isAdmin: true,+ setupCompleted: true,+ };+ server.loading = false;+ server.notify();+ });+ expect(screen.getByText("The app")).toBeInTheDocument();+ expect(sessionStorage.getItem("stirling.setupSignInHandoff")).toBeNull();+ });++ it("never shows setup when login is off", () => {+ server.config = {+ enableLogin: false,+ isAdmin: true,+ setupCompleted: false,+ };+ renderGate();+ expect(screen.getByText("The app")).toBeInTheDocument();+ });++ it("only shows setup to admins", () => {+ server.config.isAdmin = false;+ renderGate();+ expect(screen.getByText("The app")).toBeInTheDocument();+ });++ it("offers no way to skip setup", async () => {+ renderGate();+ await screen.findByRole("heading", { name: "Your server is up" });+ expect(screen.queryByRole("button", { name: "Not now" })).toBeNull();+ expect(api.markSetupComplete).not.toHaveBeenCalled();+ });++ it("keeps setup up until the server says it is done", async () => {+ vi.mocked(api.markSetupComplete).mockRejectedValue(new Error("offline"));+ renderGate();+ await openQuickStart();+ click("Continue");+ acceptAnalytics();+ await screen.findByRole("heading", { name: "Couldn't save your settings" });+ expect(api.markSetupComplete).toHaveBeenCalled();+ expect(screen.queryByText("The app")).toBeNull();+ });++ it("only offers a retry when the settings fail to load", async () => {+ vi.mocked(api.fetchServerSettings).mockRejectedValue(new Error("offline"));+ renderGate();+ await screen.findByRole("heading", { name: "Couldn't load your settings" });+ expect(+ screen.getByRole("button", { name: "Try again" }),+ ).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Not now" })).toBeNull();+ expect(screen.queryByText("The app")).toBeNull();+ });++ it("saves Quick start's summary in one write, then restarts", async () => {+ renderGate();+ await screen.findByRole("heading", { name: "Your server is up" });+ expect(screen.queryByText("Sign in with")).toBeNull();+ click("Continue");+ expect(+ screen.getByRole("heading", { name: "Quick start" }),+ ).toBeInTheDocument();+ expect(screen.getByText("1 of 2")).toBeInTheDocument();+ click("Continue");++ // The last card's two buttons start unfocused, so Enter carried over+ // from Continue cannot press one.+ expect(+ screen.getByRole("heading", { name: "Server analytics" }),+ ).toBeInTheDocument();+ expect(+ screen.getByText(+ "You can change this at any time in Settings → Server → Legal & privacy.",+ ),+ ).toBeInTheDocument();+ const decline = screen.getByRole("button", { name: "Decline and finish" });+ const accept = screen.getByRole("button", { name: "Accept and finish" });+ expect(document.activeElement).not.toBe(decline);+ expect(document.activeElement).not.toBe(accept);+ expect(+ decline.compareDocumentPosition(accept) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ acceptAnalytics();++ await screen.findByRole("heading", { name: "Settings saved" });+ expect(api.saveServerSettings).toHaveBeenCalledWith({+ "system.frontendUrl": window.location.origin,+ "system.backendUrl": window.location.origin,+ });+ expect(api.answerAnalytics).toHaveBeenCalledWith(true);+ expect(api.requestRestart).toHaveBeenCalled();+ expect(+ screen.getByText(/This server can't restart itself/),+ ).toBeInTheDocument();++ click("Continue");+ await screen.findByText("The app");+ });++ it("says so when a restart fails rather than being unsupported", async () => {+ vi.mocked(api.requestRestart).mockResolvedValue("failed");+ renderGate();+ await openQuickStart();+ click("Continue");+ click("Decline and finish");+ await screen.findByText(/The server didn't restart/);+ expect(api.answerAnalytics).toHaveBeenCalledWith(false);+ });++ it("checks the summary before moving on", async () => {+ renderGate();+ await openQuickStart();+ fireEvent.change(screen.getByRole("textbox", { name: /^Web address/ }), {+ target: { value: "pdf.example.com" },+ });+ click("Continue");++ expect(+ screen.getByText(+ "Enter a full address, starting with http:// or https://",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("heading", { name: "Quick start" }),+ ).toBeInTheDocument();+ });++ it("goes back to the first card and on into Custom", async () => {+ renderGate();+ await openQuickStart();+ click("Back");+ expect(+ screen.getByRole("heading", { name: "Your server is up" }),+ ).toBeInTheDocument();++ fireEvent.click(screen.getByRole("radio", { name: "Custom" }));+ click("Continue");+ expect(screen.getByText("1 of 7")).toBeInTheDocument();+ });++ it("starts MCP from the server's value and leaves it off", async () => {+ renderGate();+ await openQuickStart();+ turnAiOn();+ expect(option("MCP server", "Off")).toBeChecked();+ fireEvent.click(option("Document questions", "Off"));+ fireEvent.change(+ screen.getByRole("textbox", { name: /^AI engine address/ }),+ { target: { value: "http://engine" } },+ );+ click("Continue");+ acceptAnalytics();++ await waitFor(() => expect(api.saveServerSettings).toHaveBeenCalled());+ const saved = vi.mocked(api.saveServerSettings).mock.calls[0][0];+ expect(saved).not.toHaveProperty("mcp.enabled");+ expect(saved).not.toHaveProperty("mcp.auth.mode");+ });++ it("turns MCP on with API keys when the admin switches it on", async () => {+ renderGate();+ await openQuickStart();+ turnAiOn();+ fireEvent.click(option("MCP server", "On"));+ fireEvent.click(option("Document questions", "Off"));+ fireEvent.change(+ screen.getByRole("textbox", { name: /^AI engine address/ }),+ { target: { value: "http://engine" } },+ );+ click("Continue");+ acceptAnalytics();++ await waitFor(() => expect(api.saveServerSettings).toHaveBeenCalled());+ expect(vi.mocked(api.saveServerSettings).mock.calls[0][0]).toMatchObject({+ "mcp.enabled": true,+ "mcp.auth.mode": "apikey",+ });+ });++ it("leaves MCP alone on a server that already runs it", async () => {+ vi.mocked(api.fetchServerSettings).mockResolvedValue({+ ...NEW_SERVER_SETTINGS,+ mcp: { enabled: true, auth: { mode: "oauth" } },+ });+ renderGate();+ await openQuickStart();+ click("Continue");+ acceptAnalytics();++ await waitFor(() => expect(api.saveServerSettings).toHaveBeenCalled());+ const saved = vi.mocked(api.saveServerSettings).mock.calls[0][0];+ expect(saved).not.toHaveProperty("mcp.enabled");+ expect(saved).not.toHaveProperty("mcp.auth.mode");+ });++ async function reachAccountStep() {+ await screen.findByRole("heading", { name: "Set up your account" });+ }++ const type = (label: string, value: string) =>+ fireEvent.change(screen.getByLabelText(new RegExp(`^${label}`)), {+ target: { value },+ });++ const fillAccount = (username: string, password = "a-new-pass") => {+ type("Username", username);+ type("New password", password);+ type("Confirm new password", password);+ };++ it("starts with the account, keeping the admin signed in", async () => {+ const onPasswordChanged = vi.fn();+ renderGate({ usingDefaultCredentials: true }, onPasswordChanged);+ await reachAccountStep();+ expect(screen.queryByLabelText(/^Current password/)).toBeNull();+ expect(screen.getByRole("textbox", { name: /^Username/ })).toHaveValue("");+ // Not the (i) before its label, whose tooltip would open over the card.+ await waitFor(() =>+ expect(screen.getByRole("textbox", { name: /^Username/ })).toHaveFocus(),+ );++ fillAccount("admin");+ click("Save and continue");++ await screen.findByRole("heading", { name: "Your server is up" });+ expect(api.changeAdminPassword).toHaveBeenCalledWith(+ "stirling",+ "a-new-pass",+ );+ expect(api.changeAdminUsername).not.toHaveBeenCalled();+ expect(onPasswordChanged).toHaveBeenCalled();+ // Moving on to the next card is the confirmation; a toast would repeat it.+ expect(alert).not.toHaveBeenCalled();+ // Refreshing reloads the app's auth state, so it waits until setup closes.+ expect(auth.refreshSession).not.toHaveBeenCalled();++ click("Continue");+ click("Continue"); // Quick start summary+ acceptAnalytics();+ await screen.findByRole("heading", { name: "Settings saved" });+ expect(api.changeAdminPassword).toHaveBeenCalledTimes(1);++ click("Continue");+ expect(auth.refreshSession).toHaveBeenCalled();+ await screen.findByText("The app");+ });++ it("renames the admin after the password, then signs straight back in", async () => {+ let finishSignIn: (value: unknown) => void = () => {};+ signIn.mockReturnValue(+ new Promise((resolve) => {+ finishSignIn = resolve;+ }),+ );+ renderGate({ usingDefaultCredentials: true });+ await reachAccountStep();+ fillAccount("pdf-admin");+ click("Save and continue");++ expect(+ screen.getByRole("heading", { name: "Updating your details" }),+ ).toBeInTheDocument();+ await waitFor(() =>+ expect(api.changeAdminUsername).toHaveBeenCalledWith(+ "a-new-pass",+ "pdf-admin",+ ),+ );+ expect(+ vi.mocked(api.changeAdminPassword).mock.invocationCallOrder[0],+ ).toBeLessThan(+ vi.mocked(api.changeAdminUsername).mock.invocationCallOrder[0],+ );+ expect(signIn).toHaveBeenCalledWith({+ email: "pdf-admin",+ password: "a-new-pass",+ });++ finishSignIn({ session: { access_token: "t" }, error: null });+ await screen.findByRole("heading", { name: "Your server is up" });+ });++ it("keeps the new password when only the username is refused", async () => {+ vi.mocked(api.changeAdminUsername)+ .mockRejectedValueOnce({+ response: { status: 409, data: { error: "usernameExists" } },+ })+ .mockResolvedValueOnce(undefined);+ signIn.mockResolvedValue({ session: { access_token: "t" }, error: null });+ renderGate({ usingDefaultCredentials: true });+ await reachAccountStep();+ fillAccount("taken-name");+ click("Save and continue");++ await screen.findByText("That username is taken");+ type("Username", "free-name");+ click("Save and continue");++ await screen.findByRole("heading", { name: "Your server is up" });+ expect(api.changeAdminPassword).toHaveBeenCalledTimes(1);+ expect(api.changeAdminUsername).toHaveBeenLastCalledWith(+ "a-new-pass",+ "free-name",+ );+ });++ it("asks for a fresh sign-in when signing back in fails", async () => {+ signIn.mockResolvedValue({ session: null, error: { message: "nope" } });+ renderGate({ usingDefaultCredentials: true });+ await reachAccountStep();+ fillAccount("pdf-admin");+ click("Save and continue");++ await screen.findByRole("heading", { name: "Your details are saved" });+ click("Sign in");+ expect(auth.signOut).toHaveBeenCalled();+ });++ it("rotates the token as setup closes after the account", async () => {+ renderGate({ usingDefaultCredentials: true });+ await reachAccountStep();+ fillAccount("admin");+ click("Save and continue");+ await screen.findByRole("heading", { name: "Your server is up" });++ click("Continue");+ click("Continue");+ acceptAnalytics();+ await screen.findByRole("heading", { name: "Settings saved" });+ expect(auth.refreshSession).not.toHaveBeenCalled();+ click("Continue");+ await waitFor(() => expect(auth.refreshSession).toHaveBeenCalled());+ });++ it("checks the details before saving them", async () => {+ renderGate({ usingDefaultCredentials: true });+ await reachAccountStep();+ fillAccount("a", "short");+ type("Confirm new password", "other");+ click("Save and continue");++ expect(+ screen.getByText(/Use 3 to 50 letters, numbers/),+ ).toBeInTheDocument();+ expect(screen.getByText("Use at least 8 characters")).toBeInTheDocument();+ expect(screen.getByText("Passwords don't match")).toBeInTheDocument();+ expect(api.changeAdminPassword).not.toHaveBeenCalled();+ });++ it("stays on the account card when the server refuses the password", async () => {+ vi.mocked(api.changeAdminPassword).mockRejectedValue({+ response: { status: 401, data: { error: "incorrectPassword" } },+ });+ renderGate({ usingDefaultCredentials: true });+ await reachAccountStep();+ fillAccount("admin");+ click("Save and continue");++ await screen.findByText("Incorrect password");+ expect(api.changeAdminUsername).not.toHaveBeenCalled();+ });++ it("says so when the details could not be saved at all", async () => {+ vi.mocked(api.changeAdminPassword).mockRejectedValue(new Error("offline"));+ renderGate({ usingDefaultCredentials: true });+ await reachAccountStep();+ fillAccount("admin");+ click("Save and continue");++ await screen.findByText(/Couldn't save your details/);+ expect(+ screen.getByRole("heading", { name: "Set up your account" }),+ ).toBeInTheDocument();+ });++ it("keeps one expanded section open at a time", async () => {+ renderGate();+ await openQuickStart();++ fireEvent.click(+ within(group("Send email")).getByRole("radio", { name: "On" }),+ );+ expect(isShown(/^SMTP host/)).toBe(true);++ turnAiOn();+ expect(isShown(/^SMTP host/)).toBe(false);+ expect(isShown(/^AI engine address/)).toBe(true);++ fireEvent.click(option("Send email", "Configured"));+ expect(isShown(/^SMTP host/)).toBe(true);+ expect(isShown(/^AI engine address/)).toBe(false);+ });++ it("puts Off before On, and folds a setting from its chosen On, then reads Configured", async () => {+ renderGate();+ await openQuickStart();+ const email = screen.getByRole("radiogroup", { name: "Send email" });+ expect(+ within(email)+ .getAllByRole("radio")+ .map((radio) => radio.getAttribute("value")),+ ).toEqual(["off", "on"]);++ fireEvent.click(option("Send email", "On"));+ expect(isShown(/^SMTP host/)).toBe(true);+ fireEvent.click(option("Send email", "On"));+ expect(isShown(/^SMTP host/)).toBe(false);+ expect(option("Send email", "Configured")).toBeChecked();+ fireEvent.click(option("Send email", "Configured"));+ expect(isShown(/^SMTP host/)).toBe(true);+ expect(option("Send email", "Configured")).toBeChecked();+ });++ it("drops an MCP change when AI is switched back off", async () => {+ renderGate();+ await openQuickStart();+ turnAiOn();+ fireEvent.click(option("MCP server", "On"));+ fireEvent.click(option("Self-hosted AI", "Off"));+ click("Continue");+ acceptAnalytics();++ await waitFor(() => expect(api.saveServerSettings).toHaveBeenCalled());+ const saved = vi.mocked(api.saveServerSettings).mock.calls[0][0];+ expect(saved).not.toHaveProperty("mcp.enabled");+ });++ it("saves a section and opens the next one that is on", async () => {+ renderGate();+ await openQuickStart();+ turnAiOn();+ fireEvent.click(+ within(group("Send email")).getByRole("radio", { name: "On" }),+ );+ fireEvent.change(screen.getByRole("textbox", { name: /^SMTP host/ }), {+ target: { value: "smtp.example.org" },+ });+ fireEvent.change(screen.getByRole("textbox", { name: /^Port/ }), {+ target: { value: "587" },+ });+ fireEvent.change(screen.getByRole("textbox", { name: /^From address/ }), {+ target: { value: "[email protected]" },+ });++ fireEvent.click(+ within(group("Send email")).getByRole("button", { name: "Save" }),+ );+ expect(isShown(/^SMTP host/)).toBe(false);+ expect(isShown(/^AI engine address/)).toBe(true);++ fireEvent.click(+ within(group("Self-hosted AI")).getAllByRole("button", {+ name: "Save",+ })[0],+ );+ expect(isShown(/^Embedding model/)).toBe(true);++ fireEvent.click(+ within(group("Document questions")).getByRole("button", {+ name: "Save",+ }),+ );+ expect(isShown(/^Embedding model/)).toBe(false);+ });++ it("keeps a section open until its fields are filled in", async () => {+ renderGate();+ await openQuickStart();+ fireEvent.click(+ within(group("Send email")).getByRole("radio", { name: "On" }),+ );+ fireEvent.click(+ within(group("Send email")).getByRole("button", { name: "Save" }),+ );++ expect(isShown(/^SMTP host/)).toBe(true);+ expect(screen.getByRole("textbox", { name: /^SMTP host/ })).toHaveAttribute(+ "aria-invalid",+ "true",+ );+ });++ it("asks for an embedding setup only while document questions are on", async () => {+ renderGate();+ await openQuickStart();+ expect(screen.queryByText("Document questions")).not.toBeInTheDocument();+ turnAiOn();+ fireEvent.click(+ within(group("Document questions")).getByRole("radio", { name: "Off" }),+ );+ fireEvent.change(+ screen.getByRole("textbox", { name: /^AI engine address/ }),+ { target: { value: "http://engine" } },+ );+ click("Continue");+ acceptAnalytics();++ await waitFor(() => expect(api.saveServerSettings).toHaveBeenCalled());+ const saved = vi.mocked(api.saveServerSettings).mock.calls[0][0];+ expect(saved).toMatchObject({+ "aiEngine.features.documentQuestions": false,+ });+ expect(saved).not.toHaveProperty("aiEngine.rag.embeddingModel");+ });++ it("won't move on with an issuer the server can't reach", async () => {+ vi.mocked(api.checkIssuer).mockResolvedValue(false);+ vi.mocked(api.fetchServerSettings).mockResolvedValue({+ ...NEW_SERVER_SETTINGS,+ security: {+ oauth2: {+ enabled: true,+ client: { keycloak: { clientId: "id", clientSecret: "secret" } },+ },+ },+ });+ renderGate();+ await openQuickStart();+ fireEvent.change(screen.getByRole("textbox", { name: /^Issuer URL/ }), {+ target: { value: "https://id.example.com" },+ });+ click("Continue");++ await screen.findByText(/Couldn't reach this issuer/);+ expect(api.checkIssuer).toHaveBeenCalledWith("https://id.example.com");+ expect(+ screen.getByRole("heading", { name: "Quick start" }),+ ).toBeInTheDocument();+ });++ it("starts Custom's AI card on, with its fields open", async () => {+ renderGate();+ await screen.findByRole("heading", { name: "Your server is up" });+ fireEvent.click(screen.getByRole("radio", { name: "Custom" }));+ click("Continue");+ for (let card = 1; card < 6; card += 1) click("Continue");++ expect(screen.getByRole("heading", { name: "AI" })).toBeInTheDocument();+ expect(option("Self-hosted AI", "On")).toBeChecked();+ expect(isShown(/^AI engine address/)).toBe(true);+ });++ it("drops Custom's AI default on a switch back to Quick start", async () => {+ renderGate();+ await screen.findByRole("heading", { name: "Your server is up" });+ fireEvent.click(screen.getByRole("radio", { name: "Custom" }));+ click("Continue");+ for (let card = 1; card < 6; card += 1) click("Continue");+ for (let card = 0; card < 6; card += 1) click("Back");++ fireEvent.click(screen.getByRole("radio", { name: "Quick start" }));+ click("Continue");+ expect(option("Self-hosted AI", "Off")).toBeChecked();+ });++ it("opens a setting that starts on when its card shows", async () => {+ vi.mocked(api.fetchServerSettings).mockResolvedValue({+ ...NEW_SERVER_SETTINGS,+ mail: { enabled: true, host: "smtp.example.org", port: 587 },+ });+ renderGate();+ await openQuickStart();+ expect(isShown(/^SMTP host/)).toBe(true);+ });++ it("leaves out settings the server already has", async () => {+ vi.mocked(api.fetchServerSettings).mockResolvedValue({+ ...NEW_SERVER_SETTINGS,+ system: {+ frontendUrl: "https://pdf.example.com",+ backendUrl: "https://pdf.example.com",+ enableAnalytics: false,+ },+ mail: {+ enabled: true,+ host: "smtp.example.org",+ port: 587,+ from: "[email protected]",+ },+ });+ renderGate();+ await openQuickStart();++ expect(screen.getByText("1 of 1")).toBeInTheDocument();+ expect(screen.queryByRole("textbox", { name: /^SMTP host/ })).toBeNull();+ expect(screen.queryByRole("textbox", { name: /^Web address/ })).toBeNull();+ expect(+ screen.getByRole("group", { name: "Sign in with" }),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/src/editor/proprietary/components/startup/ServerSetupGate.tsx b/frontend/src/editor/proprietary/components/startup/ServerSetupGate.tsxnew file mode 100644index 0000000000..585b615e19--- /dev/null+++ b/frontend/src/editor/proprietary/components/startup/ServerSetupGate.tsx@@ -0,0 +1,56 @@+import { useEffect } from "react";+import type { ServerSetupGateProps } from "@editor-core/components/startup/ServerSetupGate";+import { useAppConfig } from "@editor/contexts/AppConfigContext";+import { ServerSetupWizard } from "@editor/components/serverSetup/ServerSetupWizard";+import { SetupSignInScreen } from "@editor/components/serverSetup/SetupScreen";+import {+ clearSetupSignIn,+ isSetupSignInPending,+} from "@editor/components/serverSetup/setupSignInHandoff";++/** Pending for an admin of a server with login on that hasn't finished setup;+ * never without login, nor for an older server that sends no flag. */+export function useServerSetupPending(): boolean {+ const { config } = useAppConfig();+ return (+ config?.enableLogin === true &&+ config.isAdmin === true &&+ config.setupCompleted === false+ );+}++/** Keeps the automatic first sign-in's card up while startup checks load. */+export function ServerSetupLoading() {+ return isSetupSignInPending() ? <SetupSignInScreen /> : null;+}++export function ServerSetupGate({+ children,+ passwordChange,+ onPasswordChanged,+}: ServerSetupGateProps) {+ const pending = useServerSetupPending();+ const { config, loading, refetch } = useAppConfig();+ // The default login is an admin, so a config without isAdmin is still the+ // one from before sign-in.+ const signedInConfig = !loading && config?.isAdmin === true;+ // Straight after the automatic first sign-in, hold its card until the+ // signed-in config arrives rather than flash the editor, then let go.+ const holdingSignIn = !pending && !signedInConfig && isSetupSignInPending();++ useEffect(() => {+ if (signedInConfig && !pending) clearSetupSignIn();+ }, [signedInConfig, pending]);++ // Up until the server reports setup complete, never on a local flag: showing+ // the app early would let the default password through.+ if (holdingSignIn) return <SetupSignInScreen />;+ if (!pending) return <>{children}</>;+ return (+ <ServerSetupWizard+ passwordChange={passwordChange}+ onPasswordChanged={onPasswordChanged}+ onDone={() => void refetch()}+ />+ );+}diff --git a/frontend/src/editor/proprietary/routes/Login.test.tsx b/frontend/src/editor/proprietary/routes/Login.test.tsxindex a5174cc90c..c102bb8e0b 100644--- a/frontend/src/editor/proprietary/routes/Login.test.tsx+++ b/frontend/src/editor/proprietary/routes/Login.test.tsx@@ -873,6 +873,98 @@ describe("Login", () => {);});+ describe("on a fresh server", () => {+ const renderFresh = () =>+ render(+ <TestWrapper>+ <BrowserRouter>+ <Login />+ </BrowserRouter>+ </TestWrapper>,+ );++ beforeEach(() => {+ sessionStorage.clear();+ vi.mocked(apiClient.get).mockResolvedValue({+ data: {+ enableLogin: true,+ providerList: {},+ firstTimeSetup: true,+ showDefaultCredentials: true,+ defaultSignIn: true,+ },+ });+ });++ it("signs in with the default credentials by itself", async () => {+ vi.mocked(springAuth.signInWithPassword).mockReturnValue(+ new Promise(() => {}),+ );+ renderFresh();++ expect(+ await screen.findByText("Signing in with default credentials"),+ ).toBeInTheDocument();+ expect(springAuth.signInWithPassword).toHaveBeenCalledTimes(1);+ expect(springAuth.signInWithPassword).toHaveBeenCalledWith({+ email: "admin",+ password: "stirling",+ });+ });++ it("shows the form, without the default credentials, when they fail", async () => {+ vi.mocked(springAuth.signInWithPassword).mockResolvedValueOnce({+ user: null,+ session: null,+ error: { message: "Invalid credentials" },+ });+ renderFresh();++ await waitFor(() =>+ expect(document.getElementById("email")).toBeTruthy(),+ );+ expect(screen.queryByText("Default Login Credentials")).toBeNull();+ });++ it("does not try again in a tab where it already failed", async () => {+ sessionStorage.setItem("stirling_default_sign_in_failed", "1");+ renderFresh();++ await waitFor(() =>+ expect(document.getElementById("email")).toBeTruthy(),+ );+ expect(springAuth.signInWithPassword).not.toHaveBeenCalled();+ });++ it("only shows the defaults once the server has finished setup", async () => {+ vi.mocked(apiClient.get).mockResolvedValue({+ data: {+ enableLogin: true,+ providerList: {},+ firstTimeSetup: true,+ showDefaultCredentials: true,+ defaultSignIn: false,+ },+ });+ renderFresh();++ expect(+ await screen.findByText("Default Login Credentials"),+ ).toBeInTheDocument();+ expect(springAuth.signInWithPassword).not.toHaveBeenCalled();+ });++ it("leaves a signed-out admin on the form", async () => {+ sessionStorage.setItem("stirling_sso_auto_login_logged_out", "1");+ renderFresh();++ await waitFor(() =>+ expect(document.getElementById("email")).toBeTruthy(),+ );+ expect(springAuth.signInWithPassword).not.toHaveBeenCalled();+ });+ });+describe("SSO auto-login", () => {const mockLoginConfig = (loginMethod: string,diff --git a/frontend/src/editor/proprietary/routes/Login.tsx b/frontend/src/editor/proprietary/routes/Login.tsxindex f31eb7c1d1..caa149c6bd 100644--- a/frontend/src/editor/proprietary/routes/Login.tsx+++ b/frontend/src/editor/proprietary/routes/Login.tsx@@ -24,9 +24,14 @@ import { BASE_PATH, withBasePath } from "@editor/constants/app";import { updateSupportedLanguages } from "@editor/i18n";import SpringLoginForm from "@editor/auth/ui/SpringLoginForm";import AuthDefaultCredentials from "@editor/auth/ui/AuthDefaultCredentials";+import { SetupSignInScreen } from "@editor/components/serverSetup/SetupScreen";+import { markSetupSignIn } from "@editor/components/serverSetup/setupSignInHandoff";+import { DEFAULT_ADMIN_CREDENTIALS } from "@editor/auth/defaultCredentials";+import { springAuth } from "@editor/auth/spring/springAuthClient";import { useSpringLogin } from "@editor/auth/ui/useSpringLogin";import {clearSignedOutFlag,+ hasSignedOutInThisTab,isSsoAutoLoginAllowed,recordSsoAutoLoginAttempt,recordSsoAutoLoginError,@@ -35,6 +40,26 @@ import {import { LoadingFallback } from "@editor/components/shared/LoadingFallback";import loginHeader from "@editor/assets/brand/modern-logo/LoginLightModeHeader.svg";+// A failed default sign-in counts towards the admin's lockout, so a tab that+// saw one fail (or can't read storage) never tries again.+const DEFAULT_SIGN_IN_FAILED_KEY = "stirling_default_sign_in_failed";++function defaultSignInFailedInThisTab(): boolean {+ try {+ return window.sessionStorage.getItem(DEFAULT_SIGN_IN_FAILED_KEY) === "1";+ } catch {+ return true;+ }+}++function recordDefaultSignInFailure(): void {+ try {+ window.sessionStorage.setItem(DEFAULT_SIGN_IN_FAILED_KEY, "1");+ } catch {+ // Storage blocked: the read above already stops the next attempt.+ }+}+export default function Login() {const navigate = useNavigate();const location = useLocation();@@ -75,9 +100,15 @@ export default function Login() {const backendProbe = useBackendProbe();const [isFirstTimeSetup, setIsFirstTimeSetup] = useState(false);const [showDefaultCredentials, setShowDefaultCredentials] = useState(false);+ const [defaultSignInAllowed, setDefaultSignInAllowed] = useState(false);+ const [loginConfigLoaded, setLoginConfigLoaded] = useState(false);const loginDisabled =backendProbe.loginDisabled === true || _enableLogin === false;const autoLoginAttempted = useRef(false);+ const defaultSignInAttempted = useRef(false);+ const [defaultSignIn, setDefaultSignIn] = useState<+ "idle" | "signingIn" | "signedIn" | "failed"+ >("idle");const autoLoginErrorRecorded = useRef(false);const errorFromState = (location.state as { error?: string } | null)?.error;@@ -136,6 +167,9 @@ export default function Login() {setSsoAutoLogin(Boolean(data.ssoAutoLogin));setIsFirstTimeSetup(data.firstTimeSetup ?? false);setShowDefaultCredentials(data.showDefaultCredentials ?? false);+ // Only an explicit yes: a server too old to send it never gets the attempt.+ setDefaultSignInAllowed(data.defaultSignIn === true);+ setLoginConfigLoaded(true);// Apply language configuration from serverif (data.languages || data.defaultLocale) {updateSupportedLanguages(data.languages, data.defaultLocale);@@ -278,6 +312,51 @@ export default function Login() {awaitsPasswordSignIn,]);+ // A server still in setup on the default login signs in by itself: the page+ // prints those credentials anyway. The server decides; otherwise, the form.+ const defaultSignInDue =+ defaultSignIn === "idle" &&+ defaultSignInAllowed &&+ login.isUserPassAllowed &&+ !hasSsoLoginError &&+ !hasSignedOutInThisTab() &&+ !session &&+ !defaultSignInFailedInThisTab();++ useEffect(() => {+ if (+ !defaultSignInDue ||+ defaultSignInAttempted.current ||+ loading ||+ session ||+ backendProbe.status !== "up"+ ) {+ return;+ }+ defaultSignInAttempted.current = true;+ setDefaultSignIn("signingIn");+ void springAuth+ .signInWithPassword({+ email: DEFAULT_ADMIN_CREDENTIALS.username,+ password: DEFAULT_ADMIN_CREDENTIALS.password,+ })+ .then(+ ({ session: signedIn, error }) => {+ if (error || !signedIn) {+ recordDefaultSignInFailure();+ setDefaultSignIn("failed");+ return;+ }+ markSetupSignIn();+ setDefaultSignIn("signedIn");+ },+ () => {+ recordDefaultSignInFailure();+ setDefaultSignIn("failed");+ },+ );+ }, [defaultSignInDue, loading, session, backendProbe.status]);+// Handle query params (email prefill, success messages, and session expiry)useEffect(() => {try {@@ -373,6 +452,16 @@ export default function Login() {return <Navigate to={EDITOR_BASENAME} replace />;}+ // Checked before the auth state and session: once signing in starts, this+ // card stays up until the app takes over, so nothing flashes in between.+ if (+ defaultSignInDue ||+ defaultSignIn === "signingIn" ||+ defaultSignIn === "signedIn"+ ) {+ return <SetupSignInScreen />;+ }+// The form is only for visitors known to be signed out; splash until then.if (loading) {return <LoadingFallback />;@@ -440,6 +529,12 @@ export default function Login() {);}+ // Until the login settings arrive it is unknown whether this server signs+ // in by itself, so the form would only flash up and vanish.+ if (!loginConfigLoaded) {+ return <LoadingFallback />;+ }+return (<AuthLayout><SpringLoginForm@@ -478,7 +573,10 @@ export default function Login() {) : undefined}footer={- isFirstTimeSetup && showDefaultCredentials && isUserPassAllowed ? (+ isFirstTimeSetup &&+ showDefaultCredentials &&+ isUserPassAllowed &&+ defaultSignIn !== "failed" ? (<AuthDefaultCredentials />) : undefined}diff --git a/frontend/src/editor/saas/components/runLocation/AnimatedHeight.tsx b/frontend/src/editor/saas/components/runLocation/AnimatedHeight.tsxdeleted file mode 100644index 8cacf4f9cb..0000000000--- a/frontend/src/editor/saas/components/runLocation/AnimatedHeight.tsx+++ /dev/null@@ -1,41 +0,0 @@-import { useLayoutEffect, useRef, useState, type ReactNode } from "react";-import styles from "@editor/components/runLocation/RunLocation.module.css";--/**- * Eases its height to fit whatever it holds. CSS cannot transition to `auto`,- * so the content is measured and the measured height applied. Clipping is only- * on mid-transition: left on, it would cut off focus rings at the edges.- */-export function AnimatedHeight({ children }: { children: ReactNode }) {- const contentRef = useRef<HTMLDivElement>(null);- const [height, setHeight] = useState<number>();- const [animating, setAnimating] = useState(false);-- useLayoutEffect(() => {- const content = contentRef.current;- if (!content) return;- const observer = new ResizeObserver(() => {- const next = content.offsetHeight;- setHeight((previous) => {- if (previous !== undefined && previous !== next) setAnimating(true);- return next;- });- });- observer.observe(content);- return () => observer.disconnect();- }, []);-- return (- <div- className={[styles.animatedHeight, animating ? styles.animating : ""]- .filter(Boolean)- .join(" ")}- style={{ height }}- onTransitionEnd={(event) => {- if (event.target === event.currentTarget) setAnimating(false);- }}- >- <div ref={contentRef}>{children}</div>- </div>- );-}diff --git a/frontend/src/editor/saas/components/runLocation/DesktopDownloadStep.tsx b/frontend/src/editor/saas/components/runLocation/DesktopDownloadStep.tsxindex e6b1726143..15febe4801 100644--- a/frontend/src/editor/saas/components/runLocation/DesktopDownloadStep.tsx+++ b/frontend/src/editor/saas/components/runLocation/DesktopDownloadStep.tsx@@ -11,7 +11,7 @@ import {type DesktopTargetId,} from "@editor/components/runLocation/desktopTargets";import { startDownload } from "@editor/components/runLocation/startDownload";-import styles from "@editor/components/runLocation/RunLocation.module.css";+import styles from "@editor/components/shared/setupCard/SetupCard.module.css";interface DesktopDownloadStepProps {onBack: () => void;diff --git a/frontend/src/editor/saas/components/runLocation/RunLocation.module.css b/frontend/src/editor/saas/components/runLocation/RunLocation.module.cssindex 921366d0b3..d6a1994ae5 100644--- a/frontend/src/editor/saas/components/runLocation/RunLocation.module.css+++ b/frontend/src/editor/saas/components/runLocation/RunLocation.module.css@@ -1,38 +1,3 @@-.header {- display: flex;- align-items: center;- gap: var(--space-4);- margin-bottom: var(--space-6);-}--.headerText {- display: flex;- flex-direction: column;- gap: var(--space-1);- min-width: 0;-}--.title {- margin: 0;- font-size: 1.25rem;- font-weight: var(--font-weight-semibold);- line-height: 1.3;- color: var(--c-text);-}--.subtitle {- margin: 0;- font-size: 0.9375rem;- line-height: 1.5;- color: var(--c-text-muted);-}--.body {- display: flex;- flex-direction: column;- gap: var(--space-4);-}-.choices {display: flex;flex-direction: column;@@ -129,100 +94,9 @@background: var(--c-primary);}-.settingRow {- display: flex;- align-items: center;- justify-content: space-between;- gap: var(--space-4);- padding: var(--space-3) 0;- border-top: 1px solid var(--c-border-subtle);- border-bottom: 1px solid var(--c-border-subtle);-}--.settingLabel {- font-size: 0.9375rem;- font-weight: var(--font-weight-semibold);- color: var(--c-text);- white-space: nowrap;-}--.settingControl {- flex: 0 1 13rem;- min-width: 0;-}--.note {- display: flex;- align-items: flex-start;- gap: var(--space-2);- margin: 0;- padding: var(--space-3) var(--space-4);- border-radius: var(--radius-md);- background: var(--c-surface-sunken);- font-size: 0.875rem;- line-height: 1.45;- color: var(--c-text-muted);-}--.noteBody {- display: flex;- flex-direction: column;- align-items: flex-start;- gap: var(--space-2);- min-width: 0;-}--.noteText {- margin: 0;-}--.inlineCode {- padding: 0.0625rem 0.375rem;- border: 1px solid var(--c-border-subtle);- border-radius: var(--radius-sm);- background: var(--c-surface);- font-family: var(--font-mono);- font-size: 0.8125rem;- color: var(--c-text);- white-space: nowrap;-}--.noteLink {- display: inline-flex;- align-items: center;- gap: var(--space-1);- font-weight: var(--font-weight-medium);- color: var(--c-accent-fg, var(--c-primary));- text-decoration: none;-}--.noteLink:hover {- text-decoration: underline;-}-/* 1.75rem is the vertical padding of .sui-code__pre in CodeBlock.css; keep thetwo in sync or the longest command scrolls. */.command :global(.sui-code__pre) {box-sizing: border-box;height: calc(var(--command-lines) * 1lh + 1.75rem);}--.noteIcon {- flex: 0 0 auto;- margin-top: 0.0625rem;- color: var(--c-accent-fg, var(--c-primary));-}--.animatedHeight {- transition: height var(--motion-slow);-}--.animating {- overflow: hidden;-}--@media (prefers-reduced-motion: reduce) {- .animatedHeight {- transition: none;- }-}diff --git a/frontend/src/editor/saas/components/runLocation/RunLocationChooser.tsx b/frontend/src/editor/saas/components/runLocation/RunLocationChooser.tsxindex 67cef68263..658be86480 100644--- a/frontend/src/editor/saas/components/runLocation/RunLocationChooser.tsx+++ b/frontend/src/editor/saas/components/runLocation/RunLocationChooser.tsx@@ -4,7 +4,7 @@ import { AuthShell } from "@editor/auth/ui/AuthShell";import { Button } from "@editor/ui/Button";import { Icon, type IconName } from "@editor/ui/Icon";import { RunLocationStepLayout } from "@editor/components/runLocation/RunLocationStepLayout";-import { AnimatedHeight } from "@editor/components/runLocation/AnimatedHeight";+import { AnimatedHeight } from "@editor/components/shared/setupCard/AnimatedHeight";import { DesktopDownloadStep } from "@editor/components/runLocation/DesktopDownloadStep";import { SelfHostStep } from "@editor/components/runLocation/SelfHostStep";import { markRunLocationChosen } from "@editor/components/runLocation/runLocationChosen";diff --git a/frontend/src/editor/saas/components/runLocation/RunLocationStepLayout.tsx b/frontend/src/editor/saas/components/runLocation/RunLocationStepLayout.tsxindex 8ed04de329..f5aee3aac2 100644--- a/frontend/src/editor/saas/components/runLocation/RunLocationStepLayout.tsx+++ b/frontend/src/editor/saas/components/runLocation/RunLocationStepLayout.tsx@@ -2,8 +2,7 @@ import type { ReactNode } from "react";import { useTranslation } from "react-i18next";import { Button } from "@editor/ui/Button";import { Icon } from "@editor/ui/Icon";-import { Logo } from "@editor/ui/Logo";-import styles from "@editor/components/runLocation/RunLocation.module.css";+import { SetupCardLayout } from "@editor/components/shared/setupCard/SetupCardLayout";interface RunLocationStepLayoutProps {title: ReactNode;@@ -21,28 +20,19 @@ export function RunLocationStepLayout({}: RunLocationStepLayoutProps) {const { t } = useTranslation();return (- <>- <header className={styles.header}>- <Logo variant="iconOnly" iconHeight="2.5rem" />- <div className={styles.headerText}>- <h1 className={styles.title}>{title}</h1>- <p className={styles.subtitle}>{subtitle}</p>- </div>- </header>- <div className={styles.body}>- {children}- {onBack && (- <Button- variant="secondary"- fat- fullWidth- leftSection={<Icon name="arrow-left" size={18} />}- onClick={onBack}- >- {t("runLocation.back", "Back")}- </Button>- )}- </div>- </>+ <SetupCardLayout title={title} subtitle={subtitle}>+ {children}+ {onBack && (+ <Button+ variant="secondary"+ fat+ fullWidth+ leftSection={<Icon name="arrow-left" size={18} />}+ onClick={onBack}+ >+ {t("runLocation.back", "Back")}+ </Button>+ )}+ </SetupCardLayout>);}diff --git a/frontend/src/editor/saas/components/runLocation/SelfHostStep.tsx b/frontend/src/editor/saas/components/runLocation/SelfHostStep.tsxindex 97ab5035e7..4d0e218185 100644--- a/frontend/src/editor/saas/components/runLocation/SelfHostStep.tsx+++ b/frontend/src/editor/saas/components/runLocation/SelfHostStep.tsx@@ -13,6 +13,7 @@ import {SERVER_JAR_URL,} from "@editor/constants/selfHosting";import { RunLocationStepLayout } from "@editor/components/runLocation/RunLocationStepLayout";+import cardStyles from "@editor/components/shared/setupCard/SetupCard.module.css";import styles from "@editor/components/runLocation/RunLocation.module.css";type SelfHostMethod = "docker" | "compose" | "kubernetes" | "manual";@@ -74,11 +75,11 @@ export function SelfHostStep({ onBack }: SelfHostStepProps) {"Run this on your server, then open it in a browser.",)}>- <div className={styles.settingRow}>- <span className={styles.settingLabel} id="run-location-method">+ <div className={cardStyles.settingRow}>+ <span className={cardStyles.settingLabel} id="run-location-method">{t("runLocation.server.methodLabel", "Run it with")}</span>- <div className={styles.settingControl}>+ <div className={cardStyles.settingControl}><Selectaria-labelledby="run-location-method"options={METHODS.map((id) => ({@@ -117,21 +118,23 @@ export function SelfHostStep({ onBack }: SelfHostStepProps) {? t("runLocation.server.copyCompose", "Copy compose file"): t("runLocation.server.copy", "Copy command")}</Button>- <div className={styles.note}>- <Icon name="info" size={16} className={styles.noteIcon} />- <div className={styles.noteBody}>- <p className={styles.noteText}>+ <div className={cardStyles.note}>+ <Icon name="info" size={16} className={cardStyles.noteIcon} />+ <div className={cardStyles.noteBody}>+ <p className={cardStyles.noteText}><Transt={t}i18nKey="runLocation.server.note"defaults="Then open <url/> to finish setup."components={{- url: <code className={styles.inlineCode}>{SERVER_URL}</code>,+ url: (+ <code className={cardStyles.inlineCode}>{SERVER_URL}</code>+ ),}}/></p><a- className={styles.noteLink}+ className={cardStyles.noteLink}href={GUIDES[method]}target="_blank"rel="noopener noreferrer"diff --git a/testing/compose/docker-compose-keycloak-oauth.yml b/testing/compose/docker-compose-keycloak-oauth.ymlindex f7502f2860..55da90e336 100644--- a/testing/compose/docker-compose-keycloak-oauth.yml+++ b/testing/compose/docker-compose-keycloak-oauth.yml@@ -71,6 +71,8 @@ services:environment:# Basic settingsDOCKER_ENABLE_SECURITY: "true"+ # A fresh server signs in as the default admin and hides the SSO buttons.+ SYSTEM_SETUPCOMPLETED: "true"SECURITY_ENABLELOGIN: "true"SECURITY_LOGINMETHOD: "${SECURITY_LOGINMETHOD:-all}"SYSTEM_DEFAULTLOCALE: en-USdiff --git a/testing/compose/docker-compose-keycloak-saml.yml b/testing/compose/docker-compose-keycloak-saml.ymlindex c5ce1c9282..256495f824 100644--- a/testing/compose/docker-compose-keycloak-saml.yml+++ b/testing/compose/docker-compose-keycloak-saml.yml@@ -73,6 +73,8 @@ services:environment:# Basic settingsDOCKER_ENABLE_SECURITY: "true"+ # A fresh server signs in as the default admin and hides the SSO buttons.+ SYSTEM_SETUPCOMPLETED: "true"SECURITY_ENABLELOGIN: "true"SECURITY_LOGINMETHOD: "${SECURITY_LOGINMETHOD:-all}"SYSTEM_DEFAULTLOCALE: "${SYSTEM_DEFAULTLOCALE:-en-US}"