#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
Fix self-hosted billing session renewal (#7952)
ConnorYoh1e9beedce13b
diff --git a/.github/workflows/PR-Auto-Deploy-V2.yml b/.github/workflows/PR-Auto-Deploy-V2.ymlindex aa5e4ca03d..791946a6bc 100644--- a/.github/workflows/PR-Auto-Deploy-V2.yml+++ b/.github/workflows/PR-Auto-Deploy-V2.yml@@ -322,9 +322,8 @@ jobs:# Off so preview traffic never accrues against a real wallet or trips its cap. The# 402 gate is separate and stays on, so gating is still testable here.STIRLING_BILLING_ACCOUNT_LINK_METERING_ENABLED: "false"- # Stated rather than inferred from the request: the callback has to come back to the- # preview hostname, not to the container's own :8080 behind this proxy.- SYSTEM_FRONTENDURL: "https://${V2_PORT}.ssl.stirlingpdf.cloud"+ # Browser connection state belongs to the origin advertised in the preview link.+ SYSTEM_FRONTENDURL: "http://${NEW_VPS_HOST}:${V2_PORT}"SECURITY_ENABLELOGIN: "true"SECURITY_INITIALLOGIN_USERNAME: "${TEST_LOGIN_USERNAME}"SECURITY_INITIALLOGIN_PASSWORD: "${TEST_LOGIN_PASSWORD}"diff --git a/.github/workflows/e2e-stubbed.yml b/.github/workflows/e2e-stubbed.ymlindex 939b4feab6..7c0b69a1e1 100644--- a/.github/workflows/e2e-stubbed.yml+++ b/.github/workflows/e2e-stubbed.yml@@ -51,7 +51,8 @@ jobs:- name: Build frontend (production bundle for vite preview)env:VITE_BUILD_FOR_PREVIEW: "1"- run: task frontend:build+ VITE_INCLUDE_PORTAL: "true"+ run: task frontend:build:proprietary- name: Run stubbed E2E tests (${{ matrix.browser }})env:# The official Playwright image expects its browser runtime underdiff --git a/.taskfiles/frontend.yml b/.taskfiles/frontend.ymlindex 2ba473786a..faf77ce251 100644--- a/.taskfiles/frontend.yml+++ b/.taskfiles/frontend.yml@@ -85,6 +85,7 @@ tasks:ignore_error: truevars:MODE: '{{.MODE}}'+ SAAS_BASE_URL: '{{.SAAS_BASE_URL | default ""}}'PORT: '{{.PORT | default "5173"}}'BACKEND_URL: '{{.BACKEND_URL | default "http://localhost:8080"}}'OPEN: '{{.OPEN | default ""}}'@@ -92,7 +93,7 @@ tasks:BACKEND_URL: '{{.BACKEND_URL}}'STIRLING_DEV_LABEL: '{{.DEV_LABEL}}'cmds:- - npx vite editor --mode {{.MODE}} --port {{.PORT}}{{if .OPEN}} --open{{end}}+ - '{{if .SAAS_BASE_URL}}VITE_SAAS_API_URL={{.SAAS_BASE_URL}} {{end}}npx vite editor --mode {{.MODE}} --port {{.PORT}}{{if .OPEN}} --open{{end}}'# Separate from dev:_run rather than a flag on it: Task sets an `env:` key even# when its value resolves to empty, and Vite treats an empty process.env VITE_* as@@ -154,7 +155,7 @@ tasks:deps: [prepare]cmds:- task: dev:_run- vars: { MODE: proprietary, PORT: '{{.PORT}}', BACKEND_URL: '{{.BACKEND_URL}}', OPEN: '{{.OPEN}}' }+ vars: { MODE: proprietary, PORT: '{{.PORT}}', BACKEND_URL: '{{.BACKEND_URL}}', SAAS_BASE_URL: '{{.SAAS_BASE_URL}}', OPEN: '{{.OPEN}}' }dev:saas:desc: "Start frontend dev server in SaaS mode (SAAS_ENV=dev|staging|prod)"diff --git a/Taskfile.yml b/Taskfile.ymlindex c974b9d667..013cc202e8 100644--- a/Taskfile.yml+++ b/Taskfile.yml@@ -168,6 +168,7 @@ tasks:vars:PORT: '{{.APP_FRONTEND_PORT}}'BACKEND_URL: 'http://localhost:{{.APP_BACKEND_PORT}}'+ SAAS_BASE_URL: 'http://localhost:{{.SAAS_BACKEND_PORT}}'OPEN: "true"- task: linked:_readyvars:diff --git a/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java b/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.javaindex 7d11efa7fc..0f934d8034 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java@@ -1,5 +1,7 @@package stirling.software.SPDF.config;+import java.net.URI;+import java.net.URISyntaxException;import java.util.Arrays;import java.util.HashMap;import java.util.List;@@ -49,6 +51,9 @@ public class CleanUrlInterceptor implements HandlerInterceptor {String queryString = request.getQueryString();if (queryString != null && !queryString.isEmpty()) {Map<String, String> allowedParameters = new HashMap<>();+ // The frontend needs state to bind the SaaS response to the initiating browser.+ boolean accountLinkCallback =+ requestURI.equals(request.getContextPath() + "/account-link/callback");// Keep only the allowed parametersString[] queryParameters = queryString.split("&");@@ -57,7 +62,8 @@ public class CleanUrlInterceptor implements HandlerInterceptor {if (keyValuePair.length != 2) {continue;}- if (ALLOWED_PARAMS.contains(keyValuePair[0])) {+ if (ALLOWED_PARAMS.contains(keyValuePair[0])+ || (accountLinkCallback && "state".equals(keyValuePair[0]))) {allowedParameters.put(keyValuePair[0], keyValuePair[1]);}}@@ -76,7 +82,20 @@ public class CleanUrlInterceptor implements HandlerInterceptor {// Redirect to the URL with only allowed query parametersString redirectUrl = requestURI + "?" + newQueryString;- response.sendRedirect(request.getContextPath() + redirectUrl);+ try {+ URI redirectUri = new URI(redirectUrl);+ // Relative URIs can still name another host through a leading //.+ if (redirectUri.isAbsolute()+ || redirectUri.getRawAuthority() != null+ || !redirectUrl.startsWith("/")+ || redirectUrl.startsWith("//")) {+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);+ return false;+ }+ response.sendRedirect(redirectUri.toString());+ } catch (URISyntaxException ex) {+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);+ }return false;}}diff --git a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorMvcTest.java b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorMvcTest.javanew file mode 100644index 0000000000..aa025bc7bf--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorMvcTest.java@@ -0,0 +1,81 @@+package stirling.software.SPDF.config;++import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.http.MediaType;+import org.springframework.test.util.ReflectionTestUtils;+import org.springframework.test.web.servlet.MockMvc;+import org.springframework.test.web.servlet.setup.MockMvcBuilders;++import stirling.software.SPDF.controller.web.ReactRoutingController;++class CleanUrlInterceptorMvcTest {++ private static final String BROWSER_STATE = "a".repeat(64);+ private static final String SPA_HTML = "<html><body>Stirling PDF</body></html>";++ private MockMvc mvc;++ @BeforeEach+ void setUp() {+ ReactRoutingController controller = new ReactRoutingController();+ ReflectionTestUtils.setField(controller, "cachedIndexHtml", SPA_HTML);+ ReflectionTestUtils.setField(controller, "indexHtmlExists", true);+ mvc =+ MockMvcBuilders.standaloneSetup(controller)+ .addInterceptors(new CleanUrlInterceptor())+ .build();+ }++ @ParameterizedTest+ @ValueSource(strings = {"", "/stirling", "/stirling/nested"})+ void servesAccountLinkCallbackWithoutStrippingBrowserState(String contextPath)+ throws Exception {+ mvc.perform(+ get(contextPath + "/account-link/callback")+ .contextPath(contextPath)+ .queryParam("state", BROWSER_STATE))+ .andExpect(status().isOk())+ .andExpect(header().doesNotExist("Location"))+ .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML))+ .andExpect(content().string(SPA_HTML));+ }++ @ParameterizedTest+ @ValueSource(strings = {"", "/stirling", "/stirling/nested"})+ void callbackCleaningPreservesBrowserStateAndContextPath(String contextPath) throws Exception {+ String callbackPath = contextPath + "/account-link/callback";+ String cleanedUrl = callbackPath + "?state=" + BROWSER_STATE;++ mvc.perform(+ get(callbackPath)+ .contextPath(contextPath)+ .queryParam("state", BROWSER_STATE)+ .queryParam("unexpected", "discard"))+ .andExpect(status().isFound())+ .andExpect(redirectedUrl(cleanedUrl));++ mvc.perform(get(cleanedUrl).contextPath(contextPath))+ .andExpect(status().isOk())+ .andExpect(header().doesNotExist("Location"))+ .andExpect(content().string(SPA_HTML));+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "/settings",+ "/settings/account-link",+ "/account-link/other",+ "/other/callback"+ })+ void stateRemainsDisallowedOutsideAccountLinkCallback(String path) throws Exception {+ mvc.perform(get(path).queryParam("state", BROWSER_STATE))+ .andExpect(status().isFound())+ .andExpect(redirectedUrl(path + "?"));+ }+}diff --git a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.javaindex c6a479dea0..37f9b6ec75 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java@@ -5,6 +5,8 @@ import static org.mockito.Mockito.*;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;@@ -61,7 +63,7 @@ class CleanUrlInterceptorTest {@Testvoid preHandleRedirectsStrippingAllDisallowedParams() throws Exception {- when(request.getRequestURI()).thenReturn("/page");+ when(request.getRequestURI()).thenReturn("/ctx/page");when(request.getContextPath()).thenReturn("/ctx");when(request.getQueryString()).thenReturn("unknown=bad");assertFalse(interceptor.preHandle(request, response, new Object()));@@ -86,6 +88,46 @@ class CleanUrlInterceptorTest {assertFalse(interceptor.preHandle(request, response, new Object()));}+ @ParameterizedTest+ @ValueSource(+ strings = {+ "https://untrusted.invalid/path",+ "http://untrusted.invalid",+ "//untrusted.invalid/path",+ "///untrusted.invalid/path",+ "/\\untrusted.invalid/path",+ "\\\\untrusted.invalid/path",+ "\t//untrusted.invalid/path",+ "/\t/untrusted.invalid/path",+ "/\r\n/untrusted.invalid/path",+ "javascript:alert(1)",+ "settings"+ })+ void rejectsUnsafeRedirectTargets(String requestUri) throws Exception {+ when(request.getRequestURI()).thenReturn(requestUri);+ when(request.getContextPath()).thenReturn("");+ when(request.getQueryString()).thenReturn("unknown=discard");++ assertFalse(interceptor.preHandle(request, response, new Object()));++ verify(response).sendError(HttpServletResponse.SC_BAD_REQUEST);+ verify(response, never()).sendRedirect(anyString());+ }++ @ParameterizedTest+ @ValueSource(strings = {"/", "/folder%20name/page", "/caf%C3%A9"})+ void preservesLocalPathsAndEncodedQueryValues(String requestUri) throws Exception {+ String fileUrl = "https%3A%2F%2Fexample.invalid%2Fdocument.pdf";+ when(request.getRequestURI()).thenReturn(requestUri);+ when(request.getContextPath()).thenReturn("");+ when(request.getQueryString()).thenReturn("file=" + fileUrl + "&unknown=discard");++ assertFalse(interceptor.preHandle(request, response, new Object()));++ verify(response).sendRedirect(requestUri + "?file=" + fileUrl);+ verify(response, never()).sendError(anyInt());+ }+@Testvoid postHandleDoesNotThrow() {assertDoesNotThrow(() -> interceptor.postHandle(request, response, new Object(), null));diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.javaindex 9294d816fa..fd487665aa 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java@@ -23,15 +23,15 @@ import lombok.extern.slf4j.Slf4j;/*** Same-origin account-link surface on the self-hosted instance (combined billing).*- * <p>Admin-only class-wide: everything here is server-scoped, the free-tier meter included. A- * non-admin learns of the wall from the {@code reason} on the 402, not from here.+ * <p>Owner-only class-wide: everything here is server-scoped, the free-tier meter included. Other+ * users learn of the wall from the {@code reason} on the 402, not from here.*/@Slf4j@Hidden@RestController@RequestMapping("/api/v1/account-link")@Profile("!saas")-@PreAuthorize("hasRole('ADMIN')")+@PreAuthorize("hasRole('ADMIN') and @orgOwnerService.isCurrentUser(authentication)")@ConditionalOnProperty(name = "stirling.billing.account-link.enabled",havingValue = "true",diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.javaindex 80c6ed5981..8720a781e9 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java@@ -67,6 +67,8 @@ public class ConnectService {EXPIRED,/** Declined or already used; start a new one. */REJECTED,+ /** The browser callback would be rewritten, losing its origin or connection state. */+ CALLBACK_MISMATCH,/** SaaS could not be reached; the handshake is still valid and can be retried. */UNAVAILABLE}@@ -116,6 +118,10 @@ public class ConnectService {throw new IOException("Cannot determine where to send the admin back to; set system.frontendUrl");}+ if (hint.requestedCallbackUrl() != null+ && !callbackUrl.equals(hint.requestedCallbackUrl().strip())) {+ return ConnectStatus.of(Phase.CALLBACK_MISMATCH);+ }String nonce = randomSecret();String claimSecret = randomSecret();@@ -144,8 +150,8 @@ public class ConnectService {public ConnectStatus complete(String nonce) {Optional<ConnectState> found = stateRepo.findById(ConnectState.SINGLETON_ID);if (found.isEmpty()) {- // Already finished (a double-submitted callback) or never started.- return status();+ // An existing device credential does not authenticate an unsolicited callback.+ return ConnectStatus.of(Phase.REJECTED);}ConnectState state = found.get();if (state.isExpired(LocalDateTime.now())) {@@ -214,7 +220,27 @@ public class ConnectService {String resolveCallbackUrl(CallbackHint hint) {String configured = applicationProperties.getSystem().getFrontendUrl();if (configured != null && !configured.isBlank()) {- return trimTrailingSlash(configured.strip()) + CALLBACK_PATH;+ String callback = trimTrailingSlash(configured.strip()) + CALLBACK_PATH;+ String requested = hint.requestedCallbackUrl();+ if (requested != null) {+ try {+ URI uri = new URI(requested.strip());+ if (callback.equals(+ new URI(+ uri.getScheme(),+ uri.getAuthority(),+ uri.getPath(),+ null,+ null)+ .toString())+ && uri.getFragment() == null) {+ return requested.strip();+ }+ } catch (URISyntaxException ignored) {+ // Invalid hints cannot override the configured callback.+ }+ }+ return callback;}String browserOrigin = originOf(hint.browserOrigin());if (browserOrigin != null) {diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkAuthorizationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkAuthorizationTest.javanew file mode 100644index 0000000000..ada639e884--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkAuthorizationTest.java@@ -0,0 +1,177 @@+package stirling.software.proprietary.accountlink;++import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.util.List;+import java.util.Map;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.EnumSource;+import org.springframework.context.annotation.AnnotationConfigApplicationContext;+import org.springframework.context.annotation.Configuration;+import org.springframework.core.env.MapPropertySource;+import org.springframework.mock.web.MockHttpServletRequest;+import org.springframework.security.access.AccessDeniedException;+import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;+import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;+import org.springframework.security.core.authority.SimpleGrantedAuthority;+import org.springframework.security.core.context.SecurityContextHolder;++import stirling.software.common.model.enumeration.Role;+import stirling.software.proprietary.service.OrgOwnerService;++/** Invokes the Spring security proxy, so role checks cannot be bypassed by a direct unit call. */+class AccountLinkAuthorizationTest {+ private AnnotationConfigApplicationContext context;+ private AccountLinkController controller;+ private AccountLinkService service;+ private ConnectService connectService;+ private OrgOwnerService ownerService;++ @Configuration(proxyBeanMethods = false)+ @EnableMethodSecurity+ static class SecurityConfig {}++ @BeforeEach+ void setUp() {+ service = mock(AccountLinkService.class);+ connectService = mock(ConnectService.class);+ context = new AnnotationConfigApplicationContext();+ context.getEnvironment().setActiveProfiles("test");+ context.getEnvironment()+ .getPropertySources()+ .addFirst(+ new MapPropertySource(+ "accountLinkTest",+ Map.of("stirling.billing.account-link.enabled", "true")));+ context.register(SecurityConfig.class);+ ownerService = mock(OrgOwnerService.class);+ context.registerBean("orgOwnerService", OrgOwnerService.class, () -> ownerService);+ context.registerBean(+ AccountLinkController.class,+ () ->+ new AccountLinkController(+ service,+ connectService,+ mock(LocalUsageService.class),+ mock(FreeTierUsageService.class),+ context.getBeanProvider(UsageSyncService.class)));+ context.refresh();+ controller = context.getBean(AccountLinkController.class);+ }++ @AfterEach+ void tearDown() {+ SecurityContextHolder.clearContext();+ context.close();+ }++ @Test+ void ownerCanStartRenewalCompleteAndUnlink() throws Exception {+ authenticate(Role.ADMIN);+ when(ownerService.isCurrentUser(any())).thenReturn(true);+ controller.connectStart(null, new MockHttpServletRequest());+ controller.connectReauth(null, new MockHttpServletRequest());+ controller.connectComplete(new AccountLinkController.ConnectCompleteRequest("nonce"));+ controller.unlink();+ controller.recheck();+ verify(service).recheck();+ verify(connectService).start(any(), any());+ verify(connectService).startReauth(any());+ verify(connectService).complete("nonce");+ verify(service).unlink();+ }++ @ParameterizedTest+ @EnumSource(value = Role.class, mode = EnumSource.Mode.EXCLUDE, names = "ADMIN")+ void nonAdminRolesAreDeniedEvenIfMarkedAsOwner(Role role) {+ authenticate(role);+ when(ownerService.isCurrentUser(any())).thenReturn(true);+ assertDenied();+ }++ @Test+ void adminWhoDoesNotOwnTheOrganizationIsDenied() {+ authenticate(Role.ADMIN);+ assertDenied();+ }++ @Test+ void formerOwnerIsDeniedImmediatelyAfterOwnershipChanges() throws Exception {+ authenticate(Role.ADMIN);+ when(ownerService.isCurrentUser(any())).thenReturn(true);+ controller.connectReauth(null, new MockHttpServletRequest());+ verify(connectService).startReauth(any());+ clearInvocations(connectService);+ when(ownerService.isCurrentUser(any())).thenReturn(false);+ assertDenied();+ }++ @Test+ void anonymousRequestsAreDenied() {+ SecurityContextHolder.clearContext();+ assertDenied();+ }++ private void assertDenied() {+ assertThatThrownBy(() -> controller.connectStart(null, new MockHttpServletRequest()))+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ assertThatThrownBy(() -> controller.connectReauth(null, new MockHttpServletRequest()))+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ assertThatThrownBy(+ () ->+ controller.connectComplete(+ new AccountLinkController.ConnectCompleteRequest("nonce")))+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ assertThatThrownBy(() -> controller.unlink())+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ assertThatThrownBy(() -> controller.recheck())+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ assertThatThrownBy(() -> controller.status())+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ assertThatThrownBy(() -> controller.usage())+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ assertThatThrownBy(() -> controller.freeTier())+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ assertThatThrownBy(() -> controller.syncNow())+ .isInstanceOfAny(+ AccessDeniedException.class,+ AuthenticationCredentialsNotFoundException.class);+ verifyNoInteractions(service, connectService);+ }++ private void authenticate(Role role) {+ SecurityContextHolder.getContext()+ .setAuthentication(+ new UsernamePasswordAuthenticationToken(+ "local-user",+ "unused",+ List.of(new SimpleGrantedAuthority(role.getRoleId()))));+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/ConnectServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/ConnectServiceTest.javaindex 5af25d7250..30ce1d5884 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/ConnectServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/ConnectServiceTest.java@@ -14,6 +14,8 @@ import java.util.Optional;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import org.mockito.ArgumentCaptor;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;@@ -78,6 +80,77 @@ class ConnectServiceTest {org.mockito.ArgumentMatchers.isNull());}+ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void start_refusesThePreviewOriginMismatchBeforeContactingSaaS(boolean reauth)+ throws Exception {+ configureFrontendUrl("https://7952.ssl.stirlingpdf.cloud");+ if (reauth) {+ when(credentialStore.get()).thenReturn(Optional.of(credential(7L)));+ }+ ConnectService.CallbackHint hint =+ new ConnectService.CallbackHint(+ "http://54.175.155.236:7952/account-link/callback?state=browser-state",+ "http://54.175.155.236:7952",+ "http://localhost:8080");++ ConnectService.ConnectStatus result =+ reauth ? service.startReauth(hint) : service.start("preview", hint);++ assertThat(result.phase()).isEqualTo(Phase.CALLBACK_MISMATCH);+ assertThat(result.authorizeUrl()).isNull();+ verifyNoInteractions(client, stateRepo, entitlementCache);+ verify(credentialStore, never()).save(anyString(), anyString(), any());+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "http://pdf.example.com/account-link/callback?state=browser-state",+ "https://pdf.example.com:8443/account-link/callback?state=browser-state",+ "https://pdf.example.com/base/account-link/callback?state=browser-state",+ "https://other.example.com/account-link/callback?state=browser-state"+ })+ void start_refusesARewrittenBrowserCallback(String requested) throws Exception {+ configureFrontendUrl("https://pdf.example.com");++ ConnectService.ConnectStatus result =+ service.start(+ "instance",+ new ConnectService.CallbackHint(+ requested, "https://pdf.example.com", null));++ assertThat(result.phase()).isEqualTo(Phase.CALLBACK_MISMATCH);+ assertThat(result.authorizeUrl()).isNull();+ verifyNoInteractions(client, stateRepo);+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void start_preservesBrowserStateWhenThePreviewAddressMatches(boolean reauth) throws Exception {+ configureFrontendUrl("http://54.175.155.236:7952/");+ if (reauth) {+ when(credentialStore.get()).thenReturn(Optional.of(credential(7L)));+ }+ stubCreate();+ String requested = "http://54.175.155.236:7952/account-link/callback?state=browser-state";+ ConnectService.CallbackHint hint =+ new ConnectService.CallbackHint(+ requested, "http://54.175.155.236:7952", "http://localhost:8080");++ ConnectService.ConnectStatus result =+ reauth ? service.startReauth(hint) : service.start("preview", hint);++ assertThat(result.phase()).isEqualTo(Phase.PENDING);+ assertThat(result.authorizeUrl()).isEqualTo(AUTHORIZE_URL);+ ArgumentCaptor<String> callback = ArgumentCaptor.forClass(String.class);+ verify(client).connectRequest(any(), callback.capture(), anyString(), anyString(), any());+ assertThat(callback.getValue()).isEqualTo(requested);+ ArgumentCaptor<ConnectState> saved = ArgumentCaptor.forClass(ConnectState.class);+ verify(stateRepo).save(saved.capture());+ assertThat(saved.getValue().getCallbackUrl()).isEqualTo(requested);+ }+@Testvoid start_fallsBackToTheAddressTheRequestArrivedOn() throws Exception {stubCreate();@@ -239,6 +312,31 @@ class ConnectServiceTest {verify(client, never()).connectClaim(anyString(), anyString());}+ @Test+ void complete_withoutAnOpenHandshakeRejectsEvenWhenTheInstanceIsLinked() {+ when(credentialStore.get()).thenReturn(Optional.of(credential(7L)));+ assertThat(service.complete(NONCE).phase()).isEqualTo(Phase.REJECTED);+ verifyNoInteractions(credentialStore, client);+ }++ @Test+ void configuredCallbackPreservesTheBrowserCorrelator() {+ applicationProperties.getSystem().setFrontendUrl("https://pdf.example.com/base");+ String callback = "https://pdf.example.com/base/account-link/callback?state=browser-state";+ assertThat(+ service.resolveCallbackUrl(+ new ConnectService.CallbackHint(+ callback, "https://pdf.example.com", null)))+ .isEqualTo(callback);+ assertThat(+ service.resolveCallbackUrl(+ new ConnectService.CallbackHint(+ "https://other.example.com/account-link/callback?state=wrong",+ null,+ null)))+ .isEqualTo("https://pdf.example.com/base/account-link/callback");+ }+@Testvoid complete_whenSaaSHasNotCommittedTheApprovalKeepsTheHandshake() {when(stateRepo.findById(ConnectState.SINGLETON_ID))diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.javaindex e3819fd16f..2a751c8120 100644--- a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java@@ -97,11 +97,8 @@ public class ConnectController {ConnectRequestService.CreateResult result;if (reauthRequested) {- Long pinnedTeamId =- accountLinkService- .resolveActiveInstance(deviceId, deviceSecret)- .map(LinkedInstance::getTeamId)- .orElse(null);+ Optional<LinkedInstance> instance =+ accountLinkService.resolveActiveInstance(deviceId, deviceSecret);result =service.createReauth(body.name(),@@ -109,7 +106,8 @@ public class ConnectController {body.nonce(),body.claimSecret(),clientIp(http),- pinnedTeamId);+ instance.map(LinkedInstance::getTeamId).orElse(null),+ instance.map(LinkedInstance::getCreatedByUserId).orElse(null));} else {result =service.create(@@ -189,11 +187,14 @@ public class ConnectController {return service.lookup(requestId).map(v -> {- boolean canDeny = !leaderTeams.resolve(auth).isError();+ LeaderTeam caller = leaderTeams.resolve(auth);+ boolean reauth = v.mode() == ConnectRequest.Mode.REAUTH;boolean canApprove =- v.mode() == ConnectRequest.Mode.REAUTH- ? !leaderTeams.resolveMember(auth).isError()- : canDeny;+ !caller.isError()+ && (!reauth+ || v.isLinkedAccount(+ caller.teamId(), caller.userId()));+ boolean canDeny = !reauth && !caller.isError();return ResponseEntity.ok(new ViewResponse(v.requestId(),@@ -216,8 +217,7 @@ public class ConnectController {if (view.isEmpty()) {return ResponseEntity.notFound().build();}- boolean reauth = view.get().mode() == ConnectRequest.Mode.REAUTH;- LeaderTeam lt = reauth ? leaderTeams.resolveMember(auth) : leaderTeams.resolve(auth);+ LeaderTeam lt = leaderTeams.resolve(auth);if (lt.isError()) {return ResponseEntity.status(lt.error()).build();}@@ -227,9 +227,9 @@ public class ConnectController {return switch (result.rejection()) {// Named separately so the page can say "you are signed in to a different account"// rather than implying the request itself was bad.- case WRONG_TEAM ->+ case WRONG_ACCOUNT ->ResponseEntity.status(HttpStatus.CONFLICT)- .body(Map.of("error", "WRONG_TEAM"));+ .body(Map.of("error", "WRONG_ACCOUNT"));case UNAVAILABLE -> ResponseEntity.notFound().build();};}diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequest.java b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequest.javaindex f9c204eef3..833e8f5571 100644--- a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequest.java+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequest.java@@ -78,6 +78,7 @@ public class ConnectRequest {@Column(name = "team_id")private Long teamId;+ /** LINK: set on approval. REAUTH: pinned to the original linking user at creation. */@Column(name = "approved_by_user_id")private Long approvedByUserId;diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequestService.java b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequestService.javaindex 64abc12fa6..7d7ad48b35 100644--- a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequestService.java+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequestService.java@@ -83,7 +83,16 @@ public class ConnectRequestService {String callbackOrigin,boolean insecureTransport,ConnectRequest.Mode mode,- ConnectRequest.Status status) {}+ ConnectRequest.Status status,+ Long teamId,+ Long linkedUserId) {+ boolean isLinkedAccount(Long callerTeamId, Long callerUserId) {+ return teamId != null+ && linkedUserId != null+ && teamId.equals(callerTeamId)+ && linkedUserId.equals(callerUserId);+ }+ }/** Where to send the browser once approved, plus the correlator the instance is expecting. */public record ApprovalTarget(String callbackUrl, String nonce) {}@@ -110,7 +119,7 @@ public class ConnectRequestService {@Transactionalpublic CreateResult create(String name, String callbackUrl, String nonce, String claimSecret, String requesterIp) {- return create(name, callbackUrl, nonce, claimSecret, requesterIp, null);+ return create(name, callbackUrl, nonce, claimSecret, requesterIp, null, null);}/**@@ -124,11 +133,13 @@ public class ConnectRequestService {String nonce,String claimSecret,String requesterIp,- Long pinnedTeamId) {- if (pinnedTeamId == null) {+ Long pinnedTeamId,+ Long pinnedUserId) {+ if (pinnedTeamId == null || pinnedUserId == null) {return CreateResult.rejected(CreateRejection.NOT_LINKED);}- return create(name, callbackUrl, nonce, claimSecret, requesterIp, pinnedTeamId);+ return create(+ name, callbackUrl, nonce, claimSecret, requesterIp, pinnedTeamId, pinnedUserId);}private CreateResult create(@@ -137,7 +148,8 @@ public class ConnectRequestService {String nonce,String claimSecret,String requesterIp,- Long pinnedTeamId) {+ Long pinnedTeamId,+ Long pinnedUserId) {if (nonce == null || nonce.isBlank() || nonce.length() > MAX_NONCE_LENGTH) {return CreateResult.rejected(CreateRejection.BAD_NONCE);}@@ -167,6 +179,7 @@ public class ConnectRequestService {request.setMode(pinnedTeamId == null ? ConnectRequest.Mode.LINK : ConnectRequest.Mode.REAUTH);request.setTeamId(pinnedTeamId);+ request.setApprovedByUserId(pinnedUserId);request.setRequesterIp(requesterIp);request.setExpiresAt(now.plusMinutes(LIFETIME_MINUTES));repo.save(request);@@ -185,23 +198,27 @@ public class ConnectRequestService {public Optional<ConnectView> lookup(String requestId) {return repo.findByRequestId(requestId).filter(r -> !r.isExpired(LocalDateTime.now()))- .map(- r ->- new ConnectView(- r.getRequestId(),- r.getName(),- r.getCallbackOrigin(),- !"https".equals(schemeOf(r.getCallbackOrigin())),- r.getMode(),- r.getStatus()));+ .map(ConnectRequestService::viewOf);+ }++ private static ConnectView viewOf(ConnectRequest request) {+ return new ConnectView(+ request.getRequestId(),+ request.getName(),+ request.getCallbackOrigin(),+ !"https".equals(schemeOf(request.getCallbackOrigin())),+ request.getMode(),+ request.getStatus(),+ request.getTeamId(),+ request.getApprovedByUserId());}/** Why an approval was refused, so the page can say something useful. */public enum ApproveRejection {/** Unknown, expired, or already settled. */UNAVAILABLE,- /** The approver's team is not the team this server already belongs to. */- WRONG_TEAM+ /** The approver is not the account and team this server was linked with. */+ WRONG_ACCOUNT}public record ApproveResult(ApprovalTarget target, ApproveRejection rejection) {@@ -222,15 +239,9 @@ public class ConnectRequestService {if (request.isExpired(now) || request.getStatus() != ConnectRequest.Status.PENDING) {return new ApproveResult(null, ApproveRejection.UNAVAILABLE);}- Long pinned = request.getTeamId();- if (pinned != null && !pinned.equals(teamId)) {- log.warn(- "Account-link connect: request {} approved by team {} but is pinned to team {};"- + " refusing",- requestId,- teamId,- pinned);- return new ApproveResult(null, ApproveRejection.WRONG_TEAM);+ if (request.getMode() == ConnectRequest.Mode.REAUTH+ && !viewOf(request).isLinkedAccount(teamId, userId)) {+ return new ApproveResult(null, ApproveRejection.WRONG_ACCOUNT);}request.setStatus(ConnectRequest.Status.APPROVED);request.setTeamId(teamId);@@ -254,7 +265,10 @@ public class ConnectRequestService {return false;}ConnectRequest request = found.get();- if (request.getStatus() != ConnectRequest.Status.PENDING) {+ // Renewal is dismissed locally; it must never cancel or change the existing link.+ if (request.getMode() == ConnectRequest.Mode.REAUTH+ || request.isExpired(LocalDateTime.now())+ || request.getStatus() != ConnectRequest.Status.PENDING) {return false;}request.setStatus(ConnectRequest.Status.DENIED);diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/LeaderTeamResolver.java b/app/saas/src/main/java/stirling/software/saas/accountlink/LeaderTeamResolver.javaindex 7f19260678..bfe1443d9a 100644--- a/app/saas/src/main/java/stirling/software/saas/accountlink/LeaderTeamResolver.java+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/LeaderTeamResolver.java@@ -38,15 +38,6 @@ public class LeaderTeamResolver {/** Caller must lead their team. */public LeaderTeam resolve(Authentication auth) {- return resolve(auth, true);- }-- /** Caller need only belong to a team. */- public LeaderTeam resolveMember(Authentication auth) {- return resolve(auth, false);- }-- private LeaderTeam resolve(Authentication auth, boolean requireLeader) {User user;try {user = AuthenticationUtils.getCurrentUser(auth, userRepository);@@ -57,7 +48,7 @@ public class LeaderTeamResolver {if (teamId.isEmpty()) {return new LeaderTeam(null, null, HttpStatus.FORBIDDEN);}- if (requireLeader && !userTeamResolver.isLeader(user)) {+ if (!userTeamResolver.isLeader(user)) {return new LeaderTeam(null, null, HttpStatus.FORBIDDEN);}return new LeaderTeam(teamId.get(), user.getId(), null);diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.javaindex f460e82d5b..e0e2f48986 100644--- a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java@@ -45,7 +45,8 @@ public class LinkedInstance {private Long teamId;/**- * Admin who registered the instance; informational (no FK, so a user delete never offlines it).+ * Account allowed to renew browser sign-in. No FK: deleting the user does not stop device+ * access.*/@Column(name = "created_by_user_id")private Long createdByUserId;diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.javaindex 2691d2353b..7e76c49e47 100644--- a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java@@ -4,13 +4,19 @@ import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.isNull;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.time.LocalDateTime;import java.util.Optional;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.mockito.junit.jupiter.MockitoSettings;@@ -126,7 +132,14 @@ class ConnectControllerTest {// createReauth is the credentialled path; a first link must not reach it.org.mockito.Mockito.verify(service, org.mockito.Mockito.never())- .createReauth(anyString(), anyString(), anyString(), anyString(), any(), isNull());+ .createReauth(+ anyString(),+ anyString(),+ anyString(),+ anyString(),+ any(),+ isNull(),+ isNull());}@Test@@ -158,11 +171,9 @@ class ConnectControllerTest {}@Test- void reauthLookupAllowsMembersToApproveButNotDeny() {+ void reauthLookupAllowsOnlyTheLinkedOwnerToRenew() {pendingRequest(ConnectRequest.Mode.REAUTH);- when(leaderTeams.resolve(auth))- .thenReturn(new LeaderTeam(null, null, HttpStatus.FORBIDDEN));- when(leaderTeams.resolveMember(auth)).thenReturn(new LeaderTeam(1L, 2L, null));+ when(leaderTeams.resolve(auth)).thenReturn(new LeaderTeam(1L, 2L, null));var body = controller.view("req-1", auth).getBody();@@ -171,6 +182,81 @@ class ConnectControllerTest {assertThat(body.canDeny()).isFalse();}+ @ParameterizedTest+ @CsvSource({"1,3", "99,2", "99,3"})+ void reauthLookupOffersNoActionsToAnotherAccountOrTeam(Long teamId, Long userId) {+ pendingRequest(ConnectRequest.Mode.REAUTH);+ when(leaderTeams.resolve(auth)).thenReturn(new LeaderTeam(teamId, userId, null));++ var body = controller.view("req-1", auth).getBody();++ assertThat(body).isNotNull();+ assertThat(body.canApprove()).isFalse();+ assertThat(body.canDeny()).isFalse();+ }++ @Test+ void reauthRequiresTheLinkedAccountToStillOwnItsTeam() {+ pendingRequest(ConnectRequest.Mode.REAUTH);+ when(leaderTeams.resolve(auth))+ .thenReturn(new LeaderTeam(null, null, HttpStatus.FORBIDDEN));++ var body = controller.view("req-1", auth).getBody();+ assertThat(body).isNotNull();+ assertThat(body.canApprove()).isFalse();+ assertThat(body.canDeny()).isFalse();+ assertThat(controller.approve("req-1", auth).getStatusCode())+ .isEqualTo(HttpStatus.FORBIDDEN);+ verify(service, never()).approve(anyString(), any(), any());+ }++ @Test+ void reauthCreationUsesTheAuthenticatedInstancesOriginalAccount() {+ LinkedInstance instance = new LinkedInstance();+ instance.setTeamId(1L);+ instance.setCreatedByUserId(2L);+ when(accountLinkService.resolveActiveInstance("device", "secret"))+ .thenReturn(Optional.of(instance));+ when(service.createReauth("prod-1", BODY.callbackUrl(), "n", "s", "127.0.0.1", 1L, 2L))+ .thenReturn(ConnectRequestService.CreateResult.ok("req-1", 1800));+ MockHttpServletRequest request = request("https", "api.example.com", 443);+ request.addHeader(ConnectController.HEADER_DEVICE_ID, "device");+ request.addHeader(ConnectController.HEADER_DEVICE_SECRET, "secret");++ assertThat(controller.request(BODY, request).getStatusCode()).isEqualTo(HttpStatus.CREATED);+ verify(service).createReauth("prod-1", BODY.callbackUrl(), "n", "s", "127.0.0.1", 1L, 2L);+ }++ @ParameterizedTest+ @CsvSource({"1,3", "99,2", "99,3"})+ void directRenewalPostsCannotApproveOrDenyForAnotherAccount(Long teamId, Long userId) {+ ConnectRequestRepository repo = mock(ConnectRequestRepository.class);+ ConnectRequest row = new ConnectRequest();+ row.setRequestId("req-1");+ row.setMode(ConnectRequest.Mode.REAUTH);+ row.setTeamId(1L);+ row.setApprovedByUserId(2L);+ row.setCallbackOrigin("https://pdf.example.com");+ row.setExpiresAt(LocalDateTime.now().plusMinutes(10));+ when(repo.findByRequestId("req-1")).thenReturn(Optional.of(row));+ when(repo.findByRequestIdForUpdate("req-1")).thenReturn(Optional.of(row));+ when(leaderTeams.resolve(auth)).thenReturn(new LeaderTeam(teamId, userId, null));+ ConnectController realController =+ new ConnectController(+ new ConnectRequestService(repo, accountLinkService),+ leaderTeams,+ accountLinkService,+ applicationProperties);++ var approval = realController.approve("req-1", auth);+ assertThat(approval.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);+ assertThat(approval.getBody()).isEqualTo(java.util.Map.of("error", "WRONG_ACCOUNT"));+ assertThat(realController.deny("req-1", auth).getStatusCode())+ .isEqualTo(HttpStatus.NOT_FOUND);+ assertThat(row.getStatus()).isEqualTo(ConnectRequest.Status.PENDING);+ verify(repo, never()).save(any());+ }+private void pendingRequest(ConnectRequest.Mode mode) {when(service.lookup("req-1")).thenReturn(@@ -181,6 +267,8 @@ class ConnectControllerTest {"https://pdf.example.com",false,mode,- ConnectRequest.Status.PENDING)));+ ConnectRequest.Status.PENDING,+ 1L,+ 2L)));}}diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectRequestServiceTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectRequestServiceTest.javaindex e15d9749f2..2db21bfb6c 100644--- a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectRequestServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectRequestServiceTest.java@@ -16,6 +16,7 @@ import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.junit.jupiter.params.provider.ValueSource;import org.mockito.ArgumentCaptor;import org.mockito.Mock;@@ -178,22 +179,24 @@ class ConnectRequestServiceTest {}@Test- void createReauth_pinsTheTeamItWasToldByTheCredential() {+ void createReauth_pinsTheAccountAndTeamFromTheCredential() {ConnectRequestService.CreateResult result =- service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, 7L);+ service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, 7L, 42L);assertThat(result.isRejected()).isFalse();ArgumentCaptor<ConnectRequest> saved = ArgumentCaptor.forClass(ConnectRequest.class);verify(repo).save(saved.capture());assertThat(saved.getValue().getMode()).isEqualTo(ConnectRequest.Mode.REAUTH);assertThat(saved.getValue().getTeamId()).isEqualTo(7L);+ assertThat(saved.getValue().getApprovedByUserId()).isEqualTo(42L);+ assertThat(saved.getValue().getApprovedAt()).isNull();}@Testvoid createReauth_withoutAnAuthenticatedInstanceIsRefused() {// The controller passes null when the offered device credential did not authenticate.assertThat(- service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, null)+ service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, null, null).rejection()).isEqualTo(CreateRejection.NOT_LINKED);verify(repo, never()).save(any());@@ -218,13 +221,14 @@ class ConnectRequestServiceTest {ConnectRequestService.ApproveResult result = service.approve("req", 99L, 42L);// This is the "signed in to the wrong account" case, and it must not silently rebind.- assertThat(result.rejection()).isEqualTo(ConnectRequestService.ApproveRejection.WRONG_TEAM);+ assertThat(result.rejection())+ .isEqualTo(ConnectRequestService.ApproveRejection.WRONG_ACCOUNT);assertThat(row.getStatus()).isEqualTo(ConnectRequest.Status.PENDING);assertThat(row.getTeamId()).isEqualTo(7L);}@Test- void approve_acceptsTheTeamTheServerAlreadyBelongsTo() {+ void approve_acceptsTheOriginalAccountInTheLinkedTeam() {ConnectRequest row = reauthPinnedTo(7L);when(repo.findByRequestIdForUpdate("req")).thenReturn(Optional.of(row));@@ -232,6 +236,66 @@ class ConnectRequestServiceTest {assertThat(row.getStatus()).isEqualTo(ConnectRequest.Status.APPROVED);}+ @Test+ void createReauth_withoutAnOriginalLinkingUserFailsClosed() {+ assertThat(+ service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, 7L, null)+ .rejection())+ .isEqualTo(CreateRejection.NOT_LINKED);+ verify(repo, never()).save(any());+ }++ @ParameterizedTest+ @CsvSource(+ value = {"7,43", "99,43", "NULL,42", "7,NULL"},+ nullValues = "NULL")+ void approve_rejectsAnotherAccountOrMissingIdentity(Long teamId, Long userId) {+ ConnectRequest row = reauthPinnedTo(7L);+ when(repo.findByRequestIdForUpdate("req")).thenReturn(Optional.of(row));++ assertThat(service.approve("req", teamId, userId).rejection())+ .isEqualTo(ConnectRequestService.ApproveRejection.WRONG_ACCOUNT);+ assertThat(row.getStatus()).isEqualTo(ConnectRequest.Status.PENDING);+ assertThat(row.getTeamId()).isEqualTo(7L);+ assertThat(row.getApprovedByUserId()).isEqualTo(42L);+ assertThat(row.getApprovedAt()).isNull();+ verify(repo, never()).save(any());+ verifyNoInteractions(accountLinkService);+ }++ @ParameterizedTest+ @ValueSource(booleans = {true, false})+ void approve_rejectsLegacyRenewalRequestsWithoutBothPins(boolean missingUser) {+ ConnectRequest row = reauthPinnedTo(7L);+ if (missingUser) row.setApprovedByUserId(null);+ else row.setTeamId(null);+ when(repo.findByRequestIdForUpdate("req")).thenReturn(Optional.of(row));++ assertThat(service.approve("req", 7L, 42L).rejection())+ .isEqualTo(ConnectRequestService.ApproveRejection.WRONG_ACCOUNT);+ assertThat(row.getStatus()).isEqualTo(ConnectRequest.Status.PENDING);+ verify(repo, never()).save(any());+ }++ @Test+ void deny_cannotCancelARenewal() {+ ConnectRequest row = reauthPinnedTo(7L);+ when(repo.findByRequestIdForUpdate("req")).thenReturn(Optional.of(row));++ assertThat(service.deny("req")).isFalse();+ assertThat(row.getStatus()).isEqualTo(ConnectRequest.Status.PENDING);+ verify(repo, never()).save(any());+ }++ @Test+ void deny_stillDeclinesAFirstLink() {+ ConnectRequest row = pending();+ when(repo.findByRequestIdForUpdate("req")).thenReturn(Optional.of(row));++ assertThat(service.deny("req")).isTrue();+ assertThat(row.getStatus()).isEqualTo(ConnectRequest.Status.DENIED);+ }+@Testvoid claim_onAReauthConfirmsWithoutMintingASecondCredential() {ConnectRequest row = reauthPinnedTo(7L);@@ -342,6 +406,7 @@ class ConnectRequestServiceTest {ConnectRequest row = pending();row.setMode(ConnectRequest.Mode.REAUTH);row.setTeamId(teamId);+ row.setApprovedByUserId(42L);return row;}diff --git a/frontend/editor/playwright.config.ts b/frontend/editor/playwright.config.tsindex ad47be40c6..8b7f19da5b 100644--- a/frontend/editor/playwright.config.ts+++ b/frontend/editor/playwright.config.ts@@ -162,7 +162,7 @@ export default defineConfig({// all-tool-pages-load.spec.ts). Locally, keep `vite` dev for HMR.command: process.env.CI? `npx vite preview --port ${DEV_PORT} --strictPort`- : `npx vite --port ${DEV_PORT} --strictPort`,+ : `npx vite --mode proprietary --port ${DEV_PORT} --strictPort`,url:process.env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${DEV_PORT}`,reuseExistingServer: !process.env.CI,diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 358b1422d2..e78620e065 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -3866,6 +3866,13 @@ title = "Connect a server"body = "This connection request is not valid. It may have expired, or already been used. Start another one from your server."title = "Request not valid"+[connect.renewal]+approve = "Renew sign-in"+failed = "Your sign-in could not be renewed. Try again, or dismiss this page and start again from your server."+lead = "This server is already linked to your account. Renew your sign-in to return to billing and usage on your server."+title = "Renew your server sign-in"+wrongAccount = "This account cannot renew this server's sign-in. Switch to the account originally used to link the server. That account must still own the linked team."+[convert]autoRotate = "Auto Rotate"autoRotateDescription = "Automatically rotate images to better fit the PDF page"@@ -7393,7 +7400,7 @@ switchOnProcessor = "Switch on the Processor"title = "Connected"[portal.accountLink.connect.handoff]-going = "Taking you to stirling.com"+opening = "Opening Stirling sign-in..."reauthLede = "Your Stirling session expired. Signing in again keeps usage and billing visible. This server stays connected either way."title = "Connecting"@@ -7419,12 +7426,13 @@ otherTitle = "No other connected instances"title = "No connected instances"[portal.accountLink.modal]+callbackMismatch = "This server's configured frontend address does not match the address you opened. Open the server at its configured address, or update Frontend URL in General settings, then try again."cancel = "Cancel"continueReauth = "Sign in again"exhaustedTitle = "Add more monthly credits"+identity = "Stirling account"linkTitle = "Connect your Stirling account"noAuthorizeUrl = "Stirling did not return somewhere to continue. Try again in a moment."-reauthTitle = "Sign in again"startFailed = "Could not reach Stirling to start the connection. Check this server's outbound network access, then try again."[portal.accountLink.modal.loginNotConfigured]@@ -7440,6 +7448,7 @@ manageCloud = "Manage on stirling.com"otherInstancesSub = "Other self-hosted servers connected to the same team in Stirling Cloud."otherInstancesTitle = "Other connected instances"revokeError = "Couldn't revoke instance"+sessionRequired = "Connected instances will appear after you renew billing access."sub = "Manage this server’s connection to your Stirling Cloud account."[portal.accountLink.panel.loadError]@@ -7447,11 +7456,20 @@ forbidden = "Only the team owner can manage connected instances."generic = "Your connections could not be checked. Try again."title = "Couldn’t load connected instances"-[portal.accountLink.rail]-cta = "Connect"-later = "Not now"-sub = "Adds monthly credits and room for more users. Everything on this server already works without one."-title = "Connect your Stirling account"+[portal.accountLink.renewal]+dataUnavailable = "Your plan and usage will appear after you renew billing access. This server stays connected, and local document processing remains available."+expired = "This sign-in request expired. Try again to renew billing access; your server is still connected."+expiredTitle = "Sign-in request expired"+incomplete = "This server is still connected, but we could not restore billing access in this browser. Try signing in again."+malformed = "We could not verify this sign-in response. Start again from Usage & billing; your server is still connected."+malformedTitle = "Could not verify sign-in"+rejected = "This sign-in request was declined or has already been used. Try again to renew billing access."+rejectedTitle = "Sign-in not completed"+retry = "Stirling could not finish renewing billing access. Try again in a moment; your server is still connected."+retryTitle = "Billing access not restored"+success = "Your billing access has been renewed. This server is still connected to the same Stirling account."+title = "Renew billing access"+working = "Restoring billing access."[portal.accountLink.state]free = "Editor plan"@@ -7474,6 +7492,9 @@ typing = "Typing"loading = "Loading"redirectingToEditor = "Redirecting to the editor..."+[portal.billing]+dataUnavailable = "Usage figures are currently unavailable."+[portal.billing.activation]maybeLater = "Maybe later"title = "Switch on the Processor"@@ -10084,9 +10105,7 @@ loadError = "Couldn't read this server's credit usage. Try again in a moment."loadErrorTitle = "Couldn't load credit usage"[portal.usage.sessionExpired]-action = "Sign in again"body = "Your Stirling account session has expired. Sign in again to view billing — your instance stays linked."-title = "Session expired"[portal.users]title = "Users"diff --git a/frontend/editor/src/cloud/tsconfig.json b/frontend/editor/src/cloud/tsconfig.jsonindex 2b703ea335..015d1fc5b0 100644--- a/frontend/editor/src/cloud/tsconfig.json+++ b/frontend/editor/src/cloud/tsconfig.json@@ -10,7 +10,13 @@"@portal/*": ["../../src/portal/*"],"@cloud/*": ["../../src/cloud/*"],"@proprietary/*": ["../../src/proprietary/*"],- "@core/*": ["../../src/core/*"]+ "@core/*": ["../../src/core/*"],+ "@app/portal/*": [+ "../../src/cloud/portal/*",+ "../../src/proprietary/portal/*",+ "../../src/core/portal/*",+ "../../src/portal/*"+ ]}},"include": [diff --git a/frontend/editor/src/core/tests/helpers/api-stubs.ts b/frontend/editor/src/core/tests/helpers/api-stubs.tsindex 5627ac19cc..728165a43e 100644--- a/frontend/editor/src/core/tests/helpers/api-stubs.ts+++ b/frontend/editor/src/core/tests/helpers/api-stubs.ts@@ -132,6 +132,7 @@ export interface MockAppApiOptions {role?: string;/** Portal (Processor) access flag — gates the super search's Processor lanes. */portalAccess?: boolean;+ orgOwner?: boolean;} | null;/** Languages advertised by `/config/app-config`. */languages?: string[];diff --git a/frontend/editor/src/core/tests/stubbed/account-link-dialogs.spec.ts b/frontend/editor/src/core/tests/stubbed/account-link-dialogs.spec.tsnew file mode 100644index 0000000000..90ee58282c--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/account-link-dialogs.spec.ts@@ -0,0 +1,340 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++test.use({+ autoGoto: false,+ seedJwt: true,+ stubOptions: {+ enableLogin: true,+ isAdmin: true,+ user: {+ id: 1,+ username: "owner",+ role: "ROLE_ADMIN",+ portalAccess: true,+ orgOwner: true,+ },+ },+});++test.beforeEach(async ({ page, context }) => {+ await context.route("**/api/v1/**", (route) => route.fulfill({ json: {} }));+ await page.route("**/api/v1/config/app-config", (route) =>+ route.fulfill({+ json: {+ enableLogin: true,+ isAdmin: true,+ enableAnalytics: false,+ languages: ["en-US"],+ defaultLocale: "en-US",+ accountLinkAvailable: true,+ },+ }),+ );+ await page.route("**/api/v1/account-link/status", (route) =>+ route.fulfill({ json: { linked: false, name: "Test server" } }),+ );+ await page.route("**/api/v1/account-link/free-tier", (route) =>+ route.fulfill({+ json: {+ grantUnits: 1000,+ usedUnits: 125,+ remainingUnits: 875,+ periodStart: "2026-09-01T00:00:00",+ periodEnd: "2026-10-01T00:00:00",+ },+ }),+ );+});++for (const [path, action] of [+ ["/settings/account-link", "Connect your Stirling account"],+ ["/settings/billing", "Connect a Stirling account"],+ ["/settings/billing", "Switch on the Processor"],+ ["/processor/pipelines", "Link Stirling account"],+]) {+ test(`dismissing ${action} on ${path} leaves one usable connection action`, async ({+ page,+ }) => {+ await page.goto(path);+ await page.getByRole("button", { name: action, exact: true }).click();+ const dialog = page.getByRole("dialog");+ await expect(dialog).toHaveCount(1);+ await expect(+ dialog.getByRole("button", {+ name: "Connect Stirling account",+ exact: true,+ }),+ ).toBeVisible();+ await dialog.getByRole("button", { name: "Not now", exact: true }).click();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: action, exact: true }),+ ).toBeVisible();+ });+}++for (const path of ["/settings/account-link", "/settings/billing"]) {+ test(`expired billing access on ${path} has one recovery action after dismissal`, async ({+ page,+ }) => {+ await page.route("**/api/v1/account-link/status", (route) =>+ route.fulfill({+ json: { linked: true, name: "Test server", deviceId: "test-device" },+ }),+ );+ await page.goto(path);+ const renew = page.getByRole("button", {+ name: "Sign in again",+ exact: true,+ });+ await expect(renew).toHaveCount(1);+ await renew.click();+ await expect(page.getByRole("dialog")).toHaveCount(1);+ await expect(renew).toHaveCount(1);+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Cancel", exact: true })+ .click();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(renew).toHaveCount(1);+ await expect(+ page.getByRole("button", { name: "Try again", exact: true }),+ ).toHaveCount(0);+ await expect(+ page.getByText("This server has no Stirling account"),+ ).toHaveCount(0);+ });+}++test("dismissing the trial connection prerequisite does not reopen it", async ({+ page,+}) => {+ await page.goto("/settings/billing?procurement=start");+ await expect(page.getByRole("dialog")).toHaveCount(1);+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Not now", exact: true })+ .click();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await page+ .getByRole("button", { name: "Connect a Stirling account", exact: true })+ .click();+ await expect(page.getByRole("dialog")).toHaveCount(1);+});++test("late exhausted-credit responses do not reopen a dismissed dialog", async ({+ page,+}) => {+ await page.goto("/processor/pipelines");+ await expect(+ page.getByRole("button", { name: "Link Stirling account" }),+ ).toBeVisible();+ await page.evaluate(() =>+ window.dispatchEvent(new Event("stirling:portal-free-tier-exhausted")),+ );+ await expect(page.getByRole("dialog")).toHaveCount(1);+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Not now", exact: true })+ .click();+ await page.evaluate(() =>+ window.dispatchEvent(new Event("stirling:portal-free-tier-exhausted")),+ );+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await page.getByRole("button", { name: "Link Stirling account" }).click();+ await expect(page.getByRole("dialog")).toHaveCount(1);+});++for (const role of ["ROLE_ADMIN", "ROLE_TEAM_LEAD", "ROLE_USER"]) {+ for (const path of [+ "/settings/account-link",+ "/settings/billing",+ "/processor/documents",+ ]) {+ test(`non-owner ${role} has no account or billing prompts on ${path}`, async ({+ page,+ }) => {+ await page.route("**/api/v1/auth/me", (route) =>+ route.fulfill({+ json: {+ user: {+ id: 2,+ username: "colleague",+ role,+ portalAccess: true,+ orgOwner: false,+ },+ },+ }),+ );+ let linkRequests = 0;+ await page.route("**/api/v1/account-link/**", (route) => {+ linkRequests++;+ return route.fulfill({ status: 403, json: {} });+ });+ await page.goto(path);+ await expect(+ page.getByRole("button", { name: "colleague — Account", exact: true }),+ ).toBeVisible();+ await page.evaluate(() =>+ window.dispatchEvent(new Event("stirling:portal-free-tier-exhausted")),+ );+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(+ page.getByRole("button", {+ name: /^(Connect your Stirling account|Connect a Stirling account|Link Stirling account|Sign in again)$/,+ }),+ ).toHaveCount(0);+ await expect(+ page.getByText("Renew billing access", { exact: true }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Usage & Billing", exact: true }),+ ).toHaveCount(0);+ expect(linkRequests).toBe(0);+ });+ }+}++for (const linked of [false, true]) {+ test(`Documents loads local records when the server is ${linked ? "linked without billing access" : "unlinked"}`, async ({+ page,+ }) => {+ await page.route("**/api/v1/account-link/status", (route) =>+ route.fulfill({+ json: {+ linked,+ name: "Test server",+ },+ }),+ );+ const localDocuments = page.waitForRequest(+ "**/api/v1/proprietary/ui-data/documents?*",+ );+ await page.route("**/api/v1/proprietary/ui-data/documents?*", (route) =>+ route.fulfill({+ json: {+ summary: {+ totalInQueue: 0,+ processed: 1,+ errors: 0,+ processedToday: 1,+ },+ documents: [+ {+ id: "local-document",+ name: "Local invoice.pdf",+ type: "PDF",+ classification: null,+ auto: false,+ note: "Compressed locally",+ product: "Editor",+ action: null,+ user: "owner",+ status: "processed",+ reviewer: null,+ source: "Upload",+ confidence: null,+ fieldsExtracted: 0,+ time: "just now",+ sensitive: false,+ extractions: [],+ audit: [],+ },+ ],+ },+ }),+ );+ await page.goto("/processor/documents");+ const request = await localDocuments;+ expect(new URL(request.url()).origin).toBe(new URL(page.url()).origin);+ await expect(page.getByText("Local invoice.pdf")).toBeVisible();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(+ page.getByText("Renew billing access", { exact: true }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Sign in again", exact: true }),+ ).toHaveCount(0);+ });+}++for (const connectionState of [+ "unlinked",+ "connected",+ "offline",+ "expired",+ "revoked",+]) {+ const linked = connectionState !== "unlinked";+ test(`local navigation has no connection banner with a ${connectionState} server`, async ({+ page,+ }) => {+ await page.route("**/api/v1/account-link/status", (route) =>+ route.fulfill({+ json: {+ linked,+ name: "Test server",+ connection: { state: connectionState },+ },+ }),+ );+ await page.route("**/v1/editor/deployment*", (route) =>+ route.fulfill({+ json: { instances: [], summary: { workspaceUrl: null } },+ }),+ );+ for (const path of ["policies", "policies/runs", "integrations"]) {+ await page.route(`**/api/v1/${path}`, (route) =>+ route.fulfill({ json: [] }),+ );+ }+ await page.route("**/api/v1/sources*", (route) =>+ route.fulfill({ json: { sources: [], kpis: [] } }),+ );+ if (linked) {+ await page.goto("/settings/billing");+ await expect(+ page.getByRole("button", { name: "Sign in again", exact: true }),+ ).toBeVisible();+ await page+ .getByRole("button", { name: "Processor", exact: true })+ .click();+ } else {+ await page.goto("/processor");+ }+ await expect(+ page.getByRole("button", { name: "Documents", exact: true }),+ ).toBeVisible();+ for (const section of ["Home", "Documents", "Pipelines"]) {+ await page.getByRole("button", { name: section, exact: true }).click();+ await expect(+ page.locator(`.portal-${section.toLowerCase()}`),+ ).toBeVisible();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(+ page.getByText("Connect your Stirling account", { exact: true }),+ ).toHaveCount(0);+ await expect(+ page.getByText("Renew billing access", { exact: true }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Sign in again", exact: true }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Check connection", exact: true }),+ ).toHaveCount(0);+ }+ if (linked) {+ await page+ .getByRole("button", { name: "owner — Account", exact: true })+ .click();+ await page+ .getByRole("button", { name: "Usage & Billing", exact: true })+ .click();+ await expect(+ page.getByRole("button", { name: "Sign in again", exact: true }),+ ).toHaveCount(1);+ }+ });+}diff --git a/frontend/editor/src/portal-saas/PortalProviders.test.tsx b/frontend/editor/src/portal-saas/PortalProviders.test.tsxnew file mode 100644index 0000000000..c2e126c9d8--- /dev/null+++ b/frontend/editor/src/portal-saas/PortalProviders.test.tsx@@ -0,0 +1,66 @@+import type { ReactNode } from "react";+import { render, screen, fireEvent, cleanup } from "@testing-library/react";+import { MemoryRouter } from "react-router-dom";+import { afterEach, expect, it, vi } from "vitest";+import { PortalProviders } from "@app/portal/PortalProviders";+import { PortalSettingsProviders } from "@app/portal/components/settings/PortalSettingsProviders";+import { useUI } from "@app/portal/contexts/UIContext";+vi.mock("@app/portal/contexts/TierContext", () => ({+ TierProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ AppConfigProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@app/contexts/LicenseContext", () => ({+ LicenseProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@app/contexts/CheckoutContext", () => ({+ CheckoutProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@app/components/startup/StartupPrompts", () => ({+ StartupPrompts: () => null,+}));+vi.mock("@app/portal/components/PortalChrome", () => ({+ PortalChrome: () => <Trigger />,+}));+function Trigger() {+ const { openLinkModal, publishConnectOutcome } = useUI();+ return (+ <>+ <button onClick={() => openLinkModal("reauth")}>Request renewal</button>+ <button+ onClick={() =>+ publishConnectOutcome({+ mode: "reauth",+ state: "expired",+ sessionRestored: false,+ })+ }+ >+ Publish callback+ </button>+ </>+ );+}+afterEach(cleanup);+it.each(["Processor", "Settings"])(+ "SaaS %s has no link or renewal modal host",+ (surface) => {+ render(+ <MemoryRouter>+ {surface === "Processor" ? (+ <PortalProviders />+ ) : (+ <PortalSettingsProviders>+ <Trigger />+ </PortalSettingsProviders>+ )}+ </MemoryRouter>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Request renewal" }));+ fireEvent.click(screen.getByRole("button", { name: "Publish callback" }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.queryByText("Renew billing access")).not.toBeInTheDocument();+ expect(screen.queryByText("Sign in again")).not.toBeInTheDocument();+ },+);diff --git a/frontend/editor/src/portal-saas/auth/portalSaasSession.test.ts b/frontend/editor/src/portal-saas/auth/portalSaasSession.test.tsindex 5a0425af09..200e476cf5 100644--- a/frontend/editor/src/portal-saas/auth/portalSaasSession.test.ts+++ b/frontend/editor/src/portal-saas/auth/portalSaasSession.test.ts@@ -1,29 +1,58 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-const { getSession, getLinkedClient, ensureLinkClient, fetchMock } = vi.hoisted(- () => ({- getSession: vi.fn(),- getLinkedClient: vi.fn(() => null),- ensureLinkClient: vi.fn(() => null),- fetchMock: vi.fn(),- }),-);+const {+ getSession,+ refreshSession,+ invoke,+ rpc,+ getLinkedClient,+ ensureLinkClient,+ fetchMock,+} = vi.hoisted(() => ({+ getSession: vi.fn(),+ refreshSession: vi.fn(),+ invoke: vi.fn(),+ rpc: vi.fn(),+ getLinkedClient: vi.fn(() => null),+ ensureLinkClient: vi.fn(() => null),+ fetchMock: vi.fn(),+}));++const login = vi.hoisted(() => ({ redirect: vi.fn() }));+vi.mock("@app/auth/redirectToLogin", () => ({+ redirectToLogin: login.redirect,+}));-vi.mock("@app/auth/supabase", () => ({ supabase: { auth: { getSession } } }));+vi.mock("@app/auth/supabase", () => ({+ supabase: {+ auth: { getSession, refreshSession },+ functions: { invoke },+ rpc,+ },+}));vi.mock("@app/auth/supabase/supabaseClient", () => ({getSupabaseClient: getLinkedClient,}));-vi.mock("@portal/auth/saasSupabase", () => ({+vi.mock("@app/portal/auth/saasSupabase", () => ({ensureSaasSupabase: ensureLinkClient,}));-import { getPortalSaasToken } from "@portal/auth/portalSaasSession";-import { fetchWallet } from "@portal/api/billing";-import { SaasNotLinkedError } from "@portal/api/http";+import {+ getPortalSaasToken,+ resetPortalSaasSessionState,+} from "@app/portal/auth/portalSaasSession";+import {+ createPortalSession,+ getLatestBundleQuote,+} from "@app/portal/billing/stripe";+import { invokeSaasFunction } from "@app/portal/auth/saasFunctions";+import { fetchWallet } from "@app/portal/api/billing";+import { apiClient, SaasSessionRequiredError } from "@app/portal/api/http";describe("SaaS billing session", () => {beforeEach(() => {vi.clearAllMocks();+ resetPortalSaasSessionState();vi.stubEnv("VITE_API_BASE_URL", "https://saas.example");vi.stubGlobal("fetch", fetchMock);getSession.mockResolvedValue({@@ -53,6 +82,38 @@ describe("SaaS billing session", () => {expect(getLinkedClient).not.toHaveBeenCalled();});+ it("renews a rejected SaaS login token and retries a wallet read once", async () => {+ refreshSession.mockResolvedValue({+ data: { session: { access_token: "renewed-saas-token" } },+ error: null,+ });+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 401 }));+ await expect(fetchWallet()).resolves.toEqual({ teamId: 42 });+ expect(refreshSession).toHaveBeenCalledOnce();+ expect(fetchMock).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({+ headers: expect.objectContaining({+ Authorization: "Bearer renewed-saas-token",+ }),+ }),+ );+ expect(getLinkedClient).not.toHaveBeenCalled();+ });++ it("never replays a rejected hosted billing mutation", async () => {+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 401 }));+ await expect(+ apiClient.saas.json("/api/v1/payg/cap", {+ method: "PATCH",+ body: { capUsd: 100 },+ }),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ expect(fetchMock).toHaveBeenCalledOnce();+ expect(refreshSession).not.toHaveBeenCalled();+ expect(login.redirect).toHaveBeenCalled();+ });+it("reads the current SaaS session after its token changes", async () => {expect(await getPortalSaasToken()).toBe("signed-in-saas-token");getSession.mockResolvedValue({@@ -64,8 +125,47 @@ describe("SaaS billing session", () => {it("does not borrow an account-link session when the SaaS user signs out", async () => {getSession.mockResolvedValue({ data: { session: null } });expect(await getPortalSaasToken()).toBeNull();- await expect(fetchWallet()).rejects.toBeInstanceOf(SaasNotLinkedError);+ await expect(fetchWallet()).rejects.toBeInstanceOf(+ SaasSessionRequiredError,+ );expect(fetchMock).not.toHaveBeenCalled();+ expect(login.redirect).toHaveBeenCalled();expect(ensureLinkClient).not.toHaveBeenCalled();});});++it("uses the hosted client for edge calls, billing management and quote RPCs", async () => {+ resetPortalSaasSessionState();+ getSession.mockResolvedValue({+ data: { session: { access_token: "hosted-token" } },+ error: null,+ });+ invoke.mockResolvedValue({+ data: { success: true, url: "https://billing.example/session" },+ error: null,+ });+ rpc.mockResolvedValue({ data: [], error: null, status: 200 });+ getLinkedClient.mockClear();+ ensureLinkClient.mockClear();+ await expect(+ invokeSaasFunction("quote-pdf", { method: "GET" }, true),+ ).resolves.toMatchObject({ error: null });+ await expect(+ createPortalSession({+ teamId: 42,+ returnUrl: "https://app.example/settings/billing",+ }),+ ).resolves.toBe("https://billing.example/session");+ await expect(getLatestBundleQuote(42)).resolves.toBeNull();+ expect(invoke).toHaveBeenLastCalledWith(+ "create-customer-portal-session",+ expect.objectContaining({+ headers: { Authorization: "Bearer hosted-token" },+ }),+ );+ expect(rpc).toHaveBeenCalledWith("payg_get_latest_bundle_quote", {+ p_team_id: 42,+ });+ expect(getLinkedClient).not.toHaveBeenCalled();+ expect(ensureLinkClient).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/portal-saas/auth/portalSaasSession.ts b/frontend/editor/src/portal-saas/auth/portalSaasSession.tsdeleted file mode 100644index c5838366d7..0000000000--- a/frontend/editor/src/portal-saas/auth/portalSaasSession.ts+++ /dev/null@@ -1,2 +0,0 @@-/** Hosted billing shares the app's signed-in session; it has no instance-link session to initialise. */-export { getAccessToken as getPortalSaasToken } from "@app/auth/session";diff --git a/frontend/editor/src/portal-saas/auth/sessionClient.ts b/frontend/editor/src/portal-saas/auth/sessionClient.tsnew file mode 100644index 0000000000..50a01431c9--- /dev/null+++ b/frontend/editor/src/portal-saas/auth/sessionClient.ts@@ -0,0 +1,9 @@+import { supabase } from "@app/auth/supabase";+export { redirectToLogin as handlePortalSessionRequired } from "@app/auth/redirectToLogin";++/** Hosted billing shares the app login and must never create an instance-link session. */+export function getPortalSessionClient() {+ return supabase;+}++export const ensurePortalSessionClient = getPortalSessionClient;diff --git a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsxindex 68695465a7..a1d9b4ae59 100644--- a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx+++ b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx@@ -1,20 +1,26 @@import { describe, expect, it, vi } from "vitest";import { render, screen } from "@testing-library/react";import { MemoryRouter } from "react-router-dom";--vi.mock("@portal/views/Usage", () => ({- Usage: () => <div data-testid="usage" />,+const props = vi.hoisted(() => ({ seen: {} as Record<string, unknown> }));+vi.mock("@app/portal/views/Usage", () => ({+ Usage: (value: Record<string, unknown>) => {+ props.seen = value;+ return <div data-testid="usage" />;+ },}));--import { BillingSettingsSection } from "@portal/components/settings/BillingSettingsSection";+import { BillingSettingsSection } from "@app/portal/components/settings/BillingSettingsSection";+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";describe("PortalBillingGate — SaaS", () => {- it("renders the Usage page directly, with no link concept", () => {+ it("renders hosted billing without any self-hosted renewal or connection actions", () => {render(<MemoryRouter initialEntries={["/settings/billing"]}><BillingSettingsSection /></MemoryRouter>,);expect(screen.getByTestId("usage")).toBeInTheDocument();+ expect(props.seen.sessionRecovery).toBeUndefined();+ expect(props.seen.onReauth).toBeUndefined();+ expect(useAccountLinkOwner()).toBe(false);});});diff --git a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsxindex 73c3eba8f3..a12325dab1 100644--- a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx+++ b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx@@ -1,21 +1,6 @@-import { withBasePath } from "@app/constants/app";-import { Usage } from "@portal/views/Usage";+import { Usage } from "@app/portal/views/Usage";-/**- * SaaS billing gate: there is no link concept — the signed-in account IS the SaaS- * account (auth is handled upstream by PortalAuthBoundary), so render the Usage- * page directly. No link state, no prompt.- *- * onReauth sends the user back to the editor's Supabase login if the session- * lapses mid-view: PortalAuthBoundary only re-gates on mount / session change, so- * without this a "Session expired" notice would dead-end until a manual reload.- */+/** Hosted billing uses app authentication and never offers instance-link renewal. */export function PortalBillingGate() {- return (- <Usage- onReauth={() => {- window.location.href = withBasePath("/login");- }}- />- );+ return <Usage />;}diff --git a/frontend/editor/src/portal-saas/hooks/useAccountLinkOwner.ts b/frontend/editor/src/portal-saas/hooks/useAccountLinkOwner.tsnew file mode 100644index 0000000000..6adcf58fc3--- /dev/null+++ b/frontend/editor/src/portal-saas/hooks/useAccountLinkOwner.ts@@ -0,0 +1,4 @@+/** Hosted accounts use the app session; instance linking belongs to self-hosted owners. */+export function useAccountLinkOwner(): boolean {+ return false;+}diff --git a/frontend/editor/src/portal/PortalProviders.startup.test.tsx b/frontend/editor/src/portal/PortalProviders.startup.test.tsxindex c1b6d7a773..4f57750372 100644--- a/frontend/editor/src/portal/PortalProviders.startup.test.tsx+++ b/frontend/editor/src/portal/PortalProviders.startup.test.tsx@@ -9,8 +9,9 @@ import { PortalProviders } from "@portal/PortalProviders";const h = vi.hoisted(() => ({get: vi.fn(),auth: {- user: { id: "admin" },+ user: { id: "admin", orgOwner: true },loading: false,+ isAdmin: true,isAnonymous: false,signOut: vi.fn(),},@@ -21,6 +22,7 @@ vi.mock("react-i18next", () => ({i18n: { language: "en-US" },}),}));+vi.mock("@app/auth", () => ({ useAuth: () => h.auth }));vi.mock("@app/auth/UseSession", () => ({ useAuth: () => h.auth }));vi.mock("@app/services/apiClient", () => ({ default: { get: h.get } }));vi.mock("@app/extensions/accountLogout", () => ({@@ -47,7 +49,7 @@ vi.mock("@portal/contexts/UIContext", () => ({useUI: () => ({ linkModalOpen: false }),}));vi.mock("@portal/components/account-link/LinkAccountModal", () => ({- LinkAccountModal: () => null,+ LinkAccountModalHost: () => null,}));vi.mock("@portal/components/account-link/ConnectCallbackHost", () => ({ConnectCallbackHost: () => null,diff --git a/frontend/editor/src/portal/PortalProviders.test.tsx b/frontend/editor/src/portal/PortalProviders.test.tsxindex 8a0d54b796..b510819571 100644--- a/frontend/editor/src/portal/PortalProviders.test.tsx+++ b/frontend/editor/src/portal/PortalProviders.test.tsx@@ -4,14 +4,17 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { MemoryRouter } from "react-router-dom";import { MantineProvider } from "@mantine/core";import type { ReactNode } from "react";-import { PortalProviders } from "@portal/PortalProviders";-import { ServerLicenseSection } from "@portal/components/billing/ServerLicenseSection";+import { PortalProviders } from "@app/portal/PortalProviders";+import { ServerLicenseSection } from "@app/portal/components/billing/ServerLicenseSection";const { fetchAppConfig, getLicenseInfo } = vi.hoisted(() => ({fetchAppConfig: vi.fn(),getLicenseInfo: vi.fn(),}));+vi.mock("@app/auth", () => ({+ useAuth: () => ({ user: { id: "owner" }, isAdmin: true, loading: false }),+}));vi.mock("@app/api/config", () => ({DEFAULT_APP_CONFIG: { enableLogin: true },fetchAppConfig,@@ -22,32 +25,32 @@ vi.mock("@app/services/licenseService", () => ({vi.mock("@app/testing/serverExperienceSimulations", () => ({getSimulatedLicenseInfo: () => null,}));-vi.mock("@portal/contexts/TierContext", () => ({+vi.mock("@app/portal/contexts/TierContext", () => ({TierProvider: ({ children }: { children: ReactNode }) => children,}));-vi.mock("@portal/contexts/LinkContext", () => ({+vi.mock("@app/portal/contexts/LinkContext", () => ({LinkProvider: ({ children }: { children: ReactNode }) => children,}));-vi.mock("@portal/contexts/UIContext", () => ({+vi.mock("@app/portal/contexts/UIContext", () => ({UIProvider: ({ children }: { children: ReactNode }) => children,useUI: () => ({ linkModalOpen: false }),}));-vi.mock("@portal/contexts/AccountLinkContext", () => ({+vi.mock("@app/portal/contexts/AccountLinkContext", () => ({AccountLinkProvider: ({ children }: { children: ReactNode }) => children,}));vi.mock("@app/contexts/CheckoutContext", () => ({CheckoutProvider: ({ children }: { children: ReactNode }) => children,}));-vi.mock("@portal/components/account-link/LinkAccountModal", () => ({- LinkAccountModal: () => null,+vi.mock("@app/portal/components/account-link/LinkAccountModal", () => ({+ LinkAccountModalHost: () => null,}));-vi.mock("@portal/components/account-link/ConnectCallbackHost", () => ({+vi.mock("@app/portal/components/account-link/ConnectCallbackHost", () => ({ConnectCallbackHost: () => null,}));-vi.mock("@portal/hooks/useFreeTierExhaustedPrompt", () => ({+vi.mock("@app/portal/hooks/useFreeTierExhaustedPrompt", () => ({useFreeTierExhaustedPrompt: () => {},}));-vi.mock("@portal/components/PortalChrome", () => ({+vi.mock("@app/portal/components/PortalChrome", () => ({PortalChrome: () => <ServerLicenseSection onSaved={() => {}} />,}));diff --git a/frontend/editor/src/portal/PortalProviders.tsx b/frontend/editor/src/portal/PortalProviders.tsxindex 5ad70afbea..2254c7740a 100644--- a/frontend/editor/src/portal/PortalProviders.tsx+++ b/frontend/editor/src/portal/PortalProviders.tsx@@ -1,36 +1,21 @@-import { TierProvider } from "@portal/contexts/TierContext";-import { LinkProvider } from "@portal/contexts/LinkContext";-import { UIProvider, useUI } from "@portal/contexts/UIContext";-import { LinkAccountModal } from "@portal/components/account-link/LinkAccountModal";-import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";-import { ConnectCallbackHost } from "@portal/components/account-link/ConnectCallbackHost";-import { PortalChrome } from "@portal/components/PortalChrome";-import { useFreeTierExhaustedPrompt } from "@portal/hooks/useFreeTierExhaustedPrompt";+import { TierProvider } from "@app/portal/contexts/TierContext";+import { LinkProvider } from "@app/portal/contexts/LinkContext";+import { UIProvider } from "@app/portal/contexts/UIContext";+import { LinkAccountModalHost } from "@app/portal/components/account-link/LinkAccountModal";+import { AccountLinkProvider } from "@app/portal/contexts/AccountLinkContext";+import { ConnectCallbackHost } from "@app/portal/components/account-link/ConnectCallbackHost";+import { PortalChrome } from "@app/portal/components/PortalChrome";+import { AccountLinkSessionBoundary } from "@app/portal/components/account-link/AccountLinkSessionBoundary";+import { useFreeTierExhaustedPrompt } from "@app/portal/hooks/useFreeTierExhaustedPrompt";import { LicenseProvider } from "@app/contexts/LicenseContext";import { AppConfigProvider } from "@app/contexts/AppConfigContext";import { StartupPrompts } from "@app/components/startup/StartupPrompts";import { ServerExperienceProvider } from "@app/contexts/ServerExperienceContext";import { CheckoutProvider } from "@app/contexts/CheckoutContext";-/** The one and only account-link modal, whichever step it is on. */function LinkModalHost() {- const { linkModalOpen, linkModalMode, closeLinkModal, connectOutcome } =- useUI();- // Being unlinked prompts nothing: the free tier is the whole product. The only unprompted ask is- // the server reporting the month's grant spent.useFreeTierExhaustedPrompt();-- // Mounted only while open: kept mounted, an interrupted hand-off stays flagged and every- // later open resumes on a ghost step with no way forward.- if (!linkModalOpen) return null;- return (- <LinkAccountModal- open- mode={linkModalMode}- onClose={closeLinkModal}- outcome={connectOutcome}- />- );+ return <LinkAccountModalHost />;}/**@@ -43,22 +28,24 @@ export function PortalProviders() {return (<LinkProvider initialState="unlinked" statusKnown={false}><TierProvider>- <UIProvider>- <AccountLinkProvider>- <AppConfigProvider>- <LicenseProvider>- <CheckoutProvider>- <ServerExperienceProvider>- <StartupPrompts />- <PortalChrome />- </ServerExperienceProvider>- <LinkModalHost />- <ConnectCallbackHost />- </CheckoutProvider>- </LicenseProvider>- </AppConfigProvider>- </AccountLinkProvider>- </UIProvider>+ <AccountLinkSessionBoundary>+ <UIProvider>+ <AccountLinkProvider>+ <AppConfigProvider>+ <LicenseProvider>+ <CheckoutProvider>+ <ServerExperienceProvider>+ <StartupPrompts />+ <PortalChrome />+ </ServerExperienceProvider>+ <LinkModalHost />+ <ConnectCallbackHost />+ </CheckoutProvider>+ </LicenseProvider>+ </AppConfigProvider>+ </AccountLinkProvider>+ </UIProvider>+ </AccountLinkSessionBoundary></TierProvider></LinkProvider>);diff --git a/frontend/editor/src/portal/api/http.test.ts b/frontend/editor/src/portal/api/http.test.tsindex 031327c0cf..b4d28a04ad 100644--- a/frontend/editor/src/portal/api/http.test.ts+++ b/frontend/editor/src/portal/api/http.test.ts@@ -7,24 +7,28 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";* base with the Supabase bearer) is covered in api/link.test.ts; here we pin the* error/edge branches that gate the billing UI's error surface.*/-const { getSession, getStoredTokenMock } = vi.hoisted(() => ({+const { getSession, refreshSession, getStoredTokenMock } = vi.hoisted(() => ({getSession: vi.fn(),+ refreshSession: vi.fn(),getStoredTokenMock: vi.fn(),}));vi.mock("@app/auth", () => ({ getStoredToken: getStoredTokenMock }));vi.mock("@app/auth/supabase/supabaseClient", () => ({- getSupabaseClient: () => ({ auth: { getSession } }),+ getSupabaseClient: () => ({ auth: { getSession, refreshSession } }),configureSupabase: vi.fn(),}));-vi.mock("@portal/auth/saasSupabase", () => ({ ensureSaasSupabase: vi.fn() }));+vi.mock("@app/portal/auth/saasSupabase", () => ({+ ensureSaasSupabase: vi.fn(),+}));import {apiClient,HttpError,- SaasNotLinkedError,+ SaasSessionRequiredError,SaasUnconfiguredError,-} from "@portal/api/http";+} from "@app/portal/api/http";+import { resetPortalSaasSessionState } from "@app/portal/auth/portalSaasSession";const fetchMock = vi.fn();@@ -32,6 +36,8 @@ beforeEach(() => {vi.stubGlobal("fetch", fetchMock);fetchMock.mockReset();getSession.mockReset();+ refreshSession.mockReset();+ resetPortalSaasSessionState();getStoredTokenMock.mockReset();});@@ -48,6 +54,59 @@ function ok(body: unknown): Response {}describe("apiClient.saas", () => {+ it.each(["json", "text", "blob"] as const)(+ "renews and retries a %s read once after 401",+ async (format) => {+ vi.stubEnv("VITE_SAAS_API_URL", "https://saas.test.local");+ getSession.mockResolvedValue({+ data: { session: { access_token: "expired" } },+ });+ refreshSession.mockResolvedValue({+ data: { session: { access_token: "renewed" } },+ });+ const response = ok({ valid: true });+ const blob = new Blob(['{"valid":true}'], {+ type: "application/json",+ });+ const readBlob = vi.spyOn(response, "blob").mockResolvedValue(blob);+ fetchMock+ .mockResolvedValueOnce(new Response(null, { status: 401 }))+ .mockResolvedValueOnce(response);+ const result = await apiClient.saas[format]("/read", {+ headers: { Authorization: "stale-override" },+ });+ if (format === "json") expect(result).toEqual({ valid: true });+ else if (format === "text") expect(result).toBe('{"valid":true}');+ else {+ expect(readBlob).toHaveBeenCalledOnce();+ expect(result).toBe(blob);+ }+ expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe(+ "Bearer expired",+ );+ expect(refreshSession).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock.mock.calls[1][1].headers.Authorization).toBe(+ "Bearer renewed",+ );+ },+ );++ it("does not repeat a purchase after a 401", async () => {+ vi.stubEnv("VITE_SAAS_API_URL", "https://saas.test.local");+ getSession.mockResolvedValue({+ data: { session: { access_token: "expired" } },+ });+ fetchMock.mockResolvedValue(new Response(null, { status: 401 }));+ await expect(+ apiClient.saas.json("/purchase", {+ method: "POST",+ body: { quantity: 3 },+ }),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(refreshSession).not.toHaveBeenCalled();+ });it("throws SaasUnconfiguredError when VITE_SAAS_API_URL is unset", async () => {vi.stubEnv("VITE_SAAS_API_URL", "");await expect(@@ -56,12 +115,12 @@ describe("apiClient.saas", () => {expect(fetchMock).not.toHaveBeenCalled();});- it("throws SaasNotLinkedError when there is no SaaS session", async () => {+ it("throws SaasSessionRequiredError when there is no SaaS session", async () => {vi.stubEnv("VITE_SAAS_API_URL", "https://saas.test.local");getSession.mockResolvedValue({ data: { session: null } });await expect(apiClient.saas.json("/api/v1/payg/wallet"),- ).rejects.toBeInstanceOf(SaasNotLinkedError);+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);expect(fetchMock).not.toHaveBeenCalled();});diff --git a/frontend/editor/src/portal/api/http.ts b/frontend/editor/src/portal/api/http.tsindex d34d9c62ea..d319ea9d08 100644--- a/frontend/editor/src/portal/api/http.ts+++ b/frontend/editor/src/portal/api/http.ts@@ -41,15 +41,16 @@* entitlement calls. It never enters the portal — the browser is the human* admin and uses the Supabase JWT for SaaS reads. Don't add it here.*/-import { getPortalSaasToken } from "@portal/auth/portalSaasSession";-import { reportAccountLinkBlock } from "@portal/services/accountLinkBlock";-import { resolveDemoResponse } from "@portal/api/demoData";-import { saasApiBase } from "@portal/api/saasApiBase";+import { withPortalSaasSession } from "@app/portal/auth/portalSaasSession";+import { reportAccountLinkBlock } from "@app/portal/services/accountLinkBlock";+export { SaasSessionRequiredError } from "@app/portal/auth/portalSaasSession";+import { resolveDemoResponse } from "@app/portal/api/demoData";+import { saasApiBase } from "@app/portal/api/saasApiBase";import {localAuthHeader,localBaseUrl,onLocalUnauthorized,-} from "@portal/api/localBackend";+} from "@app/portal/api/localBackend";/*** SaaS base URL via the flavor seam: self-hosted reads VITE_SAAS_API_URL (a@@ -91,16 +92,6 @@ export class SaasUnconfiguredError extends Error {}}-/** Thrown by apiClient.saas.* when the admin has no SaaS session yet. */-export class SaasNotLinkedError extends Error {- constructor() {- super(- "No SaaS session — admin must link an account before attended SaaS reads.",- );- this.name = "SaasNotLinkedError";- }-}-/*** Best-effort human-readable message from a thrown error: unwraps an* {@link HttpError}'s ProblemDetail-ish body (`detail` / `message` / `error`)@@ -251,21 +242,25 @@ async function saasJson<T>(const base = saasBaseUrl();// null = unset (self-hosted, no VITE_SAAS_API_URL). "" is same-origin (SaaS) — valid.if (base === null) throw new SaasUnconfiguredError();- const token = await getPortalSaasToken();- if (!token) throw new SaasNotLinkedError();- const res = await fetch(`${base}${path}`, {- method: options.method ?? "GET",- headers: {- Accept: "application/json",- Authorization: `Bearer ${token}`,- ...(options.body !== undefined- ? { "Content-Type": "application/json" }- : {}),- ...options.headers,- },- body: options.body !== undefined ? JSON.stringify(options.body) : undefined,- signal: options.signal,- });+ const res = await withPortalSaasSession(+ (token) =>+ fetch(`${base}${path}`, {+ method: options.method ?? "GET",+ headers: {+ Accept: "application/json",+ ...(options.body !== undefined+ ? { "Content-Type": "application/json" }+ : {}),+ ...options.headers,+ Authorization: `Bearer ${token}`,+ },+ body:+ options.body !== undefined ? JSON.stringify(options.body) : undefined,+ signal: options.signal,+ }),+ (response) => response.status === 401,+ !options.method || options.method === "GET",+ );return unwrap<T>(res);}@@ -277,19 +272,22 @@ async function saasText(const base = saasBaseUrl();// null = unset (self-hosted, no VITE_SAAS_API_URL). "" is same-origin (SaaS) — valid.if (base === null) throw new SaasUnconfiguredError();- const token = await getPortalSaasToken();- if (!token) throw new SaasNotLinkedError();- const res = await fetch(`${base}${path}`, {- method: options.method ?? "GET",- headers: {- Accept: "text/plain",- Authorization: `Bearer ${token}`,- ...options.headers,- },- signal: options.signal,- });+ const res = await withPortalSaasSession(+ (token) =>+ fetch(`${base}${path}`, {+ method: options.method ?? "GET",+ headers: {+ Accept: "text/plain",+ ...options.headers,+ Authorization: `Bearer ${token}`,+ },+ signal: options.signal,+ }),+ (response) => response.status === 401,+ !options.method || options.method === "GET",+ );if (!res.ok) {- throw new Error(`SaaS request failed (${res.status})`);+ throw new HttpError(res.status, res.statusText, null);}return res.text();}@@ -302,13 +300,16 @@ async function saasBlob(const base = saasBaseUrl();// Same-origin SaaS resolves to "" (falsy); only null means unconfigured.if (base === null) throw new SaasUnconfiguredError();- const token = await getPortalSaasToken();- if (!token) throw new SaasNotLinkedError();- const res = await fetch(`${base}${path}`, {- method: options.method ?? "GET",- headers: { Authorization: `Bearer ${token}`, ...options.headers },- signal: options.signal,- });+ const res = await withPortalSaasSession(+ (token) =>+ fetch(`${base}${path}`, {+ method: options.method ?? "GET",+ headers: { ...options.headers, Authorization: `Bearer ${token}` },+ signal: options.signal,+ }),+ (response) => response.status === 401,+ !options.method || options.method === "GET",+ );if (!res.ok) throw new HttpError(res.status, res.statusText, null);return res.blob();}diff --git a/frontend/editor/src/portal/api/link.ts b/frontend/editor/src/portal/api/link.tsindex 7dd2bcd3dc..51272125dd 100644--- a/frontend/editor/src/portal/api/link.ts+++ b/frontend/editor/src/portal/api/link.ts@@ -1,4 +1,4 @@-import { apiClient } from "@portal/api/http";+import { apiClient } from "@app/portal/api/http";import type { LinkedInstanceRow } from "@app/types/linkedInstance";export type { LinkedInstanceRow };@@ -83,7 +83,8 @@ export type ConnectPhase =| "LINKED"| "EXPIRED"| "REJECTED"- | "UNAVAILABLE";+ | "UNAVAILABLE"+ | "CALLBACK_MISMATCH";export interface ConnectStatus {phase: ConnectPhase;diff --git a/frontend/editor/src/portal/api/procurement.ts b/frontend/editor/src/portal/api/procurement.tsindex b318b82848..cc16c23a23 100644--- a/frontend/editor/src/portal/api/procurement.ts+++ b/frontend/editor/src/portal/api/procurement.ts@@ -1,7 +1,7 @@-import { apiClient } from "@portal/api/http";-import { resolveDemoResponse } from "@portal/api/demoData";-import { saasApiBase } from "@portal/api/saasApiBase";-import { getSupabaseClient } from "@app/auth/supabase/supabaseClient";+import { apiClient } from "@app/portal/api/http";+import { resolveDemoResponse } from "@app/portal/api/demoData";+import { saasApiBase } from "@app/portal/api/saasApiBase";+import { invokeSaasFunction } from "@app/portal/auth/saasFunctions";/** Procurement models the enterprise commercial journey: trial → quote → agreement → payment →@@ -369,9 +369,7 @@ async function demoEdgeResponse(async function invokeEdge<T>(fn: string, quoteId: number): Promise<T> {const demo = await demoEdgeResponse(fn, quoteId);if (demo) return (await demo.json()) as T;- const supabase = getSupabaseClient();- if (!supabase) throw new Error("No SaaS session");- const { data, error } = await supabase.functions.invoke<T>(fn, {+ const { data, error } = await invokeSaasFunction<T>(fn, {body: { quote_id: quoteId },});if (error) throw error;@@ -393,11 +391,10 @@ export function acceptQuote(quoteId: number): Promise<AcceptResult> {export async function fetchQuotePdf(quoteId: number): Promise<Blob> {const demo = await demoEdgeResponse("get-procurement-quote-pdf", quoteId);if (demo) return await demo.blob();- const supabase = getSupabaseClient();- if (!supabase) throw new Error("No SaaS session");- const { data, error } = await supabase.functions.invoke<Blob>(+ const { data, error } = await invokeSaasFunction<Blob>("get-procurement-quote-pdf",{ body: { quote_id: quoteId } },+ true,);if (error) throw error;if (!data) throw new Error("No PDF returned");diff --git a/frontend/editor/src/portal/auth/accountLinkSession.test.ts b/frontend/editor/src/portal/auth/accountLinkSession.test.tsnew file mode 100644index 0000000000..539cc7a4a5--- /dev/null+++ b/frontend/editor/src/portal/auth/accountLinkSession.test.ts@@ -0,0 +1,77 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+const { clearSupabaseSession, clearQueries } = vi.hoisted(() => ({+ clearSupabaseSession: vi.fn(),+ clearQueries: vi.fn(),+}));+vi.mock("@app/auth/supabase/supabaseClient", () => ({ clearSupabaseSession }));+vi.mock("@app/portal/queryClient", () => ({+ getPortalQueryClient: () => ({ clear: clearQueries }),+}));+import {+ bindAccountLinkSession,+ clearAccountLinkSession,+} from "@app/portal/auth/accountLinkSession";+import {+ readPendingConnect,+ rememberConnect,+} from "@app/portal/auth/pendingConnect";++const pending = {+ ownerId: "owner",+ mode: "reauth" as const,+ returnTo: "/processor/usage",+ browserState: "random-state",+};++describe("local account ownership of the billing session", () => {+ beforeEach(() => {+ localStorage.clear();+ sessionStorage.clear();+ vi.clearAllMocks();+ });++ it("preserves the same owner's redirect through a portal reload", () => {+ bindAccountLinkSession("owner");+ rememberConnect(pending);+ vi.clearAllMocks();+ bindAccountLinkSession("owner");+ expect(readPendingConnect()).toEqual(pending);+ expect(clearSupabaseSession).not.toHaveBeenCalled();+ });++ it("preserves the session for numeric owner IDs returned by Spring", () => {+ const wireUser = JSON.parse('{"id":7,"role":"ROLE_ADMIN"}');+ localStorage.setItem("stirling.portalSaasOwner", "7");+ rememberConnect({ ...pending, ownerId: "7" });+ vi.clearAllMocks();+ bindAccountLinkSession(wireUser.id);+ expect(clearSupabaseSession).not.toHaveBeenCalled();+ expect(readPendingConnect()?.ownerId).toBe("7");+ });++ it("discards credentials, callback intent and query data when the local user changes", () => {+ bindAccountLinkSession("first");+ rememberConnect(pending);+ vi.clearAllMocks();+ bindAccountLinkSession("second");+ expect(readPendingConnect()).toBeNull();+ expect(clearSupabaseSession).toHaveBeenCalledOnce();+ expect(clearQueries).toHaveBeenCalledOnce();+ });++ it("allows a fresh link after unlinking without discarding its callback on reload", () => {+ bindAccountLinkSession("owner");+ clearAccountLinkSession();+ rememberConnect({ ...pending, mode: "link" });+ bindAccountLinkSession("owner");+ expect(readPendingConnect()?.mode).toBe("link");+ });++ it("removes callback ownership when the local user is not an organization owner", () => {+ bindAccountLinkSession("owner");+ rememberConnect(pending);+ bindAccountLinkSession(null);+ expect(localStorage.getItem("stirling.portalSaasOwner")).toBeNull();+ expect(readPendingConnect()).toBeNull();+ });+});diff --git a/frontend/editor/src/portal/auth/accountLinkSession.ts b/frontend/editor/src/portal/auth/accountLinkSession.tsnew file mode 100644index 0000000000..01f1d0a326--- /dev/null+++ b/frontend/editor/src/portal/auth/accountLinkSession.ts@@ -0,0 +1,21 @@+import { clearSupabaseSession } from "@app/auth/supabase/supabaseClient";+import { clearPendingConnect } from "@app/portal/auth/pendingConnect";+import { getPortalQueryClient } from "@app/portal/queryClient";++const OWNER_KEY = "stirling.portalSaasOwner";++/** Local account changes require a new browser authorization, leaving the device link intact. */+export function bindAccountLinkSession(userId: string | number | null): void {+ const ownerId = userId == null ? null : String(userId);+ if (ownerId && localStorage.getItem(OWNER_KEY) === ownerId) return;+ clearAccountLinkSession();+ if (ownerId) localStorage.setItem(OWNER_KEY, ownerId);+ else localStorage.removeItem(OWNER_KEY);+}++/** Clears attended credentials and data without signing out the SaaS origin's shared session. */+export function clearAccountLinkSession(): void {+ clearSupabaseSession();+ clearPendingConnect();+ getPortalQueryClient().clear();+}diff --git a/frontend/editor/src/portal/auth/pendingConnect.test.ts b/frontend/editor/src/portal/auth/pendingConnect.test.tsnew file mode 100644index 0000000000..1379a521d7--- /dev/null+++ b/frontend/editor/src/portal/auth/pendingConnect.test.ts@@ -0,0 +1,59 @@+import { beforeEach, describe, expect, it } from "vitest";+import {+ clearPendingConnect,+ readPendingConnect,+ rememberConnect,+} from "@app/portal/auth/pendingConnect";++const pending = {+ ownerId: "owner",+ mode: "reauth" as const,+ returnTo: "/processor/usage?period=month",+ browserState: "unpredictable-state",+};++describe("renewal return destinations", () => {+ beforeEach(() => sessionStorage.clear());+ it("retains only the portal route and settings intent", () => {+ rememberConnect(pending);+ expect(readPendingConnect()).toEqual(pending);+ clearPendingConnect();+ expect(readPendingConnect()).toBeNull();+ });+ it.each([+ "https://attacker.example/processor",+ "//attacker.example/processor",+ "/processor-fake",+ "/settings-fake",+ "/settings/../login",+ "https://attacker.example/settings/billing",+ "/processor/../login",+ "javascript:alert(1)",+ ])("rejects unsafe destination %s", (returnTo) => {+ rememberConnect({ ...pending, returnTo });+ expect(readPendingConnect()).toBeNull();+ });+ it.each(["/settings/billing?period=month", "/settings/account-link"])(+ "retains settings destination %s",+ (returnTo) => {+ rememberConnect({ ...pending, returnTo });+ expect(readPendingConnect()?.returnTo).toBe(returnTo);+ },+ );+ it("rejects corrupt saved state", () => {+ sessionStorage.setItem("stirling.portalConnect", "{invalid");+ expect(readPendingConnect()).toBeNull();+ });+ it("stores only the allowed handoff fields, even if runtime input contains credentials", () => {+ const runtimeInput = {+ ...pending,+ access_token: "private-access",+ refresh_token: "private-refresh",+ password: "private-password",+ };+ rememberConnect(runtimeInput);+ expect(+ JSON.parse(sessionStorage.getItem("stirling.portalConnect")!),+ ).toEqual(pending);+ });+});diff --git a/frontend/editor/src/portal/auth/pendingConnect.ts b/frontend/editor/src/portal/auth/pendingConnect.tsnew file mode 100644index 0000000000..b3c98d4ece--- /dev/null+++ b/frontend/editor/src/portal/auth/pendingConnect.ts@@ -0,0 +1,59 @@+import { PORTAL_BASENAME } from "@app/routes/portalBasename";++export type ConnectMode = "link" | "reauth";+export interface PendingConnect {+ ownerId: string;+ mode: ConnectMode;+ returnTo: string;+ browserState: string;+}++const KEY = "stirling.portalConnect";++/** Retains tab-local intent across the SaaS redirect; never stores access or refresh tokens. */+export function rememberConnect(pending: PendingConnect): void {+ const { ownerId, mode, returnTo, browserState } = pending;+ sessionStorage.setItem(+ KEY,+ JSON.stringify({ ownerId, mode, returnTo, browserState }),+ );+}++/** Returns a same-origin portal or settings destination in router-relative form. */+export function readPendingConnect(): PendingConnect | null {+ try {+ const value = JSON.parse(sessionStorage.getItem(KEY) ?? "null");+ if (+ !value ||+ (value.mode !== "link" && value.mode !== "reauth") ||+ typeof value.returnTo !== "string" ||+ typeof value.ownerId !== "string" ||+ typeof value.browserState !== "string"+ )+ return null;+ const url = new URL(value.returnTo, window.location.origin);+ if (+ url.origin !== window.location.origin ||+ !(+ url.pathname === PORTAL_BASENAME ||+ url.pathname.startsWith(`${PORTAL_BASENAME}/`) ||+ url.pathname === "/settings" ||+ url.pathname.startsWith("/settings/")+ )+ )+ return null;+ return {+ ownerId: value.ownerId,+ mode: value.mode,+ browserState: value.browserState,+ returnTo: `${url.pathname}${url.search}`,+ };+ } catch {+ return null;+ }+}++/** Cancels local callback acceptance without disconnecting the instance. */+export function clearPendingConnect(): void {+ sessionStorage.removeItem(KEY);+}diff --git a/frontend/editor/src/portal/auth/portalSaasSession.integration.test.ts b/frontend/editor/src/portal/auth/portalSaasSession.integration.test.tsnew file mode 100644index 0000000000..8f8c4ee722--- /dev/null+++ b/frontend/editor/src/portal/auth/portalSaasSession.integration.test.ts@@ -0,0 +1,224 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { createClient } from "@supabase/supabase-js";++vi.mock("@app/portal/auth/saasSupabase", () => ({+ ensureSaasSupabase: vi.fn(),+}));++const key = "sb-renewal-session-auth-token";+const config = {+ url: "https://renewal-session.supabase.co",+ key: "public-key",+ authOptions: { autoRefreshToken: false, detectSessionInUrl: false },+};+const user = {+ id: "00000000-0000-0000-0000-000000000001",+ aud: "authenticated",+ role: "authenticated",+ email: "[email protected]",+};+const jwt = (exp: number) =>+ [+ btoa(JSON.stringify({ alg: "HS256", typ: "JWT" })),+ btoa(JSON.stringify({ exp, sub: user.id })),+ btoa("test-signature"),+ ]+ .map((part) =>+ part.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"),+ )+ .join(".");+const tokenResponse = (exp: number) => ({+ access_token: jwt(exp),+ refresh_token: "rotated-refresh",+ token_type: "bearer",+ expires_in: 3600,+ user,+});+const json = (data: unknown) =>+ new Response(JSON.stringify(data), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });++// Separate SDK clients share storage and exchange messages through a browser channel.+class BrowserChannel extends EventTarget {+ static channels = new Set<BrowserChannel>();+ constructor(readonly name: string) {+ super();+ BrowserChannel.channels.add(this);+ }+ postMessage(data: unknown) {+ for (const other of BrowserChannel.channels) {+ if (other !== this && other.name === this.name) {+ queueMicrotask(() =>+ other.dispatchEvent(new MessageEvent("message", { data })),+ );+ }+ }+ }+ close() {+ BrowserChannel.channels.delete(this);+ }+}++let storage: typeof import("@app/auth/supabase/supabaseClient");+let session: typeof import("@app/portal/auth/portalSaasSession");+let stopClients: (() => Promise<void>)[];+let windowListeners: [string, EventListenerOrEventListenerObject][];++beforeEach(async () => {+ vi.resetModules();+ localStorage.clear();+ stopClients = [];+ windowListeners = [];+ const add = window.addEventListener.bind(window);+ vi.spyOn(window, "addEventListener").mockImplementation(+ (type, listener, options) => {+ windowListeners.push([type, listener]);+ add(type, listener, options);+ },+ );+ vi.stubGlobal("BroadcastChannel", BrowserChannel);+ storage = await import("@app/auth/supabase/supabaseClient");+ session = await import("@app/portal/auth/portalSaasSession");+});++afterEach(async () => {+ storage.clearSupabaseSession();+ await Promise.all(stopClients.map((stop) => stop()));+ for (const [type, listener] of windowListeners)+ window.removeEventListener(type, listener);+ for (const channel of BrowserChannel.channels) channel.close();+ localStorage.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++function persist(exp: number) {+ localStorage.setItem(+ key,+ JSON.stringify({+ ...tokenResponse(exp),+ refresh_token: "old-refresh",+ expires_at: exp,+ }),+ );+}++it("renews an expired persisted session through the real Supabase SDK", async () => {+ const now = Math.floor(Date.now() / 1000);+ persist(now - 60);+ const fetch = vi.fn().mockResolvedValue(json(tokenResponse(now + 3600)));+ vi.stubGlobal("fetch", fetch);+ const client = storage.configureSupabase(config);+ stopClients.push(() => client.auth.stopAutoRefresh());+ await expect(session.getPortalSaasToken()).resolves.toBe(jwt(now + 3600));+ expect(fetch).toHaveBeenCalledOnce();+ expect(String(fetch.mock.calls[0][0])).toContain(+ "/auth/v1/token?grant_type=refresh_token",+ );+ expect(JSON.parse(fetch.mock.calls[0][1].body).refresh_token).toBe(+ "old-refresh",+ );+ expect(JSON.parse(localStorage.getItem(key)!)).toMatchObject({+ refresh_token: "rotated-refresh",+ access_token: jwt(now + 3600),+ });+});++it("clears recovery when another tab renews through the SDK broadcast channel", async () => {+ const now = Math.floor(Date.now() / 1000);+ persist(now + 1800);+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockImplementation(() =>+ Promise.resolve(json(tokenResponse(now + 3600))),+ ),+ );+ const client = storage.configureSupabase(config);+ const otherTab = createClient(config.url, config.key, {+ auth: config.authOptions,+ });+ stopClients.push(+ () => client.auth.stopAutoRefresh(),+ () => otherTab.auth.stopAutoRefresh(),+ );+ await Promise.all([client.auth.getSession(), otherTab.auth.getSession()]);+ await expect(+ session.withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ ),+ ).rejects.toBeInstanceOf(session.SaasSessionRequiredError);+ const revision = session.getPortalSaasSessionState().revision;+ expect(session.getPortalSaasSessionState().required).toBe(true);+ expect((await otherTab.auth.refreshSession()).error).toBeNull();+ await vi.waitFor(() =>+ expect(session.getPortalSaasSessionState()).toEqual({+ required: false,+ revision: revision + 1,+ }),+ );+ const read = vi.fn(async () => 200);+ await session.withPortalSaasSession(read, (status) => status === 401, true);+ expect(read).toHaveBeenCalledWith(jwt(now + 3600));+});++it.each(["same tab", "another tab"])(+ "blocks a late SDK refresh after logout in %s and preserves the next session",+ async (tab) => {+ const now = Math.floor(Date.now() / 1000);+ persist(now + 1800);+ let release!: (response: Response) => void;+ const fetch = vi.fn().mockImplementation((url: string) =>+ url.includes("/token?")+ ? new Promise<Response>((resolve) => {+ release = resolve;+ })+ : Promise.resolve(json(user)),+ );+ vi.stubGlobal("fetch", fetch);+ const oldClient = storage.configureSupabase(config);+ stopClients.push(() => oldClient.auth.stopAutoRefresh());+ await oldClient.auth.getSession();+ let otherStorage = storage;+ if (tab === "another tab") {+ vi.resetModules();+ otherStorage = await import("@app/auth/supabase/supabaseClient");+ const otherClient = otherStorage.configureSupabase(config);+ stopClients.push(() => otherClient.auth.stopAutoRefresh());+ await otherClient.auth.getSession();+ }+ const pending = oldClient.auth.refreshSession();+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());+ otherStorage.clearSupabaseSession();+ expect(localStorage.getItem(key)).toBeNull();+ const currentClient = storage.configureSupabase(config);+ stopClients.push(() => currentClient.auth.stopAutoRefresh());+ expect(+ (+ await currentClient.auth.setSession({+ access_token: jwt(now + 7200),+ refresh_token: "current-refresh",+ })+ ).error,+ ).toBeNull();+ await expect(+ session.withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ ),+ ).rejects.toBeInstanceOf(session.SaasSessionRequiredError);+ const before = session.getPortalSaasSessionState();+ release(json(tokenResponse(now + 3600)));+ await pending;+ expect(JSON.parse(localStorage.getItem(key)!)).toMatchObject({+ access_token: jwt(now + 7200),+ refresh_token: "current-refresh",+ });+ expect(session.getPortalSaasSessionState()).toEqual(before);+ expect(storage.getSupabaseClient()).toBe(currentClient);+ },+);diff --git a/frontend/editor/src/portal/auth/portalSaasSession.test.ts b/frontend/editor/src/portal/auth/portalSaasSession.test.tsindex 1b12358b38..6a622c4317 100644--- a/frontend/editor/src/portal/auth/portalSaasSession.test.ts+++ b/frontend/editor/src/portal/auth/portalSaasSession.test.ts@@ -1,43 +1,271 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import { AuthApiError, AuthRetryableFetchError } from "@supabase/supabase-js";-// Hoisted so the vi.mock factories can reference it before the import runs.-const { state } = vi.hoisted(() => ({- state: { client: null as { auth: { getSession: () => unknown } } | null },+const { getSession, refreshSession, state } = vi.hoisted(() => ({+ state: { configured: true },+ getSession: vi.fn(),+ refreshSession: vi.fn(),}));--vi.mock("@app/auth/supabase/supabaseClient", () => ({- getSupabaseClient: () => state.client,-}));-vi.mock("@portal/auth/saasSupabase", () => ({+vi.mock("@app/portal/auth/saasSupabase", () => ({ensureSaasSupabase: vi.fn(),}));+vi.mock("@app/auth/supabase/supabaseClient", () => ({+ getSupabaseClient: () =>+ state.configured ? { auth: { getSession, refreshSession } } : null,+}));+import {+ getPortalSaasToken,+ getPortalSaasSessionState,+ resetPortalSaasSessionState,+ portalSaasSessionRestored,+ SaasSessionRequiredError,+ withPortalSaasSession,+} from "@app/portal/auth/portalSaasSession";-import { getPortalSaasToken } from "@portal/auth/portalSaasSession";+const session = (token: string | null) => ({+ data: { session: token ? { access_token: token } : null },+ error: null,+});-describe("getPortalSaasToken — self-hosted (account-link login)", () => {+describe("attended SaaS session renewal", () => {beforeEach(() => {- state.client = null;+ vi.resetAllMocks();+ state.configured = true;+ resetPortalSaasSessionState();+ getSession.mockResolvedValue(session("expired"));+ refreshSession.mockResolvedValue(session("renewed"));});- it("returns null when the SaaS client isn't configured (not signed in)", async () => {+ it("returns null when the client is not configured", async () => {+ state.configured = false;expect(await getPortalSaasToken()).toBeNull();});it("returns the access token from the current session", async () => {- state.client = {- auth: {- getSession: async () => ({- data: { session: { access_token: "tok-123" } },- }),- },- };- expect(await getPortalSaasToken()).toBe("tok-123");+ getSession.mockResolvedValue(session("current"));+ expect(await getPortalSaasToken()).toBe("current");});- it("returns null when there is a client but no active session", async () => {- state.client = {- auth: { getSession: async () => ({ data: { session: null } }) },- };+ it("returns null when the client has no session", async () => {+ getSession.mockResolvedValue(session(null));expect(await getPortalSaasToken()).toBeNull();});++ it("clears a previous recovery prompt after a read renews successfully", async () => {+ await expect(+ withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ ),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ expect(getPortalSaasSessionState().required).toBe(true);+ const revision = getPortalSaasSessionState().revision;+ const read = () =>+ withPortalSaasSession(+ async (token) => (token === "renewed" ? 200 : 401),+ (status) => status === 401,+ true,+ );+ expect(await read()).toBe(200);+ expect(getPortalSaasSessionState()).toEqual({+ required: false,+ revision: revision + 1,+ });+ expect(await read()).toBe(200);+ expect(getPortalSaasSessionState().revision).toBe(revision + 1);+ });++ it("clears recovery when an old request fails after the SDK has already renewed", async () => {+ let rejectOld!: (status: number) => void;+ const oldRequest = withPortalSaasSession(+ () =>+ new Promise<number>((resolve) => {+ rejectOld = resolve;+ }),+ (status) => status === 401,+ );+ const failure = expect(oldRequest).rejects.toBeInstanceOf(+ SaasSessionRequiredError,+ );+ await vi.waitFor(() => expect(rejectOld).toBeDefined());+ getSession.mockResolvedValue(session("renewed"));+ window.dispatchEvent(new Event("stirling-saas-session-restored"));+ rejectOld(401);+ await failure;+ expect(getPortalSaasSessionState().required).toBe(true);+ const read = vi.fn(async () => 200);+ await expect(+ withPortalSaasSession(read, (status) => status === 401, true),+ ).resolves.toBe(200);+ expect(read).toHaveBeenCalledWith("renewed");+ expect(refreshSession).not.toHaveBeenCalled();+ expect(getPortalSaasSessionState().required).toBe(false);+ });++ it("does not clear recovery for a server error using the same rejected token", async () => {+ await expect(+ withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ ),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ await expect(+ withPortalSaasSession(+ async () => 500,+ (status) => status === 401,+ true,+ ),+ ).resolves.toBe(500);+ expect(getPortalSaasSessionState().required).toBe(true);+ });++ it("publishes SDK recovery only when a prompt is outstanding", async () => {+ await expect(+ withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ ),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ const revision = getPortalSaasSessionState().revision;+ window.dispatchEvent(new Event("stirling-saas-session-restored"));+ expect(getPortalSaasSessionState()).toEqual({+ required: false,+ revision: revision + 1,+ });+ window.dispatchEvent(new Event("stirling-saas-session-restored"));+ expect(getPortalSaasSessionState().revision).toBe(revision + 1);+ });++ it("keeps a current owner's pending recovery valid when the callback publishes restoration", async () => {+ let resolve!: (value: ReturnType<typeof session>) => void;+ refreshSession.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const request = withPortalSaasSession(+ async (token) => (token === "renewed" ? 200 : 401),+ (status) => status === 401,+ true,+ );+ await vi.waitFor(() => expect(refreshSession).toHaveBeenCalled());+ window.dispatchEvent(new Event("stirling-saas-session-restored"));+ portalSaasSessionRestored();+ resolve(session("renewed"));+ await expect(request).resolves.toBe(200);+ });++ it("coalesces concurrent 401s and retries reads with the renewed token", async () => {+ const send = vi.fn(async (token: string) =>+ token === "renewed" ? 200 : 401,+ );+ const results = await Promise.all(+ Array.from({ length: 5 }, () =>+ withPortalSaasSession(send, (status) => status === 401, true),+ ),+ );+ expect(results).toEqual([200, 200, 200, 200, 200]);+ expect(refreshSession).toHaveBeenCalledTimes(1);+ expect(send).toHaveBeenCalledTimes(10);+ });++ it("uses a token the SDK has already refreshed", async () => {+ getSession+ .mockResolvedValueOnce(session("expired"))+ .mockResolvedValue(session("renewed"));+ const send = vi.fn(async (token: string) =>+ token === "renewed" ? 200 : 401,+ );+ expect(+ await withPortalSaasSession(send, (status) => status === 401, true),+ ).toBe(200);+ expect(refreshSession).not.toHaveBeenCalled();+ });++ it("requires reauthentication after a second 401 and stops retrying", async () => {+ const send = vi.fn(async () => 401);+ await expect(+ withPortalSaasSession(send, (status) => status === 401, true),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ expect(send).toHaveBeenCalledTimes(2);+ expect(getPortalSaasSessionState().required).toBe(true);+ });++ it("never replays purchases after a 401", async () => {+ const send = vi.fn(async () => 401);+ await expect(+ withPortalSaasSession(send, (status) => status === 401),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ expect(send).toHaveBeenCalledTimes(1);+ expect(refreshSession).not.toHaveBeenCalled();+ });++ it.each([403, 500, 429])(+ "does not treat HTTP %i as an expired session",+ async (status) => {+ expect(+ await withPortalSaasSession(+ async () => status,+ (response) => response === 401,+ true,+ ),+ ).toBe(status);+ expect(refreshSession).not.toHaveBeenCalled();+ expect(getPortalSaasSessionState().required).toBe(false);+ },+ );++ it("preserves transient SDK errors instead of requesting a sign-in", async () => {+ const error = new AuthRetryableFetchError("offline", 503);+ getSession.mockResolvedValue({ data: { session: null }, error });+ await expect(getPortalSaasToken()).rejects.toBe(error);+ expect(getPortalSaasSessionState().required).toBe(false);+ });++ it("recognizes a revoked refresh token as requiring reauthentication", async () => {+ refreshSession.mockResolvedValue({+ data: { session: null },+ error: new AuthApiError("revoked", 400, "refresh_token_not_found"),+ });+ await expect(+ withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ true,+ ),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ });++ it("does not retry a transport failure", async () => {+ const send = vi.fn().mockRejectedValue(new TypeError("offline"));+ await expect(+ withPortalSaasSession(send, () => false, true),+ ).rejects.toThrow("offline");+ expect(send).toHaveBeenCalledTimes(1);+ expect(refreshSession).not.toHaveBeenCalled();+ });++ it("discards a refresh that finishes after the local user changed", async () => {+ let resolve!: (value: ReturnType<typeof session>) => void;+ refreshSession.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const send = vi.fn(async () => 401);+ const request = withPortalSaasSession(+ send,+ (status) => status === 401,+ true,+ );+ const rejection = expect(request).rejects.toBeInstanceOf(+ SaasSessionRequiredError,+ );+ await vi.waitFor(() => expect(refreshSession).toHaveBeenCalled());+ resetPortalSaasSessionState();+ resolve(session("previous-owner"));+ await rejection;+ expect(send).toHaveBeenCalledTimes(1);+ expect(getPortalSaasSessionState().required).toBe(false);+ });});diff --git a/frontend/editor/src/portal/auth/portalSaasSession.ts b/frontend/editor/src/portal/auth/portalSaasSession.tsindex 600f75082c..e908370300 100644--- a/frontend/editor/src/portal/auth/portalSaasSession.ts+++ b/frontend/editor/src/portal/auth/portalSaasSession.ts@@ -1,15 +1,148 @@-import { getSupabaseClient } from "@app/auth/supabase/supabaseClient";-import { ensureSaasSupabase } from "@portal/auth/saasSupabase";--/**- * Self-hosted portal→SaaS reads use the account-link session alongside the local- * Spring session. Returns null until that separate SaaS session exists. The- * hosted build overrides this with its existing app session.- */+import { isAuthError, isAuthSessionMissingError } from "@supabase/supabase-js";+import {+ getPortalSessionClient,+ ensurePortalSessionClient,+ handlePortalSessionRequired,+} from "@app/portal/auth/sessionClient";++let refreshPromise: Promise<string | null> | null = null;+let generation = 0;+let rejectedToken: string | null = null;+let snapshot = { required: false, revision: 0 };+const listeners = new Set<() => void>();+window.addEventListener(+ "stirling-saas-session-cleared",+ resetPortalSaasSessionState,+);++window.addEventListener("stirling-saas-session-restored", clearRecoveryPrompt);++function clearRecoveryPrompt(): void {+ if (snapshot.required) update(false);+}++/** Browser authorization can expire while the instance remains linked. */+export class SaasSessionRequiredError extends Error {+ constructor() {+ super("Sign in again to renew access to your Stirling account.");+ this.name = "SaasSessionRequiredError";+ }+}++/** Subscribe to terminal auth failures and successful callback recovery. */+export function subscribePortalSaasSession(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++export function getPortalSaasSessionState() {+ return snapshot;+}++/** Invalidates pending renewal results when the local user or link changes. */+export function resetPortalSaasSessionState(): void {+ generation++;+ refreshPromise = null;+ update(false);+}++/** Reload attended data after the callback validates and installs the session. */+export function portalSaasSessionRestored(): void {+ update(false);+}++function update(required: boolean): void {+ if (!required) rejectedToken = null;+ snapshot = { required, revision: snapshot.revision + 1 };+ listeners.forEach((listener) => listener());+}++function sessionRequired(token: string | null = null): never {+ rejectedToken = token;+ handlePortalSessionRequired();+ if (!snapshot.required) update(true);+ throw new SaasSessionRequiredError();+}++/** Terminal provider failures require a fresh sign-in, not another attempt with the same tokens. */+export function isTerminalSaasAuthError(error: unknown): boolean {+ return (+ isAuthSessionMissingError(error) ||+ (isAuthError(error) &&+ (error.status === 401 ||+ [+ "refresh_token_not_found",+ "refresh_token_already_used",+ "session_not_found",+ "user_not_found",+ "user_banned",+ ].includes(error.code ?? "")))+ );+}++/** SDK getSession renews expired tokens; transient auth failures remain retryable errors. */export async function getPortalSaasToken(): Promise<string | null> {- ensureSaasSupabase();- const supabase = getSupabaseClient();+ ensurePortalSessionClient();+ const supabase = getPortalSessionClient();if (!supabase) return null;- const { data } = await supabase.auth.getSession();- return data.session?.access_token ?? null;+ const started = generation;+ const { data, error } = await supabase.auth.getSession();+ if (!getPortalSessionClient() || started !== generation) return null;+ if (error && !isTerminalSaasAuthError(error)) throw error;+ return error ? null : (data.session?.access_token ?? null);+}++/** Coalesces 401 recovery and reuses a token already renewed by another request. */+export function refreshPortalSaasToken(+ rejectedToken: string,+): Promise<string | null> {+ if (refreshPromise) return refreshPromise;+ const started = generation;+ const pending = (async () => {+ const current = await getPortalSaasToken();+ if (started !== generation) return null;+ if (!current || current !== rejectedToken) return current;+ const supabase = getPortalSessionClient();+ if (!supabase) return null;+ const { data, error } = await supabase.auth.refreshSession();+ if (!getPortalSessionClient() || started !== generation) return null;+ if (error && !isTerminalSaasAuthError(error)) throw error;+ return error ? null : (data.session?.access_token ?? null);+ })();+ refreshPromise = pending;+ void pending+ .finally(() => {+ if (refreshPromise === pending) refreshPromise = null;+ })+ .catch(() => {});+ return pending;+}++/** Only repeat operations explicitly known to be safe to replay; never retry transport failures. */+export async function withPortalSaasSession<T>(+ send: (token: string) => Promise<T>,+ unauthorized: (response: T) => boolean,+ retry: boolean = false,+): Promise<T> {+ const started = generation;+ const token = await getPortalSaasToken();+ if (started !== generation) throw new SaasSessionRequiredError();+ if (!token) return sessionRequired();+ const response = await send(token);+ if (started !== generation) throw new SaasSessionRequiredError();+ if (!unauthorized(response)) {+ if (token !== rejectedToken) clearRecoveryPrompt();+ return response;+ }+ if (!retry) return sessionRequired(token);+ const renewed = await refreshPortalSaasToken(token);+ if (started !== generation) throw new SaasSessionRequiredError();+ if (!renewed) return sessionRequired(token);+ const retried = await send(renewed);+ if (started !== generation) throw new SaasSessionRequiredError();+ if (unauthorized(retried)) return sessionRequired(renewed);+ clearRecoveryPrompt();+ return retried;}diff --git a/frontend/editor/src/portal/auth/saasFunctions.test.ts b/frontend/editor/src/portal/auth/saasFunctions.test.tsnew file mode 100644index 0000000000..73dca15dfe--- /dev/null+++ b/frontend/editor/src/portal/auth/saasFunctions.test.ts@@ -0,0 +1,65 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { FunctionsHttpError } from "@supabase/supabase-js";+const { invoke, getSession, refreshSession } = vi.hoisted(() => ({+ invoke: vi.fn(),+ getSession: vi.fn(),+ refreshSession: vi.fn(),+}));+vi.mock("@app/portal/auth/saasSupabase", () => ({+ ensureSaasSupabase: vi.fn(),+}));+vi.mock("@app/auth/supabase/supabaseClient", () => ({+ getSupabaseClient: () => ({+ auth: { getSession, refreshSession },+ functions: { invoke },+ }),+}));+import { invokeSaasFunction } from "@app/portal/auth/saasFunctions";+import {+ resetPortalSaasSessionState,+ SaasSessionRequiredError,+} from "@app/portal/auth/portalSaasSession";++describe("SaaS edge session recovery", () => {+ beforeEach(() => {+ vi.resetAllMocks();+ resetPortalSaasSessionState();+ getSession.mockResolvedValue({+ data: { session: { access_token: "old" } },+ });+ refreshSession.mockResolvedValue({+ data: { session: { access_token: "renewed" } },+ });+ invoke.mockResolvedValue({+ data: null,+ error: new FunctionsHttpError(new Response(null, { status: 401 })),+ });+ });++ it("retries a quote download with the refreshed bearer", async () => {+ invoke+ .mockResolvedValueOnce({+ data: null,+ error: new FunctionsHttpError(new Response(null, { status: 401 })),+ })+ .mockResolvedValueOnce({ data: "pdf", error: null });+ const result = await invokeSaasFunction(+ "quote-pdf",+ { method: "GET" },+ true,+ );+ expect(result.data).toBe("pdf");+ expect(invoke).toHaveBeenCalledTimes(2);+ expect(invoke.mock.calls[1][1].headers.Authorization).toBe(+ "Bearer renewed",+ );+ });++ it("requires renewal without automatically replaying checkout", async () => {+ await expect(+ invokeSaasFunction("checkout", { body: { seats: 3 } }),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ expect(invoke).toHaveBeenCalledOnce();+ expect(refreshSession).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/portal/auth/saasFunctions.ts b/frontend/editor/src/portal/auth/saasFunctions.tsnew file mode 100644index 0000000000..8e7f672393--- /dev/null+++ b/frontend/editor/src/portal/auth/saasFunctions.ts@@ -0,0 +1,27 @@+import { FunctionsHttpError } from "@supabase/supabase-js";+import {+ getPortalSessionClient,+ ensurePortalSessionClient,+} from "@app/portal/auth/sessionClient";+import { withPortalSaasSession } from "@app/portal/auth/portalSaasSession";++/** Attended edge calls share auth recovery; only explicitly read-only operations may be replayed. */+export async function invokeSaasFunction<T>(+ name: string,+ options: { body?: Record<string, unknown>; method?: "GET" | "POST" } = {},+ readOnly = false,+) {+ ensurePortalSessionClient();+ const supabase = getPortalSessionClient();+ if (!supabase) throw new Error("SaaS authentication is not configured");+ return withPortalSaasSession(+ (token) =>+ supabase.functions.invoke<T>(name, {+ ...options,+ headers: { Authorization: `Bearer ${token}` },+ }),+ ({ error }) =>+ error instanceof FunctionsHttpError && error.context.status === 401,+ readOnly,+ );+}diff --git a/frontend/editor/src/portal/auth/saasSupabase.test.ts b/frontend/editor/src/portal/auth/saasSupabase.test.tsindex b748cdd150..9ccefcaacd 100644--- a/frontend/editor/src/portal/auth/saasSupabase.test.ts+++ b/frontend/editor/src/portal/auth/saasSupabase.test.ts@@ -23,12 +23,13 @@ describe("ensureSaasSupabase — configures the shared client from VITE_SUPABASEvi.stubEnv("VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY", "anon-key");// Dynamic import so the module reads the stubbed env at load.const { ensureSaasSupabase, isSaasSupabaseConfigured } =- await import("@portal/auth/saasSupabase");+ await import("@app/portal/auth/saasSupabase");expect(isSaasSupabaseConfigured).toBe(true);const client = ensureSaasSupabase();expect(configureSupabase).toHaveBeenCalledWith({url: "https://proj.supabase.co",key: "anon-key",+ authOptions: { detectSessionInUrl: false },});expect(client).not.toBeNull();});@@ -37,7 +38,7 @@ describe("ensureSaasSupabase — configures the shared client from VITE_SUPABASEvi.stubEnv("VITE_SUPABASE_URL", "");vi.stubEnv("VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY", "");const { ensureSaasSupabase, isSaasSupabaseConfigured } =- await import("@portal/auth/saasSupabase");+ await import("@app/portal/auth/saasSupabase");expect(isSaasSupabaseConfigured).toBe(false);expect(ensureSaasSupabase()).toBeNull();expect(configureSupabase).not.toHaveBeenCalled();diff --git a/frontend/editor/src/portal/auth/saasSupabase.ts b/frontend/editor/src/portal/auth/saasSupabase.tsindex 45598c369b..21cded699c 100644--- a/frontend/editor/src/portal/auth/saasSupabase.ts+++ b/frontend/editor/src/portal/auth/saasSupabase.ts@@ -3,43 +3,26 @@ import {getSupabaseClient,} from "@app/auth/supabase/supabaseClient";-/**- * Configures the shared Supabase client against the Stirling Supabase project so- * the portal can mint a SaaS JWT IN-APP for account linking (no popup). This is a- * separate, transient SaaS auth — the portal's own session stays Spring (the- * local instance admin); calls to the local backend still carry the Spring- * bearer, and the SaaS JWT is passed only in the link request body.- *- * Config: VITE_SUPABASE_URL + VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY (both public)- * — the one Stirling Supabase project every flavor talks to (same vars the editor- * and proprietary billing client use; there is no separate SaaS project). SaaS- * needs no per-flavor override: the signed-in editor session is on this same- * project, so the client picks it up. Absent → {@link isSaasSupabaseConfigured}- * is false and the link UI degrades to a "configure Supabase" state.- */+// The browser's SaaS billing session is independent of its local Spring login.const url = import.meta.env.VITE_SUPABASE_URL;const key = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY;export const isSaasSupabaseConfigured = Boolean(url && key);-/*- * SAAS_OAUTH_PROVIDERS and PENDING_LINK_KEY are gone. They served an in-portal SSO sign-in that- * could not work: the provider only redirects to allow-listed URLs, so a customer's origin was- * never returned to and the admin was left on stirling.com. Provider choice now happens on our own- * origin during the connect handshake, where the redirect can actually complete.- */-let configured = false;/**- * Configure the shared Supabase client once (idempotent). Returns the client, or- * null when the SaaS Supabase env isn't set. `detectSessionInUrl` (on by default)- * means an SSO redirect back to the portal is picked up here.+ * Returns the shared client, or null when SaaS isn't configured. Callback tokens+ * must be validated by the account-link host before installation, never by URL detection.*/export function ensureSaasSupabase() {if (!isSaasSupabaseConfigured) return null;- if (!configured) {- configureSupabase({ url: url, key: key });+ if (!configured || !getSupabaseClient()) {+ configureSupabase({+ url: url,+ key: key,+ authOptions: { detectSessionInUrl: false },+ });configured = true;}return getSupabaseClient();diff --git a/frontend/editor/src/portal/auth/sessionClient.ts b/frontend/editor/src/portal/auth/sessionClient.tsnew file mode 100644index 0000000000..9b1a9d8312--- /dev/null+++ b/frontend/editor/src/portal/auth/sessionClient.ts@@ -0,0 +1,5 @@+/** The attended billing session is separate from the local Spring login. */+export { getSupabaseClient as getPortalSessionClient } from "@app/auth/supabase/supabaseClient";+export { ensureSaasSupabase as ensurePortalSessionClient } from "@app/portal/auth/saasSupabase";++export function handlePortalSessionRequired(): void {}diff --git a/frontend/editor/src/portal/billing/stripe.test.ts b/frontend/editor/src/portal/billing/stripe.test.tsindex 5b6d97b9f9..0322793101 100644--- a/frontend/editor/src/portal/billing/stripe.test.ts+++ b/frontend/editor/src/portal/billing/stripe.test.ts@@ -11,7 +11,9 @@ const { getClient, invoke, rpc } = vi.hoisted(() => ({rpc: vi.fn(),}));-vi.mock("@portal/auth/saasSupabase", () => ({ ensureSaasSupabase: vi.fn() }));+vi.mock("@app/portal/auth/saasSupabase", () => ({+ ensureSaasSupabase: vi.fn(),+}));vi.mock("@app/auth/supabase/supabaseClient", () => ({getSupabaseClient: () => getClient(),configureSupabase: vi.fn(),@@ -28,14 +30,23 @@ import {getLatestBundleQuote,StripeFunctionError,upsertBundleQuote,-} from "@portal/billing/stripe";+} from "@app/portal/billing/stripe";+import { SaasSessionRequiredError } from "@app/portal/auth/portalSaasSession";const req = { teamId: 1, successUrl: "s", cancelUrl: "c" } as const;beforeEach(() => {invoke.mockReset();rpc.mockReset();- getClient.mockReset().mockReturnValue({ functions: { invoke }, rpc });+ getClient.mockReset().mockReturnValue({+ functions: { invoke },+ rpc,+ auth: {+ getSession: async () => ({+ data: { session: { access_token: "billing-token" } },+ }),+ },+ });});afterEach(() => vi.restoreAllMocks());@@ -216,6 +227,18 @@ describe("upsertBundleQuote", () => {eulaVersion: "2026-07-draft",} as const;+ it("does not replay a quote mutation after a 401", async () => {+ rpc.mockResolvedValue({+ data: null,+ error: { message: "expired" },+ status: 401,+ });+ await expect(upsertBundleQuote(quoteInput)).rejects.toBeInstanceOf(+ SaasSessionRequiredError,+ );+ expect(rpc).toHaveBeenCalledOnce();+ });+it("maps the RPC row and sends p_* args (create — no p_quote_id)", async () => {rpc.mockResolvedValue({data: [@@ -270,6 +293,31 @@ describe("upsertBundleQuote", () => {});});+it("renews once when reading a saved quote returns 401", async () => {+ const refreshSession = vi+ .fn()+ .mockResolvedValue({ data: { session: { access_token: "renewed" } } });+ getClient.mockReturnValue({+ rpc,+ auth: {+ getSession: vi+ .fn()+ .mockResolvedValue({ data: { session: { access_token: "old" } } }),+ refreshSession,+ },+ });+ rpc+ .mockResolvedValueOnce({+ data: null,+ error: { message: "expired" },+ status: 401,+ })+ .mockResolvedValueOnce({ data: [], error: null, status: 200 });+ await expect(getLatestBundleQuote(1)).resolves.toBeNull();+ expect(refreshSession).toHaveBeenCalledOnce();+ expect(rpc).toHaveBeenCalledTimes(2);+});+describe("finalizeBundleInvoice", () => {it("maps the invoice response and sends quote_id (+ optional po_number)", async () => {invoke.mockResolvedValue({diff --git a/frontend/editor/src/portal/billing/stripe.ts b/frontend/editor/src/portal/billing/stripe.tsindex 9efcc9b0a1..598db229d9 100644--- a/frontend/editor/src/portal/billing/stripe.ts+++ b/frontend/editor/src/portal/billing/stripe.ts@@ -1,6 +1,10 @@import type { Stripe } from "@stripe/stripe-js";-import { getSupabaseClient } from "@app/auth/supabase/supabaseClient";-import { ensureSaasSupabase } from "@portal/auth/saasSupabase";+import {+ getPortalSessionClient,+ ensurePortalSessionClient,+} from "@app/portal/auth/sessionClient";+import { invokeSaasFunction } from "@app/portal/auth/saasFunctions";+import { withPortalSaasSession } from "@app/portal/auth/portalSaasSession";/*** Stripe checkout + portal sessions, minted via the SaaS Supabase edge@@ -67,15 +71,15 @@ async function invoke<T>(name: string,body: Record<string, unknown>,): Promise<T> {- ensureSaasSupabase();- const supabase = getSupabaseClient();+ ensurePortalSessionClient();+ const supabase = getPortalSessionClient();if (!supabase) {throw new StripeFunctionError("SaaS Supabase not configured — set VITE_SUPABASE_URL.","unconfigured",);}- const { data, error } = await supabase.functions.invoke<T>(name, { body });+ const { data, error } = await invokeSaasFunction<T>(name, { body });if (error) {throw new StripeFunctionError(error.message ?? `Edge function ${name} failed`,@@ -88,16 +92,24 @@ async function invoke<T>(}/** Call a SECURITY DEFINER public.* RPC with the admin's JWT (same client as {@link invoke}). */-async function rpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {- ensureSaasSupabase();- const supabase = getSupabaseClient();+async function rpc<T>(+ fn: string,+ args: Record<string, unknown>,+ readOnly = false,+): Promise<T> {+ ensurePortalSessionClient();+ const supabase = getPortalSessionClient();if (!supabase) {throw new StripeFunctionError("SaaS Supabase not configured — set VITE_SUPABASE_URL.","unconfigured",);}- const { data, error } = await supabase.rpc(fn, args);+ const { data, error } = await withPortalSaasSession(+ () => Promise.resolve(supabase.rpc(fn, args)),+ (response) => response.status === 401,+ readOnly,+ );if (error) {throw new StripeFunctionError(error.message ?? `RPC ${fn} failed`,@@ -224,6 +236,7 @@ export async function getLatestBundleQuote(const rows = await rpc<LatestBundleQuoteRow[]>("payg_get_latest_bundle_quote",{ p_team_id: teamId },+ true,);const row = rows?.[0];if (!row) return null;@@ -462,17 +475,18 @@ export async function cancelBundleQuote(req: {* GET route (streams application/pdf). Returns a Blob the caller can object-URL for download.*/export async function fetchBundleQuotePdf(quoteId: number): Promise<Blob> {- ensureSaasSupabase();- const supabase = getSupabaseClient();+ ensurePortalSessionClient();+ const supabase = getPortalSessionClient();if (!supabase) {throw new StripeFunctionError("SaaS Supabase not configured — set VITE_SUPABASE_URL.","unconfigured",);}- const { data, error } = await supabase.functions.invoke<Blob>(+ const { data, error } = await invokeSaasFunction<Blob>(`create-payg-bundle-quote?quote_id=${quoteId}`,{ method: "GET" },+ true,);if (error) {throw new StripeFunctionError(error.message ?? "quote PDF fetch failed");diff --git a/frontend/editor/src/portal/components/ConnectAccountRail.css b/frontend/editor/src/portal/components/ConnectAccountRail.cssdeleted file mode 100644index 9f4ad4a77e..0000000000--- a/frontend/editor/src/portal/components/ConnectAccountRail.css+++ /dev/null@@ -1,53 +0,0 @@-/* ──────────────────────────────────────────────────────────────────────── */-/* Connect rail — the ambient prompt above Home's deployment card */-/* ──────────────────────────────────────────────────────────────────────── */--/* Flat and quiet: it sits above the hero every visit until the account is- connected, so it has to be legible without competing with the card below it. */--.portal-connect-rail {- display: flex;- align-items: center;- gap: 1rem;- padding: 0.875rem 1rem;- margin-bottom: 0.75rem;- border: 1px solid var(--c-border);- border-radius: 0.5rem;- background: var(--c-surface);-}--.portal-connect-rail__text {- display: flex;- flex-direction: column;- min-width: 0;-}--.portal-connect-rail__title {- font-size: 0.875rem;- font-weight: 600;- color: var(--c-text);-}--.portal-connect-rail__sub {- font-size: 0.8125rem;- color: var(--c-text-muted);-}--.portal-connect-rail__actions {- display: flex;- align-items: center;- gap: 0.5rem;- margin-left: auto;- flex: none;-}--@media (max-width: 40rem) {- .portal-connect-rail {- flex-direction: column;- align-items: flex-start;- }-- .portal-connect-rail__actions {- margin-left: 0;- }-}diff --git a/frontend/editor/src/portal/components/ConnectAccountRail.stories.tsx b/frontend/editor/src/portal/components/ConnectAccountRail.stories.tsxdeleted file mode 100644index c813db9b3c..0000000000--- a/frontend/editor/src/portal/components/ConnectAccountRail.stories.tsx+++ /dev/null@@ -1,46 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse } from "msw";-import { LinkProvider, type LinkState } from "@portal/contexts/LinkContext";-import { ConnectAccountRail } from "@portal/components/ConnectAccountRail";--/**- * Both halves of "can link but has not" come from outside the component, and the global mock answers- * app-config without the flag — so a story that wants the rail has to ask for it.- */-const canLink = {- msw: {- handlers: [- http.get("/api/v1/config/app-config", () =>- HttpResponse.json({ accountLinkAvailable: true }),- ),- ],- },-};--const withLinkState = (state: LinkState) => [- (Story: () => React.JSX.Element) => (- <LinkProvider initialState={state}>- <Story />- </LinkProvider>- ),-];--const meta: Meta<typeof ConnectAccountRail> = {- title: "Portal/AccountLink/ConnectAccountRail",- component: ConnectAccountRail,- parameters: { layout: "padded" },-};-export default meta;-type Story = StoryObj<typeof ConnectAccountRail>;--/** On Home: the ask, plus a way to defer it for this session. */-export const Default: Story = {- parameters: canLink,- decorators: withLinkState("unlinked"),-};--/** Connected, so the rail removes itself. Renders nothing on purpose. */-export const Hidden: Story = {- parameters: canLink,- decorators: withLinkState("linked-free"),-};diff --git a/frontend/editor/src/portal/components/ConnectAccountRail.tsx b/frontend/editor/src/portal/components/ConnectAccountRail.tsxdeleted file mode 100644index 82c8048aa0..0000000000--- a/frontend/editor/src/portal/components/ConnectAccountRail.tsx+++ /dev/null@@ -1,57 +0,0 @@-import { useState } from "react";-import { useTranslation } from "react-i18next";-import { Button } from "@app/ui";-import { useConnectGate } from "@portal/hooks/useConnectGate";-import "@portal/components/ConnectAccountRail.css";--const DISMISSED_KEY = "portal::connect-rail-dismissed";--function readDismissed(): boolean {- try {- return sessionStorage.getItem(DISMISSED_KEY) === "true";- } catch {- return false;- }-}--/** Session-scoped dismissal, so the ask comes back until it is answered rather than for good. */-export function ConnectAccountRail() {- const { t } = useTranslation();- const { gated, loading, connect } = useConnectGate();- const [dismissed, setDismissed] = useState(readDismissed);-- if (loading || !gated || dismissed) return null;-- const dismiss = () => {- try {- sessionStorage.setItem(DISMISSED_KEY, "true");- } catch {- // Storage refusing is no reason to leave the rail stuck on screen.- }- setDismissed(true);- };-- return (- <section className="portal-connect-rail">- <div className="portal-connect-rail__text">- <b className="portal-connect-rail__title">- {t("portal.accountLink.rail.title", "Connect your Stirling account")}- </b>- <span className="portal-connect-rail__sub">- {t(- "portal.accountLink.rail.sub",- "Adds monthly credits and room for more users. Everything on this server already works without one.",- )}- </span>- </div>- <div className="portal-connect-rail__actions">- <Button variant="quiet" accent="neutral" onClick={dismiss}>- {t("portal.accountLink.rail.later", "Not now")}- </Button>- <Button variant="primary" onClick={connect}>- {t("portal.accountLink.rail.cta", "Connect")}- </Button>- </div>- </section>- );-}diff --git a/frontend/editor/src/portal/components/HomeHero.tsx b/frontend/editor/src/portal/components/HomeHero.tsxindex 6a507a25c1..bd6510593b 100644--- a/frontend/editor/src/portal/components/HomeHero.tsx+++ b/frontend/editor/src/portal/components/HomeHero.tsx@@ -1,11 +1,5 @@-import { EditorStatusCard } from "@portal/components/EditorStatusCard";-import { ConnectAccountRail } from "@portal/components/ConnectAccountRail";+import { EditorStatusCard } from "@app/portal/components/EditorStatusCard";export function HomeHero() {- return (- <>- <ConnectAccountRail />- <EditorStatusCard />- </>- );+ return <EditorStatusCard />;}diff --git a/frontend/editor/src/portal/components/LinkAccountEntryPoints.test.tsx b/frontend/editor/src/portal/components/LinkAccountEntryPoints.test.tsxnew file mode 100644index 0000000000..b7b7e1b357--- /dev/null+++ b/frontend/editor/src/portal/components/LinkAccountEntryPoints.test.tsx@@ -0,0 +1,58 @@+import { beforeEach, expect, it, vi } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { LinkProvider } from "@app/portal/contexts/LinkContext";+import { UIProvider, useUI } from "@app/portal/contexts/UIContext";+import { LinkAccountFooterItem } from "@app/portal/components/LinkAccountFooterItem";+const flags = vi.hoisted(() => ({ isAdmin: true, orgOwner: true }));+vi.mock("@app/auth", () => ({+ useAuth: () => ({ ...flags, user: { orgOwner: flags.orgOwner } }),+}));+vi.mock("@app/portal/hooks/useConnectGate", () => ({+ useConnectGate: () => ({ gated: true, loading: false, connect: vi.fn() }),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));+let ui: ReturnType<typeof useUI>;+function Entries() {+ ui = useUI();+ return <LinkAccountFooterItem />;+}+function show() {+ render(+ <MantineProvider>+ <LinkProvider initialState="unlinked">+ <UIProvider>+ <Entries />+ </UIProvider>+ </LinkProvider>+ </MantineProvider>,+ );+}+beforeEach(() => {+ flags.isAdmin = true;+ flags.orgOwner = true;+ sessionStorage.clear();+});+it("offers the sidebar connection action to the owner", () => {+ show();+ expect(+ screen.getByRole("button", { name: "Link Stirling account" }),+ ).toBeVisible();+ fireEvent.click(+ screen.getByRole("button", { name: "Link Stirling account" }),+ );+ expect(ui.linkModalOpen).toBe(true);+});+it("does not offer owner-only connection actions to other processor users", () => {+ flags.isAdmin = false;+ show();+ expect(screen.queryByRole("button")).toBeNull();+});++it("hides the sidebar connection action from ordinary admins", () => {+ flags.orgOwner = false;+ show();+ expect(screen.queryByRole("button")).toBeNull();+});diff --git a/frontend/editor/src/portal/components/LinkAccountFooterItem.tsx b/frontend/editor/src/portal/components/LinkAccountFooterItem.tsxindex 0f3d712daf..1f08c0a293 100644--- a/frontend/editor/src/portal/components/LinkAccountFooterItem.tsx+++ b/frontend/editor/src/portal/components/LinkAccountFooterItem.tsx@@ -1,8 +1,9 @@+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";import { useTranslation } from "react-i18next";import { NavItem } from "@app/ui";-import { useUI } from "@portal/contexts/UIContext";-import { useLink } from "@portal/contexts/LinkContext";-import { LinkIcon } from "@portal/components/icons";+import { useUI } from "@app/portal/contexts/UIContext";+import { useLink } from "@app/portal/contexts/LinkContext";+import { LinkIcon } from "@app/portal/components/icons";/*** Sidebar-footer link-account CTA. Only visible when the org is unlinked — once@@ -12,10 +13,11 @@ import { LinkIcon } from "@portal/components/icons";* IS the SaaS account, so there is nothing to link.*/export function LinkAccountFooterItem() {+ const isOwner = useAccountLinkOwner();const { t } = useTranslation();const { openLinkModal } = useUI();const { linkState, statusKnown } = useLink();- if (!statusKnown || linkState !== "unlinked") return null;+ if (!isOwner || !statusKnown || linkState !== "unlinked") return null;return (<NavItemid="account-link"diff --git a/frontend/editor/src/portal/components/PortalChrome.tsx b/frontend/editor/src/portal/components/PortalChrome.tsxindex 3350623525..9adc3bc4c4 100644--- a/frontend/editor/src/portal/components/PortalChrome.tsx+++ b/frontend/editor/src/portal/components/PortalChrome.tsx@@ -1,10 +1,10 @@-import { AccountConnectionNotice } from "@portal/components/account-link/AccountConnectionNotice";+import { AccountConnectionRefresh } from "@app/portal/components/account-link/AccountConnectionNotice";import { useLocation } from "react-router-dom";import { AppConfigProvider } from "@app/contexts/AppConfigContext";import { ToolRegistryProvider } from "@app/contexts/ToolRegistryProvider";-import { ErrorBoundary } from "@portal/components/ErrorBoundary";-import { AppShell } from "@portal/components/AppShell";-import { ViewRouter } from "@portal/ViewRouter";+import { ErrorBoundary } from "@app/portal/components/ErrorBoundary";+import { AppShell } from "@app/portal/components/AppShell";+import { ViewRouter } from "@app/portal/ViewRouter";/*** The routed view, wrapped in an error boundary so a single view crashing can't@@ -28,15 +28,14 @@ function RoutedContent() {* PortalProviders, not here.*/export function PortalChrome() {- const { pathname } = useLocation();return (// One app-config instance for every portal consumer (the search gates, the// sidebar) so they can't fetch twice or disagree.<AppConfigProvider bootstrapMode="non-blocking">{/* The pipeline builder reads the tool registry to list and configure operations. */}<ToolRegistryProvider>+ <AccountConnectionRefresh /><AppShell>- {!pathname.endsWith("/account-link") && <AccountConnectionNotice />}<RoutedContent /></AppShell></ToolRegistryProvider>diff --git a/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.test.tsx b/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.test.tsxindex 0dcfc20c52..3d75debb83 100644--- a/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.test.tsx+++ b/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.test.tsx@@ -1,6 +1,9 @@import { render, screen, fireEvent, waitFor } from "@testing-library/react";-import { describe, it, expect, vi } from "vitest";-import { AccountConnectionNotice } from "@portal/components/account-link/AccountConnectionNotice";+import { beforeEach, describe, it, expect, vi } from "vitest";+import {+ AccountConnectionNotice,+ AccountConnectionRefresh,+} from "@app/portal/components/account-link/AccountConnectionNotice";const mocks = vi.hoisted(() => ({link: {@@ -13,10 +16,22 @@ const mocks = vi.hoisted(() => ({refresh: vi.fn().mockResolvedValue(undefined),},refetch: vi.fn(),+ isOwner: true,+ required: false,+ linkModalOpen: false,}));-vi.mock("@portal/contexts/AccountLinkContext", () => ({+vi.mock("@app/portal/contexts/AccountLinkContext", () => ({useAccountLinkOptional: () => mocks.link,}));+vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({+ useAccountLinkOwner: () => mocks.isOwner,+}));+vi.mock("@app/portal/hooks/usePortalSaasSession", () => ({+ usePortalSaasSession: () => ({ required: mocks.required }),+}));+vi.mock("@app/portal/contexts/UIContext", () => ({+ useUI: () => ({ linkModalOpen: mocks.linkModalOpen }),+}));vi.mock("@app/contexts/AppConfigContext", () => ({useAppConfig: () => ({ refetch: mocks.refetch }),}));@@ -44,6 +59,14 @@ vi.mock("@app/ui", () => ({),}));+beforeEach(() => {+ vi.clearAllMocks();+ mocks.isOwner = true;+ mocks.required = false;+ mocks.linkModalOpen = false;+ mocks.link.status.connection.state = "expired";+});+describe("offline account notice", () => {it("explains paused features, retries and removes the warning on recovery", async () => {mocks.link.status.connection.state = "expired";@@ -56,7 +79,7 @@ describe("offline account notice", () => {mocks.link.status.connection.state = "connected";view.rerender(<AccountConnectionNotice />);expect(screen.queryByRole("alert")).toBeNull();- expect(mocks.refetch).toHaveBeenCalled();+ expect(mocks.refetch).not.toHaveBeenCalled();});it("warns before the deadline without claiming features are paused", () => {mocks.link.status.connection.state = "offline";@@ -69,3 +92,30 @@ describe("offline account notice", () => {);});});++it.each(["isOwner", "required", "linkModalOpen"] as const)(+ "hides the connection notice when %s prevents a competing owner action",+ (flag) => {+ mocks[flag] = flag !== "isOwner";+ render(<AccountConnectionNotice />);+ expect(screen.queryByRole("alert")).toBeNull();+ },+);++it("refreshes feature availability on local pages without rendering a notice", () => {+ const updated = vi.fn();+ window.addEventListener("stirling:billing-updated", updated);+ try {+ const view = render(<AccountConnectionRefresh />);+ expect(view.container).toBeEmptyDOMElement();+ mocks.link.status.connection.state = "connected";+ view.rerender(<AccountConnectionRefresh />);+ expect(view.container).toBeEmptyDOMElement();+ expect(mocks.refetch).toHaveBeenCalledOnce();+ expect(updated).toHaveBeenCalledOnce();+ view.rerender(<AccountConnectionRefresh />);+ expect(updated).toHaveBeenCalledOnce();+ } finally {+ window.removeEventListener("stirling:billing-updated", updated);+ }+});diff --git a/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.tsx b/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.tsxindex c9a58dbcc3..f41684b11f 100644--- a/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.tsx+++ b/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.tsx@@ -2,16 +2,18 @@ import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { Banner, Button } from "@app/ui";import { useAppConfig } from "@app/contexts/AppConfigContext";-import { useAccountLinkOptional } from "@portal/contexts/AccountLinkContext";+import { useAccountLinkOptional } from "@app/portal/contexts/AccountLinkContext";-/** Shows the server's cloud-access deadline and refreshes feature visibility when it changes. */-export function AccountConnectionNotice() {- const { t } = useTranslation();+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import { usePortalSaasSession } from "@app/portal/hooks/usePortalSaasSession";+import { useUI } from "@app/portal/contexts/UIContext";++/** Keep feature availability current without placing a notice on local pages. */+export function AccountConnectionRefresh() {const link = useAccountLinkOptional();const { refetch } = useAppConfig();const state = link?.status?.connection?.state;const previous = useRef(state);- const [checking, setChecking] = useState(false);useEffect(() => {if (previous.current && previous.current !== state) {void refetch();@@ -19,14 +21,34 @@ export function AccountConnectionNotice() {}previous.current = state;}, [state, refetch]);- if (!link || !state || state === "connected" || state === "unlinked")+ return null;+}++/** Contextual server-connection status for the owner's account and billing pages. */+export function AccountConnectionNotice() {+ const { t } = useTranslation();+ const link = useAccountLinkOptional();+ const isOwner = useAccountLinkOwner();+ const { required } = usePortalSaasSession();+ const { linkModalOpen } = useUI();+ const [checking, setChecking] = useState(false);+ const state = link?.status?.connection?.state;+ if (+ !isOwner ||+ required ||+ linkModalOpen ||+ !link ||+ !state ||+ state === "connected" ||+ state === "unlinked"+ )return null;const expired = state === "expired";const revoked = state === "revoked";const deadline = link.status?.connection?.offlineAccessUntil;return (<Banner- tone={expired || revoked ? "danger" : "warning"}+ tone={expired || revoked ? "danger" : "neutral"}title={expired? t(diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsxindex 4843222a8b..5f87ca06f3 100644--- a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx+++ b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx@@ -8,7 +8,7 @@ import {within,} from "@testing-library/react";import { MantineProvider } from "@mantine/core";-import type { UseAccountLink } from "@portal/hooks/useAccountLink";+import type { UseAccountLink } from "@app/portal/hooks/useAccountLink";const state = vi.hoisted(() => ({fetchInstances: vi.fn(),@@ -19,11 +19,18 @@ const state = vi.hoisted(() => ({status: { linked: true, name: "Production" } as UseAccountLink["status"],statusError: null as string | null,email: "[email protected]" as string | null,+ isOwner: true,}));-vi.mock("@portal/hooks/useLinkedAccountEmail", () => ({+vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({+ useAccountLinkOwner: () => state.isOwner,+}));+vi.mock("@app/portal/contexts/LinkContext", () => ({+ useLink: () => ({ isLinked: state.status?.linked ?? false }),+}));+vi.mock("@app/portal/hooks/useLinkedAccountEmail", () => ({useLinkedAccountEmail: () => state.email,}));-vi.mock("@portal/contexts/AccountLinkContext", () => ({+vi.mock("@app/portal/contexts/AccountLinkContext", () => ({useAccountLinkOptional: () => null,useAccountLinkContext: () => ({loginConfigured: true,@@ -35,10 +42,10 @@ vi.mock("@portal/contexts/AccountLinkContext", () => ({refresh: state.refresh,}),}));-vi.mock("@portal/contexts/UIContext", () => ({+vi.mock("@app/portal/contexts/UIContext", () => ({useUI: () => ({ openLinkModal: state.openLinkModal }),}));-vi.mock("@portal/api/link", () => ({+vi.mock("@app/portal/api/link", () => ({fetchInstances: state.fetchInstances,revokeInstance: state.revokeInstance,}));@@ -52,7 +59,8 @@ vi.mock("react-i18next", () => ({}),}));-import { AccountLinkPanel } from "@portal/components/account-link/AccountLinkPanel";+import { SaasSessionRequiredError } from "@app/portal/auth/portalSaasSession";+import { AccountLinkPanel } from "@app/portal/components/account-link/AccountLinkPanel";const instance = {instanceId: 42,@@ -80,6 +88,7 @@ describe("Self-hosted account connection", () => {state.unlink.mockReset();state.status = { linked: true, name: "Production" };state.statusError = null;+ state.isOwner = true;state.email = "[email protected]";});@@ -272,4 +281,26 @@ describe("Self-hosted account connection", () => {screen.queryByRole("button", { name: "Connect your Stirling account" }),).not.toBeInTheDocument();});++ it("leaves session recovery to the shell instead of offering an ineffective data retry", async () => {+ state.status = { linked: true, name: "Production" };+ state.fetchInstances.mockRejectedValue(new SaasSessionRequiredError());+ mount();+ expect(+ await screen.findByText(+ "Connected instances will appear after you renew billing access.",+ ),+ ).toBeVisible();+ expect(screen.queryByRole("button", { name: "Try again" })).toBeNull();+ expect(screen.queryByText("Couldn’t load connected instances")).toBeNull();+ });+});++it("does not mount account management or fetch team instances for a non-owner", () => {+ state.isOwner = false;+ state.fetchInstances.mockClear();+ mount();+ expect(screen.queryByText("Account connection")).toBeNull();+ expect(screen.queryByRole("button")).toBeNull();+ expect(state.fetchInstances).not.toHaveBeenCalled();});diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsxindex 0fe8182255..2a7bcec0cc 100644--- a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx+++ b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx@@ -1,24 +1,34 @@-import { AccountConnectionNotice } from "@portal/components/account-link/AccountConnectionNotice";+import { AccountConnectionNotice } from "@app/portal/components/account-link/AccountConnectionNotice";import { useCallback, useState } from "react";+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import { SaasSessionBanner } from "@app/portal/components/account-link/SaasSessionBanner";import { useTranslation } from "react-i18next";import { Banner, Button, InfoTooltip, Skeleton } from "@app/ui";import { Icon } from "@app/ui/Icon";import { AccountConnectionLayout } from "@app/components/settings/AccountConnectionLayout";-import { useAsync } from "@portal/hooks/useAsync";-import { useAccountLinkContext } from "@portal/contexts/AccountLinkContext";-import { HttpError } from "@portal/api/http";+import { useAsync } from "@app/portal/hooks/useAsync";+import { useAccountLinkContext } from "@app/portal/contexts/AccountLinkContext";+import { SaasSessionRequiredError } from "@app/portal/auth/portalSaasSession";+import { HttpError } from "@app/portal/api/http";+import { usePortalSaasSession } from "@app/portal/hooks/usePortalSaasSession";import {fetchInstances,revokeInstance as apiRevokeInstance,type LinkedInstanceRow,-} from "@portal/api/link";-import { LinkAccountCard } from "@portal/components/account-link/LinkAccountCard";-import { LinkedInstancesTable } from "@portal/components/account-link/LinkedInstancesTable";-import "@portal/views/AccountLink.css";+} from "@app/portal/api/link";+import { LinkAccountCard } from "@app/portal/components/account-link/LinkAccountCard";+import { LinkedInstancesTable } from "@app/portal/components/account-link/LinkedInstancesTable";+import "@app/portal/views/AccountLink.css";/** Self-hosted connection status plus the owning team's connected instances. */export function AccountLinkPanel() {+ const isOwner = useAccountLinkOwner();+ return isOwner ? <OwnerAccountLinkPanel /> : null;+}++function OwnerAccountLinkPanel() {const { t } = useTranslation();+ const { revision: sessionRevision } = usePortalSaasSession();const link = useAccountLinkContext();const linked = link.status?.linked ?? false;@@ -29,7 +39,7 @@ export function AccountLinkPanel() {// (so showing the team's other instances would be confusing).const instancesState = useAsync<LinkedInstanceRow[]>(() => (linked ? fetchInstances() : Promise.resolve([])),- [reloadKey, linked],+ [reloadKey, linked, sessionRevision],);const [revokingId, setRevokingId] = useState<number | null>(null);@@ -87,6 +97,7 @@ export function AccountLinkPanel() {)}>+ <SaasSessionBanner /><AccountConnectionNotice /><LinkAccountCard link={link} instanceName={currentInstance?.name} />@@ -118,6 +129,13 @@ export function AccountLinkPanel() {<Skeleton key={i} height="3rem" />))}</div>+ ) : instancesState.error instanceof SaasSessionRequiredError ? (+ <p>+ {t(+ "portal.accountLink.panel.sessionRequired",+ "Connected instances will appear after you renew billing access.",+ )}+ </p>) : instancesState.error ? (<Bannertone="danger"diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkSessionBoundary.test.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkSessionBoundary.test.tsxnew file mode 100644index 0000000000..0b5ef85000--- /dev/null+++ b/frontend/editor/src/portal/components/account-link/AccountLinkSessionBoundary.test.tsx@@ -0,0 +1,164 @@+import { StrictMode } from "react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import type { SupabaseClient } from "@supabase/supabase-js";+import { AuthContext } from "@app/auth/context";+import type { AuthContextValue, AuthUser } from "@app/auth/types";+import {+ configureSupabase,+ clearSupabaseSession,+} from "@app/auth/supabase/supabaseClient";+import { getPortalQueryClient } from "@app/portal/queryClient";+import { AccountLinkSessionBoundary } from "@app/portal/components/account-link/AccountLinkSessionBoundary";++const storageKey = "sb-boundary-reload-auth-token";+const ownerKey = "stirling.portalSaasOwner";+const generationKey = "stirling.saasSessionGeneration";+const savedGeneration = "persisted-generation";+const user: AuthUser = {+ id: "7",+ email: "[email protected]",+ username: "owner",+ role: "ROLE_ADMIN",+ orgOwner: true,+};+const pending: AuthContextValue = {+ user: null,+ session: null,+ displayName: null,+ isAnonymous: false,+ isAdmin: false,+ portalAccess: false,+ role: null,+ loading: true,+ error: null,+ signOut: async () => {},+ refreshSession: async () => {},+};+const owner: AuthContextValue = {+ ...pending,+ user,+ session: { user, access_token: "local-token", expires_in: 3600 },+ loading: false,+ isAdmin: true,+ portalAccess: true,+ role: user.role,+};+const clients: SupabaseClient[] = [];+let persisted: string;++function sessionClient() {+ const client = configureSupabase({+ url: "https://boundary-reload.supabase.co",+ key: "public-test-key",+ authOptions: { autoRefreshToken: false, detectSessionInUrl: false },+ });+ clients.push(client);+ return client;+}++function tree(auth: AuthContextValue) {+ return (+ <StrictMode>+ <AuthContext.Provider value={auth}>+ <AccountLinkSessionBoundary>+ <span>Attended data</span>+ </AccountLinkSessionBoundary>+ </AuthContext.Provider>+ </StrictMode>+ );+}++beforeEach(() => {+ clearSupabaseSession();+ localStorage.clear();+ localStorage.setItem(ownerKey, user.id);+ localStorage.setItem(generationKey, savedGeneration);+ persisted = JSON.stringify({+ access_token: "persisted-access-token",+ refresh_token: "persisted-refresh-token",+ expires_at: Math.floor(Date.now() / 1000) + 3600,+ user: { id: "saas-owner" },+ stirlingSessionGeneration: savedGeneration,+ });+ localStorage.setItem(storageKey, persisted);+ vi.stubGlobal(+ "fetch",+ vi.fn(() => {+ throw new Error("Unexpected network request");+ }),+ );+});++afterEach(async () => {+ cleanup();+ clearSupabaseSession();+ await Promise.all(+ clients.splice(0).map((client) => client.auth.stopAutoRefresh()),+ );+ getPortalQueryClient().clear();+ localStorage.clear();+ vi.unstubAllGlobals();+});++it.each([false, true])(+ "preserves the owner's persisted session on reload (auth loading: %s)",+ async (loading) => {+ const view = render(tree(loading ? pending : owner));+ if (loading) expect(screen.queryByText("Attended data")).toBeNull();+ expect(localStorage.getItem(storageKey)).toBe(persisted);+ expect(localStorage.getItem(generationKey)).toBe(savedGeneration);+ view.rerender(tree(owner));+ expect(screen.getByText("Attended data")).toBeInTheDocument();+ expect(localStorage.getItem(ownerKey)).toBe(user.id);+ expect(+ (await sessionClient().auth.getSession()).data.session?.access_token,+ ).toBe("persisted-access-token");+ },+);++it("hides attended content during an identity recheck without discarding the session", async () => {+ const client = sessionClient();+ await client.auth.getSession();+ const view = render(tree(owner));+ view.rerender(tree({ ...owner, loading: true }));+ expect(screen.queryByText("Attended data")).toBeNull();+ expect(localStorage.getItem(generationKey)).toBe(savedGeneration);+ view.rerender(tree(owner));+ expect(screen.getByText("Attended data")).toBeInTheDocument();+ expect((await client.auth.getSession()).data.session?.access_token).toBe(+ "persisted-access-token",+ );+});++it.each([+ ["signed out", { ...pending, loading: false }],+ ["another owner", { ...owner, user: { ...user, id: "8" } }],+ ["non-owner", { ...owner, isAdmin: false }],+ [+ "admin after ownership transfer",+ { ...owner, user: { ...user, orgOwner: false } },+ ],+ [+ "admin without ownership information",+ { ...owner, user: { ...user, orgOwner: undefined } },+ ],+] as const)(+ "clears credentials and cached data when authentication resolves to %s",+ async (_label, auth) => {+ await sessionClient().auth.getSession();+ getPortalQueryClient().setQueryData(+ ["private-billing"],+ "previous-owner-data",+ );+ const view = render(tree(pending));+ expect(localStorage.getItem(generationKey)).toBe(savedGeneration);+ view.rerender(tree(auth));+ expect(localStorage.getItem(storageKey)).toBeNull();+ expect(localStorage.getItem(generationKey)).not.toBe(savedGeneration);+ expect(+ getPortalQueryClient().getQueryData(["private-billing"]),+ ).toBeUndefined();+ expect((await sessionClient().auth.getSession()).data.session).toBeNull();+ },+);diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkSessionBoundary.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkSessionBoundary.tsxnew file mode 100644index 0000000000..5cb1c16a24--- /dev/null+++ b/frontend/editor/src/portal/components/account-link/AccountLinkSessionBoundary.tsx@@ -0,0 +1,21 @@+import { useEffect, useState, type ReactNode } from "react";+import { useAuth } from "@app/auth";+import { bindAccountLinkSession } from "@app/portal/auth/accountLinkSession";++/** Prevents attended queries and callbacks from running under a previous local user's session. */+export function AccountLinkSessionBoundary({+ children,+}: {+ children: ReactNode;+}) {+ const { user, isAdmin, loading } = useAuth();+ const identity = isAdmin && user?.orgOwner === true ? user.id : null;+ const [bound, setBound] = useState<string | null>();+ useEffect(() => {+ if (loading) return;+ bindAccountLinkSession(identity);+ setBound(identity);+ }, [identity, loading]);+ if (loading || identity !== bound) return null;+ return children;+}diff --git a/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx b/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsxindex 2fcbfdea0f..123199ecad 100644--- a/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx+++ b/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx@@ -1,112 +1,186 @@import { useEffect, useRef } from "react";-import { useLocation } from "react-router-dom";-import { completeConnect, type ConnectPhase } from "@portal/api/link";-import { ensureSaasSupabase } from "@portal/auth/saasSupabase";-import { useAccountLinkContext } from "@portal/contexts/AccountLinkContext";-import { useUI } from "@portal/contexts/UIContext";-import type { ConnectCallbackState } from "@portal/components/account-link/ConnectCallbackView";+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import { useLocation, useNavigate } from "react-router-dom";+import { completeConnect, type ConnectPhase } from "@app/portal/api/link";+import { ensureSaasSupabase } from "@app/portal/auth/saasSupabase";+import { getSupabaseClient } from "@app/auth/supabase/supabaseClient";+import { clearAccountLinkSession } from "@app/portal/auth/accountLinkSession";+import {+ isTerminalSaasAuthError,+ portalSaasSessionRestored,+} from "@app/portal/auth/portalSaasSession";+import type { PendingConnect } from "@app/portal/auth/pendingConnect";+import { useAccountLinkContext } from "@app/portal/contexts/AccountLinkContext";+import { useUI } from "@app/portal/contexts/UIContext";+import { getPortalQueryClient } from "@app/portal/queryClient";+import type { ConnectCallbackState } from "@app/portal/components/account-link/ConnectCallbackView";-/** What the callback route hands over, read from the URL fragment before stripping it. */+/** Tokens are consumed once and removed from router history before any network request. */export interface AccountLinkReturn {type: string | null;nonce: string | null;accessToken: string | null;refreshToken: string | null;+ pending: PendingConnect | null;}interface LocationState {accountLinkReturn?: AccountLinkReturn;}-/**- * Renders nothing: the result belongs on step 3 of the dialog the admin left, so this publishes the- * outcome and the single dialog host reopens there. Mounted app-wide because the callback route- * only reads the fragment and navigates, so it is gone by the time there is an outcome.- */+/** Owns the validated callback and publishes its outcome to the existing modal. */export function ConnectCallbackHost() {+ const isOwner = useAccountLinkOwner();const location = useLocation();+ const navigate = useNavigate();const { refresh } = useAccountLinkContext();const { publishConnectOutcome } = useUI();const handover = (location.state as LocationState | null)?.accountLinkReturn;-- const startedRef = useRef(false);-- // Refs so the effect runs on the hand-over alone: it consumes a single-use nonce.+ const startedRef = useRef<AccountLinkReturn | null>(null);const publishRef = useRef(publishConnectOutcome);publishRef.current = publishConnectOutcome;const refreshRef = useRef(refresh);refreshRef.current = refresh;+ const mounted = useRef(false);+ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);useEffect(() => {- if (!handover || startedRef.current) return;- startedRef.current = true;+ if (!handover || startedRef.current === handover) return;+ startedRef.current = handover;+ navigate(`${location.pathname}${location.search}`, {+ replace: true,+ state: null,+ });- const { type, nonce, accessToken, refreshToken } = handover;- if (type !== "link" || !nonce) {- publishRef.current({ state: "malformed", sessionRestored: false });+ if (!isOwner) {+ handover.accessToken = null;+ handover.refreshToken = null;return;}- void (async () => {- let sessionRestored = false;- if (accessToken && refreshToken) {- try {- const supabase = ensureSaasSupabase();- // Logged, not swallowed: this resurfaces later as "session expired" otherwise.- if (!supabase) {- console.warn(- "[account-link] no Supabase client: VITE_SUPABASE_URL / VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY are not set for this build",- );- } else {- const { error } = await supabase.auth.setSession({- access_token: accessToken,- refresh_token: refreshToken,- });- if (error) {- console.warn("[account-link] setSession failed:", error.message);- } else {- sessionRestored = true;+ const callback = handover;+ const { type, nonce, pending } = callback;+ const metadata = {+ mode: pending?.mode ?? ("link" as const),+ };+ if (+ (type !== "link" && type !== "reauth") ||+ !nonce ||+ !pending ||+ pending.ownerId !== localStorage.getItem("stirling.portalSaasOwner")+ ) {+ handover.accessToken = null;+ handover.refreshToken = null;+ publishRef.current({+ ...metadata,+ state: "malformed",+ sessionRestored: false,+ });+ return;+ }++ let accepted = false;+ let busy = false;+ let cancelled = false;+ const supabase = ensureSaasSupabase();+ const current = () =>+ !cancelled &&+ mounted.current &&+ supabase === getSupabaseClient() &&+ pending.ownerId === localStorage.getItem("stirling.portalSaasOwner");+ const discardTokens = () => {+ callback.accessToken = null;+ callback.refreshToken = null;+ };+ const cancel = () => {+ cancelled = true;+ discardTokens();+ if (supabase === getSupabaseClient()) clearAccountLinkSession();+ };+ void claim();++ async function claim() {+ if (busy || !current()) return;+ busy = true;+ publishRef.current({+ ...metadata,+ state: "working",+ sessionRestored: false,+ cancel,+ });+ try {+ if (!accepted) {+ const state = toViewState((await completeConnect(nonce!)).phase);+ if (!current()) return;+ if (state !== "linked") {+ if (state !== "retry") {+ discardTokens();}+ publishRef.current({+ ...metadata,+ state,+ sessionRestored: false,+ reclaim: state === "retry" ? claim : undefined,+ cancel,+ });+ return;}- } catch (e) {- console.warn("[account-link] session hand-off threw:", e);+ accepted = true;+ await refreshRef.current();+ if (!current()) return;}- } else {- console.warn(- "[account-link] callback carried no tokens; the approval page had no session to pass",- );- }-- await claim(nonce, sessionRestored);- })();- /** Passes itself as {@code reclaim} so Try again re-claims rather than opening a handshake. */- async function claim(nonce: string, sessionRestored: boolean) {- publishRef.current({ state: "working", sessionRestored });- const again = () => void claim(nonce, sessionRestored);- try {- const state = toViewState((await completeConnect(nonce)).phase);- publishRef.current({- state,- sessionRestored,- reclaim: state === "retry" ? again : undefined,- });- // Without this the page behind the dialog says unlinked until a reload.- if (state === "linked") await refreshRef.current();- } catch {- // Our own backend is unreachable; the handshake is untouched, so retrying beats restarting.- publishRef.current({ state: "retry", sessionRestored, reclaim: again });+ let sessionRestored = false;+ if (callback.accessToken && callback.refreshToken) {+ if (!supabase)+ throw new Error("SaaS authentication is not configured");+ const { error } = await supabase.auth.setSession({+ access_token: callback.accessToken,+ refresh_token: callback.refreshToken,+ });+ if (!current()) return;+ if (error) throw error;+ sessionRestored = true;+ portalSaasSessionRestored();+ void getPortalQueryClient().invalidateQueries();+ }+ discardTokens();+ publishRef.current({ ...metadata, state: "linked", sessionRestored });+ } catch (error) {+ if (current() && isTerminalSaasAuthError(error)) {+ discardTokens();+ publishRef.current({+ ...metadata,+ state: "rejected",+ sessionRestored: false,+ cancel,+ });+ return;+ }+ // A confirmed claim is single-use; retry only session installation after it succeeds.+ if (current())+ publishRef.current({+ ...metadata,+ state: "retry",+ sessionRestored: false,+ reclaim: claim,+ cancel,+ });+ } finally {+ if (!current()) discardTokens();+ busy = false;}}- }, [handover]);+ }, [handover, navigate, location.pathname, location.search, isOwner]);return null;}-/**- * PENDING and UNAVAILABLE collapse into one "try again" state: both mean the handshake is intact but- * unfinished, which is the same thing to do about it.- */function toViewState(phase: ConnectPhase): ConnectCallbackState {switch (phase) {case "LINKED":diff --git a/frontend/editor/src/portal/components/account-link/ConnectCallbackView.tsx b/frontend/editor/src/portal/components/account-link/ConnectCallbackView.tsxindex ae9e268849..0b2e470c4b 100644--- a/frontend/editor/src/portal/components/account-link/ConnectCallbackView.tsx+++ b/frontend/editor/src/portal/components/account-link/ConnectCallbackView.tsx@@ -1,7 +1,8 @@import { useTranslation } from "react-i18next";import { Banner, Spinner } from "@app/ui";-import { ConnectDoneSlide } from "@portal/components/account-link/connect/ConnectDoneSlide";-import "@portal/components/account-link/connect/connect.css";+import { ConnectDoneSlide } from "@app/portal/components/account-link/connect/ConnectDoneSlide";+import type { ConnectMode } from "@app/portal/auth/pendingConnect";+import "@app/portal/components/account-link/connect/connect.css";/** Outcomes of returning from the approval page. */export type ConnectCallbackState =@@ -13,11 +14,14 @@ export type ConnectCallbackState =| "malformed";export interface ConnectOutcome {+ mode?: ConnectMode;state: ConnectCallbackState;- /** True once the SaaS session landed, regardless of how the link itself went. */+ /** True only after the server accepts the callback and the SDK installs its session. */sessionRestored: boolean;- /** Present only while the handshake is still open, so a retry re-claims rather than opening one. */+ /** Retries the uncompleted phase without repeating a claim already accepted by the server. */reclaim?: () => void;+ /** Discards an unfinished callback when its dialog is dismissed. */+ cancel?: () => void;}export function isRetryableOutcome(state: ConnectCallbackState): boolean {@@ -25,6 +29,7 @@ export function isRetryableOutcome(state: ConnectCallbackState): boolean {}export interface ConnectCallbackViewProps {+ mode?: ConnectMode;state: ConnectCallbackState;sessionRestored: boolean;onDone: () => void;@@ -36,6 +41,7 @@ export interface ConnectCallbackViewProps {* dialog's footer, not here, so they stay where steps 1 and 2 put them.*/export function ConnectCallbackView({+ mode = "link",state,sessionRestored,onDone,@@ -47,16 +53,36 @@ export function ConnectCallbackView({<div className="portal-connect-callback portal-connect-callback--working"><Spinner size="md" /><p>- {t(- "portal.accountLink.connect.callback.working",- "Finishing the connection.",- )}+ {mode === "reauth"+ ? t(+ "portal.accountLink.renewal.working",+ "Restoring billing access.",+ )+ : t(+ "portal.accountLink.connect.callback.working",+ "Finishing the connection.",+ )}</p></div>);}if (state === "linked") {+ if (mode === "reauth") {+ return (+ <p className="portal-connect__lede">+ {sessionRestored+ ? t(+ "portal.accountLink.renewal.success",+ "Your billing access has been renewed. This server is still connected to the same Stirling account.",+ )+ : t(+ "portal.accountLink.renewal.incomplete",+ "This server is still connected, but we could not restore billing access in this browser. Try signing in again.",+ )}+ </p>+ );+ }return (<div className="portal-connect-callback"><p className="portal-connect__lede">@@ -80,7 +106,7 @@ export function ConnectCallbackView({);}- const { tone, title, body } = failure(state, t);+ const { tone, title, body } = failure(state, t, mode === "reauth");return (<div className="portal-connect-callback"><Banner tone={tone} title={title}>@@ -102,11 +128,55 @@ export function ConnectCallbackView({type Translate = ReturnType<typeof useTranslation>["t"];-function failure(state: ConnectCallbackState, t: Translate) {+function failure(state: ConnectCallbackState, t: Translate, reauth: boolean) {+ if (reauth) {+ const messages = {+ expired: t(+ "portal.accountLink.renewal.expired",+ "This sign-in request expired. Try again to renew billing access; your server is still connected.",+ ),+ rejected: t(+ "portal.accountLink.renewal.rejected",+ "This sign-in request was declined or has already been used. Try again to renew billing access.",+ ),+ malformed: t(+ "portal.accountLink.renewal.malformed",+ "We could not verify this sign-in response. Start again from Usage & billing; your server is still connected.",+ ),+ retry: t(+ "portal.accountLink.renewal.retry",+ "Stirling could not finish renewing billing access. Try again in a moment; your server is still connected.",+ ),+ };+ return {+ tone: "neutral" as const,+ title:+ state === "expired"+ ? t(+ "portal.accountLink.renewal.expiredTitle",+ "Sign-in request expired",+ )+ : state === "rejected"+ ? t(+ "portal.accountLink.renewal.rejectedTitle",+ "Sign-in not completed",+ )+ : state === "malformed"+ ? t(+ "portal.accountLink.renewal.malformedTitle",+ "Could not verify sign-in",+ )+ : t(+ "portal.accountLink.renewal.retryTitle",+ "Billing access not restored",+ ),+ body: messages[state as keyof typeof messages] ?? messages.retry,+ };+ }switch (state) {case "expired":return {- tone: "warning" as const,+ tone: "neutral" as const,title: t("portal.accountLink.connect.callback.expired.title","Request expired",@@ -118,7 +188,7 @@ function failure(state: ConnectCallbackState, t: Translate) {};case "rejected":return {- tone: "warning" as const,+ tone: "neutral" as const,title: t("portal.accountLink.connect.callback.rejected.title","Connection not completed",@@ -142,7 +212,7 @@ function failure(state: ConnectCallbackState, t: Translate) {};default:return {- tone: "warning" as const,+ tone: "neutral" as const,// Not "retry.*": that key is the button label, and TOML cannot hold a// value and a table under the same name.title: t(diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsxindex 8ed726e3b4..1f7b305f4a 100644--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx@@ -1,7 +1,12 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { act, render, screen, waitFor } from "@testing-library/react";+import { act, render, screen, waitFor, within } from "@testing-library/react";import { MemoryRouter } from "react-router-dom";-import { PortalTestProviders } from "@portal/test/TestQueryProvider";+import {+ UIProvider,+ useUI,+ type LinkModalMode,+} from "@app/portal/contexts/UIContext";+import { PortalTestProviders } from "@app/portal/test/TestQueryProvider";/** The step machine: what drives each step, and what must not skip or repeat one. */const { startConnect, startReauth, fetchWallet, EMAIL } = vi.hoisted(() => ({@@ -11,9 +16,9 @@ const { startConnect, startReauth, fetchWallet, EMAIL } = vi.hoisted(() => ({EMAIL: "[email protected]",}));-vi.mock("@portal/api/link", () => ({ startConnect, startReauth }));-vi.mock("@portal/api/billing", () => ({ fetchWallet }));-vi.mock("@portal/auth/saasSupabase", () => ({+vi.mock("@app/portal/api/link", () => ({ startConnect, startReauth }));+vi.mock("@app/portal/api/billing", () => ({ fetchWallet }));+vi.mock("@app/portal/auth/saasSupabase", () => ({isSaasSupabaseConfigured: true,// Step 3 reads the connected account's email off this session.ensureSaasSupabase: () => ({@@ -27,9 +32,33 @@ vi.mock("@portal/auth/saasSupabase", () => ({}),}));-import { LinkAccountModal } from "@portal/components/account-link/LinkAccountModal";-import type { ConnectOutcome } from "@portal/components/account-link/ConnectCallbackView";-import { freeWallet } from "@portal/components/billing/walletFixtures";+import {+ LinkAccountModal,+ LinkAccountModalHost,+} from "@app/portal/components/account-link/LinkAccountModal";+import type { ConnectOutcome } from "@app/portal/components/account-link/ConnectCallbackView";+import { freeWallet } from "@app/portal/components/billing/walletFixtures";++const ownership = vi.hoisted(() => ({ isAdmin: true, orgOwner: true }));+vi.mock("@app/auth", () => ({+ useAuth: () => ({+ ...ownership,+ user: { orgOwner: ownership.orgOwner },+ loading: false,+ }),+}));++function HostedModal() {+ const { openLinkModal } = useUI();+ return (+ <>+ <button onClick={() => openLinkModal("reauth")}>+ Open billing renewal+ </button>+ <LinkAccountModalHost />+ </>+ );+}const AUTHORIZE = "http://localhost:5174/link?request=req-1";const deployment = vi.hoisted(() => ({ basePath: "" }));@@ -39,22 +68,24 @@ vi.mock("@app/constants/app", async (importOriginal) => ({}));const BENEFITS = "Pipelines, policies, sources and audit";-const GHOST = /Taking you to stirling\.com/;+const GHOST = /Opening Stirling sign-in/;const CONNECT = /Connect Stirling account/;function renderModal(- mode?: "link" | "reauth",+ mode?: LinkModalMode,outcome: ConnectOutcome | null = null,) {return render(<PortalTestProviders>- <MemoryRouter>- <LinkAccountModal- open- onClose={() => {}}- mode={mode}- outcome={outcome}- />+ <MemoryRouter initialEntries={["/processor/usage"]}>+ <UIProvider>+ <LinkAccountModal+ open+ onClose={() => {}}+ mode={mode}+ outcome={outcome}+ />+ </UIProvider></MemoryRouter></PortalTestProviders>,);@@ -76,6 +107,10 @@ describe("LinkAccountModal", () => {beforeEach(() => {vi.clearAllMocks();+ ownership.isAdmin = true;+ ownership.orgOwner = true;+ sessionStorage.clear();+ localStorage.setItem("stirling.portalSaasOwner", "owner");deployment.basePath = "";fetchWallet.mockResolvedValue(freeWallet);startConnect.mockResolvedValue({@@ -103,6 +138,62 @@ describe("LinkAccountModal", () => {});});+ it.each([+ { isAdmin: true, orgOwner: false },+ { isAdmin: false, orgOwner: true },+ ])(+ "does not mount a requested renewal for $isAdmin admin / $orgOwner owner",+ (auth) => {+ Object.assign(ownership, auth);+ render(+ <PortalTestProviders>+ <MemoryRouter>+ <UIProvider>+ <HostedModal />+ </UIProvider>+ </MemoryRouter>+ </PortalTestProviders>,+ );+ click("Open billing renewal");+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(startReauth).not.toHaveBeenCalled();+ expect(startConnect).not.toHaveBeenCalled();+ },+ );++ it.each([+ { state: "expired" as const, sessionRestored: false },+ { state: "linked" as const, sessionRestored: false },+ ])(+ "shows a failed renewal retry after $state and lets the owner retry again",+ async (outcome) => {+ startReauth.mockRejectedValueOnce(new Error("offline"));+ renderModal("reauth", outcome);+ click(/Try again/);+ expect(await screen.findByText(/outbound network access/)).toBeTruthy();+ expect(assign).not.toHaveBeenCalled();+ expect(screen.queryByText(GHOST)).toBeNull();+ click(/Sign in again/);+ await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));+ expect(startReauth).toHaveBeenCalledTimes(2);+ expect(startConnect).not.toHaveBeenCalled();+ },+ );++ it("shows callback configuration guidance when retrying a partial session fails", async () => {+ startReauth.mockResolvedValue({+ phase: "CALLBACK_MISMATCH",+ authorizeUrl: null,+ });+ renderModal("reauth", { state: "linked", sessionRestored: false });+ click(/Try again/);+ expect(+ await screen.findByText(/configured frontend address does not match/),+ ).toBeTruthy();+ expect(screen.getByRole("button", { name: /Sign in again/ })).toBeTruthy();+ expect(assign).not.toHaveBeenCalled();+ });+it("opens on the pitch, and asks nothing of the backend until told", () => {renderModal();@@ -112,13 +203,55 @@ describe("LinkAccountModal", () => {expect(startConnect).not.toHaveBeenCalled();});- it("offers no sign-in form, because a sign-in started here cannot complete", () => {- const { container } = renderModal();- click(CONNECT);+ it("starts renewal on HTTP hosts without crypto.randomUUID", async () => {+ const original = crypto.randomUUID;+ Object.defineProperty(crypto, "randomUUID", {+ configurable: true,+ value: undefined,+ });+ try {+ renderModal("reauth");+ click(/Sign in again/);+ await waitFor(() => expect(startReauth).toHaveBeenCalled(), {+ timeout: 500,+ });+ expect(startReauth.mock.calls[0][0]).toMatch(/state=.+/);+ } finally {+ Object.defineProperty(crypto, "randomUUID", {+ configurable: true,+ value: original,+ });+ }+ });++ it("does not redirect if the renewal dialog closes while the request is pending", async () => {+ let resolve!: (value: unknown) => void;+ startReauth.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const view = renderModal("reauth");+ click(/Sign in again/);+ view.unmount();+ await act(async () => {+ resolve({ phase: "PENDING", authorizeUrl: AUTHORIZE });+ });+ expect(assign).not.toHaveBeenCalled();+ });- // A sign-in started on this origin cannot complete, so nothing here may collect credentials.- expect(container.querySelector("input[type=password]")).toBeNull();- expect(container.querySelector("input[type=email]")).toBeNull();+ it("keeps credential fields out of the portaled connection dialog", async () => {+ renderModal();+ const dialog = screen.getByRole("dialog");+ expect(dialog).toBeVisible();+ expect(+ dialog.querySelector('input[type="password"], input[type="email"]'),+ ).toBeNull();+ click(CONNECT);+ await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));+ expect(+ dialog.querySelector('input[type="password"], input[type="email"]'),+ ).toBeNull();});it("hands over on the first click, showing the ghost while it goes", async () => {@@ -131,7 +264,9 @@ describe("LinkAccountModal", () => {// The backend checks this against the request's Origin header.expect(startConnect).toHaveBeenCalledWith("http://localhost:5173",- "http://localhost:5173/account-link/callback",+ expect.stringMatching(+ /^http:\/\/localhost:5173\/account-link\/callback\?state=/,+ ),);await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));expect(startReauth).not.toHaveBeenCalled();@@ -149,7 +284,9 @@ describe("LinkAccountModal", () => {// A different endpoint: reauth presents the credential, so the team is pinned server-side.await waitFor(() =>expect(startReauth).toHaveBeenCalledWith(- "http://localhost:5173/account-link/callback",+ expect.stringMatching(+ /^http:\/\/localhost:5173\/account-link\/callback\?state=/,+ ),),);expect(startConnect).not.toHaveBeenCalled();@@ -165,7 +302,9 @@ describe("LinkAccountModal", () => {await waitFor(() =>expect(startConnect).toHaveBeenCalledWith("http://localhost:5173/pdf",- "http://localhost:5173/pdf/account-link/callback",+ expect.stringMatching(+ /^http:\/\/localhost:5173\/pdf\/account-link\/callback\?state=/,+ ),),);});@@ -184,6 +323,46 @@ describe("LinkAccountModal", () => {expect(filledSteps()).toBe(1);});+ it.each(["link", "reauth"] as const)(+ "explains a callback address mismatch during %s and allows retry after correction",+ async (mode) => {+ const start = mode === "reauth" ? startReauth : startConnect;+ const button = mode === "reauth" ? /Sign in again/ : CONNECT;+ start.mockResolvedValue({+ phase: "CALLBACK_MISMATCH",+ authorizeUrl: null,+ secondsRemaining: null,+ teamId: null,+ });+ renderModal(mode);+ click(button);++ expect(+ await screen.findByText(/configured frontend address does not match/),+ ).toBeTruthy();+ expect(assign).not.toHaveBeenCalled();+ expect(sessionStorage.getItem("stirling.portalConnect")).toBeNull();+ expect(screen.queryByText(GHOST)).toBeNull();++ start.mockResolvedValue({+ phase: "PENDING",+ authorizeUrl: AUTHORIZE,+ secondsRemaining: 900,+ teamId: null,+ });+ click(button);+ await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));+ const callbackUrl = start.mock.calls[1][mode === "reauth" ? 0 : 1];+ const pending = JSON.parse(+ sessionStorage.getItem("stirling.portalConnect")!,+ );+ expect(pending.browserState).toBe(+ new URL(callbackUrl).searchParams.get("state"),+ );+ expect(pending.mode).toBe(mode);+ },+ );+it("does not navigate when there is nothing to navigate to", async () => {// Already linked: the backend reports status without an authorize URL.startConnect.mockResolvedValue({@@ -216,24 +395,93 @@ describe("LinkAccountModal", () => {expect(filledSteps()).toBe(1);});- /**- * Not the close path itself (the host unmounts, so a fresh mount is clean by construction) but- * the property behind it: hoist the flag into UIContext and the trap returns, failing here.- */- it("keeps the in-flight flag local, so a fresh mount cannot inherit one", async () => {- const first = renderModal();- click(CONNECT);- await waitFor(() => expect(screen.getByText(GHOST)).toBeTruthy());-- first.unmount();- renderModal();-- expect(screen.getByText(BENEFITS)).toBeTruthy();+ it("dismisses a pending renewal and opens a fresh attempt through the real host", async () => {+ let finish!: (value: unknown) => void;+ startReauth.mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ render(+ <PortalTestProviders>+ <MemoryRouter>+ <UIProvider>+ <HostedModal />+ </UIProvider>+ </MemoryRouter>+ </PortalTestProviders>,+ );+ click("Open billing renewal");+ click(/Sign in again/);+ expect(screen.getByText(GHOST)).toBeVisible();+ act(() =>+ within(screen.getByRole("dialog"))+ .getAllByRole("button", { name: "Close" })[0]+ .click(),+ );+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ await act(async () =>+ finish({ phase: "PENDING", authorizeUrl: AUTHORIZE }),+ );+ expect(assign).not.toHaveBeenCalled();+ expect(sessionStorage.getItem("stirling.portalConnect")).toBeNull();++ click("Open billing renewal");expect(screen.queryByText(GHOST)).toBeNull();+ click(/Sign in again/);+ await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));+ expect(startReauth).toHaveBeenCalledTimes(2);});});describe("resuming after the round trip", () => {+ it("renews missing browser access after an exhausted free-tier link succeeds", async () => {+ renderModal("exhausted", {+ state: "linked",+ sessionRestored: false,+ });++ expect(screen.getByText("Renew billing access")).toBeTruthy();+ expect(filledSteps()).toBe(0);+ click(/Try again/);++ await waitFor(() => expect(startReauth).toHaveBeenCalledTimes(1));+ expect(startConnect).not.toHaveBeenCalled();+ });++ it("keeps the normal completion after an exhausted free-tier link restores access", async () => {+ renderModal("exhausted", { state: "linked", sessionRestored: true });++ expect(+ await screen.findByText(/now runs against your Stirling account/),+ ).toBeTruthy();+ expect(filledSteps()).toBe(3);+ expect(startReauth).not.toHaveBeenCalled();+ });++ it("keeps a renewal success to one step without the link onboarding", async () => {+ renderModal("reauth", {+ mode: "reauth",+ state: "linked",+ sessionRestored: true,+ });+ expect(+ await screen.findByText(/billing access has been renewed/),+ ).toBeTruthy();+ expect(screen.queryByText("Invite your team")).toBeNull();+ expect(filledSteps()).toBe(0);+ });++ it("retries expired renewal with reauth rather than registering again", async () => {+ renderModal("reauth", {+ mode: "reauth",+ state: "expired",+ sessionRestored: false,+ });+ click(/Try again/);+ await waitFor(() => expect(startReauth).toHaveBeenCalledTimes(1));+ expect(startConnect).not.toHaveBeenCalled();+ });it("lands on step 3 rather than restarting the pitch", async () => {renderModal("link", { state: "linked", sessionRestored: true });diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsxindex cb35772595..41e50524e8 100644--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx@@ -1,17 +1,18 @@import { useTranslation } from "react-i18next";import { Button } from "@app/ui";-import { FlowModal } from "@portal/components/shared/FlowModal";-import { StepModalHeader } from "@portal/components/shared/StepModalHeader";-import { ConnectAskStep } from "@portal/components/account-link/connect/ConnectAskStep";-import { ConnectHandoffGhost } from "@portal/components/account-link/connect/ConnectHandoffGhost";+import { FlowModal } from "@app/portal/components/shared/FlowModal";+import { StepModalHeader } from "@app/portal/components/shared/StepModalHeader";+import { ConnectAskStep } from "@app/portal/components/account-link/connect/ConnectAskStep";+import { ConnectHandoffGhost } from "@app/portal/components/account-link/connect/ConnectHandoffGhost";import {ConnectCallbackView,isRetryableOutcome,type ConnectOutcome,-} from "@portal/components/account-link/ConnectCallbackView";-import { useConnectHandoff } from "@portal/hooks/useConnectHandoff";-import type { LinkModalMode } from "@portal/contexts/UIContext";-import "@portal/views/ConnectCallback.css";+} from "@app/portal/components/account-link/ConnectCallbackView";+import { useConnectHandoff } from "@app/portal/hooks/useConnectHandoff";+import { useUI, type LinkModalMode } from "@app/portal/contexts/UIContext";+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import "@app/portal/views/ConnectCallback.css";/*** Ordered, so a step's position in this list is its number and the list's length is the total.@@ -30,6 +31,22 @@ interface Props {outcome?: ConnectOutcome | null;}+/** Unmounting on close discards an interrupted handoff before the next attempt. */+export function LinkAccountModalHost() {+ const { linkModalOpen, linkModalMode, closeLinkModal, connectOutcome } =+ useUI();+ const isOwner = useAccountLinkOwner();+ if (!isOwner || !linkModalOpen) return null;+ return (+ <LinkAccountModal+ open+ mode={linkModalMode}+ onClose={closeLinkModal}+ outcome={connectOutcome}+ />+ );+}+/*** The progress bar spans the redirect on purpose: the admin leaves on the hand-off and returns on* the outcome step of the dialog they left, rather than being greeted by a different one.@@ -41,14 +58,16 @@ export function LinkAccountModal({outcome = null,}: Props) {const { t } = useTranslation();- const reauth = mode === "reauth";+ const reauth =+ mode === "reauth" ||+ (outcome?.state === "linked" && !outcome.sessionRestored);const exhausted = mode === "exhausted";const handoff = useConnectHandoff(reauth);// Busy outranks a stale outcome, or a retry sits on the old result until the browser leaves.let step: StepId = "ask";if (handoff.busy) step = "handoff";- else if (outcome) step = "outcome";+ else if (outcome && !handoff.error) step = "outcome";const title = stepTitle();const current = STEP_ORDER.indexOf(step) + 1;@@ -62,7 +81,10 @@ export function LinkAccountModal({stepLabel: t("portal.accountLink.connect.step","Step {{current}} of {{total}}",- { current, total: STEP_ORDER.length },+ {+ current,+ total: STEP_ORDER.length,+ },),};@@ -74,7 +96,7 @@ export function LinkAccountModal({footer={stepFooter()}><StepModalHeader- brand+ brand={t("portal.accountLink.modal.identity", "Stirling account")}title={title}{...stepChrome}closeLabel={t("portal.accountLink.connect.close", "Close")}@@ -86,7 +108,7 @@ export function LinkAccountModal({function stepTitle(): string {if (reauth) {- return t("portal.accountLink.modal.reauthTitle", "Sign in again");+ return t("portal.accountLink.renewal.title", "Renew billing access");}if (step === "ask") {return exhausted@@ -123,6 +145,7 @@ export function LinkAccountModal({case "outcome":return outcome ? (<ConnectCallbackView+ mode={reauth ? "reauth" : "link"}state={outcome.state}sessionRestored={outcome.sessionRestored}onDone={onClose}@@ -197,6 +220,15 @@ export function LinkAccountModal({);}+ if (outcome?.state === "linked" && !outcome.sessionRestored) {+ return (+ <>+ {closeButton()}+ {retryButton(handoff.begin)}+ </>+ );+ }+if (outcome && isRetryableOutcome(outcome.state)) {return (<>diff --git a/frontend/editor/src/portal/components/account-link/SaasSessionBanner.test.tsx b/frontend/editor/src/portal/components/account-link/SaasSessionBanner.test.tsxnew file mode 100644index 0000000000..22820687c8--- /dev/null+++ b/frontend/editor/src/portal/components/account-link/SaasSessionBanner.test.tsx@@ -0,0 +1,95 @@+import { beforeEach, expect, it, vi } from "vitest";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { UIProvider, useUI } from "@app/portal/contexts/UIContext";+import { LinkProvider } from "@app/portal/contexts/LinkContext";+import { SaasSessionBanner } from "@app/portal/components/account-link/SaasSessionBanner";++const flags = vi.hoisted(() => ({ isAdmin: true, orgOwner: true }));+vi.mock("@app/auth", () => ({+ useAuth: () => ({+ isAdmin: flags.isAdmin,+ user: { orgOwner: flags.orgOwner },+ }),+}));+vi.mock("@app/auth/supabase/supabaseClient", () => ({+ getSupabaseClient: () => null,+}));+vi.mock("@app/portal/auth/saasSupabase", () => ({+ ensureSaasSupabase: vi.fn(),+}));+import {+ resetPortalSaasSessionState,+ withPortalSaasSession,+ SaasSessionRequiredError,+} from "@app/portal/auth/portalSaasSession";+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));+let ui: ReturnType<typeof useUI>;+function Probe() {+ ui = useUI();+ return null;+}+function show(linked = true) {+ return render(+ <MantineProvider>+ <LinkProvider initialState={linked ? "linked-free" : "unlinked"}>+ <UIProvider>+ <Probe />+ <SaasSessionBanner />+ </UIProvider>+ </LinkProvider>+ </MantineProvider>,+ );+}+beforeEach(async () => {+ flags.isAdmin = true;+ flags.orgOwner = true;+ resetPortalSaasSessionState();+ await expect(+ withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ ),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+});+it("opens renewal for a linked owner without changing the device link", () => {+ show();+ fireEvent.click(screen.getByRole("button", { name: "Sign in again" }));+ expect(ui.linkModalOpen).toBe(true);+ expect(ui.linkModalMode).toBe("reauth");+});+it("does not expose the renewal action to a non-owner", () => {+ flags.isAdmin = false;+ show();+ expect(screen.queryByRole("button")).toBeNull();+});+it("does not ask an unlinked instance to renew a billing session", () => {+ show(false);+ expect(screen.queryByRole("button")).toBeNull();+});++it("removes the renewal prompt when the SDK restores access", () => {+ show();+ expect(screen.getByRole("button", { name: "Sign in again" })).toBeTruthy();+ act(() => window.dispatchEvent(new Event("stirling-saas-session-restored")));+ expect(screen.queryByRole("button", { name: "Sign in again" })).toBeNull();+});++it("keeps one recovery prompt and restores it after the dialog is dismissed", () => {+ show();+ fireEvent.click(screen.getByRole("button", { name: "Sign in again" }));+ expect(screen.queryByText("Renew billing access")).toBeNull();+ act(() => ui.closeLinkModal());+ expect(screen.getAllByRole("button", { name: "Sign in again" })).toHaveLength(+ 1,+ );+});++it("does not show billing renewal to an admin who is not the organization owner", () => {+ flags.orgOwner = false;+ show();+ expect(screen.queryByText("Renew billing access")).toBeNull();+ expect(screen.queryByRole("button")).toBeNull();+});diff --git a/frontend/editor/src/portal/components/account-link/SaasSessionBanner.tsx b/frontend/editor/src/portal/components/account-link/SaasSessionBanner.tsxnew file mode 100644index 0000000000..b01985c489--- /dev/null+++ b/frontend/editor/src/portal/components/account-link/SaasSessionBanner.tsx@@ -0,0 +1,32 @@+import { useTranslation } from "react-i18next";+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import { Banner, Button } from "@app/ui";+import { usePortalSaasSession } from "@app/portal/hooks/usePortalSaasSession";+import { useLink } from "@app/portal/contexts/LinkContext";+import { useUI } from "@app/portal/contexts/UIContext";++/** Recovery for attended calls, including checkout and settings, without changing instance status. */+export function SaasSessionBanner() {+ const { t } = useTranslation();+ const isOwner = useAccountLinkOwner();+ const { required } = usePortalSaasSession();+ const { isLinked } = useLink();+ const { openLinkModal, linkModalOpen } = useUI();+ if (!required || !isLinked || !isOwner || linkModalOpen) return null;+ return (+ <Banner+ tone="neutral"+ title={t("portal.accountLink.renewal.title", "Renew billing access")}+ action={+ <Button size="sm" onClick={() => openLinkModal("reauth")}>+ {t("portal.accountLink.modal.continueReauth", "Sign in again")}+ </Button>+ }+ >+ {t(+ "portal.usage.sessionExpired.body",+ "Your Stirling account session has expired. Sign in again to view billing — your instance stays linked.",+ )}+ </Banner>+ );+}diff --git a/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx b/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsxindex 5dc580d120..feacd71e6e 100644--- a/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx+++ b/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx@@ -1,8 +1,8 @@import { useTranslation } from "react-i18next";import { Banner } from "@app/ui";-import { isSaasSupabaseConfigured } from "@portal/auth/saasSupabase";-import { ConnectBenefitsSlide } from "@portal/components/account-link/connect/ConnectBenefitsSlide";-import "@portal/components/account-link/connect/connect.css";+import { isSaasSupabaseConfigured } from "@app/portal/auth/saasSupabase";+import { ConnectBenefitsSlide } from "@app/portal/components/account-link/connect/ConnectBenefitsSlide";+import "@app/portal/components/account-link/connect/connect.css";interface Props {/** Re-auth says why it is being asked; a first link is pitched instead. */@@ -44,7 +44,7 @@ export function ConnectAskStep({ reauth, exhausted = false, error }: Props) {{!isSaasSupabaseConfigured && (<Banner- tone="warning"+ tone="neutral"title={t("portal.accountLink.modal.loginNotConfigured.title","Stirling connection not configured",diff --git a/frontend/editor/src/portal/components/account-link/connect/ConnectHandoffGhost.tsx b/frontend/editor/src/portal/components/account-link/connect/ConnectHandoffGhost.tsxindex 251652de73..ec44fe7281 100644--- a/frontend/editor/src/portal/components/account-link/connect/ConnectHandoffGhost.tsx+++ b/frontend/editor/src/portal/components/account-link/connect/ConnectHandoffGhost.tsx@@ -1,28 +1,18 @@import { useTranslation } from "react-i18next";-import { Skeleton } from "@app/ui";-import "@portal/components/account-link/connect/connect.css";+import { Spinner } from "@app/ui";+import "@app/portal/components/account-link/connect/connect.css";-/**- * A ghost rather than a screen: the admin has already decided. It earns its place when the local- * backend is slow to open the handshake, where a blank dialog would look broken.- */export function ConnectHandoffGhost() {const { t } = useTranslation();-return (- <div className="portal-connect__ghost">+ <div className="portal-connect__ghost" role="status">+ <Spinner size="sm" /><p className="portal-connect__lede">{t(- "portal.accountLink.connect.handoff.going",- "Taking you to stirling.com",+ "portal.accountLink.connect.handoff.opening",+ "Opening Stirling sign-in…",)}</p>-- <div className="portal-connect__ghost-bars" aria-hidden>- <Skeleton height="2.25rem" />- <Skeleton height="2.25rem" width="80%" />- <Skeleton height="2.25rem" width="55%" />- </div></div>);}diff --git a/frontend/editor/src/portal/components/account-link/connect/connect.css b/frontend/editor/src/portal/components/account-link/connect/connect.cssindex 393695bb0a..c22bbb62a1 100644--- a/frontend/editor/src/portal/components/account-link/connect/connect.css+++ b/frontend/editor/src/portal/components/account-link/connect/connect.css@@ -38,20 +38,12 @@text-align: right;}-/* ── Step 2: the ghost ──────────────────────────────────────────────────── */-.portal-connect__ghost {display: flex;- flex-direction: column;+ align-items: center;gap: 0.75rem;}-.portal-connect__ghost-bars {- display: flex;- flex-direction: column;- gap: 0.5rem;-}-/* ── Step 3 ─────────────────────────────────────────────────────────────── *//* Standalone, so it needs the top edge the benefits list would have given it. */diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsxindex 256a496d14..95a9cff169 100644--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx@@ -1,4 +1,4 @@-vi.mock("@portal/hooks/useServerPlan", () => ({+vi.mock("@app/portal/hooks/useServerPlan", () => ({useServerPlan: () => ({ serverPlan: undefined, loading: false }),}));@@ -46,41 +46,48 @@ vi.mock("@app/services/licenseService", () => ({}));vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));-vi.mock("@portal/hooks/useConnectGate", () => ({+vi.mock("@app/portal/hooks/useConnectGate", () => ({useConnectGate: () => ({ ...gate, connect, guard: (f: unknown) => f }),}));-vi.mock("@portal/contexts/LinkContext", () => ({+vi.mock("@app/portal/contexts/LinkContext", () => ({useApplyLinkFacts: () => applyLinkFacts,useLinkOptional: () => ({ isLinked: link.is }),}));-vi.mock("@portal/contexts/UIContext", () => ({+vi.mock("@app/portal/contexts/UIContext", () => ({useUI: () => ({ openLinkModal: vi.fn() }),}));-vi.mock("@portal/hooks/usePortalAdmin", () => ({- usePortalAdmin: () => admin.is,+vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({+ useAccountLinkOwner: () => admin.is,}));-vi.mock("@portal/views/Usage", () => ({+vi.mock("@app/portal/views/Usage", () => ({Usage: ({onWalletLoaded,renderLicenseSection,+ sessionRecovery,}: {onWalletLoaded?: (w: unknown) => void;+ sessionRecovery?: ReactNode;renderLicenseSection?: (onSaved: () => void) => ReactNode;}) => {onWalletLoaded?.({ status: "free" });return (- <div data-testid="usage">{renderLicenseSection?.(onLicenseSaved)}</div>+ <div+ data-testid="usage"+ data-session-recovery-in-shell={Boolean(sessionRecovery)}+ >+ {renderLicenseSection?.(onLicenseSaved)}+ </div>);},}));-vi.mock("@portal/components/billing/FreeTierPlanView", () => ({+vi.mock("@app/portal/components/billing/FreeTierPlanView", () => ({FreeTierPlanView: ({ licenseSection }: { licenseSection?: ReactNode }) => (<div data-testid="free-tier">{licenseSection}</div>),}));-import { BillingSettingsSection } from "@portal/components/settings/BillingSettingsSection";+import { BillingSettingsSection } from "@app/portal/components/settings/BillingSettingsSection";function Location() {const location = useLocation();@@ -153,6 +160,10 @@ describe("PortalBillingGate — self-hosted", () => {link.is = true;renderGate();expect(screen.getByTestId("usage")).toBeInTheDocument();+ expect(screen.getByTestId("usage")).toHaveAttribute(+ "data-session-recovery-in-shell",+ "true",+ );expect(screen.queryByTestId("free-tier")).toBeNull();expect(applyLinkFacts).toHaveBeenCalledWith(true, false);});diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsxindex e2c75ffcf5..077cbd97f4 100644--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx@@ -1,18 +1,20 @@-import { useServerPlan } from "@portal/hooks/useServerPlan";+import { useServerPlan } from "@app/portal/hooks/useServerPlan";import { ManageBillingButton } from "@app/components/shared/ManageBillingButton";import { useCallback, useEffect, useRef } from "react";import { useSearchParams } from "react-router-dom";-import { ServerLicenseSection } from "@portal/components/billing/ServerLicenseSection";+import { ServerLicenseSection } from "@app/portal/components/billing/ServerLicenseSection";import {useApplyLinkFacts,useLinkOptional,-} from "@portal/contexts/LinkContext";-import { useUI } from "@portal/contexts/UIContext";-import { useConnectGate } from "@portal/hooks/useConnectGate";-import { usePortalAdmin } from "@portal/hooks/usePortalAdmin";-import { FreeTierPlanView } from "@portal/components/billing/FreeTierPlanView";-import { Usage } from "@portal/views/Usage";-import type { Wallet } from "@portal/api/billing";+} from "@app/portal/contexts/LinkContext";+import { useUI } from "@app/portal/contexts/UIContext";+import { useConnectGate } from "@app/portal/hooks/useConnectGate";+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import { AccountConnectionNotice } from "@app/portal/components/account-link/AccountConnectionNotice";+import { SaasSessionBanner } from "@app/portal/components/account-link/SaasSessionBanner";+import { FreeTierPlanView } from "@app/portal/components/billing/FreeTierPlanView";+import { Usage } from "@app/portal/views/Usage";+import type { Wallet } from "@app/portal/api/billing";/*** The seam the SaaS build shadows: picks which usage page this instance has one of.@@ -23,14 +25,14 @@ import type { Wallet } from "@portal/api/billing";*/export function PortalBillingGate() {const applyLinkFacts = useApplyLinkFacts();- const { openLinkModal, trialSetupRequested } = useUI();+ const { trialSetupRequested } = useUI();const { loading, gated, connect } = useConnectGate();- const isAdmin = usePortalAdmin();+ const isOwner = useAccountLinkOwner();const {serverPlan,usersInUse,loading: licenseLoading,- } = useServerPlan(isAdmin);+ } = useServerPlan(isOwner);const serverPlanAction = serverPlan ? <ManageBillingButton /> : undefined;const link = useLinkOptional();const [searchParams] = useSearchParams();@@ -40,21 +42,20 @@ export function PortalBillingGate() {useEffect(() => {if (!procurementRequested || link?.isLinked) prompted.current = false;- else if (isAdmin && !loading && gated && !prompted.current) {+ else if (isOwner && !loading && gated && !prompted.current) {prompted.current = true;connect();}- }, [procurementRequested, link?.isLinked, isAdmin, loading, gated, connect]);+ }, [procurementRequested, link?.isLinked, isOwner, loading, gated, connect]);const onWalletLoaded = useCallback((w: Wallet) => applyLinkFacts(true, w.status === "subscribed"),[applyLinkFacts],);- const onReauth = useCallback(() => openLinkModal("reauth"), [openLinkModal]);- // Administrators only: the figures are instance-wide and the endpoints ADMIN-gated. The nav- // hides the entry to match, so this is the backstop for a typed URL.- if (!isAdmin) return null;+ // Only the organization owner manages the server's account and billing.+ // The nav hides these sections too; this guards a directly entered URL.+ if (!isOwner) return null;// Neither page while the answer is unknown: showing the local meter to a linked instance would// present a dormant ledger as its live one.if (loading || licenseLoading) return null;@@ -74,10 +75,15 @@ export function PortalBillingGate() {serverPlan={serverPlan}serverPlanAction={serverPlanAction}onWalletLoaded={onWalletLoaded}- onReauth={onReauth}renderLicenseSection={(onSaved) => (<ServerLicenseSection onSaved={onSaved} />)}+ sessionRecovery={+ <>+ <SaasSessionBanner />+ <AccountConnectionNotice />+ </>+ }/>);}diff --git a/frontend/editor/src/portal/components/procurement/ProcurementFlow.test.tsx b/frontend/editor/src/portal/components/procurement/ProcurementFlow.test.tsxnew file mode 100644index 0000000000..e5da2c60d4--- /dev/null+++ b/frontend/editor/src/portal/components/procurement/ProcurementFlow.test.tsx@@ -0,0 +1,68 @@+import { useState } from "react";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { it, expect, vi } from "vitest";+import { MantineProvider } from "@mantine/core";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { UIProvider, useUI } from "@app/portal/contexts/UIContext";+import { LinkProvider } from "@app/portal/contexts/LinkContext";+import { ProcurementFlow } from "@app/portal/components/procurement/ProcurementFlow";+import { useProcurement } from "@app/portal/components/procurement/useProcurement";+import { LinkAccountModal } from "@app/portal/components/account-link/LinkAccountModal";+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ i18n: { language: "en-US" },+ }),+}));+vi.mock("@app/portal/hooks/useLinkedAccountEmail", () => ({+ useLinkedAccountEmail: () => null,+}));+vi.mock("@app/portal/hooks/useConnectHandoff", () => ({+ useConnectHandoff: () => ({ busy: false, error: null, begin: vi.fn() }),+}));+function Flow() {+ const controller = useProcurement();+ const [open, setOpen] = useState(true);+ const ui = useUI();+ return (+ <>+ <ProcurementFlow controller={{ ...controller, open, setOpen }} />+ {ui.linkModalOpen && (+ <LinkAccountModal+ open+ mode={ui.linkModalMode}+ onClose={ui.closeLinkModal}+ />+ )}+ </>+ );+}+it("suspends procurement while connecting and returns to its next action on dismissal", async () => {+ render(+ <MantineProvider>+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ <LinkProvider initialState="unlinked">+ <UIProvider>+ <Flow />+ </UIProvider>+ </LinkProvider>+ </QueryClientProvider>+ </MantineProvider>,+ );+ fireEvent.click(+ screen.getByRole("button", { name: "portal.procurement.link.cta" }),+ );+ await waitFor(() => expect(screen.getAllByRole("dialog")).toHaveLength(1));+ expect(+ screen.getByRole("dialog", { name: "Connect your Stirling account" }),+ ).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));+ await waitFor(() => expect(screen.getAllByRole("dialog")).toHaveLength(1));+ expect(+ screen.getByRole("button", { name: "portal.procurement.link.cta" }),+ ).toBeVisible();+});diff --git a/frontend/editor/src/portal/components/procurement/ProcurementFlow.tsx b/frontend/editor/src/portal/components/procurement/ProcurementFlow.tsxindex 670b6d6782..a828477817 100644--- a/frontend/editor/src/portal/components/procurement/ProcurementFlow.tsx+++ b/frontend/editor/src/portal/components/procurement/ProcurementFlow.tsx@@ -1,22 +1,22 @@import { useTranslation } from "react-i18next";import { Banner, Button, EmptyState, Skeleton } from "@app/ui";-import { useUI } from "@portal/contexts/UIContext";-import { useLinkedAccountEmail } from "@portal/hooks/useLinkedAccountEmail";-import { ProcurementAgreement } from "@portal/components/procurement/ProcurementAgreement";+import { useUI } from "@app/portal/contexts/UIContext";+import { useLinkedAccountEmail } from "@app/portal/hooks/useLinkedAccountEmail";+import { ProcurementAgreement } from "@app/portal/components/procurement/ProcurementAgreement";import {DocumentsModal,LicenseModal,ScheduleCallModal,TrialManageModal,TrialSetupModal,-} from "@portal/components/procurement/ProcurementExtras";-import { ProcurementModal } from "@portal/components/procurement/ProcurementModal";+} from "@app/portal/components/procurement/ProcurementExtras";+import { ProcurementModal } from "@app/portal/components/procurement/ProcurementModal";import {LiveStageCard,PaymentStageCard,-} from "@portal/components/procurement/ProcurementStages";-import { QuoteBuilder } from "@portal/components/procurement/QuoteBuilder";-import type { ProcurementController } from "@portal/components/procurement/useProcurement";+} from "@app/portal/components/procurement/ProcurementStages";+import { QuoteBuilder } from "@app/portal/components/procurement/QuoteBuilder";+import type { ProcurementController } from "@app/portal/components/procurement/useProcurement";/*** The procurement takeover flow: the full-screen journey modal (quote builder →@@ -30,7 +30,7 @@ export function ProcurementFlow({controller: ProcurementController;}) {const { t } = useTranslation();- const { openLinkModal } = useUI();+ const { openLinkModal, linkModalOpen } = useUI();const scheduleEmail = useLinkedAccountEmail();const {isLinked,@@ -77,7 +77,7 @@ export function ProcurementFlow({return (<><ProcurementModal- open={open}+ open={open && !linkModalOpen}onClose={() => setOpen(false)}title={t("portal.procurement.title")}subtitle={t("portal.procurement.subtitle")}@@ -174,7 +174,7 @@ export function ProcurementFlow({</ProcurementModal><TrialSetupModal- open={extra === "setup"}+ open={extra === "setup" && !linkModalOpen}onClose={() => setExtra(null)}busy={busy}email={scheduleEmail ?? undefined}@@ -183,7 +183,7 @@ export function ProcurementFlow({/>{data?.licenseKey && (<LicenseModal- open={extra === "license"}+ open={extra === "license" && !linkModalOpen}onClose={() => setExtra(null)}licenseKey={data.licenseKey}offlineAvailable={data.deployment === "airgap"}@@ -193,13 +193,13 @@ export function ProcurementFlow({/>)}<ScheduleCallModal- open={extra === "schedule"}+ open={extra === "schedule" && !linkModalOpen}onClose={() => setExtra(null)}email={scheduleEmail}/>{data && (<TrialManageModal- open={extra === "trial"}+ open={extra === "trial" && !linkModalOpen}onClose={() => setExtra(null)}snapshot={data}busy={busy}@@ -214,7 +214,7 @@ export function ProcurementFlow({/>)}<DocumentsModal- open={extra === "documents"}+ open={extra === "documents" && !linkModalOpen}onClose={() => setExtra(null)}agreementVersion={data?.agreementSignedVersion}downloadingAgreement={downloadingAgreement}diff --git a/frontend/editor/src/portal/components/procurement/useProcurement.test.tsx b/frontend/editor/src/portal/components/procurement/useProcurement.test.tsxindex c4094156a8..55611f8df3 100644--- a/frontend/editor/src/portal/components/procurement/useProcurement.test.tsx+++ b/frontend/editor/src/portal/components/procurement/useProcurement.test.tsx@@ -21,21 +21,22 @@ const { fetchSnapshot, startAgreement, issueQuote } = vi.hoisted(() => ({issueQuote: vi.fn(),}));-vi.mock("@portal/api/procurement", async (importOriginal) => ({- ...(await importOriginal<typeof import("@portal/api/procurement")>()),+vi.mock("@app/portal/api/procurement", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/portal/api/procurement")>()),fetchSnapshot,startAgreement,issueQuote,}));-vi.mock("@portal/contexts/usePortalLinked", () => ({+vi.mock("@app/portal/contexts/usePortalLinked", () => ({usePortalLinked: () => true,}));import {useProcurement,type ProcurementController,-} from "@portal/components/procurement/useProcurement";-import type { QuoteResult } from "@portal/api/procurement";+} from "@app/portal/components/procurement/useProcurement";+import { SaasSessionRequiredError } from "@app/portal/auth/portalSaasSession";+import type { QuoteResult } from "@app/portal/api/procurement";const SNAPSHOT = {dealId: 1,@@ -135,3 +136,26 @@ describe("useProcurement", () => {expect(ctl.error).toBeNull();});});++it("does not compete with session recovery when the procurement read needs sign-in", async () => {+ fetchSnapshot.mockRejectedValue(new SaasSessionRequiredError());+ mount();+ await waitFor(() => expect(ctl.loading).toBe(false));+ expect(ctl.loadError).toBeNull();+});+it("closes the purchase dialog on expired authorization without replaying the mutation", async () => {+ mount();+ await waitFor(() => expect(ctl.started).toBe(true));+ act(() => {+ ctl.setOpen(true);+ ctl.setExtra("setup");+ });+ startAgreement.mockRejectedValue(new SaasSessionRequiredError());+ await act(async () => {+ await ctl.onAcceptQuote();+ });+ expect(ctl.open).toBe(false);+ expect(ctl.extra).toBeNull();+ expect(ctl.error).toBeNull();+ expect(startAgreement).toHaveBeenCalledOnce();+});diff --git a/frontend/editor/src/portal/components/procurement/useProcurement.ts b/frontend/editor/src/portal/components/procurement/useProcurement.tsindex 583d55401b..5c1b215404 100644--- a/frontend/editor/src/portal/components/procurement/useProcurement.ts+++ b/frontend/editor/src/portal/components/procurement/useProcurement.ts@@ -1,9 +1,10 @@+import { SaasSessionRequiredError } from "@app/portal/auth/portalSaasSession";import { useState } from "react";import { useTranslation } from "react-i18next";import { useQuery, useQueryClient } from "@tanstack/react-query";-import { usePortalLinked } from "@portal/contexts/usePortalLinked";-import { qk } from "@portal/queries/keys";-import { toAsyncState } from "@portal/queries/adapters";+import { usePortalLinked } from "@app/portal/contexts/usePortalLinked";+import { qk } from "@app/portal/queries/keys";+import { toAsyncState } from "@app/portal/queries/adapters";import {acceptQuote,extendTrial,@@ -19,7 +20,7 @@ import {type ProcurementSnapshot,type QuoteResult,type TrialSetupDetails,-} from "@portal/api/procurement";+} from "@app/portal/api/procurement";export type ProcurementExtra =| null@@ -122,6 +123,17 @@ export function useProcurement(): ProcurementController {!latest ||["draft", "expired", "canceled", "cancelled"].includes(latest.status);+ function reportError(cause: unknown, message: string) {+ if (cause instanceof SaasSessionRequiredError) {+ // Recovery is in the billing shell; keep unfinished purchases for an explicit retry.+ setOpen(false);+ setExtra(null);+ setError(null);+ } else {+ setError(message);+ }+ }+/*** Run a deal action, then refresh the snapshot so every reader sees the new stage.*@@ -146,7 +158,7 @@ export function useProcurement(): ProcurementController {return true;} catch (e) {console.error("[procurement] action failed", e);- setError(e instanceof Error ? e.message : String(e));+ reportError(e, e instanceof Error ? e.message : String(e));return false;} finally {setBusy(false);@@ -160,9 +172,10 @@ export function useProcurement(): ProcurementController {setExtra("setup");void recordInterest().then((snap) => queryClient.setQueryData(snapshotKey, snap))- .catch((e) =>- console.error("[procurement] recording interest failed", e),- );+ .catch((e) => {+ console.error("[procurement] recording interest failed", e);+ if (e instanceof SaasSessionRequiredError) reportError(e, e.message);+ });};const onConfirmSetup = (deployment: string,@@ -232,7 +245,7 @@ export function useProcurement(): ProcurementController {setTimeout(() => URL.revokeObjectURL(url), 60_000);} catch (e) {console.error("[procurement] quote PDF download failed", e);- setError(t("portal.procurement.milestone.downloadError"));+ reportError(e, t("portal.procurement.milestone.downloadError"));} finally {setDownloading(false);}@@ -253,7 +266,7 @@ export function useProcurement(): ProcurementController {setTimeout(() => URL.revokeObjectURL(url), 60_000);} catch (e) {console.error("[procurement] offline licence download failed", e);- setError(t("portal.procurement.license.downloadError"));+ reportError(e, t("portal.procurement.license.downloadError"));} finally {setDownloadingLicense(false);}@@ -273,7 +286,7 @@ export function useProcurement(): ProcurementController {setTimeout(() => URL.revokeObjectURL(url), 60_000);} catch (e) {console.error("[procurement] signed agreement download failed", e);- setError(t("portal.procurement.agreement.downloadError"));+ reportError(e, t("portal.procurement.agreement.downloadError"));} finally {setDownloadingAgreement(false);}@@ -282,11 +295,12 @@ export function useProcurement(): ProcurementController {return {isLinked,loading: state.loading,- loadError: state.error- ? state.error instanceof Error- ? state.error.message- : String(state.error)- : null,+ loadError:+ state.error && !(state.error instanceof SaasSessionRequiredError)+ ? state.error instanceof Error+ ? state.error.message+ : String(state.error)+ : null,retry: () => {void query.refetch();},diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsxindex a9316444da..477c248adf 100644--- a/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsx+++ b/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsx@@ -1,23 +1,12 @@import type { ReactNode } from "react";-import { LinkProvider } from "@portal/contexts/LinkContext";-import { TierProvider } from "@portal/contexts/TierContext";-import { UIProvider, useUI } from "@portal/contexts/UIContext";-import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";-import { LinkAccountModal } from "@portal/components/account-link/LinkAccountModal";--function LinkModalHost() {- const { linkModalOpen, linkModalMode, closeLinkModal, connectOutcome } =- useUI();- if (!linkModalOpen) return null;- return (- <LinkAccountModal- open- mode={linkModalMode}- onClose={closeLinkModal}- outcome={connectOutcome}- />- );-}+import { LinkProvider } from "@app/portal/contexts/LinkContext";+import { TierProvider } from "@app/portal/contexts/TierContext";+import { UIProvider } from "@app/portal/contexts/UIContext";+import { AccountLinkProvider } from "@app/portal/contexts/AccountLinkContext";+import { AccountLinkSessionBoundary } from "@app/portal/components/account-link/AccountLinkSessionBoundary";+import { ConnectCallbackHost } from "@app/portal/components/account-link/ConnectCallbackHost";+import { AccountConnectionRefresh } from "@app/portal/components/account-link/AccountConnectionNotice";+import { LinkAccountModalHost } from "@app/portal/components/account-link/LinkAccountModal";/** The instance link starts unknown; checkout and license are inherited from AppProviders. */export function PortalSettingsProviders({ children }: { children: ReactNode }) {@@ -25,10 +14,14 @@ export function PortalSettingsProviders({ children }: { children: ReactNode }) {<LinkProvider initialState="unlinked" statusKnown={false}><TierProvider><UIProvider>- <AccountLinkProvider>- {children}- <LinkModalHost />- </AccountLinkProvider>+ <AccountLinkSessionBoundary>+ <AccountLinkProvider>+ <AccountConnectionRefresh />+ {children}+ <LinkAccountModalHost />+ <ConnectCallbackHost />+ </AccountLinkProvider>+ </AccountLinkSessionBoundary></UIProvider></TierProvider></LinkProvider>diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsxindex ec06b02bea..0367e8ff5e 100644--- a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx+++ b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx@@ -1,15 +1,34 @@+import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";import { render, screen } from "@testing-library/react";-import { PortalSettingsSectionHost } from "@portal/components/settings/PortalSettingsSectionHost";-import { useLinkOptional } from "@portal/contexts/LinkContext";+import { PortalSettingsSectionHost } from "@app/portal/components/settings/PortalSettingsSectionHost";+import { useLinkOptional } from "@app/portal/contexts/LinkContext";++vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({+ useAccountLinkOwner: () => true,+}));const { fetchStatus } = vi.hoisted(() => ({ fetchStatus: vi.fn() }));-vi.mock("@portal/api/link", () => ({ fetchStatus }));-vi.mock("@portal/auth/saasSupabase", () => ({+vi.mock("@app/portal/api/link", () => ({ fetchStatus }));+vi.mock("@app/portal/auth/saasSupabase", () => ({isSaasSupabaseConfigured: true,}));-vi.mock("@portal/components/account-link/LinkAccountModal", () => ({- LinkAccountModal: () => null,+vi.mock("@app/portal/components/account-link/LinkAccountModal", () => ({+ LinkAccountModalHost: () => null,+}));++vi.mock(+ "@app/portal/components/account-link/AccountLinkSessionBoundary",+ () => ({+ AccountLinkSessionBoundary: ({ children }: { children: ReactNode }) =>+ children,+ }),+);+vi.mock("@app/portal/components/account-link/SaasSessionBanner", () => ({+ SaasSessionBanner: () => null,+}));+vi.mock("@app/portal/components/account-link/ConnectCallbackHost", () => ({+ ConnectCallbackHost: () => null,}));function LinkState() {diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsxindex 49534e087e..c532afbe9d 100644--- a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsx+++ b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsx@@ -1,10 +1,10 @@import { type ReactNode } from "react";import { QueryClientProvider } from "@tanstack/react-query";-import { getPortalQueryClient } from "@portal/queryClient";-import { PortalSettingsProviders } from "@portal/components/settings/PortalSettingsProviders";-import { ErrorBoundary } from "@portal/components/ErrorBoundary";-import "@portal/theme/base.css";-import "@portal/components/settings/PortalSettingsSectionHost.css";+import { getPortalQueryClient } from "@app/portal/queryClient";+import { PortalSettingsProviders } from "@app/portal/components/settings/PortalSettingsProviders";+import { ErrorBoundary } from "@app/portal/components/ErrorBoundary";+import "@app/portal/theme/base.css";+import "@app/portal/components/settings/PortalSettingsSectionHost.css";/*** Runs a portal-authored view inside the settings page. Those views are writtendiff --git a/frontend/editor/src/portal/contexts/UIContext.test.tsx b/frontend/editor/src/portal/contexts/UIContext.test.tsxindex 61fa11631c..b832a0ec79 100644--- a/frontend/editor/src/portal/contexts/UIContext.test.tsx+++ b/frontend/editor/src/portal/contexts/UIContext.test.tsx@@ -1,6 +1,6 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import { act, render } from "@testing-library/react";-import { UIProvider, useUI } from "@portal/contexts/UIContext";+import { UIProvider, useUI } from "@app/portal/contexts/UIContext";/*** The context value is memoised, so every piece of state it exposes has to appear in the memo's@@ -45,3 +45,28 @@ describe("UIContext — the trial-setup signal reaches consumers", () => {expect(p.api.trialSetupRequested).toBe(false);});});++it("does not replace an active renewal with concurrent exhausted-credit prompts", () => {+ const p = probe();+ act(() => {+ p.api.openLinkModal("reauth");+ p.api.openLinkModal("exhausted");+ });+ expect(p.api.linkModalMode).toBe("reauth");+ const cancel = vi.fn();+ act(() =>+ p.api.publishConnectOutcome({+ mode: "reauth",+ state: "working",+ sessionRestored: false,+ cancel,+ }),+ );+ act(() => p.api.openLinkModal("exhausted"));+ expect(p.api.connectOutcome?.state).toBe("working");+ act(() => p.api.closeLinkModal());+ expect(cancel).toHaveBeenCalledOnce();+ act(() => p.api.openLinkModal("link"));+ expect(p.api.linkModalMode).toBe("link");+ expect(p.api.connectOutcome).toBeNull();+});diff --git a/frontend/editor/src/portal/contexts/UIContext.tsx b/frontend/editor/src/portal/contexts/UIContext.tsxindex 354afaa6ff..ded6de8df2 100644--- a/frontend/editor/src/portal/contexts/UIContext.tsx+++ b/frontend/editor/src/portal/contexts/UIContext.tsx@@ -2,12 +2,14 @@ import {createContext,useContext,useMemo,+ useRef,useState,type ReactNode,} from "react";import { navigateToSettings } from "@app/utils/settingsNavigation";import type { NavKey } from "@app/components/shared/config/types";-import type { ConnectOutcome } from "@portal/components/account-link/ConnectCallbackView";+import type { ConnectOutcome } from "@app/portal/components/account-link/ConnectCallbackView";+import { clearPendingConnect } from "@app/portal/auth/pendingConnect";/*** Why the dialog is open. All three run the same handshake; the mode only chooses the pitch.@@ -83,6 +85,7 @@ export function UIProvider({ children }: { children: ReactNode }) {const [sidebarCollapsed, setSidebarCollapsed] =useState(readSidebarCollapsed);const [assistantOpen, setAssistantOpen] = useState(false);+ const linkModalActive = useRef(false);const [linkModalOpen, setLinkModalOpen] = useState(false);const [trialSetupRequested, setTrialSetupRequested] = useState(false);const [linkModalMode, setLinkModalMode] = useState<LinkModalMode>("link");@@ -119,8 +122,12 @@ export function UIProvider({ children }: { children: ReactNode }) {linkModalOpen,linkModalMode,openLinkModal: (mode: LinkModalMode = "link") => {+ // Background failures must not replace a handoff or callback already in progress.+ if (linkModalActive.current) return;+ linkModalActive.current = true;setMobileNavOpen(false);setLinkModalMode(mode);+ setConnectOutcome(null);setLinkModalOpen(true);},trialSetupRequested,@@ -131,13 +138,17 @@ export function UIProvider({ children }: { children: ReactNode }) {clearTrialSetupRequest: () => setTrialSetupRequested(false),connectOutcome,publishConnectOutcome: (outcome: ConnectOutcome) => {+ linkModalActive.current = true;setMobileNavOpen(false);setConnectOutcome(outcome);- setLinkModalMode("link");+ setLinkModalMode(outcome.mode ?? "link");setLinkModalOpen(true);},clearConnectOutcome: () => setConnectOutcome(null),closeLinkModal: () => {+ linkModalActive.current = false;+ connectOutcome?.cancel?.();+ clearPendingConnect();setLinkModalOpen(false);setLinkModalMode("link");// A reopen from a CTA is a fresh flow, not a handshake already dismissed.diff --git a/frontend/editor/src/portal/hooks/useAccountLink.test.ts b/frontend/editor/src/portal/hooks/useAccountLink.test.tsnew file mode 100644index 0000000000..d545ee86a6--- /dev/null+++ b/frontend/editor/src/portal/hooks/useAccountLink.test.ts@@ -0,0 +1,113 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({+ fetchStatus: vi.fn(),+ isOwner: true,+ unlinkInstance: vi.fn(),+ clearAccountLinkSession: vi.fn(),+ applyLinkFacts: vi.fn(),+ markStatusKnown: vi.fn(),+}));+vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({+ useAccountLinkOwner: () => mocks.isOwner,+}));+vi.mock("@app/portal/api/link", () => ({+ fetchStatus: mocks.fetchStatus,+ unlinkInstance: mocks.unlinkInstance,+}));+vi.mock("@app/portal/auth/saasSupabase", () => ({+ isSaasSupabaseConfigured: true,+}));+vi.mock("@app/portal/auth/accountLinkSession", () => ({+ clearAccountLinkSession: mocks.clearAccountLinkSession,+}));+vi.mock("@app/portal/contexts/LinkContext", () => ({+ useApplyLinkFacts: () => mocks.applyLinkFacts,+ useLink: () => ({ markStatusKnown: mocks.markStatusKnown }),+}));+import { useAccountLink } from "@app/portal/hooks/useAccountLink";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.isOwner = true;+ mocks.fetchStatus.mockResolvedValue({ linked: true, name: "QA" });+ mocks.unlinkInstance.mockResolvedValue(undefined);+});+it("clears browser authorization only after the server confirms unlinking", async () => {+ const { result } = renderHook(() => useAccountLink());+ await waitFor(() => expect(result.current.status?.linked).toBe(true));+ await act(async () => {+ await result.current.unlink();+ });+ expect(mocks.unlinkInstance).toHaveBeenCalledOnce();+ expect(mocks.clearAccountLinkSession).toHaveBeenCalledOnce();+ expect(result.current.status?.linked).toBe(false);+ expect(mocks.applyLinkFacts).toHaveBeenLastCalledWith(false, false);+});+it("retains browser authorization if unlinking fails", async () => {+ mocks.unlinkInstance.mockRejectedValue(new Error("offline"));+ const { result } = renderHook(() => useAccountLink());+ await waitFor(() => expect(result.current.status?.linked).toBe(true));+ await act(async () => {+ await result.current.unlink();+ });+ expect(mocks.clearAccountLinkSession).not.toHaveBeenCalled();+ expect(result.current.status?.linked).toBe(true);+ expect(result.current.error).toBe("offline");+});++it("makes no account-link requests for a non-owner, even when refresh or unlink is called", async () => {+ mocks.isOwner = false;+ const { result } = renderHook(() => useAccountLink());+ await act(async () => {+ await result.current.refresh();+ await result.current.unlink();+ });+ expect(mocks.fetchStatus).not.toHaveBeenCalled();+ expect(mocks.unlinkInstance).not.toHaveBeenCalled();+ expect(mocks.clearAccountLinkSession).not.toHaveBeenCalled();+});++afterEach(() => vi.useRealTimers());++it("polls without downgrading a known subscription and stops when ownership changes", async () => {+ vi.useFakeTimers();+ const { result, rerender } = renderHook(() => useAccountLink());+ await act(async () => {+ await Promise.resolve();+ });+ expect(mocks.applyLinkFacts).toHaveBeenCalledOnce();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(mocks.fetchStatus).toHaveBeenCalledTimes(2);+ expect(mocks.applyLinkFacts).toHaveBeenCalledOnce();+ await act(async () => {+ await result.current.refresh(true);+ });+ expect(mocks.fetchStatus).toHaveBeenLastCalledWith(true);+ mocks.isOwner = false;+ rerender();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(mocks.fetchStatus).toHaveBeenCalledTimes(3);+ expect(result.current.status).toBeNull();+});++it("discards a pending status response after ownership is lost", async () => {+ let resolve!: (value: { linked: boolean }) => void;+ mocks.fetchStatus.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const { result, rerender } = renderHook(() => useAccountLink());+ mocks.isOwner = false;+ rerender();+ await act(async () => {+ resolve({ linked: true });+ });+ expect(result.current.status).toBeNull();+ expect(mocks.applyLinkFacts).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/portal/hooks/useAccountLink.ts b/frontend/editor/src/portal/hooks/useAccountLink.tsindex 917f6fec20..a68b931e66 100644--- a/frontend/editor/src/portal/hooks/useAccountLink.ts+++ b/frontend/editor/src/portal/hooks/useAccountLink.ts@@ -1,8 +1,14 @@import { useCallback, useEffect, useState, useRef } from "react";-import { errorMessage } from "@portal/api/http";-import { isSaasSupabaseConfigured } from "@portal/auth/saasSupabase";-import { fetchStatus, unlinkInstance, type LinkStatus } from "@portal/api/link";-import { useApplyLinkFacts, useLink } from "@portal/contexts/LinkContext";+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import { errorMessage } from "@app/portal/api/http";+import { isSaasSupabaseConfigured } from "@app/portal/auth/saasSupabase";+import {+ fetchStatus,+ unlinkInstance,+ type LinkStatus,+} from "@app/portal/api/link";+import { useApplyLinkFacts, useLink } from "@app/portal/contexts/LinkContext";+import { clearAccountLinkSession } from "@app/portal/auth/accountLinkSession";/** Reads and clears THIS instance's link status. */@@ -24,6 +30,7 @@ export interface UseAccountLink {}export function useAccountLink(): UseAccountLink {+ const isOwner = useAccountLinkOwner();const applyLinkFacts = useApplyLinkFacts();const { markStatusKnown } = useLink();const [status, setStatus] = useState<LinkStatus | null>(null);@@ -32,11 +39,19 @@ export function useAccountLink(): UseAccountLink {const [error, setError] = useState<string | null>(null);const previousLinked = useRef<boolean | null>(null);+ const statusRequest = useRef(0);const refresh = useCallback(async (force = false) => {+ const request = ++statusRequest.current;setStatusError(null);+ if (!isOwner) {+ setStatus(null);+ previousLinked.current = null;+ return;+ }try {const s = await fetchStatus(force);+ if (request !== statusRequest.current) return;setStatus(s);// A linked instance is at least linked-free; subscription comes from the wallet.if (s.linked && previousLinked.current !== true)@@ -45,23 +60,30 @@ export function useAccountLink(): UseAccountLink {// Success only: marking this in the catch would read "could not ask" as "not linked".markStatusKnown();} catch (e) {- setStatusError(errorMessage(e));+ if (request === statusRequest.current) setStatusError(errorMessage(e));}},- [applyLinkFacts, markStatusKnown],+ [applyLinkFacts, markStatusKnown, isOwner],);useEffect(() => {void refresh();+ if (!isOwner) return;const timer = window.setInterval(() => void refresh(), 60_000);- return () => window.clearInterval(timer);- }, [refresh]);+ return () => {+ window.clearInterval(timer);+ statusRequest.current++;+ };+ }, [refresh, isOwner]);const unlink = useCallback(async () => {+ if (!isOwner) return;setPhase("linking");setError(null);try {await unlinkInstance();+ clearAccountLinkSession();+ statusRequest.current++;setStatus({ linked: false, name: null });previousLinked.current = false;setPhase("idle");@@ -70,7 +92,7 @@ export function useAccountLink(): UseAccountLink {setError(e instanceof Error ? e.message : String(e));setPhase("error");}- }, [applyLinkFacts]);+ }, [applyLinkFacts, isOwner]);return {loginConfigured: isSaasSupabaseConfigured,diff --git a/frontend/editor/src/portal/hooks/useAccountLinkOwner.test.ts b/frontend/editor/src/portal/hooks/useAccountLinkOwner.test.tsnew file mode 100644index 0000000000..a35cc054be--- /dev/null+++ b/frontend/editor/src/portal/hooks/useAccountLinkOwner.test.ts@@ -0,0 +1,34 @@+import { renderHook } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";++const auth = vi.hoisted(() => ({+ isAdmin: true,+ loading: false,+ user: { orgOwner: true as boolean | undefined },+}));+vi.mock("@app/auth", () => ({ useAuth: () => auth }));+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";++beforeEach(() => {+ auth.isAdmin = true;+ auth.loading = false;+ auth.user.orgOwner = true;+});+it("allows the authenticated organization owner", () => {+ expect(renderHook(() => useAccountLinkOwner()).result.current).toBe(true);+});+it.each([false, undefined])(+ "does not treat an admin as the owner when ownership is %s",+ (orgOwner) => {+ auth.user.orgOwner = orgOwner;+ expect(renderHook(() => useAccountLinkOwner()).result.current).toBe(false);+ },+);+it("does not trust an ownership flag without the admin role", () => {+ auth.isAdmin = false;+ expect(renderHook(() => useAccountLinkOwner()).result.current).toBe(false);+});+it("waits for authentication before exposing billing actions", () => {+ auth.loading = true;+ expect(renderHook(() => useAccountLinkOwner()).result.current).toBe(false);+});diff --git a/frontend/editor/src/portal/hooks/useAccountLinkOwner.ts b/frontend/editor/src/portal/hooks/useAccountLinkOwner.tsnew file mode 100644index 0000000000..bdd53b7bf8--- /dev/null+++ b/frontend/editor/src/portal/hooks/useAccountLinkOwner.ts@@ -0,0 +1,6 @@+import { useAuth } from "@app/auth";++export function useAccountLinkOwner(): boolean {+ const { user, isAdmin, loading } = useAuth();+ return !loading && isAdmin && user?.orgOwner === true;+}diff --git a/frontend/editor/src/portal/hooks/useConnectHandoff.ts b/frontend/editor/src/portal/hooks/useConnectHandoff.tsindex 1b1da16a07..7bf0900775 100644--- a/frontend/editor/src/portal/hooks/useConnectHandoff.ts+++ b/frontend/editor/src/portal/hooks/useConnectHandoff.ts@@ -1,7 +1,9 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import { useLocation } from "react-router-dom";import { withBasePath } from "@app/constants/app";-import { startConnect, startReauth } from "@portal/api/link";+import { startConnect, startReauth } from "@app/portal/api/link";+import { rememberConnect } from "@app/portal/auth/pendingConnect";interface ConnectHandoff {/** Stays true through a successful hand-off: the page is leaving, so nothing resolves. */@@ -12,27 +14,47 @@ interface ConnectHandoff {export function useConnectHandoff(reauth: boolean): ConnectHandoff {const { t } = useTranslation();+ const location = useLocation();const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ const mounted = useRef(false);+ const inFlight = useRef(false);useEffect(() => {+ mounted.current = true;// Back from Stirling can restore this page with its heap intact, leaving busy stuck on and the// dialog pinned to the ghost step. Being shown at all means we are not mid-navigation.- const shown = () => setBusy(false);+ const shown = () => {+ inFlight.current = false;+ setBusy(false);+ };window.addEventListener("pageshow", shown);- return () => window.removeEventListener("pageshow", shown);+ return () => {+ mounted.current = false;+ window.removeEventListener("pageshow", shown);+ };}, []);const begin = useCallback(() => {+ if (inFlight.current) return;+ inFlight.current = true;setBusy(true);setError(null);void (async () => {try {+ const ownerId = localStorage.getItem("stirling.portalSaasOwner");+ if (!ownerId) throw new Error("A local organization owner is required");// Stated, not inferred: only the frontend knows its own base path.- const callbackUrl = new URL(+ const browserState = Array.from(+ crypto.getRandomValues(new Uint8Array(32)),+ (byte) => byte.toString(16).padStart(2, "0"),+ ).join("");+ const callback = new URL(withBasePath("/account-link/callback"),window.location.origin,- ).toString();+ );+ callback.searchParams.set("state", browserState);+ const callbackUrl = callback.toString();const status = reauth? await startReauth(callbackUrl): await startConnect(@@ -41,7 +63,25 @@ export function useConnectHandoff(reauth: boolean): ConnectHandoff {.replace(/\/$/, ""),callbackUrl,);+ if (!mounted.current) return;+ if (status.phase === "CALLBACK_MISMATCH") {+ setError(+ t(+ "portal.accountLink.modal.callbackMismatch",+ "This server's configured frontend address does not match the address you opened. Open the server at its configured address, or update Frontend URL in General settings, then try again.",+ ),+ );+ setBusy(false);+ inFlight.current = false;+ return;+ }if (status.authorizeUrl) {+ rememberConnect({+ ownerId,+ mode: reauth ? "reauth" : "link",+ returnTo: `${location.pathname}${location.search}`,+ browserState,+ });window.location.assign(status.authorizeUrl);return;}@@ -53,7 +93,9 @@ export function useConnectHandoff(reauth: boolean): ConnectHandoff {),);setBusy(false);+ inFlight.current = false;} catch {+ if (!mounted.current) return;setError(t("portal.accountLink.modal.startFailed",@@ -61,9 +103,10 @@ export function useConnectHandoff(reauth: boolean): ConnectHandoff {),);setBusy(false);+ inFlight.current = false;}})();- }, [reauth, t]);+ }, [reauth, t, location.pathname, location.search]);return { busy, error, begin };}diff --git a/frontend/editor/src/portal/hooks/useFreeCreditsSummary.test.tsx b/frontend/editor/src/portal/hooks/useFreeCreditsSummary.test.tsxindex 9fa47c2a03..f227fad796 100644--- a/frontend/editor/src/portal/hooks/useFreeCreditsSummary.test.tsx+++ b/frontend/editor/src/portal/hooks/useFreeCreditsSummary.test.tsx@@ -1,11 +1,15 @@import { describe, expect, it, vi, beforeEach } from "vitest";import { cleanup, render, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { LinkProvider, type LinkState } from "@portal/contexts/LinkContext";-import { useFreeCreditsSummary } from "@portal/hooks/useFreeCreditsSummary";+import { LinkProvider, type LinkState } from "@app/portal/contexts/LinkContext";+import { useFreeCreditsSummary } from "@app/portal/hooks/useFreeCreditsSummary";+const ownership = vi.hoisted(() => ({ isOwner: true }));+vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({+ useAccountLinkOwner: () => ownership.isOwner,+}));const fetchWallet = vi.fn();-vi.mock("@portal/api/billing", () => ({+vi.mock("@app/portal/api/billing", () => ({fetchWallet: () => fetchWallet(),}));@@ -18,10 +22,12 @@ function Probe() {);}-function renderFor(initialState: LinkState) {- const client = new QueryClient({- defaultOptions: { queries: { retry: false } },- });+function renderFor(initialState: LinkState, queryClient?: QueryClient) {+ const client =+ queryClient ??+ new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });return render(<QueryClientProvider client={client}><LinkProvider initialState={initialState}>@@ -35,6 +41,7 @@ describe("useFreeCreditsSummary (self-hosted) — wallet behind the link gate",beforeEach(() => {// The figures persist across mounts now, so isolate the suite from itself.localStorage.clear();+ ownership.isOwner = true;fetchWallet.mockReset();fetchWallet.mockResolvedValue({status: "free",@@ -55,23 +62,30 @@ describe("useFreeCreditsSummary (self-hosted) — wallet behind the link gate",});it("hides the meter once the team subscribes", async () => {- // A paying team's headline number is spend against its cap, so a paying team- // would otherwise sit on a spent meter forever.+ const previous = renderFor("linked-free");+ await waitFor(() => expect(previous.textContent).toBe("247/500"));+ cleanup();fetchWallet.mockResolvedValue({status: "subscribed",freeRemaining: 0,freeAllowance: 500,});const el = renderFor("linked-subscribed");- // The row holds its space while the wallet loads, then drops once the- // answer says this team is paying.+ expect(el.textContent).toBe("247/500");await waitFor(() => expect(el.textContent).toBe("none"));});it("hides the meter when the wallet read fails", async () => {fetchWallet.mockRejectedValue(new Error("saas unreachable"));- const el = renderFor("linked-subscribed");- await waitFor(() => expect(el.textContent).toBe("none"));+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const el = renderFor("linked-subscribed", client);+ await waitFor(() =>+ expect(client.getQueryCache().getAll()[0]?.state.status).toBe("error"),+ );+ expect(fetchWallet).toHaveBeenCalledOnce();+ expect(el.textContent).toBe("none");});it("ignores cached figures once the instance is unlinked", async () => {@@ -87,6 +101,16 @@ describe("useFreeCreditsSummary (self-hosted) — wallet behind the link gate",expect(fetchWallet).not.toHaveBeenCalled();});+ it("hides cached owner figures and makes no wallet call for a non-owner", async () => {+ const owner = renderFor("linked-free");+ await waitFor(() => expect(owner.textContent).toBe("247/500"));+ cleanup();+ ownership.isOwner = false;+ fetchWallet.mockClear();+ expect(renderFor("linked-free").textContent).toBe("none");+ expect(fetchWallet).not.toHaveBeenCalled();+ });+it("shows the last known figures while the wallet reloads", async () => {// What stops the row popping in — and resizing the footer — every time the// processor mounts.diff --git a/frontend/editor/src/portal/hooks/useFreeCreditsSummary.ts b/frontend/editor/src/portal/hooks/useFreeCreditsSummary.tsindex ca7b9e50b6..b66128dd80 100644--- a/frontend/editor/src/portal/hooks/useFreeCreditsSummary.ts+++ b/frontend/editor/src/portal/hooks/useFreeCreditsSummary.ts@@ -1,8 +1,9 @@+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";import { useEffect, useState } from "react";import { useQuery } from "@tanstack/react-query";-import { useLink } from "@portal/contexts/LinkContext";-import { fetchWallet } from "@portal/api/billing";-import { qk } from "@portal/queries/keys";+import { useLink } from "@app/portal/contexts/LinkContext";+import { fetchWallet } from "@app/portal/api/billing";+import { qk } from "@app/portal/queries/keys";import {readCachedCredits,writeCachedCredits,@@ -31,12 +32,14 @@ import { type NavFooterCredits } from "@app/components/shared/navFooter/NavFoote*/export function useFreeCreditsSummary(): NavFooterCredits | null {const { isLinked } = useLink();+ const isOwner = useAccountLinkOwner();+ const canRead = isLinked && isOwner;// Shared query key, so the footer rides the same cached snapshot as any other// wallet reader rather than adding a fetch per mount.const { data: wallet } = useQuery({queryKey: qk.wallet(isLinked),queryFn: fetchWallet,- enabled: isLinked,+ enabled: canRead,});// Shared with the editor's seam, so crossing between the two apps shows the// figures the other one last saw rather than re-fetching into an empty row.@@ -51,14 +54,14 @@ export function useFreeCreditsSummary(): NavFooterCredits | null {useEffect(() => {// Only once linked: an unlinked instance never asks, so it has no answer of// its own and must not overwrite what the editor recorded.- if (isLinked && live !== undefined) writeCachedCredits(live);+ if (canRead && live !== undefined) writeCachedCredits(live);// eslint-disable-next-line react-hooks/exhaustive-deps- }, [wallet, isLinked]);+ }, [wallet, canRead]);// Linkage gates the seed as well as the fetch. The cache outlives an unlink// — nothing refetches or rewrites it once the instance stops asking — so// without this an unlinked instance would keep showing the figures from when// it was linked, indefinitely.- if (!isLinked) return null;+ if (!canRead) return null;return (live !== undefined ? live : seed) ?? null;}diff --git a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsxindex 4313736f92..692e2da091 100644--- a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx+++ b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx@@ -7,15 +7,22 @@ import { render } from "@testing-library/react";* grant spent — and it is raised from the real reporter here rather than a hand-fired event, so the* sentinel shape stays part of what this pins down.*/-const { openLinkModal } = vi.hoisted(() => ({ openLinkModal: vi.fn() }));+const { openLinkModal, flags } = vi.hoisted(() => ({+ openLinkModal: vi.fn(),+ flags: { isAdmin: true, isLinked: false, orgOwner: true },+}));+vi.mock("@app/auth", () => ({+ useAuth: () => ({ ...flags, user: { orgOwner: flags.orgOwner } }),+}));+vi.mock("@app/portal/contexts/LinkContext", () => ({ useLink: () => flags }));-vi.mock("@portal/contexts/UIContext", () => ({+vi.mock("@app/portal/contexts/UIContext", () => ({useUI: () => ({ openLinkModal }),}));-import { HttpError } from "@portal/api/http";-import { reportAccountLinkBlock } from "@portal/services/accountLinkBlock";-import { useFreeTierExhaustedPrompt } from "@portal/hooks/useFreeTierExhaustedPrompt";+import { HttpError } from "@app/portal/api/http";+import { reportAccountLinkBlock } from "@app/portal/services/accountLinkBlock";+import { useFreeTierExhaustedPrompt } from "@app/portal/hooks/useFreeTierExhaustedPrompt";function Probe() {useFreeTierExhaustedPrompt();@@ -29,7 +36,12 @@ const blocked = (reason: string) =>});describe("the account-link prompt", () => {- beforeEach(() => openLinkModal.mockReset());+ beforeEach(() => {+ openLinkModal.mockReset();+ flags.isAdmin = true;+ flags.orgOwner = true;+ flags.isLinked = false;+ });it("stays quiet on mount while the instance is unlinked", () => {render(<Probe />);@@ -42,6 +54,14 @@ describe("the account-link prompt", () => {expect(openLinkModal).toHaveBeenCalledWith("exhausted");});+ it("does not reopen for later responses from the same exhausted batch", () => {+ const view = render(<Probe />);+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ view.rerender(<Probe />);+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ expect(openLinkModal).toHaveBeenCalledOnce();+ });+it("leaves a linked team's own billing problems to their own surface", () => {render(<Probe />);reportAccountLinkBlock(blocked("OVER_LIMIT"));@@ -50,6 +70,17 @@ describe("the account-link prompt", () => {expect(openLinkModal).not.toHaveBeenCalled();});+ it.each(["non-owner", "already linked"])(+ "does not offer initial linking to %s",+ (state) => {+ flags.isAdmin = state !== "non-owner";+ flags.isLinked = state === "already linked";+ render(<Probe />);+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));+ expect(openLinkModal).not.toHaveBeenCalled();+ },+ );+it("ignores an unrelated failure", () => {render(<Probe />);reportAccountLinkBlock(new HttpError(403, "Forbidden", null));@@ -63,3 +94,13 @@ describe("the account-link prompt", () => {expect(openLinkModal).not.toHaveBeenCalled();});});++it("does not prompt an ordinary admin when the local allowance is exhausted", () => {+ flags.isAdmin = true;+ flags.orgOwner = false;+ flags.isLinked = false;+ openLinkModal.mockReset();+ render(<Probe />);+ window.dispatchEvent(new Event("stirling:portal-free-tier-exhausted"));+ expect(openLinkModal).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.tsindex a259589f9a..f4cd25863e 100644--- a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts+++ b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts@@ -1,6 +1,8 @@-import { useEffect } from "react";-import { useUI } from "@portal/contexts/UIContext";-import { FREE_TIER_EXHAUSTED_EVENT } from "@portal/services/accountLinkBlock";+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";+import { useLink } from "@app/portal/contexts/LinkContext";+import { useEffect, useRef } from "react";+import { useUI } from "@app/portal/contexts/UIContext";+import { FREE_TIER_EXHAUSTED_EVENT } from "@app/portal/services/accountLinkBlock";/*** Opens the account-link dialog on the "allowance spent" pitch when the instance reports a spent@@ -10,12 +12,19 @@ import { FREE_TIER_EXHAUSTED_EVENT } from "@portal/services/accountLinkBlock";* no React context to reach: same shape as the cloud build's usage-limit modals.*/export function useFreeTierExhaustedPrompt(): void {+ const prompted = useRef(false);+ const isOwner = useAccountLinkOwner();+ const { isLinked } = useLink();const { openLinkModal } = useUI();useEffect(() => {- const onExhausted = () => openLinkModal("exhausted");+ const onExhausted = () => {+ if (!isOwner || isLinked || prompted.current) return;+ prompted.current = true;+ openLinkModal("exhausted");+ };window.addEventListener(FREE_TIER_EXHAUSTED_EVENT, onExhausted);return () =>window.removeEventListener(FREE_TIER_EXHAUSTED_EVENT, onExhausted);- }, [openLinkModal]);+ }, [isOwner, isLinked, openLinkModal]);}diff --git a/frontend/editor/src/portal/hooks/useLinkedAccountEmail.test.ts b/frontend/editor/src/portal/hooks/useLinkedAccountEmail.test.tsindex 1adac2db84..269598d360 100644--- a/frontend/editor/src/portal/hooks/useLinkedAccountEmail.test.ts+++ b/frontend/editor/src/portal/hooks/useLinkedAccountEmail.test.ts@@ -8,7 +8,7 @@ const state = vi.hoisted(() => ({unsubscribe: vi.fn(),listener: null as ((event: string, session: EmailSession) => void) | null,}));-vi.mock("@portal/auth/saasSupabase", () => ({+vi.mock("@app/portal/auth/saasSupabase", () => ({ensureSaasSupabase: () =>state.configured? {@@ -27,10 +27,15 @@ vi.mock("@portal/auth/saasSupabase", () => ({: null,}));-import { useLinkedAccountEmail } from "@portal/hooks/useLinkedAccountEmail";+import { useLinkedAccountEmail } from "@app/portal/hooks/useLinkedAccountEmail";+import {+ portalSaasSessionRestored,+ resetPortalSaasSessionState,+} from "@app/portal/auth/portalSaasSession";describe("Current SaaS email", () => {beforeEach(() => {+ resetPortalSaasSessionState();state.configured = true;state.listener = null;state.unsubscribe.mockReset();@@ -70,6 +75,22 @@ describe("Current SaaS email", () => {expect(result.current).toBeNull();});+ it("rebinds after renewal and ignores the previous client's events", async () => {+ const { result, unmount } = renderHook(useLinkedAccountEmail);+ await waitFor(() => expect(result.current).toBe("[email protected]"));+ const previousListener = state.listener;+ state.getSession.mockResolvedValue({+ data: { session: { user: { email: "[email protected]" } } },+ });+ act(() => portalSaasSessionRestored());+ await waitFor(() => expect(result.current).toBe("[email protected]"));+ expect(state.unsubscribe).toHaveBeenCalledOnce();+ act(() => previousListener?.("SIGNED_OUT", null));+ expect(result.current).toBe("[email protected]");+ unmount();+ expect(state.unsubscribe).toHaveBeenCalledTimes(2);+ });+it("leaves the email unavailable if the session read fails", async () => {state.getSession.mockRejectedValue(new Error("Session unavailable"));const { result } = await act(async () => renderHook(useLinkedAccountEmail));diff --git a/frontend/editor/src/portal/hooks/useLinkedAccountEmail.ts b/frontend/editor/src/portal/hooks/useLinkedAccountEmail.tsindex 6a220fd2d2..86f9308091 100644--- a/frontend/editor/src/portal/hooks/useLinkedAccountEmail.ts+++ b/frontend/editor/src/portal/hooks/useLinkedAccountEmail.ts@@ -1,17 +1,19 @@import { useEffect, useState } from "react";-import { ensureSaasSupabase } from "@portal/auth/saasSupabase";+import { ensurePortalSessionClient } from "@app/portal/auth/sessionClient";+import { usePortalSaasSession } from "@app/portal/hooks/usePortalSaasSession";/*** Current browser SaaS identity, independent of the local server login or connection owner.* Null means no email is available. Tracks sign-in and sign-out without depending on LinkContext.*/export function useLinkedAccountEmail(): string | null {+ const { revision } = usePortalSaasSession();const [email, setEmail] = useState<string | null>(null);useEffect(() => {let cancelled = false;let sessionChanged = false;- const supabase = ensureSaasSupabase();+ const supabase = ensurePortalSessionClient();if (!supabase) {setEmail(null);return;@@ -35,7 +37,7 @@ export function useLinkedAccountEmail(): string | null {cancelled = true;subscription.unsubscribe();};- }, []);+ }, [revision]);return email;}diff --git a/frontend/editor/src/portal/hooks/useOpenPlan.ts b/frontend/editor/src/portal/hooks/useOpenPlan.tsindex 2cd4181382..e33f193180 100644--- a/frontend/editor/src/portal/hooks/useOpenPlan.ts+++ b/frontend/editor/src/portal/hooks/useOpenPlan.ts@@ -1,5 +1,6 @@+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";import { useCallback } from "react";-import { useUI } from "@portal/contexts/UIContext";+import { useUI } from "@app/portal/contexts/UIContext";/*** Self-hosted processor: settings carries no cloud Plan section, so the@@ -8,5 +9,7 @@ import { useUI } from "@portal/contexts/UIContext";*/export function useOpenPlan(): (() => void) | null {const { openSettings } = useUI();- return useCallback(() => openSettings("billing"), [openSettings]);+ const isOwner = useAccountLinkOwner();+ const open = useCallback(() => openSettings("billing"), [openSettings]);+ return isOwner ? open : null;}diff --git a/frontend/editor/src/portal/hooks/usePortalSaasSession.ts b/frontend/editor/src/portal/hooks/usePortalSaasSession.tsnew file mode 100644index 0000000000..6dd58a0ee2--- /dev/null+++ b/frontend/editor/src/portal/hooks/usePortalSaasSession.ts@@ -0,0 +1,13 @@+import { useSyncExternalStore } from "react";+import {+ getPortalSaasSessionState,+ subscribePortalSaasSession,+} from "@app/portal/auth/portalSaasSession";++/** Reactive browser authorization, independent of the instance's link status. */+export function usePortalSaasSession() {+ return useSyncExternalStore(+ subscribePortalSaasSession,+ getPortalSaasSessionState,+ );+}diff --git a/frontend/editor/src/portal/tsconfig.json b/frontend/editor/src/portal/tsconfig.jsonindex 64fef64f42..24db01389f 100644--- a/frontend/editor/src/portal/tsconfig.json+++ b/frontend/editor/src/portal/tsconfig.json@@ -7,6 +7,12 @@"../../src/proprietary/*","../../src/core/*"],+ "@app/portal/*": [+ "../../src/cloud/portal/*",+ "../../src/proprietary/portal/*",+ "../../src/core/portal/*",+ "../../src/portal/*"+ ],"@portal/*": ["../../src/portal/*"],"@cloud/*": ["../../src/cloud/*"],"@proprietary/*": ["../../src/proprietary/*"],diff --git a/frontend/editor/src/portal/views/ConnectCallback.test.tsx b/frontend/editor/src/portal/views/ConnectCallback.test.tsxindex b934e11cd7..272ea30f1e 100644--- a/frontend/editor/src/portal/views/ConnectCallback.test.tsx+++ b/frontend/editor/src/portal/views/ConnectCallback.test.tsx@@ -1,42 +1,85 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { PortalSettingsSectionHost } from "@app/portal/components/settings/PortalSettingsSectionHost";import { act, render, waitFor } from "@testing-library/react";-import { MemoryRouter, Route, Routes } from "react-router-dom";+import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";import { MantineProvider } from "@mantine/core";-import { UIProvider, useUI } from "@portal/contexts/UIContext";-import type { ConnectOutcome } from "@portal/components/account-link/ConnectCallbackView";+import { UIProvider, useUI } from "@app/portal/contexts/UIContext";+import type { ConnectOutcome } from "@app/portal/components/account-link/ConnectCallbackView";+import { rememberConnect } from "@app/portal/auth/pendingConnect";+import { AuthApiError } from "@supabase/supabase-js";/** A live session token rides in the fragment: strip it at once, refuse what cannot be verified. */-const { completeConnect, startConnect, setSession, refresh } = vi.hoisted(- () => ({- completeConnect: vi.fn(),- startConnect: vi.fn(),- setSession: vi.fn(),- refresh: vi.fn(),- }),-);+const { completeConnect, startConnect, setSession, refresh, client } =+ vi.hoisted(() => {+ const setSession = vi.fn();+ return {+ completeConnect: vi.fn(),+ startConnect: vi.fn(),+ setSession,+ client: { auth: { setSession } },+ refresh: vi.fn(),+ };+ });-vi.mock("@portal/api/link", () => ({ completeConnect, startConnect }));-vi.mock("@portal/auth/saasSupabase", () => ({- ensureSaasSupabase: () => ({ auth: { setSession } }),+vi.mock("@app/portal/api/link", () => ({ completeConnect, startConnect }));+vi.mock("@app/portal/auth/saasSupabase", () => ({+ ensureSaasSupabase: () => client,+}));+vi.mock("@app/auth/supabase/supabaseClient", () => ({+ getSupabaseClient: () => client,+ clearSupabaseSession: vi.fn(),}));-vi.mock("@portal/contexts/AccountLinkContext", () => ({+vi.mock("@app/portal/contexts/AccountLinkContext", () => ({+ AccountLinkProvider: ({ children }: { children: ReactNode }) => children,useAccountLinkContext: () => ({ refresh }),}));-import ConnectCallback from "@portal/views/ConnectCallback";-import { ConnectCallbackHost } from "@portal/components/account-link/ConnectCallbackHost";+const ownership = vi.hoisted(() => ({ orgOwner: true }));+vi.mock("@app/auth", () => ({+ useAuth: () => ({+ user: { id: "owner", orgOwner: ownership.orgOwner },+ isAdmin: true,+ loading: false,+ }),+}));+vi.mock("@app/portal/auth/accountLinkSession", () => ({+ bindAccountLinkSession: vi.fn(),+ clearAccountLinkSession: vi.fn(),+}));+vi.mock("@app/portal/components/account-link/AccountConnectionNotice", () => ({+ AccountConnectionRefresh: () => null,+ AccountConnectionNotice: () => null,+}));+vi.mock("@app/portal/components/account-link/SaasSessionBanner", () => ({+ SaasSessionBanner: () => null,+}));+vi.mock("@app/portal/components/account-link/LinkAccountModal", () => ({+ LinkAccountModalHost: () => null,+}));++import ConnectCallback from "@app/portal/views/ConnectCallback";+import { ConnectCallbackHost } from "@app/portal/components/account-link/ConnectCallbackHost";const NONCE = "the-nonce";function landOn(fragment: string) {- window.history.replaceState(null, "", `/account-link/callback${fragment}`);+ window.history.replaceState(+ null,+ "",+ `/account-link/callback?state=browser-state${fragment}`,+ );}/** Stands in for the dialog that consumes the outcome. */let published: ConnectOutcome[] = [];+let modalMode = "";+let routeState: unknown;function OutcomeSpy() {- const { connectOutcome } = useUI();+ const { connectOutcome, linkModalMode } = useUI();+ modalMode = linkModalMode;+ routeState = useLocation().state;if (connectOutcome &&published[published.length - 1]?.state !== connectOutcome.state@@ -62,6 +105,10 @@ function renderFlow() {element={<ConnectCallback />}/><Route path="/processor" element={<div data-testid="portal" />} />+ <Route+ path="/processor/usage"+ element={<div data-testid="usage" />}+ /></Routes></UIProvider></MemoryRouter>@@ -71,8 +118,17 @@ function renderFlow() {describe("account-link callback", () => {beforeEach(() => {+ ownership.orgOwner = true;vi.clearAllMocks();published = [];+ sessionStorage.clear();+ localStorage.setItem("stirling.portalSaasOwner", "owner");+ rememberConnect({+ ownerId: "owner",+ mode: "link",+ returnTo: "/processor",+ browserState: "browser-state",+ });completeConnect.mockResolvedValue({phase: "LINKED",authorizeUrl: null,@@ -82,6 +138,59 @@ describe("account-link callback", () => {setSession.mockResolvedValue({ error: null });});+ it.each(["/settings/billing", "/settings/account-link"])(+ "restores renewal through the settings host at %s",+ async (returnTo) => {+ rememberConnect({+ ownerId: "owner",+ mode: "reauth",+ returnTo,+ browserState: "browser-state",+ });+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);+ const screen = render(+ <MantineProvider>+ <MemoryRouter initialEntries={["/account-link/callback"]}>+ <Routes>+ <Route+ path="/account-link/callback"+ element={<ConnectCallback />}+ />+ <Route+ path={returnTo}+ element={+ <PortalSettingsSectionHost>+ <OutcomeSpy />+ <div data-testid="settings-destination" />+ </PortalSettingsSectionHost>+ }+ />+ </Routes>+ </MemoryRouter>+ </MantineProvider>,+ );+ await waitFor(() => expect(lastOutcome()?.state).toBe("linked"));+ expect(screen.getByTestId("settings-destination")).toBeTruthy();+ expect(modalMode).toBe("reauth");+ expect(setSession).toHaveBeenCalledWith({+ access_token: "at",+ refresh_token: "rt",+ });+ expect(routeState).toBeNull();+ },+ );++ it("discards a former owner's callback without installing a session or showing a modal", async () => {+ ownership.orgOwner = false;+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);+ renderFlow();+ await waitFor(() => expect(routeState).toBeNull());+ expect(window.location.hash).toBe("");+ expect(completeConnect).not.toHaveBeenCalled();+ expect(setSession).not.toHaveBeenCalled();+ expect(published).toEqual([]);+ });+it("removes the token-bearing fragment from the URL", async () => {landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);@@ -92,6 +201,33 @@ describe("account-link callback", () => {await waitFor(() => expect(completeConnect).toHaveBeenCalled());});+ it("rejects an approval started by a different local owner", async () => {+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);+ localStorage.setItem("stirling.portalSaasOwner", "different-owner");+ renderFlow();+ await waitFor(() => expect(lastOutcome()?.state).toBe("malformed"));+ expect(completeConnect).not.toHaveBeenCalled();+ expect(setSession).not.toHaveBeenCalled();+ });++ it("discards a callback when the dialog is dismissed during confirmation", async () => {+ let resolve!: (value: unknown) => void;+ completeConnect.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);+ renderFlow();+ await waitFor(() => expect(lastOutcome()?.state).toBe("working"));+ act(() => lastOutcome()?.cancel?.());+ await act(async () => {+ resolve({ phase: "LINKED" });+ });+ expect(setSession).not.toHaveBeenCalled();+ expect(lastOutcome()?.state).toBe("working");+ });+it("lands on the portal rather than leaving the result on a bare page", async () => {landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);@@ -108,11 +244,21 @@ describe("account-link callback", () => {await waitFor(() => expect(refresh).toHaveBeenCalled());});- it("deposits the session and then finishes the link with the nonce", async () => {+ it("waits for server acceptance before installing the browser session", async () => {+ let accept!: (value: { phase: string }) => void;+ completeConnect.mockReturnValueOnce(+ new Promise((resolve) => {+ accept = resolve;+ }),+ );landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);renderFlow();+ await waitFor(() => expect(lastOutcome()?.state).toBe("working"));+ expect(completeConnect).toHaveBeenCalledWith(NONCE);+ expect(setSession).not.toHaveBeenCalled();+ await act(async () => accept({ phase: "LINKED" }));await waitFor(() =>expect(setSession).toHaveBeenCalledWith({access_token: "at",@@ -120,16 +266,10 @@ describe("account-link callback", () => {}),);await waitFor(() => expect(completeConnect).toHaveBeenCalledWith(NONCE));- });-- it("finishes the link even when the session hand-off fails", async () => {- landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);- setSession.mockRejectedValue(new Error("nope"));-- renderFlow();-- // Independent outcomes: a failed sign-in must not strand the server unlinked.- await waitFor(() => expect(completeConnect).toHaveBeenCalledWith(NONCE));+ expect(completeConnect.mock.invocationCallOrder[0]).toBeLessThan(+ setSession.mock.invocationCallOrder[0],+ );+ expect(routeState).toBeNull();});it("links without a session when the fragment carries no tokens", async () => {@@ -137,7 +277,9 @@ describe("account-link callback", () => {renderFlow();- await waitFor(() => expect(completeConnect).toHaveBeenCalledWith(NONCE));+ await waitFor(() => expect(lastOutcome()?.state).toBe("linked"));+ expect(completeConnect).toHaveBeenCalledWith(NONCE);+ expect(lastOutcome()?.sessionRestored).toBe(false);expect(setSession).not.toHaveBeenCalled();});@@ -195,7 +337,9 @@ describe("account-link callback", () => {await waitFor(() => expect(completeConnect).toHaveBeenCalledTimes(1));await waitFor(() => expect(lastOutcome()?.state).toBe("retry"));- act(() => lastOutcome()!.reclaim!());+ await act(async () => {+ await lastOutcome()!.reclaim!();+ });// Re-claims rather than opening a new handshake, which would spend a leader's approval.await waitFor(() => expect(completeConnect).toHaveBeenCalledTimes(2));@@ -216,4 +360,85 @@ describe("account-link callback", () => {await waitFor(() => expect(lastOutcome()?.state).toBe("expired"));expect(lastOutcome()?.reclaim).toBeUndefined();});++ it.each(["REJECTED", "EXPIRED", "PENDING", "UNAVAILABLE"])(+ "does not install tokens for a %s handshake",+ async (phase) => {+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);+ completeConnect.mockResolvedValue({ phase });+ renderFlow();+ const outcome =+ phase === "REJECTED"+ ? "rejected"+ : phase === "EXPIRED"+ ? "expired"+ : "retry";+ await waitFor(() => expect(lastOutcome()?.state).toBe(outcome));+ expect(setSession).not.toHaveBeenCalled();+ },+ );++ it("rejects a callback from another browser or a cancelled flow", async () => {+ sessionStorage.clear();+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);+ renderFlow();+ await waitFor(() => expect(lastOutcome()?.state).toBe("malformed"));+ expect(setSession).not.toHaveBeenCalled();+ expect(completeConnect).not.toHaveBeenCalled();+ });++ it("preserves renewal mode and destination across the full callback", async () => {+ rememberConnect({+ mode: "reauth",+ ownerId: "owner",+ returnTo: "/processor/usage",+ browserState: "browser-state",+ });+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);+ const screen = renderFlow();+ await waitFor(() => expect(lastOutcome()?.state).toBe("linked"));+ expect(modalMode).toBe("reauth");+ expect(screen.getByTestId("usage")).toBeTruthy();+ });++ it("retries a failed session installation without consuming the handshake again", async () => {+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`);+ setSession+ .mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValue({ error: null });+ renderFlow();+ await waitFor(() => expect(lastOutcome()?.state).toBe("retry"));+ await act(async () => {+ await lastOutcome()!.reclaim!();+ });+ await waitFor(() => expect(lastOutcome()?.sessionRestored).toBe(true));+ expect(completeConnect).toHaveBeenCalledTimes(1);+ expect(setSession).toHaveBeenCalledTimes(2);+ });++ it("offers a fresh sign-in when callback credentials are permanently rejected", async () => {+ landOn(`#type=link&nonce=${NONCE}&access_token=at&refresh_token=revoked`);+ setSession.mockResolvedValue({+ error: new AuthApiError("revoked", 400, "refresh_token_not_found"),+ });+ renderFlow();+ await waitFor(() => expect(setSession).toHaveBeenCalledOnce());+ await waitFor(() => expect(lastOutcome()?.state).toBe("rejected"));+ expect(completeConnect).toHaveBeenCalledOnce();+ expect(lastOutcome()?.sessionRestored).toBe(false);+ expect(lastOutcome()?.reclaim).toBeUndefined();+ });++ it("refuses a callback with a mismatched tab correlator", async () => {+ window.history.replaceState(+ null,+ "",+ `/account-link/callback?state=wrong#type=link&nonce=${NONCE}&access_token=at&refresh_token=rt`,+ );+ renderFlow();+ await waitFor(() => expect(lastOutcome()?.state).toBe("malformed"));+ expect(completeConnect).not.toHaveBeenCalled();+ expect(setSession).not.toHaveBeenCalled();+ expect(window.location.hash).toBe("");+ });});diff --git a/frontend/editor/src/portal/views/ConnectCallback.tsx b/frontend/editor/src/portal/views/ConnectCallback.tsxindex 2fecd5244e..39891122a1 100644--- a/frontend/editor/src/portal/views/ConnectCallback.tsx+++ b/frontend/editor/src/portal/views/ConnectCallback.tsx@@ -1,7 +1,11 @@import { useEffect, useRef } from "react";import { useNavigate } from "react-router-dom";import { PORTAL_BASENAME } from "@app/routes/portalBasename";-import type { AccountLinkReturn } from "@portal/components/account-link/ConnectCallbackHost";+import type { AccountLinkReturn } from "@app/portal/components/account-link/ConnectCallbackHost";+import {+ readPendingConnect,+ clearPendingConnect,+} from "@app/portal/auth/pendingConnect";/*** Return leg of the account-link handshake. Stirling redirects here with the@@ -20,21 +24,27 @@ export default function ConnectCallback() {startedRef.current = true;const params = new URLSearchParams(window.location.hash.replace(/^#/, ""));- // Before anything else: the fragment carries a live session token.- window.history.replaceState(- null,- "",- `${window.location.pathname}${window.location.search}`,+ const pending = readPendingConnect();+ const browserState = new URLSearchParams(window.location.search).get(+ "state",);+ const matched = pending?.browserState === browserState ? pending : null;+ clearPendingConnect();+ // Before anything else: the fragment carries a live session token.+ window.history.replaceState(null, "", window.location.pathname);const accountLinkReturn: AccountLinkReturn = {type: params.get("type"),nonce: params.get("nonce"),accessToken: params.get("access_token"),refreshToken: params.get("refresh_token"),+ pending: matched,};// Router state, not the URL: the tokens are live and must not be re-shareable.- navigate(PORTAL_BASENAME, { replace: true, state: { accountLinkReturn } });+ navigate(matched?.returnTo ?? PORTAL_BASENAME, {+ replace: true,+ state: { accountLinkReturn },+ });}, [navigate]);return null;diff --git a/frontend/editor/src/portal/views/Home.tsx b/frontend/editor/src/portal/views/Home.tsxindex bd190e17e1..78adc9ed49 100644--- a/frontend/editor/src/portal/views/Home.tsx+++ b/frontend/editor/src/portal/views/Home.tsx@@ -13,7 +13,7 @@ export function Home() {return (<div className="portal-home">- {/* Paid tiers open with a greeting; free opens straight with the banner. */}+ {/* Paid tiers open with a greeting; free opens with local deployment status. */}{tier !== "free" && <HomeGreeting />}{/* Per-tier hero. Its footer is the deal-status hero while a procurementdiff --git a/frontend/editor/src/portal/views/Usage.test.tsx b/frontend/editor/src/portal/views/Usage.test.tsxindex f10f5b24b9..86d4b84d19 100644--- a/frontend/editor/src/portal/views/Usage.test.tsx+++ b/frontend/editor/src/portal/views/Usage.test.tsx@@ -1,14 +1,20 @@-vi.mock("@portal/queries/infrastructure", () => ({+vi.mock("@app/portal/queries/infrastructure", () => ({useFleetStats: () => ({ data: null, loading: false, error: null }),}));import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";import { MantineProvider } from "@mantine/core";import type { ReactElement } from "react";import { StrictMode } from "react";import { MemoryRouter, useLocation } from "react-router-dom";-import { UIProvider } from "@portal/contexts/UIContext";-import type { ProcurementSnapshot } from "@portal/api/procurement";+import { UIProvider } from "@app/portal/contexts/UIContext";+import type { ProcurementSnapshot } from "@app/portal/api/procurement";// Usage renders Mantine-backed @app/ui components (e.g. the "Manage Payment"// Button in the subscribed header), which need a MantineProvider in the tree.@@ -48,7 +54,7 @@ vi.mock("react-i18next", () => ({const fetchWallet = vi.fn();const refreshWalletCache = vi.fn();const bundleFlow = { status: "none", refresh: vi.fn() };-vi.mock("@portal/hooks/useBundleFlowState", () => ({+vi.mock("@app/portal/hooks/useBundleFlowState", () => ({useBundleFlowState: () => bundleFlow,}));const procurement = {@@ -64,42 +70,42 @@ const procurement = {onStartTrial: vi.fn(),setOpen: vi.fn(),};-vi.mock("@portal/components/procurement/useProcurement", () => ({+vi.mock("@app/portal/components/procurement/useProcurement", () => ({useProcurement: () => procurement,}));-vi.mock("@portal/components/procurement/ProcurementBanner", () => ({+vi.mock("@app/portal/components/procurement/ProcurementBanner", () => ({ControlledDealStatusHero: ({ readOnly }: { readOnly: boolean }) => (<div data-testid="procurement-summary">{readOnly ? "Read-only deal" : "Enterprise deal"}</div>),}));-vi.mock("@portal/components/procurement/ProcurementFlow", () => ({+vi.mock("@app/portal/components/procurement/ProcurementFlow", () => ({ProcurementFlow: () => <div data-testid="procurement-flow" />,}));-vi.mock("@portal/api/fleetStats", () => ({+vi.mock("@app/portal/api/fleetStats", () => ({fetchFleetStats: () => Promise.resolve(null),}));-vi.mock("@portal/api/users", () => ({+vi.mock("@app/portal/api/users", () => ({fetchAdminEmail: () => Promise.resolve(null),}));vi.mock("@app/contexts/CheckoutContext", () => ({useCheckoutOptional: () => null,}));-vi.mock("@portal/api/billing", () => ({+vi.mock("@app/portal/api/billing", () => ({fetchWallet: () => fetchWallet(),refreshWalletCache: () => refreshWalletCache(),}));const fetchLocalUsage = vi.fn().mockResolvedValue(null);-vi.mock("@portal/api/link", () => ({+vi.mock("@app/portal/api/link", () => ({fetchLocalUsage: () => fetchLocalUsage(),triggerLocalSync: () => Promise.resolve(),}));-vi.mock("@portal/hooks/useStripePortal", () => ({+vi.mock("@app/portal/hooks/useStripePortal", () => ({useStripePortal: () => ({ opening: false, open: vi.fn(), error: null }),}));// Stub the plan views so the test doesn't depend on the full wallet shape.-vi.mock("@portal/components/billing/FreePlanView", () => ({+vi.mock("@app/portal/components/billing/FreePlanView", () => ({FreePlanView: ({step,onActivationClosed,@@ -114,11 +120,24 @@ vi.mock("@portal/components/billing/FreePlanView", () => ({</div>) : null,}));-vi.mock("@portal/components/billing/SubscribedPlanView", () => ({+vi.mock("@app/portal/components/billing/SubscribedPlanView", () => ({SubscribedPlanView: () => null,}));-import { Usage } from "@portal/views/Usage";+import { Usage } from "@app/portal/views/Usage";+import {+ portalSaasSessionRestored,+ withPortalSaasSession,+ SaasSessionRequiredError,+ resetPortalSaasSessionState,+} from "@app/portal/auth/portalSaasSession";++vi.mock("@app/auth/supabase/supabaseClient", () => ({+ getSupabaseClient: () => null,+}));+vi.mock("@app/portal/auth/saasSupabase", () => ({+ ensureSaasSupabase: vi.fn(),+}));import { BillingScreen } from "@app/billing/BillingScreen";import { freeWallet } from "@app/billing/walletFixtures";@@ -142,6 +161,7 @@ describe("Usage — link-free wallet renderer", () => {});beforeEach(() => {+ resetPortalSaasSessionState();bundleFlow.status = "none";bundleFlow.refresh.mockReset();fetchWallet.mockReset();@@ -159,7 +179,12 @@ describe("Usage — link-free wallet renderer", () => {fetchWallet.mockResolvedValue(walletOf("free"));const onWalletLoaded = vi.fn();- renderUsage(<Usage onWalletLoaded={onWalletLoaded} />);+ renderUsage(+ <Usage+ onWalletLoaded={onWalletLoaded}+ sessionRecovery={<span>Renew billing access</span>}+ />,+ );// Renders immediately (no link prompt / login) and loads unconditionally.expect(screen.getByText("Usage & Billing")).toBeInTheDocument();@@ -368,6 +393,91 @@ describe("Usage — link-free wallet renderer", () => {screen.queryByRole("button", { name: "Plan" }),).not.toBeInTheDocument();});++ it("hides stale purchase controls when the billing session becomes unavailable", async () => {+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });+ renderUsage(<Usage sessionRecovery={<span>Renew billing access</span>} />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Switch on the Processor" }),+ );+ expect(screen.getByTestId("activation-step")).toBeInTheDocument();+ await act(async () => {+ await withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ ).catch(() => {});+ });+ expect(screen.queryByTestId("activation-step")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Switch on the Processor" }),+ ).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Plan" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Usage" })).toBeInTheDocument();+ });++ it("shows one recovery notice without a separate expired-session banner", async () => {+ fetchWallet.mockRejectedValue(new SaasSessionRequiredError());+ await act(async () => {+ renderUsage(+ <Usage sessionRecovery={<span>Renew billing access</span>} />,+ );+ });+ expect(screen.getAllByText("Renew billing access")).toHaveLength(1);+ expect(screen.getByText(/Your plan and usage will appear/)).toBeVisible();+ expect(screen.queryByText("Session expired")).not.toBeInTheDocument();+ });++ it("reloads billing after SDK recovery from another tab", async () => {+ await expect(+ withPortalSaasSession(+ async () => 401,+ (status) => status === 401,+ ),+ ).rejects.toBeInstanceOf(SaasSessionRequiredError);+ fetchWallet+ .mockRejectedValueOnce(new SaasSessionRequiredError())+ .mockRejectedValueOnce(new SaasSessionRequiredError())+ .mockResolvedValue(walletOf("free"));+ const onWalletLoaded = vi.fn();+ renderUsage(+ <Usage+ onWalletLoaded={onWalletLoaded}+ sessionRecovery={<span>Renew billing access</span>}+ />,+ );+ await screen.findByText(/Your plan and usage will appear/);+ act(() =>+ window.dispatchEvent(new Event("stirling-saas-session-restored")),+ );+ await waitFor(() =>+ expect(onWalletLoaded).toHaveBeenCalledWith(walletOf("free")),+ );+ expect(screen.queryByText(/Your plan and usage will appear/)).toBeNull();+ expect(screen.getByText("This cycle")).toBeVisible();+ expect(fetchWallet).toHaveBeenCalledTimes(3);+ });++ it("reloads billing and clears the expired-session view after renewal", async () => {+ fetchWallet+ .mockRejectedValueOnce(new SaasSessionRequiredError())+ .mockRejectedValueOnce(new SaasSessionRequiredError())+ .mockResolvedValue(walletOf("free"));+ const onWalletLoaded = vi.fn();+ renderUsage(+ <Usage+ onWalletLoaded={onWalletLoaded}+ sessionRecovery={<span>Renew billing access</span>}+ />,+ );+ await screen.findByText(/Your plan and usage will appear/);+ act(() => portalSaasSessionRestored());+ await waitFor(() =>+ expect(onWalletLoaded).toHaveBeenCalledWith(walletOf("free")),+ );+ expect(screen.queryByText(/Your plan and usage will appear/)).toBeNull();+ expect(screen.getByText("This cycle")).toBeVisible();+ expect(fetchWallet).toHaveBeenCalledTimes(3);+ });});it("does not request instance-local usage on SaaS", async () => {diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsxindex e6631011dc..38b25f3988 100644--- a/frontend/editor/src/portal/views/Usage.tsx+++ b/frontend/editor/src/portal/views/Usage.tsx@@ -10,35 +10,36 @@ import { useTranslation } from "react-i18next";import { useSearchParams } from "react-router-dom";import { Banner, Button } from "@app/ui";import { BillingScreen } from "@app/billing";-import { useUI } from "@portal/contexts/UIContext";-import { useProcurement } from "@portal/components/procurement/useProcurement";-import { ControlledDealStatusHero } from "@portal/components/procurement/ProcurementBanner";-import { ProcurementFlow } from "@portal/components/procurement/ProcurementFlow";+import { useUI } from "@app/portal/contexts/UIContext";+import { useProcurement } from "@app/portal/components/procurement/useProcurement";+import { ControlledDealStatusHero } from "@app/portal/components/procurement/ProcurementBanner";+import { ProcurementFlow } from "@app/portal/components/procurement/ProcurementFlow";import {fetchWallet,refreshWalletCache,type Wallet,-} from "@portal/api/billing";+} from "@app/portal/api/billing";import {fetchLocalUsage,triggerLocalSync,type LocalUsage,-} from "@portal/api/link";-import { useStripePortal } from "@portal/hooks/useStripePortal";-import { useBundleFlowState } from "@portal/hooks/useBundleFlowState";-import { FreePlanView } from "@portal/components/billing/FreePlanView";-import { PaymentSection } from "@portal/components/billing/PaymentSection";-import { InvoicesSection } from "@portal/components/billing/InvoicesSection";-import { useFleetStats } from "@portal/queries/infrastructure";+} from "@app/portal/api/link";+import { useStripePortal } from "@app/portal/hooks/useStripePortal";+import { usePortalSaasSession } from "@app/portal/hooks/usePortalSaasSession";+import { FreePlanView } from "@app/portal/components/billing/FreePlanView";+import { PaymentSection } from "@app/portal/components/billing/PaymentSection";+import { InvoicesSection } from "@app/portal/components/billing/InvoicesSection";+import { useFleetStats } from "@app/portal/queries/infrastructure";+import { useBundleFlowState } from "@app/portal/hooks/useBundleFlowState";import { useCheckoutOptional } from "@app/contexts/CheckoutContext";-import { SubscribedPlanView } from "@portal/components/billing/SubscribedPlanView";+import { SubscribedPlanView } from "@app/portal/components/billing/SubscribedPlanView";import {HttpError,- SaasNotLinkedError,+ SaasSessionRequiredError,SaasUnconfiguredError,-} from "@portal/api/http";-import "@portal/views/Usage.css";-import "@portal/components/billing/billing.css";+} from "@app/portal/api/http";+import "@app/portal/views/Usage.css";+import "@app/portal/components/billing/billing.css";export interface UsageProps {/** Local occupied seats for self-hosted; undefined keeps the SaaS membership count. */@@ -51,13 +52,8 @@ export interface UsageProps {* self-hosted maps it onto the link/tier dimension; SaaS ignores it.*/onWalletLoaded?: (wallet: Wallet) => void;- /**- * Invoked when the SaaS session has lapsed and the user chooses to re-sign-in.- * When omitted, the "session expired" notice shows without a sign-in action.- * Self-hosted wires this to its re-auth flow; SaaS leaves it unset (its session- * is owned by the app, so this path never triggers).- */- onReauth?: () => void;+ /** Self-hosted supplies its owner-only renewal notice; hosted authentication belongs to the app. */+ sessionRecovery?: ReactNode;/** Only the self-hosted host supplies local license management; notify after activation. */renderLicenseSection?: (onSaved: () => void) => ReactNode;}@@ -76,11 +72,15 @@ export function Usage({serverPlan,serverPlanAction,onWalletLoaded,- onReauth,+ sessionRecovery,renderLicenseSection,}: UsageProps = {}) {const { t } = useTranslation();- const [wallet, setWallet] = useState<Wallet | null>(null);+ const { revision: sessionRevision, required } = usePortalSaasSession();+ const [loadedWallet, setWallet] = useState<Wallet | null>(null);+ const [sessionExpired, setSessionExpired] = useState(false);+ const needsRenewal = Boolean(sessionRecovery) && (sessionExpired || required);+ const wallet = needsRenewal ? null : loadedWallet;const procurement = useProcurement();const { trialSetupRequested, clearTrialSetupRequest } = useUI();const [searchParams, setSearchParams] = useSearchParams();@@ -132,8 +132,6 @@ export function Usage({const [localUsage, setLocalUsage] = useState<LocalUsage | null>(null);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);- // The SaaS session has lapsed and needs a re-sign-in (self-hosted only).- const [sessionExpired, setSessionExpired] = useState(false);const [refreshKey, setRefreshKey] = useState(0);const previousDeal = useRef(procurement.data);useEffect(() => {@@ -195,7 +193,7 @@ export function Usage({}).catch((e) => {if (cancelled) return;- if (e instanceof SaasNotLinkedError) {+ if (e instanceof SaasSessionRequiredError) {// The attended SaaS session expired — offer a re-sign-in.setSessionExpired(true);} else if (e instanceof SaasUnconfiguredError) {@@ -221,7 +219,7 @@ export function Usage({return () => {cancelled = true;};- }, [refreshKey, onWalletLoaded, t, hasLocalInstance]);+ }, [refreshKey, onWalletLoaded, t, sessionRevision, hasLocalInstance]);const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);useEffect(() => {@@ -312,7 +310,7 @@ export function Usage({<BillingScreenusersInUse={localUsersInUse}headerAction={- paying && wallet?.role === "leader" ? (+ !needsRenewal && paying && wallet?.role === "leader" ? (<Buttonfatvariant="secondary"@@ -324,6 +322,14 @@ export function Usage({) : undefined}wallet={wallet}+ unavailable={+ needsRenewal+ ? t(+ "portal.accountLink.renewal.dataUnavailable",+ "Your plan and usage will appear after you renew billing access. This server stays connected, and local document processing remains available.",+ )+ : undefined+ }serverPlan={serverPlan}serverPlanAction={serverPlanAction}loading={loading}@@ -352,24 +358,7 @@ export function Usage({{procurement.error}</Banner>)}- {sessionExpired && (- <Banner- tone="warning"- title={t("portal.usage.sessionExpired.title", "Session expired")}- action={- onReauth ? (- <Button size="sm" onClick={onReauth}>- {t("portal.usage.sessionExpired.action", "Sign in again")}- </Button>- ) : undefined- }- >- {t(- "portal.usage.sessionExpired.body",- "Your Stirling account session has expired. Sign in again to view billing — your instance stays linked.",- )}- </Banner>- )}+ {sessionRecovery}{error && (<Bannerdiff --git a/frontend/editor/src/proprietary/auth/session.ts b/frontend/editor/src/proprietary/auth/session.tsindex f86e3f0516..0cc4894eb9 100644--- a/frontend/editor/src/proprietary/auth/session.ts+++ b/frontend/editor/src/proprietary/auth/session.ts@@ -1,8 +1,6 @@-import { supabase } from "@app/services/supabaseClient";+import { getPortalSaasToken } from "@app/portal/auth/portalSaasSession";-/** The Stirling account token used for checkout, independent of the local server login. */+/** Checkout uses the account session installed by the validated owner connection flow. */export async function getAccessToken(): Promise<string | null> {- if (!supabase) return null;- const { data } = await supabase.auth.getSession();- return data.session?.access_token ?? null;+ return getPortalSaasToken();}diff --git a/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts b/frontend/editor/src/proprietary/auth/spring/springAuthClient.tsindex b81440e9cb..aae634b345 100644--- a/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts+++ b/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts@@ -18,6 +18,7 @@ import { JWT_STORAGE_KEY } from "@app/auth/httpClient";import { type OAuthProvider } from "@app/auth/spring/oauthTypes";import { resetOAuthState } from "@app/auth/spring/oauthStorage";import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";+import { clearSupabaseSession } from "@app/auth/supabase/supabaseClient";import type {AuthUser as User,AuthSession as Session,@@ -504,6 +505,15 @@ class SpringAuthClient {*/async signOut(): Promise<{ error: AuthError | null }> {try {+ clearSupabaseSession();+ localStorage.removeItem("stirling.portalSaasOwner");+ sessionStorage.removeItem("stirling.portalConnect");+ Array.from({ length: localStorage.length }, (_, i) => localStorage.key(i))+ .filter(+ (key): key is string =>+ key !== null && (key.startsWith("sb-") || key.includes("supabase")),+ )+ .forEach((key) => localStorage.removeItem(key));if (typeof window !== "undefined") {window.sessionStorage.setItem("stirling_sso_auto_login_logged_out",@@ -533,10 +543,6 @@ class SpringAuthClient {// Clean up local storagelocalStorage.removeItem(JWT_STORAGE_KEY);try {- Object.keys(localStorage)- .filter((key) => key.startsWith("sb-") || key.includes("supabase"))- .forEach((key) => localStorage.removeItem(key));-// Clear any cached OAuth redirect/session stateresetOAuthState();} catch (err) {diff --git a/frontend/editor/src/proprietary/auth/springAuthClient.test.ts b/frontend/editor/src/proprietary/auth/springAuthClient.test.tsindex 13f5c6d651..127e95aa31 100644--- a/frontend/editor/src/proprietary/auth/springAuthClient.test.ts+++ b/frontend/editor/src/proprietary/auth/springAuthClient.test.ts@@ -248,6 +248,9 @@ describe("SpringAuthClient", () => {expectConsole.error(/\[SpringAuth\] signOut error/);const mockToken = "jwt-to-clear";localStorage.setItem("stirling_jwt", mockToken);+ localStorage.setItem("sb-project-auth-token", "old-saas-session");+ localStorage.setItem("stirling.portalSaasOwner", "previous-owner");+ sessionStorage.setItem("stirling.portalConnect", "pending-handoff");vi.mocked(apiClient.post).mockRejectedValueOnce({isAxiosError: true,@@ -258,6 +261,9 @@ describe("SpringAuthClient", () => {const result = await springAuth.signOut();expect(localStorage.getItem("stirling_jwt")).toBeNull();+ expect(localStorage.getItem("sb-project-auth-token")).toBeNull();+ expect(localStorage.getItem("stirling.portalSaasOwner")).toBeNull();+ expect(sessionStorage.getItem("stirling.portalConnect")).toBeNull();expect(result.error).toBeTruthy();});});diff --git a/frontend/editor/src/proprietary/auth/supabase/supabaseClient.test.ts b/frontend/editor/src/proprietary/auth/supabase/supabaseClient.test.tsnew file mode 100644index 0000000000..cd8a6c6b9f--- /dev/null+++ b/frontend/editor/src/proprietary/auth/supabase/supabaseClient.test.ts@@ -0,0 +1,204 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { webcrypto } from "node:crypto";++const {+ createClient,+ stopAutoRefresh,+ onAuthStateChange,+ unsubscribe,+ getSession,+} = vi.hoisted(() => ({+ createClient: vi.fn(),+ getSession: vi.fn(),+ onAuthStateChange: vi.fn(),+ unsubscribe: vi.fn(),+ stopAutoRefresh: vi.fn().mockResolvedValue(undefined),+}));+vi.mock("@supabase/supabase-js", () => ({ createClient }));+import {+ clearSupabaseSession,+ configureSupabase,+ getSupabaseClient,+} from "@app/auth/supabase/supabaseClient";++const config = { url: "https://project.supabase.co", key: "public-key" };+const key = "sb-project-auth-token";++describe("local SaaS session disposal", () => {+ beforeEach(() => {+ stopAutoRefresh.mockResolvedValue(undefined);+ clearSupabaseSession();+ localStorage.clear();+ vi.clearAllMocks();+ onAuthStateChange.mockReturnValue({+ data: { subscription: { unsubscribe } },+ });+ createClient.mockImplementation(() => ({+ auth: { stopAutoRefresh, onAuthStateChange, getSession },+ }));+ });++ it("publishes renewed SDK sessions and detaches retired client listeners", async () => {+ const restored = vi.fn();+ window.addEventListener("stirling-saas-session-restored", restored);+ try {+ configureSupabase(config);+ const notify = onAuthStateChange.mock.calls[0][0];+ notify("INITIAL_SESSION", { access_token: "current" });+ notify("SIGNED_IN", null);+ expect(restored).not.toHaveBeenCalled();+ getSession.mockResolvedValueOnce({+ data: { session: { access_token: "current" } },+ error: null,+ });+ getSession.mockResolvedValueOnce({+ data: { session: { access_token: "renewed" } },+ error: null,+ });+ notify("SIGNED_IN", { access_token: "current" });+ notify("TOKEN_REFRESHED", { access_token: "renewed" });+ await vi.waitFor(() => expect(restored).toHaveBeenCalledTimes(2));+ clearSupabaseSession();+ notify("TOKEN_REFRESHED", { access_token: "old-owner" });+ expect(restored).toHaveBeenCalledTimes(2);+ expect(unsubscribe).toHaveBeenCalledOnce();+ } finally {+ window.removeEventListener("stirling-saas-session-restored", restored);+ }+ });++ it("prevents an in-flight SDK refresh from restoring a cleared session", () => {+ configureSupabase(config);+ const storage = createClient.mock.calls[0][2].auth.storage;+ storage.setItem(key, "previous-session");+ clearSupabaseSession();+ storage.setItem(key, "late-refresh");+ expect(localStorage.getItem(key)).toBeNull();+ expect(storage.getItem(key)).toBeNull();+ expect(getSupabaseClient()).toBeNull();+ expect(stopAutoRefresh).toHaveBeenCalledOnce();+ });++ it("prevents an old client from overwriting or deleting the next user's session", () => {+ configureSupabase(config);+ const previous = createClient.mock.calls[0][2].auth.storage;+ clearSupabaseSession();+ configureSupabase(config);+ const next = createClient.mock.calls[1][2].auth.storage;+ next.setItem(key, "next-user");+ previous.setItem(key, "old-user");+ previous.removeItem(key);+ expect(next.getItem(key)).toBe("next-user");+ });+});++describe("browser session isolation", () => {+ let storageListeners: EventListenerOrEventListenerObject[];+ beforeEach(() => {+ stopAutoRefresh.mockResolvedValue(undefined);+ storageListeners = [];+ const addEventListener = window.addEventListener.bind(window);+ vi.spyOn(window, "addEventListener").mockImplementation(+ (type, listener, options) => {+ if (type === "storage") storageListeners.push(listener);+ addEventListener(type, listener, options);+ },+ );+ vi.stubGlobal("crypto", webcrypto);+ localStorage.clear();+ vi.clearAllMocks();+ onAuthStateChange.mockReturnValue({+ data: { subscription: { unsubscribe } },+ });+ createClient.mockImplementation(() => ({+ auth: { stopAutoRefresh, onAuthStateChange, getSession },+ }));+ });+ afterEach(() => {+ storageListeners.forEach((listener) =>+ window.removeEventListener("storage", listener),+ );+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("prevents another tab's pending refresh from restoring a logged-out session", async () => {+ // Each tab has its own module state but shares the origin's localStorage.+ vi.resetModules();+ const firstTab = await import("@app/auth/supabase/supabaseClient");+ firstTab.configureSupabase(config);+ vi.resetModules();+ const secondTab = await import("@app/auth/supabase/supabaseClient");+ secondTab.configureSupabase(config);+ const secondStorage = createClient.mock.calls[1][2].auth.storage;+ secondStorage.setItem(key, "old-owner");+ firstTab.clearSupabaseSession();+ window.dispatchEvent(+ new StorageEvent("storage", {+ key,+ oldValue: "old-owner",+ newValue: null,+ }),+ );+ secondStorage.setItem(key, "late-old-owner-refresh");+ expect(localStorage.getItem(key)).toBeNull();+ });++ it("reads the in-memory fallback when persistent storage rejects writes", async () => {+ vi.resetModules();+ const client = await import("@app/auth/supabase/supabaseClient");+ client.configureSupabase(config);+ const storage = createClient.mock.calls[0][2].auth.storage;+ vi.spyOn(localStorage, "setItem").mockImplementation(() => {+ throw new DOMException("Full", "QuotaExceededError");+ });+ storage.setItem(key, "renewed-session");+ expect(storage.getItem(key)).toBe("renewed-session");+ });++ it("rejects a late cross-tab write even before its storage event is delivered", async () => {+ vi.resetModules();+ const firstTab = await import("@app/auth/supabase/supabaseClient");+ firstTab.configureSupabase(config);+ vi.resetModules();+ const secondTab = await import("@app/auth/supabase/supabaseClient");+ secondTab.configureSupabase(config);+ const previous = createClient.mock.calls[1][2].auth.storage;+ previous.setItem(key, "old-session");+ const delayedWrite = localStorage.getItem(key)!;+ firstTab.clearSupabaseSession();+ expect(secondTab.getSupabaseClient()).toBeNull();+ firstTab.configureSupabase(config);+ const current = createClient.mock.calls[2][2].auth.storage;+ localStorage.setItem(key, delayedWrite);+ expect(current.getItem(key)).toBeNull();+ previous.setItem(key, "late-session");+ expect(current.getItem(key)).toBeNull();+ });++ it("does not recover stale disk credentials after deletion fails", async () => {+ vi.resetModules();+ const client = await import("@app/auth/supabase/supabaseClient");+ client.configureSupabase(config);+ createClient.mock.calls[0][2].auth.storage.setItem(key, "old-session");+ vi.spyOn(localStorage, "removeItem").mockImplementation(() => {+ throw new DOMException("Denied", "SecurityError");+ });+ expect(() => client.clearSupabaseSession()).not.toThrow();+ client.configureSupabase(config);+ expect(createClient.mock.calls[1][2].auth.storage.getItem(key)).toBeNull();+ });++ it("clears the other tab's client when it receives the invalidation event", async () => {+ vi.resetModules();+ const client = await import("@app/auth/supabase/supabaseClient");+ client.configureSupabase(config);+ window.dispatchEvent(+ new StorageEvent("storage", {+ key: "stirling.saasSessionGeneration",+ newValue: "changed",+ }),+ );+ expect(client.getSupabaseClient()).toBeNull();+ });+});diff --git a/frontend/editor/src/proprietary/auth/supabase/supabaseClient.ts b/frontend/editor/src/proprietary/auth/supabase/supabaseClient.tsindex be85a80c11..983e5c8b35 100644--- a/frontend/editor/src/proprietary/auth/supabase/supabaseClient.ts+++ b/frontend/editor/src/proprietary/auth/supabase/supabaseClient.ts@@ -1,13 +1,9 @@/*** Shared Supabase client.*- * The editor's saas build keeps its own richer client (profile pictures, pro- * status, teams). This module is the portable Supabase path used by the shared- * unified auth provider - notably so the portal can run in Supabase mode- * against a hosted backend. The client is created lazily via- * {@link configureSupabase}; until then {@link getSupabaseClient} returns null,- * so hosts that never configure it (e.g. the portal in Spring mode) don't pull- * Supabase into their session at all.+ * Used by unified Supabase auth and the self-hosted portal's attended billing+ * session. Local Spring authentication remains separate. Clearing or replacing+ * the client invalidates storage access by its pending SDK requests.*/import { createClient, type SupabaseClient } from "@supabase/supabase-js";@@ -24,21 +20,191 @@ export interface SupabaseConfig {}let client: SupabaseClient | null = null;+let unsubscribeAuth: (() => void) | null = null;+let generation = 0;+let storageKey: string | null = null;+let clientInvalidation: string | null = null;+const INVALIDATION_KEY = "stirling.saasSessionGeneration";++function readInvalidation(): string | null {+ try {+ return localStorage.getItem(INVALIDATION_KEY);+ } catch {+ return null;+ }+}++function invalidateClient(): void {+ generation++;+ unsubscribeAuth?.();+ unsubscribeAuth = null;+ if (client) void client.auth.stopAutoRefresh().catch(() => {});+ client = null;+ window.dispatchEvent(new Event("stirling-saas-session-cleared"));+}++window.addEventListener("storage", (event) => {+ if (event.key === INVALIDATION_KEY || event.key === null) invalidateClient();+});/** Create (or replace) the shared Supabase client. Returns the instance. */export function configureSupabase(config: SupabaseConfig): SupabaseClient {+ unsubscribeAuth?.();+ if (client) void client.auth.stopAutoRefresh().catch(() => {});+ const current = ++generation;+ const invalidation = readInvalidation();+ clientInvalidation = invalidation;+ const active = () =>+ current === generation && invalidation === readInvalidation();+ const memory = new Map<string, string>();+ let memoryOnly = false;+ storageKey = `sb-${new URL(config.url).hostname.split(".")[0]}-auth-token`;client = createClient(config.url, config.key, {auth: {+ storageKey,+ storage: {+ getItem: (key: string) => {+ if (!active()) return null;+ if (memoryOnly) return memory.get(key) ?? null;+ try {+ const stored = localStorage.getItem(key);+ if (!stored) return null;+ try {+ const envelope = JSON.parse(stored);+ if (envelope?.stirlingSessionVersion === 1) {+ const value =+ envelope.generation === invalidation &&+ typeof envelope.value === "string"+ ? envelope.value+ : null;+ if (value !== null) memory.set(key, value);+ return value;+ }+ if (+ envelope &&+ typeof envelope === "object" &&+ !Array.isArray(envelope)+ ) {+ if (+ (envelope.stirlingSessionGeneration ?? null) !== invalidation+ )+ return null;+ memory.set(key, stored);+ return stored;+ }+ } catch {+ // SDK code-verifier entries are plain strings, unlike serialized sessions.+ }+ if (invalidation !== null) return null;+ memory.set(key, stored);+ return stored;+ } catch {+ memoryOnly = true;+ return memory.get(key) ?? null;+ }+ },+ setItem: (key: string, value: string) => {+ if (!active()) return;+ memory.set(key, value);+ if (memoryOnly) return;+ try {+ let serialized = JSON.stringify({+ stirlingSessionVersion: 1,+ generation: invalidation,+ value,+ });+ try {+ const session = JSON.parse(value);+ if (+ session &&+ typeof session === "object" &&+ !Array.isArray(session)+ ) {+ // Preserve the SDK's session shape for clients reading the same storage key.+ serialized = JSON.stringify({+ ...session,+ stirlingSessionGeneration: invalidation,+ });+ }+ } catch {+ // Non-JSON SDK entries retain their value inside the versioned envelope.+ }+ // A late cross-tab write is unreadable even if it races the invalidation check.+ localStorage.setItem(key, serialized);+ } catch {+ memoryOnly = true;+ }+ },+ removeItem: (key: string) => {+ if (!active()) return;+ memory.delete(key);+ try {+ localStorage.removeItem(key);+ } catch {+ memoryOnly = true;+ }+ },+ },persistSession: config.authOptions?.persistSession ?? true,autoRefreshToken: config.authOptions?.autoRefreshToken ?? true,detectSessionInUrl: config.authOptions?.detectSessionInUrl ?? true,},});+ const configuredClient = client;+ const {+ data: { subscription },+ } = client.auth.onAuthStateChange((event, session) => {+ if (+ active() &&+ session &&+ (event === "SIGNED_IN" || event === "TOKEN_REFRESHED")+ ) {+ // A retired client can still broadcast a refresh; only the persisted session may restore access.+ // Do not await inside the SDK callback: getSession needs the auth lock it currently holds.+ void configuredClient.auth+ .getSession()+ .then(({ data, error }) => {+ if (+ active() &&+ !error &&+ data.session?.access_token === session.access_token+ ) {+ window.dispatchEvent(new Event("stirling-saas-session-restored"));+ }+ })+ .catch(() => {});+ }+ });+ unsubscribeAuth = () => subscription.unsubscribe();return client;}+/** Clears this browser only; late SDK refreshes cannot restore a cleared user's session. */+export function clearSupabaseSession(): void {+ invalidateClient();+ try {+ const marker = Array.from(+ crypto.getRandomValues(new Uint8Array(16)),+ (byte) => byte.toString(16).padStart(2, "0"),+ ).join("");+ localStorage.setItem(INVALIDATION_KEY, marker);+ } catch {+ // This tab is invalidated even when browser storage is unavailable.+ }+ if (storageKey) {+ for (const suffix of ["", "-user", "-code-verifier"]) {+ try {+ localStorage.removeItem(`${storageKey}${suffix}`);+ } catch {+ // The invalidation marker still blocks stale credentials when only deletion fails.+ }+ }+ }+}+/** The configured Supabase client, or null if not configured. */export function getSupabaseClient(): SupabaseClient | null {+ if (client && clientInvalidation !== readInvalidation()) invalidateClient();return client;}diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.test.tsxindex 2420bca7d9..ae07bd7170 100644--- a/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx+++ b/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx@@ -179,3 +179,24 @@ it("does not price gross usage as paid usage", () => {expect(screen.getAllByText("$30.00")).toHaveLength(2);expect(screen.queryByText("$40.00")).not.toBeInTheDocument();});++it("retains Plan and Usage while data is unavailable without inventing figures or purchase actions", () => {+ render(+ <BillingScreen+ wallet={null}+ unavailable="Renew access to read billing data."+ licenseSection={<span>Local license</span>}+ />,+ );+ expect(screen.getByRole("button", { name: "Plan" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Usage" })).toBeInTheDocument();+ expect(+ screen.getByText("Renew access to read billing data."),+ ).toBeInTheDocument();+ expect(+ screen.getByText("Usage figures are currently unavailable."),+ ).toBeInTheDocument();+ expect(screen.getByText("Local license")).toBeInTheDocument();+ expect(screen.queryByText("The full PDF Editor.")).toBeNull();+ expect(screen.queryByRole("button", { name: "Add capacity" })).toBeNull();+});diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.tsxindex 00e11bd504..4ff28183c3 100644--- a/frontend/editor/src/proprietary/billing/BillingScreen.tsx+++ b/frontend/editor/src/proprietary/billing/BillingScreen.tsx@@ -23,6 +23,8 @@ export interface BillingScreenProps {*/wallet: Wallet | null;loading?: boolean;+ /** Keeps Plan and Usage visible when their data cannot currently be read. */+ unavailable?: ReactNode;/** Self-hosted phrases its free tier differently. */selfHosted?: boolean;/** Local licence takes precedence over the cloud product names and user capacity. */@@ -90,6 +92,7 @@ export function BillingScreen({headerAction,wallet,loading = false,+ unavailable,selfHosted = false,serverPlan,serverPlanAction,@@ -132,9 +135,10 @@ export function BillingScreen({"ub-procurement",t("portal.billing.chip.procurement", "Procurement"),]);- if (wallet || serverPlan)+ if (wallet || serverPlan || unavailable)out.push(["ub-plan", t("portal.billing.chip.plan", "Plan")]);- if (wallet) out.push(["ub-usage", t("portal.billing.chip.usage", "Usage")]);+ if (wallet || unavailable)+ out.push(["ub-usage", t("portal.billing.chip.usage", "Usage")]);if (wallet && paymentSection)out.push(["ub-pay", t("portal.billing.chip.payment", "Payment")]);if (wallet && invoicesSection)@@ -148,6 +152,7 @@ export function BillingScreen({}, [wallet,serverPlan,+ unavailable,procurementSection,licenseSection,paymentSection,@@ -284,7 +289,7 @@ export function BillingScreen({</div>)}- {(procurementSection || licenseSection || identity) && (+ {(procurementSection || licenseSection || identity || unavailable) && (<div className="billing-card"><navclassName="billing-card__chips"@@ -469,6 +474,29 @@ export function BillingScreen({)}</>)}+ {unavailable && !wallet && (+ <>+ {!identity && (+ <section id="ub-plan" className="billing-sec">+ <span className="billing-eyebrow">+ {t("portal.billing.chip.plan", "Plan")}+ </span>+ <p className="billing-id__sub">{unavailable}</p>+ </section>+ )}+ <section id="ub-usage" className="billing-sec">+ <span className="billing-eyebrow">+ {t("portal.billing.chip.usage", "Usage")}+ </span>+ <p className="billing-id__sub">+ {t(+ "portal.billing.dataUnavailable",+ "Usage figures are currently unavailable.",+ )}+ </p>+ </section>+ </>+ )}{licenseSection && (<sectionid="ub-license"diff --git a/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx b/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsxindex fb79da4d2e..208ac080ab 100644--- a/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx+++ b/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx@@ -20,27 +20,27 @@ export type { SettingsNav };* processor access, audit) — so the narrower section is dropped rather than* shown twice, and its key aliases across.*- * Encryption at rest, what the deployment spends, and the link to the Stirling- * account are all operator concerns, so they are offered to admins only;- * portal access alone is not enough to reach them.+ * Admins manage encryption; only the organization owner manages billing and+ * the Stirling account connection. Portal access alone grants neither.*/export function useSettingsNav(onLeave: () => void): SettingsNav {const { t } = useTranslation();const base = useCoreSettingsNav(onLeave);const { granted: portalAccess, settled: accessSettled } =usePortalAccessState();- const { isAdmin } = useAuth();+ const { isAdmin, user } = useAuth();+ const isOwner = isAdmin && user?.orgOwner === true;const portalSections = useMemo(() =>portalAccess? buildPortalSettingsSections(t, {includeEncryption: isAdmin,- includeBilling: isAdmin,- includeAccountLink: isAdmin,+ includeBilling: isOwner,+ includeAccountLink: isOwner,}): [],- [portalAccess, isAdmin, t],+ [portalAccess, isAdmin, isOwner, t],);const sections = useMemo(diff --git a/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsx b/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsxindex 6436c76143..16ef47ae18 100644--- a/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsx+++ b/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsx@@ -36,8 +36,8 @@ export function StepModalHeader({total?: number;/** Pre-translated "Step 2 of 3"; omitted renders no badge. */stepLabel?: string;- /** Show the Stirling wordmark instead of a plain heading, for flows that stand alone. */- brand?: boolean;+ /** True uses the wordmark; a string supplies a translated flow identity above the step title. */+ brand?: boolean | string;/** Extra class on the root, so a host modal can own its own padding. */className?: string;closeLabel?: string;@@ -50,7 +50,11 @@ export function StepModalHeader({return (<div className={`portal-stepmodal__head ${className ?? ""}`.trim()}><div className="portal-stepmodal__head-top">- {brand ? (+ {typeof brand === "string" ? (+ <div className="portal-stepmodal__ident">+ <h3 className="portal-stepmodal__flow-title">{brand}</h3>+ </div>+ ) : brand ? (<div className="portal-stepmodal__brand">{/* `wordmark`, not `wordmark-light-only`: theme.css hides the former in dark mode andhas no rule for the latter, so both used to render at once. */}diff --git a/frontend/editor/src/proprietary/services/supabaseClient.test.ts b/frontend/editor/src/proprietary/services/supabaseClient.test.tsnew file mode 100644index 0000000000..6237501afb--- /dev/null+++ b/frontend/editor/src/proprietary/services/supabaseClient.test.ts@@ -0,0 +1,151 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { SupabaseClient } from "@supabase/supabase-js";+import { allowConsole } from "@app/tests/failOnConsole";++const session = vi.hoisted(() => ({ acceptedToken: null as string | null }));+vi.mock("@app/portal/auth/portalSaasSession", () => ({+ getPortalSaasToken: () => Promise.resolve(session.acceptedToken),+}));++vi.mock("@app/services/apiClient", () => ({ default: {} }));+vi.mock("@app/utils/protocolDetection", () => ({+ getCheckoutMode: () => "hosted",+}));++const url = "https://licensing-session.supabase.co";+const publicKey = "public-test-key";+const storageKey = "sb-licensing-session-auth-token";+const user = {+ id: "untrusted-account",+ aud: "authenticated",+ email: "[email protected]",+};+const token = [+ btoa(JSON.stringify({ alg: "HS256", typ: "JWT" })),+ btoa(+ JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 }),+ ),+ btoa("test-signature"),+]+ .map((part) => part.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"))+ .join(".");+const fragment =+ "#" ++ new URLSearchParams({+ access_token: token,+ refresh_token: "untrusted-refresh",+ expires_in: "3600",+ token_type: "bearer",+ });+const network = vi.fn<typeof fetch>();+let client: SupabaseClient | null;++beforeEach(() => {+ allowConsole.warn(+ /GoTrueClient@sb-licensing-session-auth-token:.*Multiple GoTrueClient instances detected/,+ );+ vi.resetModules();+ localStorage.clear();+ network.mockReset();+ session.acceptedToken = null;+ network.mockImplementation(+ async (input) =>+ new Response(+ JSON.stringify(+ String(input).includes("/auth/v1/user")+ ? user+ : {+ received: true,+ url: "https://checkout.stripe.com/test-session",+ },+ ),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ vi.stubGlobal("fetch", network);+ vi.stubEnv("VITE_SUPABASE_URL", url);+ vi.stubEnv("VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY", publicKey);+});++afterEach(async () => {+ await client?.auth.stopAutoRefresh();+ client = null;+ localStorage.clear();+ window.history.replaceState({}, "", "/");+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+});++it.each(["/", "/account-link/callback?state=untrusted"])(+ "does not capture or persist callback credentials when licensing boots at %s",+ async (path) => {+ window.history.replaceState({}, "", path + fragment);+ ({ supabase: client } = await import("@app/services/supabaseClient"));+ expect(client).not.toBeNull();+ expect((await client!.auth.getSession()).data.session).toBeNull();+ expect(localStorage.getItem(storageKey)).toBeNull();+ expect(window.location.hash).toBe(fragment);+ expect(network).not.toHaveBeenCalled();+ },+);++it("keeps license function requests independent of stored billing credentials", async () => {+ const persisted = JSON.stringify({+ access_token: token,+ refresh_token: "stored-refresh",+ expires_at: Math.floor(Date.now() / 1000) + 3600,+ user,+ });+ localStorage.setItem(storageKey, persisted);+ ({ supabase: client } = await import("@app/services/supabaseClient"));+ expect((await client!.auth.getSession()).data.session).toBeNull();+ const { default: licenseService } =+ await import("@app/services/licenseService");+ const { createServerPlanCheckoutSession } =+ await import("@app/services/serverPlanCheckout");+ await createServerPlanCheckoutSession({+ lookupKey: "selfhosted:enterpriseseat:monthly",+ serverQuantity: 1,+ requiresSeats: true,+ uiMode: "hosted",+ });+ await licenseService.createBillingPortalSession(+ "https://server.example.test/settings/billing",+ "test-license-key",+ );+ await licenseService.checkLicenseKey("test-installation");+ expect(network).toHaveBeenCalledTimes(3);+ for (const endpoint of [+ "create-checkout",+ "manage-billing",+ "get-license-key",+ ]) {+ const request = network.mock.calls.find(([input]) =>+ String(input).endsWith("/functions/v1/" + endpoint),+ );+ expect(request).toBeDefined();+ expect(new Headers(request![1]?.headers).get("authorization")).toBe(+ "Bearer " + publicKey,+ );+ }+ expect(localStorage.getItem(storageKey)).toBe(persisted);+});++it("uses only the validated owner session for Team checkout despite callback credentials", async () => {+ window.history.replaceState({}, "", "/" + fragment);+ session.acceptedToken = "validated-owner-token";+ ({ supabase: client } = await import("@app/services/supabaseClient"));+ const { createServerPlanCheckoutSession } =+ await import("@app/services/serverPlanCheckout");+ await createServerPlanCheckoutSession({+ lookupKey: "selfhosted:server:monthly",+ serverQuantity: 1,+ uiMode: "hosted",+ });+ expect(network).toHaveBeenCalledOnce();+ expect(+ new Headers(network.mock.calls[0][1]?.headers).get("authorization"),+ ).toBe("Bearer validated-owner-token");+ expect((await client!.auth.getSession()).data.session).toBeNull();+ expect(localStorage.getItem(storageKey)).toBeNull();+});diff --git a/frontend/editor/src/proprietary/services/supabaseClient.ts b/frontend/editor/src/proprietary/services/supabaseClient.tsindex 6a40fe7ed8..5b9f7634cf 100644--- a/frontend/editor/src/proprietary/services/supabaseClient.ts+++ b/frontend/editor/src/proprietary/services/supabaseClient.ts@@ -1,8 +1,3 @@-// Supabase client. Relocated out of frontend/src/core/services/ during the SaaS<->OSS-// consolidation so the Supabase SDK never reaches the OSS core bundle. Lives in-// :proprietary because licensing/checkout/billing flows in proprietary mode use it; the-// :saas mode bundle picks it up via the existing @app/* path mapping (saas to proprietary-// to core).import { createClient, SupabaseClient } from "@supabase/supabase-js";const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;@@ -11,9 +6,11 @@ const supabaseAnonKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY;// Check if Supabase is configuredexport const isSupabaseConfigured = !!(supabaseUrl && supabaseAnonKey);-// Create client only if configured, otherwise export null+// Licensing uses installation/license-key identity; attended sessions belong to the portal client.export const supabase: SupabaseClient | null = isSupabaseConfigured- ? createClient(supabaseUrl, supabaseAnonKey)+ ? createClient(supabaseUrl, supabaseAnonKey, {+ auth: { detectSessionInUrl: false, persistSession: false },+ }): null;// Log warning if not configured (for self-hosted installations)diff --git a/frontend/editor/src/proprietary/tsconfig.json b/frontend/editor/src/proprietary/tsconfig.jsonindex 39345ee241..5e79eb02ca 100644--- a/frontend/editor/src/proprietary/tsconfig.json+++ b/frontend/editor/src/proprietary/tsconfig.json@@ -3,6 +3,11 @@"compilerOptions": {"paths": {"@app/*": ["../../src/proprietary/*", "../../src/core/*"],+ "@app/portal/*": [+ "../../src/proprietary/portal/*",+ "../../src/core/portal/*",+ "../../src/portal/*"+ ],"@portal/*": ["../../src/portal/*"],"@core/*": ["../../src/core/*"]}diff --git a/frontend/editor/src/prototypes/tsconfig.json b/frontend/editor/src/prototypes/tsconfig.jsonindex 74c2316a9e..69919f86ca 100644--- a/frontend/editor/src/prototypes/tsconfig.json+++ b/frontend/editor/src/prototypes/tsconfig.json@@ -8,7 +8,14 @@"../../src/core/*"],"@proprietary/*": ["../../src/proprietary/*"],- "@core/*": ["../../src/core/*"]+ "@core/*": ["../../src/core/*"],+ "@app/portal/*": [+ "../../src/prototypes/portal/*",+ "../../src/proprietary/portal/*",+ "../../src/core/portal/*",+ "../../src/portal/*"+ ],+ "@portal/*": ["../../src/portal/*"]}},"include": [diff --git a/frontend/editor/src/saas/auth/redirectToLogin.test.ts b/frontend/editor/src/saas/auth/redirectToLogin.test.tsnew file mode 100644index 0000000000..5591ca615e--- /dev/null+++ b/frontend/editor/src/saas/auth/redirectToLogin.test.ts@@ -0,0 +1,31 @@+import { beforeEach, afterEach, expect, it, vi } from "vitest";+vi.mock("@app/constants/app", () => ({+ withBasePath: (path: string) => "/app" + path,+ stripBasePath: (path: string) => path.replace(/^\/app/, ""),+}));+import { redirectToLogin } from "@app/auth/redirectToLogin";+let href: string;+beforeEach(() => {+ href = "";+ vi.stubGlobal("location", {+ pathname: "/app/settings/billing",+ search: "?source=trial",+ hash: "#access_token=private-access&refresh_token=private-refresh",+ get href() {+ return href;+ },+ set href(value: string) {+ href = value;+ },+ });+});+afterEach(() => vi.unstubAllGlobals());+it("uses normal login with a safe destination and excludes the token fragment", () => {+ redirectToLogin();+ expect(href).toBe("/app/login?next=%2Fsettings%2Fbilling%3Fsource%3Dtrial");+});+it("does not redirect while already on login", () => {+ location.pathname = "/app/login";+ redirectToLogin();+ expect(href).toBe("");+});diff --git a/frontend/editor/src/saas/auth/redirectToLogin.ts b/frontend/editor/src/saas/auth/redirectToLogin.tsnew file mode 100644index 0000000000..695d6d0343--- /dev/null+++ b/frontend/editor/src/saas/auth/redirectToLogin.ts@@ -0,0 +1,14 @@+import { stripBasePath, withBasePath } from "@app/constants/app";+import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";++/** Keep the attended page as the destination for normal app sign-in. */+export function redirectToLogin(): void {+ const loginPath = withBasePath("/login");+ // Already on the login page: another redirect would just loop.+ if (window.location.pathname === loginPath) return;+ const returnPath =+ stripBasePath(window.location.pathname) + window.location.search;+ window.location.href = isSafePostLoginRedirect(returnPath)+ ? `${loginPath}?next=${encodeURIComponent(returnPath)}`+ : loginPath;+}diff --git a/frontend/editor/src/saas/auth/supabase/supabaseClient.test.ts b/frontend/editor/src/saas/auth/supabase/supabaseClient.test.tsnew file mode 100644index 0000000000..1ab8c15e39--- /dev/null+++ b/frontend/editor/src/saas/auth/supabase/supabaseClient.test.ts@@ -0,0 +1,40 @@+import { beforeEach, expect, it, vi } from "vitest";+const sdk = vi.hoisted(() => ({+ auth: { signOut: vi.fn().mockResolvedValue({ error: null }) },+}));+vi.mock("@app/auth/supabase", () => ({+ supabase: sdk,+ getCurrentUser: vi.fn(),+ isUserAnonymous: vi.fn(),+ signInAnonymously: vi.fn(),+}));+import {+ configureSupabase,+ getSupabaseClient,+ clearSupabaseSession,+} from "@app/auth/supabase/supabaseClient";+beforeEach(() => {+ localStorage.clear();+ sessionStorage.clear();+ sdk.auth.signOut.mockClear();+});+it("uses the hosted login client without any account-link storage or replacement client", () => {+ localStorage.setItem("stirling.saasSessionGeneration", "old-selfhost-marker");+ expect(+ configureSupabase({+ url: "https://example.test",+ key: "public-key",+ authOptions: { detectSessionInUrl: false },+ }),+ ).toBe(sdk);+ expect(getSupabaseClient()).toBe(sdk);+ expect(localStorage.getItem("stirling.portalSaasOwner")).toBeNull();+ expect(localStorage.getItem("stirling.saasSessionGeneration")).toBe(+ "old-selfhost-marker",+ );+});+it("clears the hosted session through normal SDK local sign-out", () => {+ clearSupabaseSession();+ expect(sdk.auth.signOut).toHaveBeenCalledWith({ scope: "local" });+ expect(localStorage.getItem("stirling.saasSessionGeneration")).toBeNull();+});diff --git a/frontend/editor/src/saas/auth/supabase/supabaseClient.ts b/frontend/editor/src/saas/auth/supabase/supabaseClient.tsnew file mode 100644index 0000000000..c23ff05560--- /dev/null+++ b/frontend/editor/src/saas/auth/supabase/supabaseClient.ts@@ -0,0 +1,22 @@+import { supabase } from "@app/auth/supabase";+export {+ getCurrentUser,+ isUserAnonymous,+ signInAnonymously,+} from "@app/auth/supabase";+export type {+ SupabaseConfig,+ SupabaseAuthOptions,+} from "@proprietary/auth/supabase/supabaseClient";+import type { SupabaseConfig } from "@proprietary/auth/supabase/supabaseClient";++/** Unified auth and billing share the hosted app's singleton and standard SDK storage. */+export function getSupabaseClient() {+ return supabase;+}+export function configureSupabase(_config: SupabaseConfig) {+ return supabase;+}+export function clearSupabaseSession(): void {+ void supabase.auth.signOut({ scope: "local" });+}diff --git a/frontend/editor/src/saas/routes/ConnectApprove.test.tsx b/frontend/editor/src/saas/routes/ConnectApprove.test.tsxindex ff08815a0a..e14d55f61f 100644--- a/frontend/editor/src/saas/routes/ConnectApprove.test.tsx+++ b/frontend/editor/src/saas/routes/ConnectApprove.test.tsx@@ -15,9 +15,14 @@ import { readPendingConnect } from "@app/routes/pendingConnect";import type { PendingConnect } from "@app/routes/ConnectApproveView";import apiClient from "@app/services/apiClient";-const { signOut, session } = vi.hoisted(() => ({+const { signOut, session, replace } = vi.hoisted(() => ({signOut: vi.fn(),- session: { user: { id: "member-1" } },+ replace: vi.fn(),+ session: {+ user: { id: "member-1" },+ access_token: "test-access",+ refresh_token: "test-refresh",+ },}));vi.mock("@app/auth/UseSession", () => ({@@ -56,8 +61,8 @@ const pending: PendingConnect & { status: "PENDING" } = {canDeny: false,};-function arrive() {- return render(+function TestApp() {+ return (<MantineProvider><MemoryRouter initialEntries={["/link?request=req-1"]}><ResumePendingConnect />@@ -66,12 +71,26 @@ function arrive() {<Route path="/" element={<p>App home</p>} /></Routes></MemoryRouter>- </MantineProvider>,+ </MantineProvider>);}+function arrive() {+ return render(<TestApp />);+}+beforeEach(() => {vi.clearAllMocks();+ session.user.id = "member-1";+ Object.defineProperty(window, "location", {+ configurable: true,+ value: {+ origin: "http://localhost",+ href: "http://localhost/link?request=req-1",+ search: "?request=req-1",+ replace,+ },+ });localStorage.clear();vi.mocked(apiClient.get).mockResolvedValue({ data: pending });});@@ -160,23 +179,169 @@ describe("connect approval permissions", () => {);});- it("allows a member to reauthenticate without offering decline", async () => {+ it("renews the linked owner with one explicit click and no checkbox", async () => {vi.mocked(apiClient.get).mockResolvedValue({- data: { ...pending, mode: "REAUTH", canApprove: true },+ data: { ...pending, mode: "REAUTH", canApprove: true, canDeny: true },+ });+ vi.mocked(apiClient.post).mockResolvedValue({+ data: {+ callbackUrl: "https://pdf.example.com/account-link/callback",+ nonce: "test-nonce",+ },});arrive();+ const renew = await screen.findByRole("button", {+ name: "connect.renewal.approve",+ });+ expect(renew).toBeEnabled();+ expect(screen.getByText("connect.renewal.title")).toBeInTheDocument();+ expect(screen.queryByRole("checkbox")).toBeNull();+ expect(+ screen.queryByRole("button", { name: "connect.confirm.approve" }),+ ).toBeNull();expect(- await screen.findByRole("button", { name: "connect.confirm.approve" }),- ).toBeDisabled();+ screen.queryByRole("button", { name: "connect.confirm.deny" }),+ ).toBeNull();expect(screen.getByRole("button", { name: "connect.confirm.dismiss" }),).toBeInTheDocument();+ expect(apiClient.post).not.toHaveBeenCalled();+ fireEvent.click(renew);+ await waitFor(() => expect(replace).toHaveBeenCalledOnce());+ expect(apiClient.post).toHaveBeenCalledExactlyOnceWith(+ "/api/v1/account-link/connect/req-1/approve",+ );+ const destination = new URL(replace.mock.calls[0][0]);+ expect(destination.origin).toBe("https://pdf.example.com");+ const fragment = new URLSearchParams(destination.hash.slice(1));+ expect(fragment.get("nonce")).toBe("test-nonce");+ expect(fragment.get("access_token")).toBe(session.access_token);+ expect(fragment.get("refresh_token")).toBe(session.refresh_token);+ expect(readPendingConnect()).toBeNull();+ });++ it.each(["dismiss", "switchAccount"])(+ "offers a wrong account only switching or dismissal: %s",+ async (action) => {+ vi.mocked(apiClient.get).mockResolvedValue({+ data: { ...pending, mode: "REAUTH" },+ });+ arrive();+ expect(+ await screen.findByText("connect.renewal.wrongAccount"),+ ).toBeInTheDocument();+ expect(screen.getByText("[email protected]")).toBeInTheDocument();+ expect(screen.queryByRole("checkbox")).toBeNull();+ expect(screen.getAllByRole("button")).toHaveLength(2);+ fireEvent.click(+ screen.getByRole("button", { name: `connect.confirm.${action}` }),+ );+ if (action === "dismiss") {+ expect(await screen.findByText("App home")).toBeInTheDocument();+ expect(readPendingConnect()).toBeNull();+ expect(signOut).not.toHaveBeenCalled();+ } else {+ expect(signOut).toHaveBeenCalledOnce();+ expect(readPendingConnect()).toBe("req-1");+ }+ expect(apiClient.post).not.toHaveBeenCalled();+ expect(replace).not.toHaveBeenCalled();+ },+ );++ it("lets the linked owner dismiss renewal without touching the request", async () => {+ vi.mocked(apiClient.get).mockResolvedValue({+ data: { ...pending, mode: "REAUTH", canApprove: true, canDeny: true },+ });+ arrive();+ fireEvent.click(+ await screen.findByRole("button", { name: "connect.confirm.dismiss" }),+ );+ expect(await screen.findByText("App home")).toBeInTheDocument();+ expect(apiClient.post).not.toHaveBeenCalled();+ });++ it.each([403, 409])(+ "removes renewal permission when the API rejects a stale decision (%s)",+ async (status) => {+ vi.mocked(apiClient.get).mockResolvedValue({+ data: { ...pending, mode: "REAUTH", canApprove: true },+ });+ vi.mocked(apiClient.post).mockRejectedValue({+ isAxiosError: true,+ response: { status },+ });+ arrive();+ fireEvent.click(+ await screen.findByRole("button", { name: "connect.renewal.approve" }),+ );+ expect(+ await screen.findByText("connect.renewal.wrongAccount"),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "connect.renewal.approve" }),+ ).toBeNull();+ expect(screen.getAllByRole("button")).toHaveLength(2);+ expect(replace).not.toHaveBeenCalled();+ expect(readPendingConnect()).toBe("req-1");+ },+ );++ it("leaves a recoverable renewal error after a network failure", async () => {+ vi.mocked(apiClient.get).mockResolvedValue({+ data: { ...pending, mode: "REAUTH", canApprove: true },+ });+ vi.mocked(apiClient.post).mockRejectedValue(new Error("offline"));+ arrive();+ fireEvent.click(+ await screen.findByRole("button", { name: "connect.renewal.approve" }),+ );expect(- screen.queryByRole("button", { name: "connect.confirm.deny" }),- ).toBeNull();- fireEvent.click(screen.getByRole("checkbox"));+ await screen.findByText("connect.renewal.failed"),+ ).toBeInTheDocument();expect(- screen.getByRole("button", { name: "connect.confirm.approve" }),+ screen.getByRole("button", { name: "connect.renewal.approve" }),).toBeEnabled();+ expect(replace).not.toHaveBeenCalled();+ });++ it("checks permissions again when the account changes and ignores the previous lookup", async () => {+ let resolveOld!: (value: { data: typeof pending }) => void;+ vi.mocked(apiClient.get).mockReturnValueOnce(+ new Promise((resolve) => {+ resolveOld = resolve;+ }),+ );+ const view = arrive();+ vi.mocked(apiClient.get).mockResolvedValueOnce({+ data: { ...pending, mode: "REAUTH", canApprove: false },+ });+ session.user.id = "different-owner";+ view.rerender(<TestApp />);+ expect(+ await screen.findByText("connect.renewal.wrongAccount"),+ ).toBeInTheDocument();+ await act(async () =>+ resolveOld({ data: { ...pending, mode: "REAUTH", canApprove: true } }),+ );+ expect(+ screen.queryByRole("button", { name: "connect.renewal.approve" }),+ ).toBeNull();+ expect(apiClient.get).toHaveBeenCalledTimes(2);+ });++ it("removes the old account's actions while checking the newly signed-in account", async () => {+ vi.mocked(apiClient.get).mockResolvedValueOnce({+ data: { ...pending, mode: "REAUTH", canApprove: true },+ });+ const view = arrive();+ await screen.findByRole("button", { name: "connect.renewal.approve" });+ vi.mocked(apiClient.get).mockReturnValueOnce(new Promise(() => {}));+ session.user.id = "another-account";+ view.rerender(<TestApp />);+ expect(+ screen.queryByRole("button", { name: "connect.renewal.approve" }),+ ).toBeNull();+ expect(apiClient.post).not.toHaveBeenCalled();});});diff --git a/frontend/editor/src/saas/routes/ConnectApprove.tsx b/frontend/editor/src/saas/routes/ConnectApprove.tsxindex 2becfa9260..2f8d9c6957 100644--- a/frontend/editor/src/saas/routes/ConnectApprove.tsx+++ b/frontend/editor/src/saas/routes/ConnectApprove.tsx@@ -1,4 +1,5 @@-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useState } from "react";+import { isAxiosError } from "axios";import { useNavigate, useSearchParams } from "react-router-dom";import apiClient from "@app/services/apiClient";import { useAuth } from "@app/auth/UseSession";@@ -38,12 +39,23 @@ export default function ConnectApprove() {const requestId = params.get("request");const [phase, setPhase] = useState<ApprovePhase>("loading");- const [pending, setPending] = useState<PendingConnect | null>(null);+ const [lookup, setLookup] = useState<+ (PendingConnect & { accountId: string }) | null+ >(null);+ const accountId = session?.user.id;+ const pending =+ lookup?.accountId === accountId && lookup?.requestId === requestId+ ? lookup+ : null;const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);- const lookedUpRef = useRef(false);- useDocumentMeta({ title: t("connect.meta.title", "Connect a server") });+ useDocumentMeta({+ title:+ pending?.mode === "REAUTH"+ ? t("connect.renewal.title", "Renew your server sign-in")+ : t("connect.meta.title", "Connect a server"),+ });// On arrival, not only when signed out: an approver who is already signed in can// still be sent away to re-authenticate, and needs the same way back.@@ -60,8 +72,11 @@ export default function ConnectApprove() {}, [loading, session, requestId, navigate]);useEffect(() => {- if (loading || !session || lookedUpRef.current) return;- lookedUpRef.current = true;+ if (loading || !accountId) return;+ let active = true;+ setLookup(null);+ setError(null);+ setPhase("loading");if (!requestId) {setPhase("notFound");return;@@ -71,6 +86,7 @@ export default function ConnectApprove() {const res = await apiClient.get<ConnectLookup>(`/api/v1/account-link/connect/${encodeURIComponent(requestId)}`,);+ if (!active) return;// Approving a settled request fails server-side, so offering the form again// would only produce a dead end.if (res.data.status !== "PENDING") {@@ -78,18 +94,29 @@ export default function ConnectApprove() {setPhase(res.data.status === "DENIED" ? "declined" : "notFound");return;}- setPending(res.data);+ setLookup({ ...res.data, accountId });setPhase("confirm");} catch {+ if (!active) return;clearPendingConnect();setPhase("notFound");}})();- }, [loading, session, requestId]);+ return () => {+ active = false;+ };+ }, [loading, accountId, requestId]);const onDecide = useCallback(async (approve: boolean) => {- if (!requestId || !(approve ? pending?.canApprove : pending?.canDeny))+ if (+ busy ||+ !requestId ||+ !pending ||+ !(approve+ ? pending.canApprove+ : pending.canDeny && pending.mode !== "REAUTH")+ )return;setBusy(true);setError(null);@@ -105,7 +132,23 @@ export default function ConnectApprove() {clearPendingConnect();setPhase("redirecting");window.location.replace(returnUrl(res.data, session));- } catch {+ } catch (cause) {+ if (pending.mode === "REAUTH") {+ const status = isAxiosError(cause)+ ? cause.response?.status+ : undefined;+ if (status === 403 || status === 409) {+ setLookup({ ...pending, canApprove: false, canDeny: false });+ } else {+ setError(+ t(+ "connect.renewal.failed",+ "Your sign-in could not be renewed. Try again, or dismiss this page and start again from your server.",+ ),+ );+ }+ return;+ }setError(t("connect.error.failed",@@ -116,7 +159,7 @@ export default function ConnectApprove() {setBusy(false);}},- [requestId, pending, session, t],+ [busy, requestId, pending, session, t],);/**@@ -127,7 +170,7 @@ export default function ConnectApprove() {}, [signOut]);const onDismiss = useCallback(() => {- if (!pending || pending.canDeny) return;+ if (!pending || (pending.canDeny && pending.mode !== "REAUTH")) return;clearPendingConnect();navigate("/", { replace: true });}, [pending, navigate]);@@ -153,7 +196,8 @@ export default function ConnectApprove() {</div><ConnectApproveView- phase={phase}+ key={`${requestId}:${accountId}`}+ phase={phase === "confirm" && !pending ? "loading" : phase}pending={pending}signedInEmail={user?.email ?? null}busy={busy}diff --git a/frontend/editor/src/saas/routes/ConnectApproveView.tsx b/frontend/editor/src/saas/routes/ConnectApproveView.tsxindex 1a9282b9e5..ee67762565 100644--- a/frontend/editor/src/saas/routes/ConnectApproveView.tsx+++ b/frontend/editor/src/saas/routes/ConnectApproveView.tsx@@ -3,14 +3,11 @@ import { useTranslation } from "@app/hooks/useTranslation";import { Banner, Button, Checkbox, Spinner } from "@app/ui";import { LocalIcon } from "@app/components/shared/LocalIcon";import { Tooltip } from "@app/components/shared/Tooltip";-import { StepModalHeader } from "@portal/components/shared/StepModalHeader";+import { StepModalHeader } from "@app/portal/components/shared/StepModalHeader";/*** This page is step 2 of a flow that started on the instance, so it wears the same chrome: the admin* is being asked for a security decision by what would otherwise look like a different product.- *- * <p>TODO: re-auth still wears the first link's copy and consent checkbox, which asks the approver- * to agree to a binding that already exists.*/const TOTAL_STEPS = 3;@@ -58,7 +55,7 @@ export interface PendingConnect {requestId: string;callbackOrigin: string;insecureTransport: boolean;- /** REAUTH cannot rebind: the team is pinned from the device credential at request time. */+ /** REAUTH can only confirm the original account and team authenticated by the device credential. */mode?: "LINK" | "REAUTH";canApprove: boolean;canDeny: boolean;@@ -67,7 +64,7 @@ export interface PendingConnect {export interface ConnectApproveViewProps {phase: ApprovePhase;pending: PendingConnect | null;- /** Email of the account the server would be connected to. */+ /** Email of the current signed-in account; never another account's email. */signedInEmail: string | null;busy: boolean;error: string | null;@@ -93,7 +90,8 @@ export function ConnectApproveView({// Gates the primary action: anyone can create a request, so the approver reading// the address is the only thing between one and a linked team.const [acknowledged, setAcknowledged] = useState(false);- const stepped = pending?.mode !== "REAUTH";+ const renewal = pending?.mode === "REAUTH";+ const stepped = !renewal;if (phase === "loading" || phase === "redirecting") {return (@@ -153,18 +151,32 @@ export function ConnectApproveView({return (<ApproveShellstepped={stepped}- title={t("connect.confirm.title", "Connect this server?")}+ title={+ renewal+ ? t("connect.renewal.title", "Renew your server sign-in")+ : t("connect.confirm.title", "Connect this server?")+ }><p className="saas-connect__lead">- {pending?.canApprove- ? t(- "connect.confirm.lead",- "A Stirling server is asking to connect to your team. Check the address below is yours before you approve.",- )- : t(- "connect.confirm.cannotDecide",- "Only a team owner can approve or decline this connection. Use a different account or dismiss this prompt to continue using Stirling.",- )}+ {renewal+ ? pending?.canApprove+ ? t(+ "connect.renewal.lead",+ "This server is already linked to your account. Renew your sign-in to return to billing and usage on your server.",+ )+ : t(+ "connect.renewal.wrongAccount",+ "This account cannot renew this server's sign-in. Switch to the account originally used to link the server. That account must still own the linked team.",+ )+ : pending?.canApprove+ ? t(+ "connect.confirm.lead",+ "A Stirling server is asking to connect to your team. Check the address below is yours before you approve.",+ )+ : t(+ "connect.confirm.cannotDecide",+ "Only a team owner can approve or decline this connection. Use a different account or dismiss this prompt to continue using Stirling.",+ )}</p>{/* One panel, because the account and the address are two halves of the same@@ -216,7 +228,7 @@ export function ConnectApproveView({{error ? <Banner tone="danger">{error}</Banner> : null}- {pending?.canApprove ? (+ {pending?.canApprove && !renewal ? (<Checkboxchecked={acknowledged}disabled={busy}@@ -229,7 +241,7 @@ export function ConnectApproveView({) : null}<div className="saas-connect__actions">- {pending?.canDeny ? (+ {pending?.canDeny && !renewal ? (<Buttonvariant="secondary"disabled={busy}@@ -245,10 +257,12 @@ export function ConnectApproveView({{pending?.canApprove ? (<Buttonvariant="primary"- disabled={busy || !acknowledged}+ disabled={busy || (!renewal && !acknowledged)}onClick={() => onDecide(true)}>- {t("connect.confirm.approve", "Connect server")}+ {renewal+ ? t("connect.renewal.approve", "Renew sign-in")+ : t("connect.confirm.approve", "Connect server")}</Button>) : null}</div>diff --git a/frontend/editor/src/saas/services/apiClient.ts b/frontend/editor/src/saas/services/apiClient.tsindex 3e06d4f42a..a71bcef025 100644--- a/frontend/editor/src/saas/services/apiClient.ts+++ b/frontend/editor/src/saas/services/apiClient.ts@@ -6,9 +6,8 @@ import {normalizePaygError,handlePaygError,} from "@app/services/paygErrorInterceptor";-import { stripBasePath, withBasePath } from "@app/constants/app";+import { redirectToLogin } from "@app/auth/redirectToLogin";import { getBrowserId } from "@app/utils/browserIdentifier";-import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";// Helper: decode base64url JWT payload safelyfunction decodeJwtPayload(token: string): Record<string, unknown> | null {@@ -115,21 +114,6 @@ function refreshSessionOnce(): ReturnType<typeof supabase.auth.refreshSession> {return inFlightRefresh;}-// Hard-redirect to /login, carrying where the user was so the login screen can-// return them there instead of falling through to the default landing (which-// sends opted-in users to the processor - the "refresh /editor bounces me to the-// processor" bug). Router-relative, matching what Login reads via `?next=`.-function redirectToLogin(): void {- const loginPath = withBasePath("/login");- // Already on the login page: another redirect would just loop.- if (window.location.pathname === loginPath) return;- const returnPath =- stripBasePath(window.location.pathname) + window.location.search;- window.location.href = isSafePostLoginRedirect(returnPath)- ? `${loginPath}?next=${encodeURIComponent(returnPath)}`- : loginPath;-}-// Response interceptor for handling token refreshapiClient.interceptors.response.use((response) => response,diff --git a/frontend/editor/src/saas/tsconfig.json b/frontend/editor/src/saas/tsconfig.jsonindex a887c3c5c5..3408c966db 100644--- a/frontend/editor/src/saas/tsconfig.json+++ b/frontend/editor/src/saas/tsconfig.json@@ -8,6 +8,14 @@"../../src/proprietary/*","../../src/core/*"],+ "@app/portal/*": [+ "../../src/saas/portal/*",+ "../../src/cloud/portal/*",+ "../../src/proprietary/portal/*",+ "../../src/core/portal/*",+ "../../src/portal-saas/*",+ "../../src/portal/*"+ ],"@portal/*": ["../../src/portal-saas/*", "../../src/portal/*"],"@portal-proprietary/*": ["../../src/portal/*"],"@cloud/*": ["../../src/cloud/*"],diff --git a/frontend/editor/tsconfig.portal.vite.json b/frontend/editor/tsconfig.portal.vite.jsonindex 924d616019..d05edf829e 100644--- a/frontend/editor/tsconfig.portal.vite.json+++ b/frontend/editor/tsconfig.portal.vite.json@@ -4,6 +4,12 @@"compilerOptions": {"paths": {"@app/*": ["./src/cloud/*", "./src/proprietary/*", "./src/core/*"],+ "@app/portal/*": [+ "./src/cloud/portal/*",+ "./src/proprietary/portal/*",+ "./src/core/portal/*",+ "./src/portal/*"+ ],"@portal/*": ["./src/portal/*"],"@cloud/*": ["./src/cloud/*"],"@proprietary/*": ["./src/proprietary/*"],diff --git a/frontend/editor/tsconfig.proprietary.vite.json b/frontend/editor/tsconfig.proprietary.vite.jsonindex 077a0ffd86..fc31550cea 100644--- a/frontend/editor/tsconfig.proprietary.vite.json+++ b/frontend/editor/tsconfig.proprietary.vite.json@@ -3,6 +3,11 @@"compilerOptions": {"paths": {"@app/*": ["./src/proprietary/*", "./src/core/*"],+ "@app/portal/*": [+ "./src/proprietary/portal/*",+ "./src/core/portal/*",+ "./src/portal/*"+ ],"@portal/*": ["./src/portal/*"],"@proprietary/*": ["./src/proprietary/*"],"@core/*": ["./src/core/*"]diff --git a/frontend/editor/tsconfig.prototypes.vite.json b/frontend/editor/tsconfig.prototypes.vite.jsonindex 2166b53670..d98a896999 100644--- a/frontend/editor/tsconfig.prototypes.vite.json+++ b/frontend/editor/tsconfig.prototypes.vite.json@@ -4,7 +4,14 @@"paths": {"@app/*": ["./src/prototypes/*", "./src/proprietary/*", "./src/core/*"],"@proprietary/*": ["./src/proprietary/*"],- "@core/*": ["./src/core/*"]+ "@core/*": ["./src/core/*"],+ "@app/portal/*": [+ "./src/prototypes/portal/*",+ "./src/proprietary/portal/*",+ "./src/core/portal/*",+ "./src/portal/*"+ ],+ "@portal/*": ["./src/portal/*"]}},"exclude": [diff --git a/frontend/editor/tsconfig.saas.vite.json b/frontend/editor/tsconfig.saas.vite.jsonindex f31279fac3..ee80013e66 100644--- a/frontend/editor/tsconfig.saas.vite.json+++ b/frontend/editor/tsconfig.saas.vite.json@@ -8,6 +8,14 @@"./src/proprietary/*","./src/core/*"],+ "@app/portal/*": [+ "./src/saas/portal/*",+ "./src/cloud/portal/*",+ "./src/proprietary/portal/*",+ "./src/core/portal/*",+ "./src/portal-saas/*",+ "./src/portal/*"+ ],"@portal/*": ["./src/portal-saas/*", "./src/portal/*"],"@portal-proprietary/*": ["./src/portal/*"],"@cloud/*": ["./src/cloud/*"],