Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Open OneDrive and Google Drive files from the editor (#8698)

Anthony Stirling35b2aaa2e3d4
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index 85295534af..cd829fbd2a 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -1934,6 +1934,7 @@ public class ApplicationProperties {
private String tenant = "common";
@ToString.Exclude private String clientSecret = "";
private boolean allowAccountConnections = true;
+ private boolean allowEditorSaves = true;
public boolean accountConnectionsReady() {
return enabled
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
index 161aab737c..eb3d233659 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
@@ -262,6 +262,19 @@ public class ConfigController {
enableLogin && googleDrive.accountConnectionsReady());
ApplicationProperties.Premium.ProFeatures.Microsoft microsoft =
applicationProperties.getPremium().getProFeatures().getMicrosoft();
+ if (microsoft.isEnabled()) {
+ configData.put("microsoftEnabled", true);
+ configData.put("microsoftClientId", microsoft.getClientId());
+ configData.put("microsoftTenant", microsoft.getTenant());
+ configData.put(
+ "microsoftGraphUrl",
+ applicationContext
+ .getEnvironment()
+ .getProperty(
+ "stirling.microsoft.graph-url",
+ "https://graph.microsoft.com/v1.0"));
+ configData.put("microsoftAllowEditorSaves", microsoft.isAllowEditorSaves());
+ }
configData.put(
"microsoftAccountConnections",
enableLogin && microsoft.accountConnectionsReady());
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index e160bb98e2..5c8fd4dadc 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -113,11 +113,12 @@ premium:
allowAccountConnections: true # set to 'false' to stop users connecting their own Google account
accountScope: drive # Drive scope requested when a user connects: 'drive' (every file) or 'drive.file' (only files they pick or Stirling creates)
microsoft:
- enabled: false # Enable OneDrive and SharePoint (connected accounts, pipeline locations)
+ enabled: false # Enable OneDrive and SharePoint (editor picker, connected accounts, pipeline locations)
clientId: "" # Application (client) ID of the Microsoft Entra app registration
tenant: common # 'common' (work, school and personal accounts), 'organizations' (work and school only), or a tenant ID/domain to admit one organisation
clientSecret: "" # Client secret; needed for connected accounts (redirect URI <server>/api/v1/connected-accounts/callback/microsoft)
allowAccountConnections: true # set to 'false' to stop users connecting their own Microsoft account
+ allowEditorSaves: true # set to 'false' to stop the editor saving files back to OneDrive; the server then refuses those saves
enterpriseFeatures:
audit:
enabled: true # Enable audit logging for security and compliance tracking
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
index e0be3e3722..6532f27c8e 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
@@ -218,20 +218,26 @@ class ConfigControllerMoreTest {
}
@Test
- @DisplayName("gates Microsoft account connections and never exposes the secret")
- void microsoftAccountConnections() {
+ @DisplayName(
+ "exposes the Microsoft app but never its secret, and gates account connections")
+ void microsoftEnabled() {
ApplicationProperties.Premium.ProFeatures.Microsoft microsoft =
applicationProperties.getPremium().getProFeatures().getMicrosoft();
microsoft.setClientId("app-id");
microsoft.setClientSecret("server-only");
HttpServletRequest request = mock(HttpServletRequest.class);
assertThat(bodyOf(newController().getAppConfig(request)))
+ .doesNotContainKey("microsoftClientId")
.containsEntry("microsoftAccountConnections", false);
microsoft.setEnabled(true);
+ microsoft.setTenant("organizations");
Map<String, Object> body = bodyOf(newController().getAppConfig(request));
- assertThat(body).containsKey("microsoftAccountConnections");
+ assertThat(body).containsEntry("microsoftEnabled", true);
+ assertThat(body).containsEntry("microsoftClientId", "app-id");
+ assertThat(body).containsEntry("microsoftTenant", "organizations");
+ assertThat(body).containsEntry("microsoftAllowEditorSaves", true);
assertThat(body.values()).doesNotContain("server-only");
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountController.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountController.java
index 2f10793c50..e0a055c5ee 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountController.java
@@ -1,11 +1,14 @@
package stirling.software.proprietary.connectedaccount;
import java.io.IOException;
+import java.net.URI;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.http.HttpHeaders;
@@ -19,6 +22,7 @@ import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@@ -31,6 +35,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.microsoft.GraphEndpoints;
import stirling.software.proprietary.security.model.User;
@Slf4j
@@ -44,9 +49,12 @@ public class ConnectedAccountController {
private static final String NONCE_COOKIE = "stirling_connect_nonce";
private static final String CONNECT_FAILED = "The account could not be connected.";
private static final String PERSONAL_MICROSOFT_TENANT = "9188040d-6c67-4c5b-b112-36a304b66dad";
+ private static final Set<String> SHAREPOINT_HOST_SUFFIXES =
+ Set.of(".sharepoint.com", ".sharepoint.us", ".sharepoint.de", ".sharepoint.cn");
private final ConnectedAccountService service;
private final ApplicationProperties applicationProperties;
+ private final GraphEndpoints graphEndpoints;
@GetMapping
public ConnectedAccountsResponse list(@AuthenticationPrincipal User user) {
@@ -158,6 +166,71 @@ public class ConnectedAccountController {
return ResponseEntity.noContent().build();
}
+ @PostMapping("/{id}/access-token")
+ public AccessTokenResponse accessToken(
+ @PathVariable long id,
+ @RequestBody AccessTokenRequest request,
+ @AuthenticationPrincipal User user) {
+ requireUser(user);
+ ConnectedAccount account =
+ service.findOwned(user, id)
+ .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
+ List<String> scopes = scopesFor(account.cloudProvider(), request.resource());
+ try {
+ return new AccessTokenResponse(service.accessToken(id, scopes));
+ } catch (AccountReconnectRequiredException e) {
+ throw new ResponseStatusException(HttpStatus.CONFLICT, e.getMessage());
+ } catch (IOException e) {
+ throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage());
+ }
+ }
+
+ List<String> scopesFor(CloudProvider provider, String resource) {
+ if (resource == null || resource.isBlank()) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "resource is required");
+ }
+ if (provider == CloudProvider.GOOGLE) {
+ if (!"drive".equals(resource)) {
+ throw unsupportedResource();
+ }
+ return List.of(
+ GoogleOAuthClient.browserScope(
+ applicationProperties.getPremium().getProFeatures().getGoogleDrive()));
+ }
+ if ("graph".equals(resource)) {
+ return List.of(MicrosoftOAuthClient.BROWSER_SCOPE);
+ }
+ URI uri;
+ try {
+ uri = URI.create(resource);
+ } catch (IllegalArgumentException e) {
+ throw unsupportedResource();
+ }
+ String origin = origin(uri);
+ if (origin.equals(origin(URI.create(graphEndpoints.graphUrl())))) {
+ return List.of(MicrosoftOAuthClient.BROWSER_SCOPE);
+ }
+ if (!isSharePoint(uri)) {
+ throw unsupportedResource();
+ }
+ return List.of(origin + "/.default");
+ }
+
+ private static ResponseStatusException unsupportedResource() {
+ return new ResponseStatusException(HttpStatus.BAD_REQUEST, "unsupported resource");
+ }
+
+ private static boolean isSharePoint(URI uri) {
+ String host = uri.getHost() == null ? "" : uri.getHost().toLowerCase(Locale.ROOT);
+ return "https".equals(uri.getScheme())
+ && SHAREPOINT_HOST_SUFFIXES.stream().anyMatch(host::endsWith);
+ }
+
+ private static String origin(URI uri) {
+ String port = uri.getPort() == -1 ? "" : ":" + uri.getPort();
+ return uri.getScheme() + "://" + uri.getHost() + port;
+ }
+
private String publicBaseUrl() {
String configured = applicationProperties.getSystem().getFrontendUrl();
if (configured != null && !configured.isBlank()) {
@@ -256,4 +329,8 @@ public class ConnectedAccountController {
boolean personal,
String lastError,
LocalDateTime createdAt) {}
+
+ public record AccessTokenRequest(String resource) {}
+
+ public record AccessTokenResponse(String accessToken) {}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountService.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountService.java
index 9288fe1744..78dcad9a6c 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountService.java
@@ -209,7 +209,11 @@ public class ConnectedAccountService {
try {
tokens = client.refresh(account.getRefreshToken(), scopes);
} catch (OAuthException e) {
- if (e.isRevoked()) {
+ // Signing in again cannot grant a scope the app was never given, and the
+ // account still works for the scopes it was connected with.
+ boolean extraScopeRefused =
+ scopes != null && !scopes.isEmpty() && e.isConsentRequired();
+ if (e.isRevoked() && !extraScopeRefused) {
account.setStatus(ConnectedAccount.STATUS_NEEDS_RECONNECT);
account.setLastError(e.getMessage());
accounts.save(account);
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedDriveController.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedDriveController.java
new file mode 100644
index 0000000000..0102449a4e
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedDriveController.java
@@ -0,0 +1,124 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Map;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.core.annotation.AuthenticationPrincipal;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.server.ResponseStatusException;
+
+import io.swagger.v3.oas.annotations.tags.Tag;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.microsoft.ConnectedDriveWriter;
+import stirling.software.proprietary.security.model.User;
+
+@Slf4j
+@RestController
+@RequestMapping("/api/v1/connected-accounts")
+@RequiredArgsConstructor
+@Tag(name = "Connected accounts", description = "Users' own OneDrive, SharePoint and Google Drive")
+public class ConnectedDriveController {
+
+ private final ConnectedAccountService service;
+ private final ConnectedDriveWriter writer;
+ private final ApplicationProperties applicationProperties;
+
+ @PostMapping(value = "/{id}/drive/save", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ public ResponseEntity<?> save(
+ @PathVariable long id,
+ @RequestParam("fileInput") MultipartFile file,
+ @RequestParam("driveId") String driveId,
+ @RequestParam(value = "itemId", required = false) String itemId,
+ @RequestParam(value = "eTag", required = false) String eTag,
+ @RequestParam(value = "parentId", required = false) String parentId,
+ @RequestParam(value = "name", required = false) String name,
+ @AuthenticationPrincipal User user) {
+ if (user == null) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
+ }
+ if (!editorSavesAllowed(applicationProperties)) {
+ throw new ResponseStatusException(
+ HttpStatus.FORBIDDEN, "Saving to OneDrive from the editor is turned off");
+ }
+ ConnectedAccount account =
+ service.findOwned(user, id)
+ .filter(owned -> owned.cloudProvider() == CloudProvider.MICROSOFT)
+ .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
+ ConnectedDriveWriter.Target target = target(driveId, itemId, eTag, parentId, name);
+ Path content = null;
+ try {
+ content = Files.createTempFile("stirling-drive-save-", ".bin");
+ file.transferTo(content);
+ return ResponseEntity.ok(writer.save(account.getId(), target, content));
+ } catch (ConnectedDriveWriter.ConflictException e) {
+ return ResponseEntity.status(HttpStatus.CONFLICT)
+ .body(Map.of("code", "conflict", "message", e.getMessage()));
+ } catch (ConnectedDriveWriter.MissingException e) {
+ return ResponseEntity.status(HttpStatus.GONE)
+ .body(Map.of("code", "missing", "message", e.getMessage()));
+ } catch (AccountReconnectRequiredException e) {
+ throw new ResponseStatusException(HttpStatus.CONFLICT, e.getMessage());
+ } catch (IOException e) {
+ log.warn("Saving to the connected drive failed: {}", e.getMessage());
+ throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage());
+ } finally {
+ if (content != null) {
+ try {
+ Files.deleteIfExists(content);
+ } catch (IOException e) {
+ log.debug("Could not delete {}: {}", content, e.getMessage());
+ }
+ }
+ }
+ }
+
+ static ConnectedDriveWriter.Target target(
+ String driveId, String itemId, String eTag, String parentId, String name) {
+ if (isBlank(driveId)) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "driveId is required");
+ }
+ if (!ConnectedDriveWriter.isValidId(driveId)
+ || (!isBlank(itemId) && !ConnectedDriveWriter.isValidId(itemId))
+ || (!isBlank(parentId) && !ConnectedDriveWriter.isValidId(parentId))) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "invalid drive or item ID");
+ }
+ if (!isBlank(itemId)) {
+ if (isBlank(eTag)) {
+ throw new ResponseStatusException(
+ HttpStatus.PRECONDITION_REQUIRED, "eTag is required to replace a file");
+ }
+ return new ConnectedDriveWriter.Replace(driveId, itemId, eTag);
+ }
+ if (isBlank(parentId) || isBlank(name)) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "itemId, or parentId and name, are required");
+ }
+ String trimmed = name.trim();
+ if (!ConnectedDriveWriter.isValidName(trimmed)) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "invalid file name");
+ }
+ return new ConnectedDriveWriter.Create(driveId, parentId, trimmed, true);
+ }
+
+ static boolean editorSavesAllowed(ApplicationProperties properties) {
+ return properties.getPremium().getProFeatures().getMicrosoft().isAllowEditorSaves();
+ }
+
+ private static boolean isBlank(String value) {
+ return value == null || value.isBlank();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClient.java
index d969391193..80a27b1c01 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClient.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClient.java
@@ -25,6 +25,7 @@ import tools.jackson.databind.JsonNode;
@RequiredArgsConstructor
public class GoogleOAuthClient implements CloudOAuthClient {
+ private static final String SCOPE_PREFIX = "https://www.googleapis.com/auth/";
private static final HttpClient HTTP =
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
@@ -47,7 +48,7 @@ public class GoogleOAuthClient implements CloudOAuthClient {
query.put("client_id", app().getClientId());
query.put("response_type", "code");
query.put("redirect_uri", redirectUri);
- query.put("scope", "openid email profile " + driveScope());
+ query.put("scope", consentScopes());
query.put("access_type", "offline");
query.put("prompt", "consent");
query.put("include_granted_scopes", "true");
@@ -85,12 +86,12 @@ public class GoogleOAuthClient implements CloudOAuthClient {
@Override
public OAuthTokens refresh(String refreshToken, List<String> scopes) throws IOException {
- return OAuthHttp.tokens(
- OAuthHttp.postTokenRequest(
- endpoints.tokenUrl(),
- OAuthHttp.refreshGrant(
- app().getClientId(), app().getClientSecret(), refreshToken)),
- null);
+ Map<String, String> grant =
+ OAuthHttp.refreshGrant(app().getClientId(), app().getClientSecret(), refreshToken);
+ if (scopes != null && !scopes.isEmpty()) {
+ grant.put("scope", String.join(" ", scopes));
+ }
+ return OAuthHttp.tokens(OAuthHttp.postTokenRequest(endpoints.tokenUrl(), grant), null);
}
@Override
@@ -113,12 +114,34 @@ public class GoogleOAuthClient implements CloudOAuthClient {
}
String driveScope() {
- String scope = app().validAccountScope();
+ return SCOPE_PREFIX + accountScope(app());
+ }
+
+ /**
+ * Scope for tokens handed to the browser picker, which only lists and downloads files. A
+ * refresh can only ask for scopes granted at consent, so {@link #consentScopes()} must request
+ * this one too.
+ *
+ * @throws IllegalStateException when {@code accountScope} is not a Drive scope
+ */
+ static String browserScope(ApplicationProperties.Premium.ProFeatures.GoogleDrive app) {
+ return SCOPE_PREFIX
+ + ("drive.file".equals(accountScope(app)) ? "drive.file" : "drive.readonly");
+ }
+
+ String consentScopes() {
+ String drive = driveScope();
+ String browser = browserScope(app());
+ return "openid email profile " + (drive.equals(browser) ? drive : drive + " " + browser);
+ }
+
+ private static String accountScope(ApplicationProperties.Premium.ProFeatures.GoogleDrive app) {
+ String scope = app.validAccountScope();
if (scope == null) {
throw new IllegalStateException(
"googleDrive.accountScope must be drive, drive.file or drive.readonly");
}
- return "https://www.googleapis.com/auth/" + scope;
+ return scope;
}
private ApplicationProperties.Premium.ProFeatures.GoogleDrive app() {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthException.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthException.java
index 2de866beba..77769875b1 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthException.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthException.java
@@ -7,13 +7,23 @@ public class OAuthException extends IOException {
private static final long serialVersionUID = 1L;
private final boolean revoked;
+ private final boolean consentRequired;
- public OAuthException(String message, boolean revoked) {
+ public OAuthException(String message, boolean revoked, boolean consentRequired) {
super(message);
this.revoked = revoked;
+ this.consentRequired = consentRequired;
}
public boolean isRevoked() {
return revoked;
}
+
+ /**
+ * The grant was refused because a requested scope was never consented to (Microsoft
+ * AADSTS65001), not because the grant itself is gone.
+ */
+ public boolean isConsentRequired() {
+ return consentRequired;
+ }
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthHttp.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthHttp.java
index dd234076df..a98c4ddb61 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthHttp.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthHttp.java
@@ -102,7 +102,9 @@ public final class OAuthHttp {
String detail = description != null ? firstLine(description) : error;
throw new OAuthException(
"sign-in refused: " + (detail == null ? "HTTP " + response.statusCode() : detail),
- "invalid_grant".equals(error));
+ "invalid_grant".equals(error),
+ "consent_required".equals(text(body, "suberror"))
+ || (description != null && description.startsWith("AADSTS65001")));
}
public static JsonNode idTokenClaims(String idToken) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/ConnectedDriveWriter.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/ConnectedDriveWriter.java
new file mode 100644
index 0000000000..38a75c2fc0
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/ConnectedDriveWriter.java
@@ -0,0 +1,342 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
+import stirling.software.proprietary.connectedaccount.OAuthHttp;
+import stirling.software.proprietary.policy.remote.CloudHttp;
+
+import tools.jackson.databind.JsonNode;
+
+@Slf4j
+@Component
+public class ConnectedDriveWriter {
+
+ private static final long SIMPLE_UPLOAD_LIMIT = GraphDriveClient.SIMPLE_UPLOAD_LIMIT;
+ private static final int UPLOAD_CHUNK = GraphDriveClient.UPLOAD_CHUNK;
+ private static final String ITEM_FIELDS = "id,name,eTag,webUrl,parentReference";
+ private static final Pattern GRAPH_ID = Pattern.compile("[A-Za-z0-9!_.-]{1,512}");
+ private static final int MAX_NAME_LENGTH = 255;
+
+ private final GraphEndpoints endpoints;
+ private final ConnectedAccountService accounts;
+ private final HttpClient http;
+
+ @Autowired
+ public ConnectedDriveWriter(GraphEndpoints endpoints, ConnectedAccountService accounts) {
+ this(endpoints, accounts, CloudHttp.newClient());
+ }
+
+ ConnectedDriveWriter(
+ GraphEndpoints endpoints, ConnectedAccountService accounts, HttpClient http) {
+ this.endpoints = endpoints;
+ this.accounts = accounts;
+ this.http = http;
+ }
+
+ public sealed interface Target permits Replace, Create {}
+
+ public record Replace(String driveId, String itemId, String eTag) implements Target {}
+
+ public record Create(String driveId, String parentId, String name, boolean renameOnConflict)
+ implements Target {}
+
+ public record SavedItem(
+ String driveId,
+ String itemId,
+ String parentId,
+ String name,
+ String eTag,
+ String webUrl) {}
+
+ public static class ConflictException extends IOException {
+ public ConflictException(String message) {
+ super(message);
+ }
+ }
+
+ public static class MissingException extends IOException {
+ public MissingException(String message) {
+ super(message);
+ }
+ }
+
+ public static boolean isValidId(String value) {
+ return value != null
+ && GRAPH_ID.matcher(value).matches()
+ && !".".equals(value)
+ && !"..".equals(value);
+ }
+
+ public static boolean isValidName(String value) {
+ return value != null
+ && !value.isBlank()
+ && value.length() <= MAX_NAME_LENGTH
+ && !".".equals(value)
+ && !"..".equals(value)
+ && value.chars().noneMatch(c -> c == '/' || c == '\\' || Character.isISOControl(c));
+ }
+
+ public SavedItem save(long accountId, Target target, Path content) throws IOException {
+ requireValid(target);
+ String token = accounts.accessToken(accountId, List.of());
+ long size = Files.size(content);
+ if (size <= SIMPLE_UPLOAD_LIMIT) {
+ HttpRequest.Builder request =
+ authorized(token, contentUrl(target))
+ .header("Content-Type", "application/octet-stream")
+ .PUT(HttpRequest.BodyPublishers.ofFile(content));
+ ifMatch(request, target);
+ HttpResponse<String> response = send(request.build());
+ requireSaved(response, target, "save");
+ return fetch(token, parse(response.body()));
+ }
+ return saveInSession(token, target, content, size);
+ }
+
+ private SavedItem saveInSession(String token, Target target, Path content, long size)
+ throws IOException {
+ HttpRequest.Builder start =
+ authorized(token, sessionUrl(target))
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(sessionBody(target)));
+ ifMatch(start, target);
+ HttpResponse<String> created = send(start.build());
+ requireSaved(created, target, "start saving");
+ String uploadUrl = text(parse(created.body()), "uploadUrl");
+ if (uploadUrl == null) {
+ throw new IOException("Microsoft Graph returned no upload URL");
+ }
+ byte[] buffer = new byte[(int) Math.min(UPLOAD_CHUNK, size)];
+ try (RandomAccessFile file = new RandomAccessFile(content.toFile(), "r")) {
+ long offset = 0;
+ while (offset < size) {
+ int length = (int) Math.min(buffer.length, size - offset);
+ file.readFully(buffer, 0, length);
+ HttpResponse<String> chunk =
+ send(
+ HttpRequest.newBuilder(URI.create(uploadUrl))
+ .timeout(Duration.ofMinutes(10))
+ .header(
+ "Content-Range",
+ "bytes %d-%d/%d"
+ .formatted(
+ offset, offset + length - 1, size))
+ .PUT(
+ HttpRequest.BodyPublishers.ofByteArray(
+ buffer, 0, length))
+ .build());
+ offset += length;
+ if (chunk.statusCode() >= 300) {
+ cancelSession(uploadUrl);
+ requireSaved(chunk, target, "save");
+ }
+ if (offset >= size) {
+ return fetch(token, parse(chunk.body()));
+ }
+ }
+ }
+ throw new IOException("Saving " + describe(target) + " ended without a completed item");
+ }
+
+ private SavedItem fetch(String token, JsonNode item) throws IOException {
+ String driveId = text(item.path("parentReference"), "driveId");
+ String itemId = text(item, "id");
+ if (!isValidId(driveId) || !isValidId(itemId)) {
+ throw new IOException("Microsoft Graph returned no saved item");
+ }
+ HttpResponse<String> response =
+ send(
+ authorized(token, itemUrl(driveId, itemId) + "?$select=" + ITEM_FIELDS)
+ .GET()
+ .build());
+ requireSuccess(response, "read the saved file");
+ JsonNode saved = parse(response.body());
+ return new SavedItem(
+ driveId,
+ itemId,
+ text(saved.path("parentReference"), "id"),
+ text(saved, "name"),
+ text(saved, "eTag"),
+ text(saved, "webUrl"));
+ }
+
+ private static void requireValid(Target target) throws IOException {
+ boolean valid =
+ switch (target) {
+ case Replace replace ->
+ isValidId(replace.driveId()) && isValidId(replace.itemId());
+ case Create create ->
+ isValidId(create.driveId())
+ && isValidId(create.parentId())
+ && isValidName(create.name());
+ };
+ if (!valid) {
+ throw new IOException("Invalid drive item reference");
+ }
+ }
+
+ private String contentUrl(Target target) {
+ return switch (target) {
+ case Replace replace -> itemUrl(replace.driveId(), replace.itemId()) + "/content";
+ case Create create ->
+ childUrl(create)
+ + conflictBehavior(create);
+ };
+ }
+
+ private String sessionUrl(Target target) {
+ return switch (target) {
+ case Replace replace ->
+ itemUrl(replace.driveId(), replace.itemId()) + "/createUploadSession";
+ case Create create -> childUrl(create) + ":/createUploadSession";
+ };
+ }
+
+ private static String sessionBody(Target target) {
+ String behavior =
+ switch (target) {
+ case Replace replace -> "replace";
+ case Create create -> conflictBehavior(create);
+ };
+ return "{\"item\":{\"@microsoft.graph.conflictBehavior\":\"" + behavior + "\"}}";
+ }
+
+ private static String conflictBehavior(Create create) {
+ return create.renameOnConflict() ? "rename" : "fail";
+ }
+
+ private String itemUrl(String driveId, String itemId) {
+ return endpoints.graphUrl() + "/drives/" + segment(driveId) + "/items/" + segment(itemId);
+ }
+
+ private String childUrl(Create create) {
+ return itemUrl(create.driveId(), create.parentId()) + ":/" + segment(create.name());
+ }
+
+ private static void ifMatch(HttpRequest.Builder request, Target target) {
+ if (target instanceof Replace replace
+ && replace.eTag() != null
+ && !replace.eTag().isBlank()) {
+ request.header("If-Match", replace.eTag());
+ }
+ }
+
+ private static void requireSaved(HttpResponse<String> response, Target target, String action)
+ throws IOException {
+ requireNoConflict(response, target);
+ requireSuccess(response, action + " " + describe(target));
+ }
+
+ private static void requireNoConflict(HttpResponse<String> response, Target target)
+ throws ConflictException, MissingException {
+ int status = response.statusCode();
+ if (status == 404 && target instanceof Replace) {
+ throw new MissingException("The file was moved or deleted in OneDrive");
+ }
+ if (status == 412 || status == 409) {
+ throw new ConflictException(
+ target instanceof Replace
+ ? "The file changed in OneDrive since it was opened"
+ : "A file with that name already exists in the folder");
+ }
+ }
+
+ private static String describe(Target target) {
+ return switch (target) {
+ case Replace replace -> "the OneDrive file";
+ case Create create -> create.name();
+ };
+ }
+
+ private HttpRequest.Builder authorized(String token, String url) throws IOException {
+ return HttpRequest.newBuilder(graphUri(url))
+ .timeout(Duration.ofMinutes(2))
+ .header("Authorization", "Bearer " + token)
+ .header("Accept", "application/json");
+ }
+
+ private URI graphUri(String url) throws IOException {
+ URI graph = URI.create(endpoints.graphUrl());
+ URI uri;
+ try {
+ uri = new URI(url);
+ } catch (URISyntaxException e) {
+ throw new IOException("Invalid Microsoft Graph URL");
+ }
+ if (graph.getHost() == null || !graph.getHost().equals(uri.getHost())) {
+ throw new IOException("Refusing a request outside Microsoft Graph");
+ }
+ if (!graph.getScheme().equalsIgnoreCase(uri.getScheme())
+ || !graph.getRawAuthority().equalsIgnoreCase(uri.getRawAuthority())
+ || uri.getRawPath() == null
+ || !uri.getRawPath().startsWith(graph.getRawPath() + "/")) {
+ throw new IOException("Refusing a request outside Microsoft Graph");
+ }
+ return uri;
+ }
+
+ private HttpResponse<String> send(HttpRequest request) throws IOException {
+ return CloudHttp.send(
+ http, request, HttpResponse.BodyHandlers.ofString(), "Microsoft Graph");
+ }
+
+ private void cancelSession(String uploadUrl) {
+ try {
+ CloudHttp.send(
+ http,
+ HttpRequest.newBuilder(URI.create(uploadUrl)).DELETE().build(),
+ HttpResponse.BodyHandlers.discarding(),
+ "Microsoft Graph");
+ } catch (IOException e) {
+ log.debug("Could not cancel upload session: {}", e.getMessage());
+ }
+ }
+
+ private static void requireSuccess(HttpResponse<String> response, String action)
+ throws IOException {
+ int status = response.statusCode();
+ if (status >= 200 && status < 300) {
+ return;
+ }
+ JsonNode error = parse(response.body()).path("error");
+ String code = text(error, "code");
+ String message = text(error, "message");
+ throw new IOException(
+ "Could not "
+ + action
+ + ": HTTP "
+ + status
+ + (code == null ? "" : " " + code)
+ + (message == null ? "" : " - " + message));
+ }
+
+ private static String segment(String value) {
+ return OAuthHttp.encode(value);
+ }
+
+ private static JsonNode parse(String body) {
+ return CloudHttp.parse(body);
+ }
+
+ private static String text(JsonNode node, String field) {
+ return CloudHttp.text(node, field);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackTest.java
index d72b6c6dd1..4bf10836a3 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackTest.java
@@ -14,6 +14,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.microsoft.GraphEndpoints;
import stirling.software.proprietary.security.model.User;
class ConnectedAccountCallbackTest {
@@ -23,7 +24,11 @@ class ConnectedAccountCallbackTest {
private ConnectedAccountController controller() {
ApplicationProperties properties = new ApplicationProperties();
properties.getSystem().setFrontendUrl("https://stirling.example");
- return new ConnectedAccountController(service, properties);
+ return new ConnectedAccountController(
+ service,
+ properties,
+ new GraphEndpoints(
+ GraphEndpoints.DEFAULT_GRAPH_URL, GraphEndpoints.DEFAULT_LOGIN_URL));
}
@Test
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountScopesTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountScopesTest.java
new file mode 100644
index 0000000000..b538d7c1d2
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountScopesTest.java
@@ -0,0 +1,117 @@
+package stirling.software.proprietary.connectedaccount;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.google.GoogleEndpoints;
+import stirling.software.proprietary.policy.microsoft.GraphEndpoints;
+
+class ConnectedAccountScopesTest {
+
+ private final ConnectedAccountController controller =
+ new ConnectedAccountController(
+ mock(ConnectedAccountService.class),
+ new ApplicationProperties(),
+ new GraphEndpoints(
+ GraphEndpoints.DEFAULT_GRAPH_URL, GraphEndpoints.DEFAULT_LOGIN_URL));
+
+ @ParameterizedTest
+ @ValueSource(strings = {"graph", "https://graph.microsoft.com"})
+ void graphTokensForTheBrowserAreReadOnly(String resource) {
+ assertThat(controller.scopesFor(CloudProvider.MICROSOFT, resource))
+ .containsExactly(MicrosoftOAuthClient.BROWSER_SCOPE);
+ }
+
+ @Test
+ void sharePointTokensAreScopedToThatHost() {
+ assertThat(
+ controller.scopesFor(
+ CloudProvider.MICROSOFT, "https://contoso-my.sharepoint.com"))
+ .containsExactly("https://contoso-my.sharepoint.com/.default");
+ }
+
+ @Test
+ void sharePointScopeLeavesOutUserInfo() {
+ assertThat(
+ controller.scopesFor(
+ CloudProvider.MICROSOFT,
+ "https://[email protected]/sites/x"))
+ .containsExactly("https://contoso.sharepoint.com/.default");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"https://evil.example", "https://contoso.sharepoint.com.evil.test"})
+ void otherHostsAreRefused(String resource) {
+ assertThatThrownBy(() -> controller.scopesFor(CloudProvider.MICROSOFT, resource))
+ .isInstanceOf(ResponseStatusException.class);
+ }
+
+ @Test
+ void googleTokensForTheBrowserAreReadOnly() {
+ assertThat(controller.scopesFor(CloudProvider.GOOGLE, "drive"))
+ .containsExactly("https://www.googleapis.com/auth/drive.readonly");
+ }
+
+ private static ApplicationProperties.Premium.ProFeatures.GoogleDrive drive(
+ String accountScope) {
+ ApplicationProperties.Premium.ProFeatures.GoogleDrive app =
+ new ApplicationProperties.Premium.ProFeatures.GoogleDrive();
+ app.setAccountScope(accountScope);
+ return app;
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "drive, drive.readonly",
+ "drive.readonly, drive.readonly",
+ "drive.file, drive.file"
+ })
+ void googleBrowserScopeNeverAllowsWrites(String configured, String expected) {
+ assertThat(GoogleOAuthClient.browserScope(drive(configured)))
+ .isEqualTo("https://www.googleapis.com/auth/" + expected);
+ }
+
+ @ParameterizedTest
+ @NullSource
+ @ValueSource(strings = {"bogus", "drive.full"})
+ void googleBrowserScopeRefusesAnUnknownAccountScope(String configured) {
+ assertThatThrownBy(() -> GoogleOAuthClient.browserScope(drive(configured)))
+ .isInstanceOf(IllegalStateException.class);
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "drive, drive drive.readonly",
+ "drive.readonly, drive.readonly",
+ "drive.file, drive.file"
+ })
+ void googleConsentIncludesTheBrowserScope(String configured, String expected) {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getPremium().getProFeatures().getGoogleDrive().setAccountScope(configured);
+ GoogleOAuthClient client = new GoogleOAuthClient(properties, mock(GoogleEndpoints.class));
+
+ String driveScopes =
+ Arrays.stream(expected.split(" "))
+ .map(scope -> "https://www.googleapis.com/auth/" + scope)
+ .collect(Collectors.joining(" "));
+ assertThat(client.consentScopes()).isEqualTo("openid email profile " + driveScopes);
+ }
+
+ @Test
+ void googleRefusesOtherResources() {
+ assertThatThrownBy(() -> controller.scopesFor(CloudProvider.GOOGLE, "gmail"))
+ .isInstanceOf(ResponseStatusException.class);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountServiceTest.java
index f5aab6809e..84f8ebf036 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountServiceTest.java
@@ -171,6 +171,23 @@ class ConnectedAccountServiceTest {
assertThat(microsoft.tokenRequests.get()).isEqualTo(before);
}
+ @Test
+ void aScopeTheAppWasNeverGrantedFailsWithoutPausingTheAccount() throws Exception {
+ ConnectedAccount account = connect();
+ String sharePoint = "https://contoso.sharepoint.com/.default";
+ microsoft.unconsentedScopes.add(sharePoint);
+
+ OAuthException failure =
+ assertThrows(
+ OAuthException.class,
+ () -> service.accessToken(account.getId(), List.of(sharePoint)));
+
+ assertThat(failure.getMessage()).contains("AADSTS65001");
+ assertThat(store.rows.get(account.getId()).getStatus())
+ .isEqualTo(ConnectedAccount.STATUS_CONNECTED);
+ assertThat(service.accessToken(account.getId(), List.of("Sites.Read.All"))).isNotBlank();
+ }
+
@Test
void connectionsCanBeTurnedOffByTheAdmin() {
properties.getPremium().getProFeatures().getMicrosoft().setAllowAccountConnections(false);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedDriveControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedDriveControllerTest.java
new file mode 100644
index 0000000000..cd274207bc
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedDriveControllerTest.java
@@ -0,0 +1,86 @@
+package stirling.software.proprietary.connectedaccount;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.microsoft.ConnectedDriveWriter;
+
+class ConnectedDriveControllerTest {
+
+ @Test
+ void anItemIdReplacesThatItem() {
+ assertThat(ConnectedDriveController.target("d", "i", "\"e\"", "p", "x.pdf"))
+ .isEqualTo(new ConnectedDriveWriter.Replace("d", "i", "\"e\""));
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @ValueSource(strings = " ")
+ void aReplaceWithoutAVersionIsRefused(String eTag) {
+ assertThatThrownBy(() -> ConnectedDriveController.target("d", "i", eTag, "p", "x.pdf"))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("eTag");
+ }
+
+ @Test
+ void aFolderAndNameCreateAFileThatRenamesOnConflict() {
+ assertThat(ConnectedDriveController.target("d", null, null, "p", " Report.pdf "))
+ .isEqualTo(new ConnectedDriveWriter.Create("d", "p", "Report.pdf", true));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"../x.pdf", "a/b.pdf", "a\\b.pdf", "..", "."})
+ void namesThatCouldEscapeTheFolderAreRefused(String name) {
+ assertThatThrownBy(() -> ConnectedDriveController.target("d", null, null, "p", name))
+ .isInstanceOf(ResponseStatusException.class);
+ }
+
+ @ParameterizedTest
+ @CsvSource(
+ nullValues = "null",
+ value = {
+ "'..', i, null, null",
+ "'.', i, null, null",
+ "d, '..', null, null",
+ "d, '.', null, null",
+ "d, null, '..', x.pdf",
+ "d, null, '.', x.pdf"
+ })
+ void idsThatCouldLeaveTheGraphPathAreRefused(
+ String driveId, String itemId, String parentId, String name) {
+ assertThatThrownBy(
+ () ->
+ ConnectedDriveController.target(
+ driveId, itemId, "\"e\"", parentId, name))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("invalid drive or item ID");
+ }
+
+ @ParameterizedTest
+ @CsvSource(
+ nullValues = "null",
+ value = {"' ', i, null, null", "d, null, null, x.pdf"})
+ void aDriveAndATargetAreRequired(String driveId, String itemId, String parentId, String name) {
+ assertThatThrownBy(
+ () ->
+ ConnectedDriveController.target(
+ driveId, itemId, null, parentId, name))
+ .isInstanceOf(ResponseStatusException.class);
+ }
+
+ @Test
+ void editorSavesCanBeTurnedOff() {
+ ApplicationProperties properties = new ApplicationProperties();
+ assertThat(ConnectedDriveController.editorSavesAllowed(properties)).isTrue();
+ properties.getPremium().getProFeatures().getMicrosoft().setAllowEditorSaves(false);
+ assertThat(ConnectedDriveController.editorSavesAllowed(properties)).isFalse();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/ConnectedDriveWriterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/ConnectedDriveWriterTest.java
new file mode 100644
index 0000000000..eb71b5585b
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/ConnectedDriveWriterTest.java
@@ -0,0 +1,256 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.http.HttpClient;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.Function;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
+
+class ConnectedDriveWriterTest {
+
+ private static final String SAVED_ITEM =
+ "{\"id\":\"item-1\",\"parentReference\":{\"driveId\":\"drive-1\"}}";
+ private static final String SAVED_DETAILS =
+ "{\"id\":\"item-1\",\"name\":\"Report.pdf\",\"eTag\":\"\\\"{E},2\\\"\","
+ + "\"webUrl\":\"https://contoso/Report.pdf\","
+ + "\"parentReference\":{\"driveId\":\"drive-1\",\"id\":\"folder-1\"}}";
+
+ private static final ConnectedDriveWriter.Replace REPLACE =
+ new ConnectedDriveWriter.Replace("drive-1", "item-1", "\"{E},1\"");
+
+ record Seen(String method, String uri, String ifMatch, String auth, String range, int size) {}
+
+ @TempDir Path temp;
+
+ private HttpServer server;
+ private String base;
+ private final List<Seen> seen = new CopyOnWriteArrayList<>();
+ private Function<Seen, Response> respond;
+ private ConnectedDriveWriter writer;
+
+ record Response(int status, String body) {}
+
+ @BeforeEach
+ void setUp() throws IOException {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext("/", this::handle);
+ server.start();
+ base = "http://127.0.0.1:" + server.getAddress().getPort();
+ ConnectedAccountService accounts = mock(ConnectedAccountService.class);
+ when(accounts.accessToken(eq(33L), anyList())).thenReturn("write-token");
+ writer =
+ new ConnectedDriveWriter(
+ new GraphEndpoints(base + "/v1.0", base),
+ accounts,
+ HttpClient.newHttpClient());
+ }
+
+ @AfterEach
+ void tearDown() {
+ server.stop(0);
+ }
+
+ @Test
+ void replacingSendsTheEtagSoANewerVersionIsNeverOverwritten() throws IOException {
+ respond = savedWith(200);
+
+ ConnectedDriveWriter.SavedItem saved = writer.save(33L, REPLACE, file(10));
+
+ Seen put = seen.getFirst();
+ assertThat(put.method()).isEqualTo("PUT");
+ assertThat(put.uri()).isEqualTo("/v1.0/drives/drive-1/items/item-1/content");
+ assertThat(put.ifMatch()).isEqualTo("\"{E},1\"");
+ assertThat(put.auth()).isEqualTo("Bearer write-token");
+ assertThat(put.size()).isEqualTo(10);
+ assertThat(saved.eTag()).isEqualTo("\"{E},2\"");
+ assertThat(saved.parentId()).isEqualTo("folder-1");
+ assertThat(saved.webUrl()).isEqualTo("https://contoso/Report.pdf");
+ }
+
+ @Test
+ void aChangedFileIsAConflictNotAnOverwrite() throws IOException {
+ respond = request -> new Response(412, "{\"error\":{\"code\":\"resourceModified\"}}");
+
+ Path content = file(10);
+ assertThatThrownBy(() -> writer.save(33L, REPLACE, content))
+ .isInstanceOf(ConnectedDriveWriter.ConflictException.class);
+ }
+
+ @Test
+ void aDeletedFileIsReportedAsMissingSoTheUserCanSaveACopy() throws IOException {
+ respond = request -> new Response(404, "{\"error\":{\"code\":\"itemNotFound\"}}");
+
+ Path content = file(10);
+ assertThatThrownBy(() -> writer.save(33L, REPLACE, content))
+ .isInstanceOf(ConnectedDriveWriter.MissingException.class);
+ }
+
+ @Test
+ void creatingAFileRenamesRatherThanReplacingAnExistingOne() throws IOException {
+ respond = savedWith(201);
+
+ writer.save(
+ 33L,
+ new ConnectedDriveWriter.Create("drive-1", "folder-1", "Board report.pdf", true),
+ file(10));
+
+ Seen put = seen.getFirst();
+ assertThat(put.uri())
+ .isEqualTo(
+ "/v1.0/drives/drive-1/items/folder-1:/Board%20report.pdf:/content"
+ + "[email protected]=rename");
+ assertThat(put.ifMatch()).isNull();
+ }
+
+ @Test
+ void largeFilesGoThroughAnUploadSessionInChunks() throws IOException {
+ int size = (int) GraphDriveClient.SIMPLE_UPLOAD_LIMIT + GraphDriveClient.UPLOAD_CHUNK + 5;
+ respond =
+ request -> {
+ if (request.method().equals("POST")) {
+ return new Response(
+ 200, "{\"uploadUrl\":\"" + base + "/upload/session-1\"}");
+ }
+ if (request.uri().startsWith("/upload/")) {
+ boolean last = request.range().endsWith((size - 1) + "/" + size);
+ return last
+ ? new Response(201, SAVED_ITEM)
+ : new Response(202, "{\"nextExpectedRanges\":[]}");
+ }
+ return new Response(200, SAVED_DETAILS);
+ };
+
+ writer.save(33L, REPLACE, file(size));
+
+ assertThat(seen.getFirst().uri())
+ .isEqualTo("/v1.0/drives/drive-1/items/item-1/createUploadSession");
+ assertThat(seen.getFirst().ifMatch()).isEqualTo("\"{E},1\"");
+ List<Seen> chunks = seen.stream().filter(s -> s.uri().startsWith("/upload/")).toList();
+ assertThat(chunks).hasSize(2);
+ assertThat(chunks.get(0).auth()).isNull();
+ assertThat(chunks.stream().mapToInt(Seen::size).sum()).isEqualTo(size);
+ }
+
+ @Test
+ void hostileIdsNeverReachTheNetwork() throws IOException {
+ respond = savedWith(200);
+ Path content = file(10);
+
+ for (String hostile :
+ List.of(
+ "..",
+ "item/../../evil",
+ "@evil.example",
+ "http://evil.example/x",
+ "item?x=1",
+ "item#frag",
+ "item%2F..")) {
+ assertThatThrownBy(
+ () ->
+ writer.save(
+ 33L,
+ new ConnectedDriveWriter.Replace(
+ "drive-1", hostile, "\"{E},1\""),
+ content))
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("Invalid drive item reference");
+ assertThatThrownBy(
+ () ->
+ writer.save(
+ 33L,
+ new ConnectedDriveWriter.Create(
+ hostile, "folder-1", "x.pdf", true),
+ content))
+ .isInstanceOf(IOException.class);
+ }
+ assertThatThrownBy(
+ () ->
+ writer.save(
+ 33L,
+ new ConnectedDriveWriter.Create(
+ "drive-1", "folder-1", "../x.pdf", true),
+ content))
+ .isInstanceOf(IOException.class);
+ assertThat(seen).isEmpty();
+ }
+
+ @Test
+ void savedItemIdsFromTheResponseAreValidatedBeforeTheFollowUpRead() throws IOException {
+ respond =
+ request ->
+ request.method().equals("PUT")
+ ? new Response(
+ 200,
+ "{\"id\":\"../../evil\","
+ + "\"parentReference\":{\"driveId\":\"drive-1\"}}")
+ : new Response(200, SAVED_DETAILS);
+
+ Path content = file(10);
+ assertThatThrownBy(() -> writer.save(33L, REPLACE, content))
+ .isInstanceOf(IOException.class);
+ assertThat(seen).hasSize(1);
+ }
+
+ @Test
+ void realGraphIdsAreAccepted() {
+ assertThat(ConnectedDriveWriter.isValidId("D4648F06C91D9D3D!54927")).isTrue();
+ assertThat(
+ ConnectedDriveWriter.isValidId(
+ "b!-RIj2DuyvEyV1T4NlOaMHk8XkS_I8MdFlUCq1BlcjgmhRfAj3-Z8RY2VpuvV_tpd"))
+ .isTrue();
+ assertThat(ConnectedDriveWriter.isValidId("01BYE5RZ6QN3ZWBTUFOFD3GSPGOHDJD36K")).isTrue();
+ }
+
+ private static Function<Seen, Response> savedWith(int putStatus) {
+ return request ->
+ request.method().equals("PUT")
+ ? new Response(putStatus, SAVED_ITEM)
+ : new Response(200, SAVED_DETAILS);
+ }
+
+ private Path file(int size) throws IOException {
+ Path path = Files.createTempFile(temp, "content-", ".pdf");
+ Files.write(path, new byte[size]);
+ return path;
+ }
+
+ private void handle(HttpExchange exchange) throws IOException {
+ byte[] body = exchange.getRequestBody().readAllBytes();
+ Seen request =
+ new Seen(
+ exchange.getRequestMethod(),
+ exchange.getRequestURI().toString(),
+ exchange.getRequestHeaders().getFirst("If-Match"),
+ exchange.getRequestHeaders().getFirst("Authorization"),
+ exchange.getRequestHeaders().getFirst("Content-Range"),
+ body.length);
+ seen.add(request);
+ Response response = respond.apply(request);
+ byte[] out = response.body().getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/json");
+ exchange.sendResponseHeaders(response.status(), out.length);
+ exchange.getResponseBody().write(out);
+ exchange.close();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/FakeGraphServer.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/FakeGraphServer.java
index cdc590f770..44066688ae 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/FakeGraphServer.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/FakeGraphServer.java
@@ -43,6 +43,7 @@ public final class FakeGraphServer implements AutoCloseable {
public final AtomicInteger tokenRequests = new AtomicInteger();
public final AtomicInteger throttleNext = new AtomicInteger();
public final Set<String> revokedRefreshTokens = ConcurrentHashMap.newKeySet();
+ public final Set<String> unconsentedScopes = ConcurrentHashMap.newKeySet();
public final List<Map<String, String>> tokenForms = new CopyOnWriteArrayList<>();
private final AtomicInteger refreshSerial = new AtomicInteger();
private final AtomicInteger accessSerial = new AtomicInteger();
@@ -173,6 +174,16 @@ public final class FakeGraphServer implements AutoCloseable {
+ " refresh token has expired.\\nTrace ID: 1\"}");
return;
}
+ String scope = form.getOrDefault("scope", "");
+ if (unconsentedScopes.stream().anyMatch(scope::contains)) {
+ json(
+ exchange,
+ 400,
+ "{\"error\":\"invalid_grant\",\"suberror\":\"consent_required\","
+ + "\"error_description\":\"AADSTS65001: The user or"
+ + " administrator has not consented to use the application.\"}");
+ return;
+ }
json(exchange, 200, userTokens(false));
return;
}
diff --git a/frontend/msal-redirect.html b/frontend/msal-redirect.html
new file mode 100644
index 0000000000..01dda5a8b3
--- /dev/null
+++ b/frontend/msal-redirect.html
@@ -0,0 +1,11 @@
+<!doctype html>
+<html lang="en-US">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="robots" content="noindex" />
+ <title>Signing in…</title>
+ </head>
+ <body>
+ <script type="module" src="src/msalRedirect.ts"></script>
+ </body>
+</html>
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 96aa4a84fd..9fa2b84842 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -10,6 +10,7 @@
"license": "SEE LICENSE IN https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/refs/heads/main/proprietary/LICENSE",
"dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "^2.0.2",
+ "@azure/msal-browser": "^5.24.0",
"@cantoo/pdf-lib": "^2.8.2",
"@dnd-kit/core": "^6.3.1",
"@embedpdf/core": "^2.15.1",
@@ -247,6 +248,27 @@
"raf-schd": "^4.0.3"
}
},
+ "node_modules/@azure/msal-browser": {
+ "version": "5.24.0",
+ "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-5.24.0.tgz",
+ "integrity": "sha512-jS1stt81tslcVZi7fqVD+g6vr8w/IWqFl/vAB2dx/6EOroQDuCR4+z0o3C+d6a/GpLATvdoO+kwnDcYzsBXKQA==",
+ "license": "MIT",
+ "dependencies": {
+ "@azure/msal-common": "16.14.2"
+ },
+ "engines": {
+ "node": ">=0.8.0"
+ }
+ },
+ "node_modules/@azure/msal-common": {
+ "version": "16.14.2",
+ "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.14.2.tgz",
+ "integrity": "sha512-HOBR0Gfo39TMrkxNG8k6cfjRkrRjXZc3JQs3ebMWQc9S4cihuknMYra3sgmzbZB752oQBqBN9+WF7c826p2vIQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.0"
+ }
+ },
"node_modules/@babel/code-frame": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 15c6957146..9f78cf689e 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -7,6 +7,7 @@
"proxy": "http://localhost:8080",
"dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "^2.0.2",
+ "@azure/msal-browser": "^5.24.0",
"@cantoo/pdf-lib": "^2.8.2",
"@dnd-kit/core": "^6.3.1",
"@embedpdf/core": "^2.15.1",
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 5e8def0081..90f44f2fe4 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -1020,6 +1020,7 @@ mobileScannerStretchToFitDesc = "Stretch images to fill the entire page. If disa
pageFormatA4 = "A4 (210×297mm)"
pageFormatKeep = "Keep (Original Dimensions)"
pageFormatLetter = "Letter (8.5×11in)"
+setupSteps = "How to set up {{name}}"
title = "Connections"
unlinkedServices = "Unlinked Services"
@@ -4312,7 +4313,7 @@ connectAnother = "Connect another"
connectFailed = "The account couldn't be connected. Check that the server's app registration is set up, then try again."
disconnect = "Disconnect"
google = "Google Drive"
-intro = "Connect your own accounts once. Your pipelines can then read from and save to them as you."
+intro = "Connect your own accounts once. The editor can then open files from them without signing in again, and your pipelines can read from and save to them as you."
microsoft = "Microsoft (OneDrive & SharePoint)"
needsReconnect = "Stirling can no longer reach this account, so pipelines using it are paused."
none = "Your administrator hasn't turned on connected accounts."
@@ -4322,7 +4323,7 @@ reconnect = "Sign in again"
work = "Work account"
[connectedAccounts.disconnectConfirm]
-body = "Sources and pipelines that use this account will stop until you connect it again."
+body = "Sources and pipelines that use this account will stop. After you connect it again, update their account settings to use the new connection."
confirm = "Disconnect"
title = "Disconnect {{account}}?"
@@ -5085,10 +5086,12 @@ downloadFailed = "Download failed"
dropHint = "Open files to get started"
duplicateFailed = "Could not duplicate file"
expand = "Expand sidebar"
-googleDrive = "Google Drive"
+googleDrive = "Open from Google Drive"
library = "PDF Library"
myFiles = "File library"
noFiles = "No files yet"
+oneDrive = "Open from OneDrive"
+oneDriveFailed = "Couldn't open OneDrive"
openFileManager = "Browse all files & folders"
openFromComputer = "Open from computer"
openSettings = "Open settings"
@@ -5429,6 +5432,7 @@ diskFileHint = "Stored on your computer"
diskHint = "A file in the mounted folder on your disk"
local = "Local"
localHint = "Not backed up"
+oneDrive = "OneDrive"
shared = "Shared"
sharedHint = "Shared with you via link"
@@ -6831,6 +6835,32 @@ quickAccess = "Start at the <strong>Quick Access</strong> rail to jump between R
topBar = "The top bar lets you swap between <strong>Viewer</strong>, <strong>Page Editor</strong>, and <strong>Active Files</strong>."
wrapUp = "That is what is new in V2. Open the <strong>Tours</strong> menu anytime to replay this, the Tools tour, or the Admin tour."
+[oneDriveSave]
+chooseFolder = "Choose a OneDrive folder to upload to"
+conflict = "This file has changed in OneDrive since this version was opened or saved. Save your version as a copy instead."
+failedTitle = "Couldn't save to OneDrive"
+fromOneDrive = "From OneDrive"
+linkNotStored = "This browser couldn't remember the link to the OneDrive file. After a reload, save it as a copy instead."
+missing = "This file was moved or deleted in OneDrive. Save your version as a copy instead."
+open = "Open in OneDrive"
+personalUnsupported = "Uploading to OneDrive needs a work or school Microsoft account."
+reconnect = "Reconnect"
+replaces = "Replaces {{name}}"
+saveCopyToOneDrive = "Save a copy in OneDrive"
+saved = "Saved to OneDrive"
+saving = "Saving to OneDrive..."
+signInToSave = "Sign in to your server to save to OneDrive."
+updateOriginal = "Update in OneDrive"
+uploadToOneDrive = "Upload to OneDrive..."
+
+[oneDriveSave.status]
+saved = "Saved to OneDrive"
+unsaved = "Changes not saved to OneDrive yet"
+
+[oneDriveSave.toolbar]
+replace = "Update {{name}} in OneDrive"
+saveAll = "Update all in OneDrive"
+
[overlay-pdfs]
desc = "Overlay one PDF on top of another"
submit = "Submit"
@@ -11739,6 +11769,7 @@ description = "Covers opening files from Google Drive in the editor and connecti
label = "Enable Google Drive"
[provider.googledrive.errors]
+connectFailed = "Couldn't connect your Google account. Try again from Settings > Connected accounts."
notConfigured = "Google Drive is not configured"
pickerFailed = "Failed to open Google Drive picker"
@@ -11754,6 +11785,10 @@ scope = "Files & pipelines"
description = "One sign-in for the editor and their pipelines. Turn off to allow only organisation connections."
label = "Let people connect their own account"
+[provider.microsoft.allowEditorSaves]
+description = "Turn off to keep edits in Stirling: files opened from OneDrive then download instead, and the server refuses saves to OneDrive."
+label = "Let the editor save back to OneDrive"
+
[provider.microsoft.clientId]
description = "From one Microsoft Entra app registration."
label = "Application (client) ID"
@@ -11763,13 +11798,24 @@ description = "Needed for connected accounts. Stays on the server."
label = "Client secret"
[provider.microsoft.enabled]
-description = "Let people use OneDrive and SharePoint in pipelines"
+description = "Let people open files from OneDrive and SharePoint, and use them in pipelines"
label = "Enable OneDrive & SharePoint"
+[provider.microsoft.pickerRedirectUri]
+description = "Add this as a Single-page application redirect URI on the same app registration, for signing in from the editor."
+label = "Single-page application redirect URI"
+
[provider.microsoft.redirectUri]
description = "Add this as a Web redirect URI on the Entra app registration."
label = "Redirect URI"
+[provider.microsoft.setupSteps]
+connect = "Save, restart, then connect an account under Connected accounts."
+permissions = "Add the Microsoft Graph delegated permissions Files.ReadWrite.All and Files.Read.All, and the SharePoint delegated permissions MyFiles.Read and AllSites.Read so work and school accounts can open the file picker."
+redirects = "Add the two redirect URIs below to it: one as Web, one as Single-page application."
+register = "Register an app in the Microsoft Entra admin center. Allow personal Microsoft accounts if people use personal OneDrive."
+secret = "Create a client secret, then paste its value and the app's client ID below."
+
[provider.microsoft.tenant]
description = "common for work, school and personal accounts; organizations for work and school only; or a tenant ID to admit one organisation"
label = "Directory (tenant) ID"
@@ -11875,6 +11921,19 @@ label = "Scopes"
description = "Field to use as username (email, name, given_name, family_name, preferred_username)"
label = "Use as Username"
+[provider.onedrive]
+pickerLoading = "Connecting to OneDrive..."
+pickerTitle = "Choose files from OneDrive"
+
+[provider.onedrive.errors]
+connectFailed = "Couldn't connect your Microsoft account. Try again from Settings > Connected accounts."
+notConfigured = "OneDrive is not configured"
+pickerFailed = "Failed to open OneDrive"
+popupBlocked = "Your browser blocked the Microsoft sign-in window. Allow pop-ups for this site and try again."
+reconnect = "Your Microsoft account needs to sign in again. Reconnect it in Settings > Connected accounts."
+serverError = "OneDrive or the Stirling server had a problem. Try again, or ask your administrator if it keeps happening."
+unreachable = "Couldn't reach OneDrive. Check your connection and try again."
+
[provider.saml2]
name = "SAML2"
scope = "SSO (SAML)"
@@ -12784,7 +12843,7 @@ storageSharing = "File Storage & Sharing"
systemSettings = "System Settings"
[settings.connectedAccounts]
-description = "Your own OneDrive, SharePoint and Google Drive, for your pipelines."
+description = "Your own OneDrive, SharePoint and Google Drive, for opening files and for your pipelines."
title = "Connected accounts"
[settings.connectedInstances]
diff --git a/frontend/src-tauri/src/lib.rs b/frontend/src-tauri/src/lib.rs
index c1b8b087c0..d6370fb72f 100644
--- a/frontend/src-tauri/src/lib.rs
+++ b/frontend/src-tauri/src/lib.rs
@@ -43,6 +43,27 @@ fn parse_launch_files(args: &[String]) -> Vec<String> {
.collect()
}
+const ONEDRIVE_PICKER_HOST_SUFFIXES: &[&str] = &[
+ ".sharepoint.com",
+ ".sharepoint.us",
+ ".sharepoint-mil.us",
+ ".sharepoint.de",
+ ".sharepoint.cn",
+];
+
+fn is_onedrive_picker_url(url: &tauri::Url) -> bool {
+ if url.scheme() != "https" {
+ return false;
+ }
+ match url.host_str() {
+ Some("onedrive.live.com") => true,
+ Some(host) => ONEDRIVE_PICKER_HOST_SUFFIXES
+ .iter()
+ .any(|suffix| host.ends_with(suffix)),
+ None => false,
+ }
+}
+
// URLs the webview is allowed to show: the bundled app and dev server only.
// Anything else (file://, https://...) must never replace the app UI.
fn is_app_url(url: &tauri::Url) -> bool {
@@ -72,7 +93,7 @@ pub fn run() {
// unclosable). Block every off-app navigation at the Rust layer.
tauri::plugin::Builder::<tauri::Wry, ()>::new("navigation-guard")
.on_navigation(|_webview, url| {
- let allowed = is_app_url(url);
+ let allowed = is_app_url(url) || is_onedrive_picker_url(url);
if !allowed {
add_log(format!("🚫 Blocked webview navigation to: {}", url));
}
@@ -331,7 +352,33 @@ pub fn run() {
#[cfg(test)]
mod tests {
- use super::is_app_url;
+ use super::{is_app_url, is_onedrive_picker_url};
+
+ fn picker(raw: &str) -> bool {
+ is_onedrive_picker_url(&tauri::Url::parse(raw).expect("valid url"))
+ }
+
+ #[test]
+ fn allows_the_onedrive_picker_iframe() {
+ assert!(picker(
+ "https://contoso-my.sharepoint.com/_layouts/15/FilePicker.aspx?x=1"
+ ));
+ assert!(picker(
+ "https://contoso.sharepoint.us/_layouts/15/FilePicker.aspx"
+ ));
+ assert!(picker("https://onedrive.live.com/picker"));
+ }
+
+ #[test]
+ fn picker_allowance_is_https_microsoft_hosts_only() {
+ assert!(!picker(
+ "http://contoso-my.sharepoint.com/_layouts/15/FilePicker.aspx"
+ ));
+ assert!(!picker("https://contoso.sharepoint.com.evil.test/"));
+ assert!(!picker("https://evilsharepoint.com/"));
+ assert!(!picker("https://onedrive.live.com.evil.test/"));
+ assert!(!picker("file:///Users/me/report.pdf"));
+ }
fn allows(raw: &str) -> bool {
is_app_url(&tauri::Url::parse(raw).expect("valid url"))
diff --git a/frontend/src/editor/core/components/filesPage/FileGrid.tsx b/frontend/src/editor/core/components/filesPage/FileGrid.tsx
index 1ab1bbaacc..32f9ab8e7a 100644
--- a/frontend/src/editor/core/components/filesPage/FileGrid.tsx
+++ b/frontend/src/editor/core/components/filesPage/FileGrid.tsx
@@ -1336,6 +1336,7 @@ const FileCard = React.memo(function FileCard({
<FileOriginBadge
origin={getFileOrigin(file)}
onDisk={Boolean(file.localFilePath)}
+ fromOneDrive={Boolean(file.cloudOrigin)}
compact
/>
<DiskLinkBadge file={file} compact />
@@ -2027,6 +2028,7 @@ const FileRow = React.memo(function FileRow({
<FileOriginBadge
origin={getFileOrigin(file)}
onDisk={Boolean(file.localFilePath)}
+ fromOneDrive={Boolean(file.cloudOrigin)}
compact
/>
<DiskLinkBadge file={file} compact />
diff --git a/frontend/src/editor/core/components/filesPage/FileOriginBadge.tsx b/frontend/src/editor/core/components/filesPage/FileOriginBadge.tsx
index f165e999a0..ea4bb835bd 100644
--- a/frontend/src/editor/core/components/filesPage/FileOriginBadge.tsx
+++ b/frontend/src/editor/core/components/filesPage/FileOriginBadge.tsx
@@ -3,10 +3,12 @@ import { useTranslation } from "react-i18next";
import { Tooltip } from "@mantine/core";
import { Icon } from "@editor/ui/Icon";
import { FileOrigin } from "@editor/components/filesPage/fileOrigin";
+import { OneDriveOriginTooltip } from "@editor/components/shared/OneDriveOriginTooltip";
interface FileOriginBadgeProps {
origin: FileOrigin;
onDisk?: boolean;
+ fromOneDrive?: boolean;
/** Compact (icon-only) vs full (icon + text). */
compact?: boolean;
tooltip?: string;
@@ -43,6 +45,7 @@ const styles = {
export function FileOriginBadge({
origin,
onDisk = false,
+ fromOneDrive = false,
compact = false,
tooltip,
}: FileOriginBadgeProps) {
@@ -69,6 +72,18 @@ export function FileOriginBadge({
};
case "local":
default:
+ if (fromOneDrive) {
+ return {
+ label: t("filesPage.origin.oneDrive", "OneDrive"),
+ icon: <Icon name="onedrive" size={"0.85rem"} />,
+ style: styles.local,
+ tooltip: (
+ <OneDriveOriginTooltip
+ label={t("oneDriveSave.fromOneDrive", "From OneDrive")}
+ />
+ ),
+ };
+ }
return {
label: t("filesPage.origin.local", "Local"),
icon: (
diff --git a/frontend/src/editor/core/components/filesPage/LibraryFilePicker.test.tsx b/frontend/src/editor/core/components/filesPage/LibraryFilePicker.test.tsx
index 75cb004699..65f89af372 100644
--- a/frontend/src/editor/core/components/filesPage/LibraryFilePicker.test.tsx
+++ b/frontend/src/editor/core/components/filesPage/LibraryFilePicker.test.tsx
@@ -102,9 +102,11 @@ vi.mock("@editor/hooks/useSharingEnabled", () => ({
}));
vi.mock("@editor/hooks/useGoogleDrivePicker", () => ({
useGoogleDrivePicker: () => ({
- isEnabled: false,
+ isEnabled: true,
+ isLoading: false,
error: state.driveError,
clearError: state.clearDriveError,
+ openPicker: async () => [],
}),
}));
vi.mock("@editor/hooks/useIsMobile", () => ({
diff --git a/frontend/src/editor/core/components/filesPage/LibraryFilePicker.tsx b/frontend/src/editor/core/components/filesPage/LibraryFilePicker.tsx
index aa62f6fedc..baabdc3e94 100644
--- a/frontend/src/editor/core/components/filesPage/LibraryFilePicker.tsx
+++ b/frontend/src/editor/core/components/filesPage/LibraryFilePicker.tsx
@@ -13,7 +13,7 @@ import { useFolders } from "@editor/contexts/FolderContext";
import { useAllFiles } from "@editor/contexts/FileContext";
import { useAppConfig } from "@editor/contexts/AppConfigContext";
import { useSharingEnabled } from "@editor/hooks/useSharingEnabled";
-import { useGoogleDrivePicker } from "@editor/hooks/useGoogleDrivePicker";
+import { useCloudFilePickers } from "@editor/hooks/useCloudFilePickers";
import { useProcessingFolders } from "@editor/hooks/useProcessingFolders";
import { useFolderFileStates } from "@editor/components/filesPage/useFolderFileStates";
import { pendingFilePathMappings } from "@editor/services/pendingFilePathMappings";
@@ -90,7 +90,8 @@ export function LibraryFilePicker({
);
const { config } = useAppConfig();
const { sharingEnabled } = useSharingEnabled();
- const drive = useGoogleDrivePicker();
+ const cloudPickers = useCloudFilePickers();
+ const cloudError = cloudPickers.find((picker) => picker.error)?.error ?? null;
const isPhone = useIsMobile();
const compact = useMediaQuery("(max-width: 1000px)") ?? false;
const {
@@ -593,24 +594,26 @@ export function LibraryFilePicker({
>
{t("filePicker.fromComputer", "From your computer")}
</Button>
- {drive.isEnabled && (
+ {cloudPickers.map((picker) => (
<Button
+ key={picker.id}
variant="tertiary"
disabled={busy}
- loading={drive.isLoading}
- leftSection={<Icon name="googledrive" />}
+ loading={picker.isLoading}
+ leftSection={<Icon name={picker.icon} />}
+ data-testid={`library-picker-${picker.id}`}
onClick={() => {
onExternalPickerChange(true);
- void drive
+ void picker
.openPicker({ multiple: maxSelectable !== 1 })
.then(stageFiles)
.catch(reportError)
.finally(() => onExternalPickerChange(false));
}}
>
- Google Drive
+ {picker.name}
</Button>
- )}
+ ))}
{config?.enableMobileScanner && !isPhone && (
<Button
variant="tertiary"
@@ -636,17 +639,17 @@ export function LibraryFilePicker({
/>
</div>
)}
- {(error || (!destination && drive.error)) && (
+ {(error || (!destination && cloudError)) && (
<Alert
title={t("filePicker.errorTitle", "Couldn't add files")}
withCloseButton
onClose={() => {
setError(null);
- drive.clearError();
+ cloudPickers.forEach((picker) => picker.clearError());
}}
role="alert"
>
- <PrivateContent>{error ?? drive.error}</PrivateContent>
+ <PrivateContent>{error ?? cloudError}</PrivateContent>
</Alert>
)}
<LibraryTabs
diff --git a/frontend/src/editor/core/components/filesPage/VersionHistoryModal.tsx b/frontend/src/editor/core/components/filesPage/VersionHistoryModal.tsx
index 4455d33169..458eaf16d7 100644
--- a/frontend/src/editor/core/components/filesPage/VersionHistoryModal.tsx
+++ b/frontend/src/editor/core/components/filesPage/VersionHistoryModal.tsx
@@ -10,6 +10,7 @@ import { useFileActions } from "@editor/contexts/file/fileHooks";
import { useNavigationActions } from "@editor/contexts/NavigationContext";
import { useIndexedDBRevision } from "@editor/contexts/IndexedDBContext";
import { VersionTimeline } from "@editor/components/filesPage/VersionTimeline";
+import { withLatestCloudOrigins } from "@editor/contexts/file/fileActions";
interface VersionHistoryModalProps {
opened: boolean;
@@ -72,15 +73,29 @@ export function VersionHistoryModal({
const handleAddToWorkspace = useCallback(
(ids: FileId[]) => {
- const stubs = ids
- .map((id) => stubById(id))
- .filter((s): s is StirlingFileStub => Boolean(s));
+ const newestFirst = [...chain].sort(
+ (a, b) => (b.versionNumber ?? 1) - (a.versionNumber ?? 1),
+ );
+ const stubs = withLatestCloudOrigins(
+ ids
+ .map((id) => stubById(id))
+ .filter((s): s is StirlingFileStub => Boolean(s)),
+ newestFirst,
+ );
if (stubs.length === 0) return;
+ for (const stub of stubs)
+ if (
+ stub.cloudOrigin &&
+ stub.cloudOrigin !== stubById(stub.id)?.cloudOrigin
+ )
+ void fileStorage.updateFileMetadata(stub.id, {
+ cloudOrigin: stub.cloudOrigin,
+ });
void fileActions.addStirlingFileStubs(stubs, { selectFiles: true });
navActions.setWorkbench("fileEditor");
onClose();
},
- [stubById, fileActions, navActions, onClose],
+ [chain, stubById, fileActions, navActions, onClose],
);
const handleRemove = useCallback(
diff --git a/frontend/src/editor/core/components/shared/FileSidebar.tsx b/frontend/src/editor/core/components/shared/FileSidebar.tsx
index b0c88b22ec..411b178c08 100644
--- a/frontend/src/editor/core/components/shared/FileSidebar.tsx
+++ b/frontend/src/editor/core/components/shared/FileSidebar.tsx
@@ -7,7 +7,8 @@ import React, {
forwardRef,
type RefCallback,
} from "react";
-import { Loader, Tooltip } from "@mantine/core";
+import { Loader, Menu, Tooltip } from "@mantine/core";
+import { useNavigate } from "react-router-dom";
import { ActionIcon } from "@editor/ui/ActionIcon";
import { NavSurface } from "@editor/ui/NavSurface";
import { Button } from "@editor/ui/Button";
@@ -15,7 +16,10 @@ import { Icon, type IconName } from "@editor/ui/Icon";
import { useTranslation } from "react-i18next";
import { useFileState, useFileActions } from "@editor/contexts/file/fileHooks";
import { useAppConfig } from "@editor/contexts/AppConfigContext";
-import { useGoogleDrivePicker } from "@editor/hooks/useGoogleDrivePicker";
+import {
+ useCloudFilePickers,
+ type CloudFilePicker,
+} from "@editor/hooks/useCloudFilePickers";
import {
useNavigationState,
useNavigationActions,
@@ -73,6 +77,11 @@ import { useToolEligibleFileIds } from "@editor/contexts/ToolFileEligibilityCont
import { useWorkbenchFileDrop } from "@editor/components/layout/useWorkbenchFileDrop";
import { useDamagedFileRepair } from "@editor/contexts/DamagedFileRepairContext";
import "@editor/components/shared/FileSidebar.css";
+import {
+ CONNECTED_ACCOUNTS_SETTINGS_PATH,
+ useOneDriveSave,
+} from "@editor/hooks/useOneDriveSave";
+import { hasUnsavedCloudChanges } from "@editor/services/oneDriveSave";
// Shared with the processor sidebar via tokens, so the two cannot drift.
const SIDEBAR_WIDTH = "var(--sidebar-w)";
@@ -92,8 +101,7 @@ export interface FileSidebarProps {
onUploadFiles?: (files: File[]) => void | Promise<void>;
/** Publishes the sidebar's picker so the quick navigation rail can reuse it. */
onRegisterOpenFromComputer?: (open: (() => void) | null) => void;
- /** Override the Google Drive handler. */
- onPickGoogleDriveFiles?: (files: File[]) => void | Promise<void>;
+ onPickCloudFiles?: (files: File[]) => void | Promise<void>;
/** Action rows inserted under Open-from-computer (New folder, Refresh). A
* control with more than one destination renders itself instead. */
extraActions?: Array<{
@@ -226,8 +234,8 @@ function ClearRecentsButton({
interface LibraryHeaderProps {
stubs: StirlingFileStub[];
scrolled: boolean;
- isGoogleDriveEnabled: boolean;
- onGoogleDrive: () => void;
+ cloudPickers: CloudFilePicker[];
+ onCloudPick: (picker: CloudFilePicker) => void;
onAddFiles: () => void;
onOpenFilesPage: () => void;
/** Set only for a flat list; a grouped list carries it on its Recent group. */
@@ -237,8 +245,8 @@ interface LibraryHeaderProps {
function LibraryHeader({
stubs,
scrolled,
- isGoogleDriveEnabled,
- onGoogleDrive,
+ cloudPickers,
+ onCloudPick,
onAddFiles,
onOpenFilesPage,
onClearRecents,
@@ -277,28 +285,51 @@ function LibraryHeader({
<Icon name="search" size={"1rem"} />
</ActionIcon>
{onClearRecents && <ClearRecentsButton onClick={onClearRecents} />}
- {isGoogleDriveEnabled && (
+ {cloudPickers.length === 0 ? (
<ActionIcon
variant="quiet"
- className="file-sidebar-section-btn file-sidebar-section-btn-drive"
- onClick={onGoogleDrive}
- title={t("fileSidebar.googleDrive", "Open from Google Drive")}
- aria-label={t("fileSidebar.googleDrive", "Open from Google Drive")}
- data-testid="google-drive-button"
+ className="file-sidebar-section-btn file-sidebar-section-btn-add"
+ data-testid="pdf-library-add-files"
+ onClick={onAddFiles}
+ title={t("fileSidebar.addFiles", "Add files")}
+ aria-label={t("fileSidebar.addFiles", "Add files")}
>
- <Icon name="googledrive" size={16} />
+ <Icon name="plus" size={"1rem"} />
</ActionIcon>
+ ) : (
+ <Menu position="bottom-end" withinPortal shadow="md" width={220}>
+ <Menu.Target>
+ <ActionIcon
+ variant="quiet"
+ className="file-sidebar-section-btn file-sidebar-section-btn-add"
+ data-testid="pdf-library-add-files"
+ title={t("fileSidebar.addFiles", "Add files")}
+ aria-label={t("fileSidebar.addFiles", "Add files")}
+ >
+ <Icon name="plus" size={"1rem"} />
+ </ActionIcon>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ leftSection={<Icon name="file-up" size={16} />}
+ onClick={onAddFiles}
+ data-testid="pdf-library-add-from-computer"
+ >
+ {t("fileSidebar.openFromComputer", "Open from computer")}
+ </Menu.Item>
+ {cloudPickers.map((picker) => (
+ <Menu.Item
+ key={picker.id}
+ leftSection={<Icon name={picker.icon} size={16} />}
+ onClick={() => onCloudPick(picker)}
+ data-testid={picker.testId}
+ >
+ {picker.actionLabel}
+ </Menu.Item>
+ ))}
+ </Menu.Dropdown>
+ </Menu>
)}
- <ActionIcon
- variant="quiet"
- className="file-sidebar-section-btn file-sidebar-section-btn-add"
- data-testid="pdf-library-add-files"
- onClick={onAddFiles}
- title={t("fileSidebar.addFiles", "Add files")}
- aria-label={t("fileSidebar.addFiles", "Add files")}
- >
- <Icon name="plus" size={"1rem"} />
- </ActionIcon>
</div>
);
}
@@ -504,14 +535,14 @@ interface FileLibrarySectionProps extends Omit<
LibraryFileListProps,
"scrollRef"
> {
- isGoogleDriveEnabled: boolean;
- onGoogleDrive: () => void;
+ cloudPickers: CloudFilePicker[];
+ onCloudPick: (picker: CloudFilePicker) => void;
onAddFiles: () => void;
}
function FileLibrarySection({
- isGoogleDriveEnabled,
- onGoogleDrive,
+ cloudPickers,
+ onCloudPick,
onAddFiles,
...list
}: FileLibrarySectionProps) {
@@ -521,8 +552,8 @@ function FileLibrarySection({
<LibraryHeader
stubs={list.stubs}
scrolled={scrolled}
- isGoogleDriveEnabled={isGoogleDriveEnabled}
- onGoogleDrive={onGoogleDrive}
+ cloudPickers={cloudPickers}
+ onCloudPick={onCloudPick}
onAddFiles={onAddFiles}
onOpenFilesPage={list.onOpenFilesPage}
onClearRecents={list.groups ? undefined : list.onClearRecents}
@@ -540,7 +571,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
accountHoisted = false,
onUploadFiles,
onRegisterOpenFromComputer,
- onPickGoogleDriveFiles,
+ onPickCloudFiles,
extraActions,
},
ref,
@@ -557,10 +588,8 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
);
const { config } = useAppConfig();
- const {
- isEnabled: isGoogleDriveEnabled,
- openPicker: openGoogleDrivePicker,
- } = useGoogleDrivePicker();
+ const cloudPickers = useCloudFilePickers();
+ const navigate = useNavigate();
const { state } = useFileState();
const { actions: fileActions } = useFileActions();
const damagedRepair = useDamagedFileRepair();
@@ -790,6 +819,21 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
[allFileStubs, warnDataUnavailable, t],
);
+ const oneDriveSave = useOneDriveSave();
+ const oneDriveHandlers = useMemo(() => {
+ const forStub =
+ (act: (stub: StirlingFileStub) => unknown) => (fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (stub) void act(stub);
+ };
+ return {
+ save: forStub(oneDriveSave.save),
+ saveCopy: forStub(oneDriveSave.saveCopy),
+ saveToFolder: forStub(oneDriveSave.saveToFolder),
+ open: forStub(oneDriveSave.openInOneDrive),
+ };
+ }, [allFileStubs, oneDriveSave]);
+
const handleDuplicate = useCallback(
async (fileId: FileId) => {
const stub = allFileStubs.find((s) => s.id === fileId);
@@ -925,29 +969,73 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
[],
);
- const handleGoogleDriveClick = useCallback(async () => {
- if (!isGoogleDriveEnabled) return;
- const files = await openGoogleDrivePicker({ multiple: true });
- if (files.length === 0) return;
- await trackIngest(async () => {
- if (onPickGoogleDriveFiles) {
- await onPickGoogleDriveFiles(files);
- return;
- }
- await addFiles(files);
- if (!staysOnAdd) {
- navActions.setWorkbench(files.length === 1 ? "viewer" : "fileEditor");
+ const reportUploadFailure = useCallback(
+ (err: unknown) =>
+ alert({
+ alertType: "error",
+ title: t("fileSidebar.uploadFailedTitle", "Upload failed"),
+ body:
+ err instanceof Error
+ ? err.message
+ : t(
+ "fileSidebar.uploadFailedBody",
+ "Could not add the selected files.",
+ ),
+ isPersistentPopup: false,
+ }),
+ [t],
+ );
+
+ const handleCloudPick = useCallback(
+ async (picker: CloudFilePicker) => {
+ const files = await picker.openPicker({ multiple: true });
+ if (files.length === 0) return;
+ try {
+ await trackIngest(async () => {
+ if (onPickCloudFiles) {
+ await onPickCloudFiles(files);
+ return;
+ }
+ await addFiles(files);
+ if (!staysOnAdd) {
+ navActions.setWorkbench(
+ files.length === 1 ? "viewer" : "fileEditor",
+ );
+ }
+ });
+ } catch (err) {
+ console.error("[FileSidebar] Cloud file ingest failed", err);
+ reportUploadFailure(err);
}
+ },
+ [
+ trackIngest,
+ addFiles,
+ navActions,
+ staysOnAdd,
+ onPickCloudFiles,
+ reportUploadFailure,
+ ],
+ );
+
+ const failedPicker = cloudPickers.find((picker) => picker.error);
+ useEffect(() => {
+ if (!failedPicker?.error) return;
+ alert({
+ alertType: "error",
+ title: failedPicker.failedTitle,
+ body: failedPicker.error,
+ expandable: false,
+ durationMs: 8000,
+ ...(failedPicker.reconnectNeeded
+ ? {
+ buttonText: t("oneDriveSave.reconnect", "Reconnect"),
+ buttonCallback: () => navigate(CONNECTED_ACCOUNTS_SETTINGS_PATH),
+ }
+ : {}),
});
- }, [
- isGoogleDriveEnabled,
- openGoogleDrivePicker,
- trackIngest,
- addFiles,
- navActions,
- staysOnAdd,
- onPickGoogleDriveFiles,
- ]);
+ failedPicker.clearError();
+ }, [failedPicker, navigate, t]);
const handleFileClick = useCallback(
async (fileId: FileId) => {
@@ -1109,10 +1197,17 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
const handleNativeFilePick = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
- await ingestFiles(Array.from(e.target.files ?? []));
- e.target.value = "";
+ const input = e.target;
+ try {
+ await ingestFiles(Array.from(input.files ?? []));
+ } catch (err) {
+ console.error("[FileSidebar] Native file pick failed", err);
+ reportUploadFailure(err);
+ } finally {
+ input.value = "";
+ }
},
- [ingestFiles],
+ [ingestFiles, reportUploadFailure],
);
const openNativeFilePicker = useCallback(() => {
@@ -1122,20 +1217,9 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
.then(ingestFiles)
.catch((err) => {
console.error("[FileSidebar] Native file pick failed", err);
- alert({
- alertType: "error",
- title: t("fileSidebar.uploadFailedTitle", "Upload failed"),
- body:
- err instanceof Error
- ? err.message
- : t(
- "fileSidebar.uploadFailedBody",
- "Could not add the selected files.",
- ),
- isPersistentPopup: false,
- });
+ reportUploadFailure(err);
});
- }, [ingestFiles, t]);
+ }, [ingestFiles, reportUploadFailure]);
useEffect(() => {
if (!onRegisterOpenFromComputer) return;
@@ -1207,6 +1291,26 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
onSaveToCloud={handleSaveToCloud}
canSaveToCloud={storageEnabled && fileOrigin !== "shared-with-me"}
isUploadedToCloud={fileOrigin === "cloud"}
+ hasOneDriveOrigin={Boolean(stub.cloudOrigin)}
+ oneDriveUnsaved={
+ oneDriveSave.available && hasUnsavedCloudChanges(stub)
+ }
+ oneDriveName={stub.cloudOrigin?.name}
+ onOpenInOneDrive={
+ stub.cloudOrigin?.webUrl ? oneDriveHandlers.open : undefined
+ }
+ savingToOneDrive={oneDriveSave.saving === stub.id}
+ onSaveToOneDrive={
+ oneDriveSave.available ? oneDriveHandlers.save : undefined
+ }
+ onSaveCopyToOneDrive={
+ oneDriveSave.available ? oneDriveHandlers.saveCopy : undefined
+ }
+ onSaveToOneDriveFolder={
+ oneDriveSave.canSaveToFolder
+ ? oneDriveHandlers.saveToFolder
+ : undefined
+ }
onVersionHistory={handleVersionHistory}
hasVersionHistory={(stub.versionNumber ?? 1) > 1}
primaryLabel={
@@ -1227,19 +1331,12 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
onClick: openNativeFilePicker,
testId: "pdf-library-add-files",
},
- ...(isGoogleDriveEnabled
- ? [
- {
- icon: <Icon name="googledrive" />,
- label: t(
- "fileSidebar.googleDrive",
- "Open from Google Drive",
- ),
- onClick: () => void handleGoogleDriveClick(),
- testId: "google-drive-button",
- },
- ]
- : []),
+ ...cloudPickers.map((picker) => ({
+ icon: <Icon name={picker.icon} />,
+ label: picker.actionLabel,
+ onClick: () => void handleCloudPick(picker),
+ testId: picker.testId,
+ })),
]
: []),
...(extraActions ?? []),
@@ -1295,8 +1392,8 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
groupOpen={groupOpen}
onGroupOpenChange={setGroupOpenState}
renderFileRow={renderFileRow}
- isGoogleDriveEnabled={isGoogleDriveEnabled}
- onGoogleDrive={handleGoogleDriveClick}
+ cloudPickers={cloudPickers}
+ onCloudPick={(picker) => void handleCloudPick(picker)}
onAddFiles={openNativeFilePicker}
onOpenFilesPage={() => navActions.setWorkbench("myFiles")}
onClearRecents={
diff --git a/frontend/src/editor/core/components/shared/FileSidebarFileItem.css b/frontend/src/editor/core/components/shared/FileSidebarFileItem.css
index 2082f8c872..6a9c72bc77 100644
--- a/frontend/src/editor/core/components/shared/FileSidebarFileItem.css
+++ b/frontend/src/editor/core/components/shared/FileSidebarFileItem.css
@@ -196,6 +196,7 @@
/* ---- Cloud badge (file saved to the server) ---- */
.file-sidebar-cloud-badge {
+ position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
@@ -203,6 +204,19 @@
color: var(--c-accent-text);
}
+/* Same unsaved marker as the toolbar's Save button. */
+.file-sidebar-cloud-badge-dot {
+ position: absolute;
+ top: -2px;
+ right: -3px;
+ width: 0.375rem;
+ height: 0.375rem;
+ border-radius: 999px;
+ background: var(--mantine-color-yellow-6);
+ box-shadow: 0 0 0 1.5px var(--c-bg-raised);
+ pointer-events: none;
+}
+
/* ---- Eye button (open in viewer) ---- */
.file-sidebar-eye-btn {
display: flex;
@@ -419,3 +433,17 @@
font-size: 0.7rem;
white-space: nowrap;
}
+
+.file-sidebar-kebab-item-stack {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+
+.file-sidebar-kebab-item-detail {
+ color: var(--c-text-subtle);
+ font-size: 11px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
diff --git a/frontend/src/editor/core/components/shared/FileSidebarFileItem.test.tsx b/frontend/src/editor/core/components/shared/FileSidebarFileItem.test.tsx
new file mode 100644
index 0000000000..080e9d8cda
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/FileSidebarFileItem.test.tsx
@@ -0,0 +1,90 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { expect, it, vi } from "vitest";
+import { FileItem } from "@editor/components/shared/FileSidebarFileItem";
+import type { FileId } from "@editor/types/file";
+
+vi.mock("@editor/hooks/useLazyThumbnail", () => ({
+ useLazyThumbnail: () => undefined,
+}));
+
+const fileId = "file-1" as FileId;
+
+function renderItem(props: Partial<Parameters<typeof FileItem>[0]> = {}) {
+ render(
+ <MantineProvider>
+ <FileItem
+ fileId={fileId}
+ name="Q3 Board Pack.pdf"
+ isSelected={false}
+ isActive={false}
+ isViewedInViewer={false}
+ onClick={vi.fn()}
+ onEyeClick={vi.fn()}
+ {...props}
+ />
+ </MantineProvider>,
+ );
+}
+
+function openMenu() {
+ fireEvent.click(screen.getByLabelText("fileSidebar.fileItem.moreActions"));
+}
+
+it("names the OneDrive file an update will replace and links to it", async () => {
+ const onSaveToOneDrive = vi.fn();
+ const onOpenInOneDrive = vi.fn();
+ renderItem({
+ hasOneDriveOrigin: true,
+ oneDriveName: "Q3 Board Pack (draft).pdf",
+ onSaveToOneDrive,
+ onSaveToOneDriveFolder: vi.fn(),
+ onOpenInOneDrive,
+ });
+ openMenu();
+
+ const update = await screen.findByTestId("file-save-onedrive");
+ expect(update.textContent).toContain("oneDriveSave.updateOriginal");
+ expect(screen.getByTestId("file-save-onedrive-target").textContent).toBe(
+ "oneDriveSave.replaces",
+ );
+ expect(screen.getByTestId("file-save-onedrive-folder").textContent).toContain(
+ "oneDriveSave.uploadToOneDrive",
+ );
+
+ fireEvent.click(screen.getByTestId("file-open-onedrive"));
+ expect(onOpenInOneDrive).toHaveBeenCalledWith(fileId);
+ expect(onSaveToOneDrive).not.toHaveBeenCalled();
+});
+
+it("leaves out the replaced name when it matches the file's own", async () => {
+ renderItem({
+ hasOneDriveOrigin: true,
+ oneDriveName: "Q3 Board Pack.pdf",
+ onSaveToOneDrive: vi.fn(),
+ });
+ openMenu();
+
+ expect(await screen.findByTestId("file-save-onedrive")).toBeTruthy();
+ expect(screen.queryByTestId("file-save-onedrive-target")).toBeNull();
+});
+
+it("marks a file that came from OneDrive", () => {
+ renderItem({ hasOneDriveOrigin: true });
+ expect(screen.getByTestId("file-onedrive-badge")).toBeTruthy();
+});
+
+it("offers only an upload to OneDrive for a local file", async () => {
+ renderItem({
+ onSaveToOneDrive: vi.fn(),
+ onSaveToOneDriveFolder: vi.fn(),
+ onOpenInOneDrive: vi.fn(),
+ });
+ expect(screen.queryByTestId("file-onedrive-badge")).toBeNull();
+ openMenu();
+
+ const upload = await screen.findByTestId("file-save-onedrive-folder");
+ expect(upload.textContent).toContain("oneDriveSave.uploadToOneDrive");
+ expect(screen.queryByTestId("file-save-onedrive")).toBeNull();
+ expect(screen.queryByTestId("file-open-onedrive")).toBeNull();
+});
diff --git a/frontend/src/editor/core/components/shared/FileSidebarFileItem.tsx b/frontend/src/editor/core/components/shared/FileSidebarFileItem.tsx
index e4b8366786..b9c17526be 100644
--- a/frontend/src/editor/core/components/shared/FileSidebarFileItem.tsx
+++ b/frontend/src/editor/core/components/shared/FileSidebarFileItem.tsx
@@ -18,6 +18,7 @@ import { useFileActionTerminology } from "@editor/hooks/useFileActionTerminology
import { formatFileSize, IMAGE_EXTENSIONS } from "@editor/utils/fileUtils";
import "@editor/components/shared/FileSidebarFileItem.css";
import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
+import { OneDriveOriginTooltip } from "@editor/components/shared/OneDriveOriginTooltip";
export function getFileExtension(name: string): string {
const parts = name.split(".");
@@ -145,6 +146,15 @@ export interface FileItemProps {
canSaveToCloud?: boolean;
/** File already lives on the server - shows a cloud badge + "Update" label. */
isUploadedToCloud?: boolean;
+ onSaveToOneDrive?: (fileId: FileId) => void;
+ onSaveCopyToOneDrive?: (fileId: FileId) => void;
+ onSaveToOneDriveFolder?: (fileId: FileId) => void;
+ hasOneDriveOrigin?: boolean;
+ /** Edited since the last save, and Save sends this file to OneDrive. */
+ oneDriveUnsaved?: boolean;
+ oneDriveName?: string;
+ onOpenInOneDrive?: (fileId: FileId) => void;
+ savingToOneDrive?: boolean;
/** Open the version-history modal. Only shown when hasVersionHistory. */
onVersionHistory?: (fileId: FileId) => void;
/** Whether this file has more than one version (drives the menu item). */
@@ -164,10 +174,12 @@ function FileMenuItem({
color,
onClick,
children,
+ testId,
}: {
disabledReason?: React.ReactNode;
icon: React.ReactNode;
color?: string;
+ testId?: string;
onClick: (e: React.MouseEvent) => void;
children: React.ReactNode;
}) {
@@ -185,6 +197,7 @@ function FileMenuItem({
disabled={Boolean(disabledReason)}
color={color}
leftSection={icon}
+ data-testid={testId}
onClick={(e) => {
e.stopPropagation();
onClick(e);
@@ -225,10 +238,21 @@ export const FileItem = React.memo(function FileItem({
onSaveToCloud,
canSaveToCloud = false,
isUploadedToCloud = false,
+ onSaveToOneDrive,
+ onSaveCopyToOneDrive,
+ onSaveToOneDriveFolder,
+ hasOneDriveOrigin = false,
+ oneDriveUnsaved = false,
+ oneDriveName,
+ onOpenInOneDrive,
+ savingToOneDrive = false,
onVersionHistory,
hasVersionHistory = false,
}: FileItemProps) {
const { t } = useTranslation();
+ const oneDriveBadgeLabel = oneDriveUnsaved
+ ? t("oneDriveSave.status.unsaved", "Changes not saved to OneDrive yet")
+ : t("oneDriveSave.fromOneDrive", "From OneDrive");
const toolSkipReason = isToolSkipped
? t("files.notIncludedInToolRun", "Not included in this tool run")
: undefined;
@@ -273,6 +297,23 @@ export const FileItem = React.memo(function FileItem({
return null;
};
+ const oneDriveBlockedReason = (action: string): React.ReactNode | null =>
+ savingToOneDrive
+ ? t("oneDriveSave.saving", "Saving to OneDrive...")
+ : blockedReason(action);
+ const updateInOneDriveLabel = t(
+ "oneDriveSave.updateOriginal",
+ "Update in OneDrive",
+ );
+ const saveCopyToOneDriveLabel = t(
+ "oneDriveSave.saveCopyToOneDrive",
+ "Save a copy in OneDrive",
+ );
+ const saveToOneDriveFolderLabel = t(
+ "oneDriveSave.uploadToOneDrive",
+ "Upload to OneDrive...",
+ );
+
const viewerLabel = isViewedInViewer
? t("fileSidebar.fileItem.closeViewer", "Close viewer")
: t("fileSidebar.fileItem.openInViewer", "Open in viewer");
@@ -387,6 +428,27 @@ export const FileItem = React.memo(function FileItem({
</span>
</Tooltip>
)}
+ {hasOneDriveOrigin && (
+ <Tooltip
+ label={<OneDriveOriginTooltip label={oneDriveBadgeLabel} />}
+ multiline
+ maw={220}
+ withArrow
+ position="bottom"
+ >
+ <span
+ className="file-sidebar-cloud-badge"
+ data-no-select
+ data-testid="file-onedrive-badge"
+ aria-label={oneDriveBadgeLabel}
+ >
+ <Icon name="onedrive" size={"0.85rem"} />
+ {oneDriveUnsaved && (
+ <span className="file-sidebar-cloud-badge-dot" />
+ )}
+ </span>
+ </Tooltip>
+ )}
{isUploadedToCloud && (
<Tooltip
label={t(
@@ -564,6 +626,62 @@ export const FileItem = React.memo(function FileItem({
);
})()}
+ {hasOneDriveOrigin && onSaveToOneDrive && (
+ <FileMenuItem
+ disabledReason={oneDriveBlockedReason(updateInOneDriveLabel)}
+ icon={<Icon name="cloud-upload" size={16} />}
+ onClick={() => onSaveToOneDrive(fileId)}
+ testId="file-save-onedrive"
+ >
+ <span className="file-sidebar-kebab-item-stack">
+ <span>{updateInOneDriveLabel}</span>
+ {oneDriveName && oneDriveName !== name && (
+ <span
+ className="file-sidebar-kebab-item-detail"
+ data-testid="file-save-onedrive-target"
+ >
+ {t("oneDriveSave.replaces", "Replaces {{name}}", {
+ name: oneDriveName,
+ })}
+ </span>
+ )}
+ </span>
+ </FileMenuItem>
+ )}
+ {hasOneDriveOrigin && onSaveCopyToOneDrive && (
+ <FileMenuItem
+ disabledReason={oneDriveBlockedReason(
+ saveCopyToOneDriveLabel,
+ )}
+ icon={<Icon name="copy-plus" size={16} />}
+ onClick={() => onSaveCopyToOneDrive(fileId)}
+ testId="file-save-onedrive-copy"
+ >
+ {saveCopyToOneDriveLabel}
+ </FileMenuItem>
+ )}
+ {onSaveToOneDriveFolder && (
+ <FileMenuItem
+ disabledReason={oneDriveBlockedReason(
+ saveToOneDriveFolderLabel,
+ )}
+ icon={<Icon name="folder-up" size={16} />}
+ onClick={() => onSaveToOneDriveFolder(fileId)}
+ testId="file-save-onedrive-folder"
+ >
+ {saveToOneDriveFolderLabel}
+ </FileMenuItem>
+ )}
+ {hasOneDriveOrigin && onOpenInOneDrive && (
+ <FileMenuItem
+ icon={<Icon name="external-link" size={16} />}
+ onClick={() => onOpenInOneDrive(fileId)}
+ testId="file-open-onedrive"
+ >
+ {t("oneDriveSave.open", "Open in OneDrive")}
+ </FileMenuItem>
+ )}
+
{hasVersionHistory && onVersionHistory && (
<FileMenuItem
disabledReason={blockedReason(
diff --git a/frontend/src/editor/core/components/shared/OneDriveOriginTooltip.tsx b/frontend/src/editor/core/components/shared/OneDriveOriginTooltip.tsx
new file mode 100644
index 0000000000..bfca737d88
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/OneDriveOriginTooltip.tsx
@@ -0,0 +1,17 @@
+import { Stack } from "@mantine/core";
+import { useOneDriveSaveBlockedHint } from "@editor/hooks/useOneDriveSaveBlockedHint";
+
+interface OneDriveOriginTooltipProps {
+ label: string;
+}
+
+export function OneDriveOriginTooltip({ label }: OneDriveOriginTooltipProps) {
+ const hint = useOneDriveSaveBlockedHint();
+ if (!hint) return <>{label}</>;
+ return (
+ <Stack gap={2} data-testid="onedrive-save-blocked-hint">
+ <span>{label}</span>
+ <span>{hint}</span>
+ </Stack>
+ );
+}
diff --git a/frontend/src/editor/core/components/shared/Tooltip.test.tsx b/frontend/src/editor/core/components/shared/Tooltip.test.tsx
new file mode 100644
index 0000000000..ad4b2348a6
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/Tooltip.test.tsx
@@ -0,0 +1,53 @@
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { Tooltip } from "@editor/components/shared/Tooltip";
+
+vi.mock("@editor/hooks/useTooltipPosition", () => ({
+ useTooltipPosition: () => ({
+ coords: { top: 0, left: 0, arrowOffset: null },
+ positionReady: true,
+ }),
+}));
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+it("does not restore a hovered tooltip after disabling and enabling it", () => {
+ const trigger = (disabled: boolean) => (
+ <Tooltip
+ content="More save options"
+ disabled={disabled}
+ openOnFocus={false}
+ >
+ <button>Save menu</button>
+ </Tooltip>
+ );
+ const { rerender } = render(trigger(false));
+ fireEvent.pointerEnter(screen.getByRole("button"));
+ act(() => vi.runAllTimers());
+ expect(screen.getByRole("tooltip")).toBeInTheDocument();
+
+ rerender(trigger(true));
+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
+ rerender(trigger(false));
+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
+
+ fireEvent.pointerLeave(screen.getByRole("button"));
+ fireEvent.pointerEnter(screen.getByRole("button"));
+ act(() => vi.runAllTimers());
+ expect(screen.getByRole("tooltip")).toBeInTheDocument();
+});
+
+it("cancels a pending hover when disabled", () => {
+ const trigger = (disabled: boolean) => (
+ <Tooltip content="More save options" disabled={disabled} delay={100}>
+ <button>Save menu</button>
+ </Tooltip>
+ );
+ const { rerender } = render(trigger(false));
+ fireEvent.pointerEnter(screen.getByRole("button"));
+ rerender(trigger(true));
+ act(() => vi.runAllTimers());
+ rerender(trigger(false));
+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
+});
diff --git a/frontend/src/editor/core/components/shared/Tooltip.tsx b/frontend/src/editor/core/components/shared/Tooltip.tsx
index e2d6ba4faf..47ed3d45b0 100644
--- a/frontend/src/editor/core/components/shared/Tooltip.tsx
+++ b/frontend/src/editor/core/components/shared/Tooltip.tsx
@@ -217,6 +217,14 @@ export const Tooltip: React.FC<TooltipProps> = ({
useEffect(() => () => clearTimers(), [clearTimers]);
+ useEffect(() => {
+ if (disabled) {
+ clearTimers();
+ setInternalOpen(false);
+ setIsPinned(false);
+ }
+ }, [disabled, clearTimers]);
+
const arrowClass = useMemo(() => {
if (sidebarTooltip) return null;
const map: Record<NonNullable<TooltipProps["position"]>, string> = {
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.tsx b/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.tsx
index 9d47bfc4f1..5c64823b78 100644
--- a/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.tsx
+++ b/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.tsx
@@ -11,6 +11,7 @@ import {
type CloudProvider,
type ConnectedAccount,
} from "@editor/services/connectedAccountsService";
+import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
const PROVIDERS: { id: CloudProvider; icon: "onedrive" | "googledrive" }[] = [
{ id: "microsoft", icon: "onedrive" },
@@ -57,7 +58,7 @@ export default function ConnectedAccountsSection() {
<Text size="sm" c="dimmed">
{t(
"connectedAccounts.intro",
- "Connect your own accounts once. Your pipelines can then read from and save to them as you.",
+ "Connect your own accounts once. The editor can then open files from them without signing in again, and your pipelines can read from and save to them as you.",
)}
</Text>
{error && (
@@ -127,10 +128,14 @@ export default function ConnectedAccountsSection() {
onClose={() => setPendingDisconnect(null)}
width="sm"
zIndex={Z_INDEX_OVER_CONFIG_MODAL}
- title={t("connectedAccounts.disconnectConfirm.title", {
- defaultValue: "Disconnect {{account}}?",
- account: pendingDisconnect ? accountLabel(pendingDisconnect) : "",
- })}
+ title={
+ <span className={privateContentClassName}>
+ {t("connectedAccounts.disconnectConfirm.title", {
+ defaultValue: "Disconnect {{account}}?",
+ account: pendingDisconnect ? accountLabel(pendingDisconnect) : "",
+ })}
+ </span>
+ }
footer={
<Group justify="flex-end" gap="sm">
<Button
@@ -160,7 +165,7 @@ export default function ConnectedAccountsSection() {
<Text size="sm">
{t(
"connectedAccounts.disconnectConfirm.body",
- "Sources and pipelines that use this account will stop until you connect it again.",
+ "Sources and pipelines that use this account will stop. After you connect it again, update their account settings to use the new connection.",
)}
</Text>
</Modal>
@@ -191,7 +196,11 @@ function AccountRow({
>
<Stack gap={4} style={{ flex: "1 1 16rem", minWidth: 0 }}>
<Group gap="xs">
- <Text size="sm" style={{ overflowWrap: "anywhere" }}>
+ <Text
+ size="sm"
+ className={privateContentClassName}
+ style={{ overflowWrap: "anywhere" }}
+ >
{accountLabel(account)}
</Text>
<StatusBadge tone={needsReconnect ? "danger" : "success"} size="sm">
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.test.tsx b/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.test.tsx
index 9350554ac9..4b1647fa15 100644
--- a/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.test.tsx
+++ b/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.test.tsx
@@ -84,3 +84,36 @@ describe("ProviderCard copy field", () => {
expect(onSave).toHaveBeenCalledWith({ clientId: "abc" });
});
});
+
+describe("ProviderCard setup steps", () => {
+ const stepsButton = { name: "admin.settings.connections.setupSteps" };
+
+ function renderWithSteps(setupSteps?: string[]) {
+ render(
+ <MantineProvider>
+ <ProviderCard
+ provider={{ ...provider, setupSteps }}
+ isConfigured={false}
+ />
+ </MantineProvider>,
+ );
+ }
+
+ it("lists the steps in order behind an info button", async () => {
+ renderWithSteps(["Register an app", "Paste its client ID"]);
+
+ fireEvent.focus(screen.getByRole("button", stepsButton));
+
+ const steps = await screen.findAllByRole("listitem");
+ expect(steps.map((step) => step.textContent)).toEqual([
+ "Register an app",
+ "Paste its client ID",
+ ]);
+ });
+
+ it("shows no info button for a provider without steps", () => {
+ renderWithSteps(undefined);
+
+ expect(screen.queryByRole("button", stepsButton)).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.tsx b/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.tsx
index 74f65ea324..40694917f3 100644
--- a/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.tsx
+++ b/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.tsx
@@ -12,8 +12,10 @@ import {
NumberInput,
TagsInput,
Anchor,
+ List,
} from "@mantine/core";
import { Button } from "@editor/ui/Button";
+import { InfoTooltip } from "@editor/ui/InfoTooltip";
import { useTranslation } from "react-i18next";
import EditableSecretField from "@editor/components/shared/EditableSecretField";
import {
@@ -274,9 +276,28 @@ export default function ProviderCard({
<Group gap="sm" style={{ flex: 1, minWidth: 0 }}>
{renderProviderIcon()}
<div style={{ flex: 1, minWidth: 0 }}>
- <Text fw={600} size="sm">
- {provider.name}
- </Text>
+ <Group gap={4} wrap="nowrap">
+ <Text fw={600} size="sm">
+ {provider.name}
+ </Text>
+ {provider.setupSteps && (
+ <InfoTooltip
+ label={
+ <List type="ordered" size="xs" spacing={4}>
+ {provider.setupSteps.map((step) => (
+ <List.Item key={step}>{step}</List.Item>
+ ))}
+ </List>
+ }
+ ariaLabel={t(
+ "admin.settings.connections.setupSteps",
+ "How to set up {{name}}",
+ { name: provider.name },
+ )}
+ position="right"
+ />
+ )}
+ </Group>
<Text size="xs" c="dimmed" truncate>
{provider.scope}
</Text>
diff --git a/frontend/src/editor/core/components/shared/config/configSections/providerDefinitions.ts b/frontend/src/editor/core/components/shared/config/configSections/providerDefinitions.ts
index 35caa52112..92b5d4ea6a 100644
--- a/frontend/src/editor/core/components/shared/config/configSections/providerDefinitions.ts
+++ b/frontend/src/editor/core/components/shared/config/configSections/providerDefinitions.ts
@@ -1,4 +1,6 @@
import { useTranslation } from "react-i18next";
+import { absoluteWithBasePath } from "@editor/constants/app";
+import { ONEDRIVE_REDIRECT_PATH } from "@editor/services/oneDrivePickerService";
import { useConnectRedirectUri } from "@editor/hooks/useConnectRedirectUri";
export type ProviderType =
| "oauth2"
@@ -42,6 +44,8 @@ export interface Provider {
scope: string; // Summary of what this provider does
businessTier?: boolean; // Enterprise only
documentationUrl?: string; // Optional link to documentation
+ /** What an admin does outside Stirling before the provider works, in order. */
+ setupSteps?: string[];
fields: ProviderField[];
}
@@ -927,6 +931,7 @@ const useGoogleDriveProvider = (): Provider => {
const useMicrosoftProvider = (): Provider => {
const { t } = useTranslation();
+ const pickerRedirect = absoluteWithBasePath(ONEDRIVE_REDIRECT_PATH);
const redirectUri = useConnectRedirectUri("microsoft");
return {
@@ -936,6 +941,28 @@ const useMicrosoftProvider = (): Provider => {
icon: "onedrive",
type: "microsoft",
scope: t("provider.microsoft.scope", "Files & pipelines"),
+ setupSteps: [
+ t(
+ "provider.microsoft.setupSteps.register",
+ "Register an app in the Microsoft Entra admin center. Allow personal Microsoft accounts if people use personal OneDrive.",
+ ),
+ t(
+ "provider.microsoft.setupSteps.redirects",
+ "Add the two redirect URIs below to it: one as Web, one as Single-page application.",
+ ),
+ t(
+ "provider.microsoft.setupSteps.permissions",
+ "Add the Microsoft Graph delegated permissions Files.ReadWrite.All and Files.Read.All, and the SharePoint delegated permissions MyFiles.Read and AllSites.Read so work and school accounts can open the file picker.",
+ ),
+ t(
+ "provider.microsoft.setupSteps.secret",
+ "Create a client secret, then paste its value and the app's client ID below.",
+ ),
+ t(
+ "provider.microsoft.setupSteps.connect",
+ "Save, restart, then connect an account under Connected accounts.",
+ ),
+ ],
fields: [
{
key: "enabled",
@@ -946,7 +973,7 @@ const useMicrosoftProvider = (): Provider => {
),
description: t(
"provider.microsoft.enabled.description",
- "Let people use OneDrive and SharePoint in pipelines",
+ "Let people open files from OneDrive and SharePoint, and use them in pipelines",
),
defaultValue: false,
},
@@ -973,6 +1000,19 @@ const useMicrosoftProvider = (): Provider => {
),
value: redirectUri,
},
+ {
+ key: "pickerRedirectUri",
+ type: "copy",
+ label: t(
+ "provider.microsoft.pickerRedirectUri.label",
+ "Single-page application redirect URI",
+ ),
+ description: t(
+ "provider.microsoft.pickerRedirectUri.description",
+ "Add this as a Single-page application redirect URI on the same app registration, for signing in from the editor.",
+ ),
+ value: pickerRedirect,
+ },
{
key: "tenant",
type: "text",
@@ -1006,6 +1046,19 @@ const useMicrosoftProvider = (): Provider => {
),
defaultValue: true,
},
+ {
+ key: "allowEditorSaves",
+ type: "switch",
+ label: t(
+ "provider.microsoft.allowEditorSaves.label",
+ "Let the editor save back to OneDrive",
+ ),
+ description: t(
+ "provider.microsoft.allowEditorSaves.description",
+ "Turn off to keep edits in Stirling: files opened from OneDrive then download instead, and the server refuses saves to OneDrive.",
+ ),
+ defaultValue: true,
+ },
],
};
};
diff --git a/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx b/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
index 91ad9c0151..035f2fccbf 100644
--- a/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
+++ b/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
@@ -105,6 +105,7 @@ export default function WorkbenchBarDesktopActions({
arrow
// Over the open menu it would cover the first items.
disabled={saveMenuOpen}
+ openOnFocus={false}
portalTarget={document.body}
>
<div className="workbench-bar-tooltip-wrapper workbench-bar-save-group-caret">
diff --git a/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx b/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
index c743e3db49..bf10470737 100644
--- a/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
+++ b/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
@@ -83,6 +83,11 @@ export default function WorkbenchBarMobileActions({
onClick={item.onClick}
>
{item.label}
+ {item.description && (
+ <span className="workbench-bar-menu-hint">
+ {item.description}
+ </span>
+ )}
</Menu.Item>
))}
{showFileActions && (
diff --git a/frontend/src/editor/core/contexts/FileContext.tsx b/frontend/src/editor/core/contexts/FileContext.tsx
index 29934d9b2e..f7439d6038 100644
--- a/frontend/src/editor/core/contexts/FileContext.tsx
+++ b/frontend/src/editor/core/contexts/FileContext.tsx
@@ -1163,6 +1163,7 @@ function FileContextInner({
filesRef,
dispatchWithUnlock,
indexedDB,
+ outputFileIds.map((id) => stateRef.current.files.byId[id]),
);
},
[indexedDB, dispatchWithUnlock],
diff --git a/frontend/src/editor/core/contexts/file/fileActions.ts b/frontend/src/editor/core/contexts/file/fileActions.ts
index daf65cf292..11598cf6b5 100644
--- a/frontend/src/editor/core/contexts/file/fileActions.ts
+++ b/frontend/src/editor/core/contexts/file/fileActions.ts
@@ -31,6 +31,7 @@ import { fileStorage } from "@editor/services/fileStorage";
import { zipFileService } from "@editor/services/zipFileService";
import { FileAnalyzer } from "@editor/services/fileAnalyzer";
import { trackPdfUploaded } from "@editor/services/analytics";
+import { cloudOriginOf } from "@editor/services/cloudOrigin";
import {
reportBulkAddProgress,
clearBulkAddProgress,
@@ -550,6 +551,9 @@ export async function addFiles(
}
Object.assign(fileStub, await sourceLinkForNewFile(file));
+ const cloudOrigin = cloudOriginOf(file);
+ if (cloudOrigin)
+ fileStub.cloudOrigin = { ...cloudOrigin, savedFileId: fileId };
// Store insertion position if provided
if (options.insertAfterPageId !== undefined) {
@@ -745,6 +749,22 @@ export async function consumeFiles(
return outputStirlingFileStubs.map((stub) => stub.id);
}
+export function withLatestCloudOrigins(
+ inputs: StirlingFileStub[],
+ outputs: readonly (StirlingFileStub | undefined)[],
+): StirlingFileStub[] {
+ return inputs.map((input) => {
+ const origin = input.cloudOrigin;
+ if (!origin) return input;
+ const latest = outputs.find(
+ (output) =>
+ output?.cloudOrigin?.driveId === origin.driveId &&
+ output.cloudOrigin.itemId === origin.itemId,
+ )?.cloudOrigin;
+ return latest ? { ...input, cloudOrigin: latest } : input;
+ });
+}
+
/**
/**
* Undoes a previous consumeFiles operation by restoring input files and removing output files (unless pinned)
@@ -764,6 +784,7 @@ export async function undoConsumeFiles(
deleteFile: (fileId: FileId) => Promise<void>;
bumpRevision?: () => void;
} | null,
+ outputStirlingFileStubs: readonly (StirlingFileStub | undefined)[] = [],
): Promise<void> {
if (DEBUG)
console.log(
@@ -791,9 +812,10 @@ export async function undoConsumeFiles(
});
// Mark restored files dirty if they have a local path (they now differ from disk).
- const stubsWithDirtyMarked = inputStirlingFileStubs.map((stub) =>
- stub.localFilePath ? { ...stub, isDirty: true } : stub,
- );
+ const stubsWithDirtyMarked = withLatestCloudOrigins(
+ inputStirlingFileStubs,
+ outputStirlingFileStubs,
+ ).map((stub) => (stub.localFilePath ? { ...stub, isDirty: true } : stub));
// Dispatch with filesRef and state.files.ids now in sync.
dispatch({
@@ -829,6 +851,7 @@ export async function undoConsumeFiles(
.updateFileMetadata(stub.id, {
isLeaf: true,
...(stub.isDirty ? { isDirty: true } : {}),
+ ...(stub.cloudOrigin ? { cloudOrigin: stub.cloudOrigin } : {}),
})
.catch((error) => {
console.warn(
diff --git a/frontend/src/editor/core/contexts/file/undoCarriesCloudOrigin.test.ts b/frontend/src/editor/core/contexts/file/undoCarriesCloudOrigin.test.ts
new file mode 100644
index 0000000000..8133bbc2ae
--- /dev/null
+++ b/frontend/src/editor/core/contexts/file/undoCarriesCloudOrigin.test.ts
@@ -0,0 +1,80 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import type { CloudOrigin, FileId } from "@editor/types/file";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+
+const updateFileMetadata = vi.fn().mockResolvedValue(true);
+
+vi.mock("@editor/services/fileStorage", () => ({
+ fileStorage: { updateFileMetadata },
+}));
+
+const { undoConsumeFiles, withLatestCloudOrigins } =
+ await import("@editor/contexts/file/fileActions");
+
+const origin = (itemId: string, eTag: string): CloudOrigin => ({
+ provider: "onedrive",
+ accountId: 2,
+ driveId: "drive-1",
+ itemId,
+ parentId: "folder-1",
+ name: `${itemId}.pdf`,
+ eTag,
+ webUrl: null,
+});
+
+const stub = (id: string, cloudOrigin?: CloudOrigin) =>
+ ({
+ id: id as FileId,
+ name: `${id}.pdf`,
+ isLeaf: false,
+ ...(cloudOrigin ? { cloudOrigin } : {}),
+ }) as StirlingFileStub;
+
+describe("withLatestCloudOrigins", () => {
+ it("takes the newer OneDrive version from the same item", () => {
+ const [restored] = withLatestCloudOrigins(
+ [stub("v1", origin("item-1", "e1"))],
+ [stub("v2", origin("item-1", "e2"))],
+ );
+ expect(restored.cloudOrigin?.eTag).toBe("e2");
+ });
+
+ it("ignores links to other OneDrive items", () => {
+ const [restored] = withLatestCloudOrigins(
+ [stub("v1", origin("item-1", "e1"))],
+ [stub("v2", origin("item-2", "e9"))],
+ );
+ expect(restored.cloudOrigin?.eTag).toBe("e1");
+ });
+
+ it("never links a file that had no OneDrive origin", () => {
+ const [restored] = withLatestCloudOrigins(
+ [stub("v1")],
+ [stub("v2", origin("item-1", "e2"))],
+ );
+ expect(restored.cloudOrigin).toBeUndefined();
+ });
+});
+
+describe("undoConsumeFiles", () => {
+ beforeEach(() => updateFileMetadata.mockClear());
+
+ it("restores a saved file with the OneDrive version its undone edit saved", async () => {
+ const dispatch = vi.fn();
+ await undoConsumeFiles(
+ [new File(["x"], "v1.pdf")],
+ [stub("v1", origin("item-1", "e1"))],
+ ["v2" as FileId],
+ { current: new Map<FileId, File>() },
+ dispatch,
+ null,
+ [stub("v2", origin("item-1", "e2"))],
+ );
+ const restored = dispatch.mock.calls[0][0].payload.inputStirlingFileStubs;
+ expect(restored[0].cloudOrigin.eTag).toBe("e2");
+ expect(updateFileMetadata).toHaveBeenCalledWith("v1", {
+ isLeaf: true,
+ cloudOrigin: origin("item-1", "e2"),
+ });
+ });
+});
diff --git a/frontend/src/editor/core/hooks/useCloudFilePickers.test.ts b/frontend/src/editor/core/hooks/useCloudFilePickers.test.ts
new file mode 100644
index 0000000000..6e477c3735
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useCloudFilePickers.test.ts
@@ -0,0 +1,68 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+import { useCloudFilePickers } from "@editor/hooks/useCloudFilePickers";
+
+const google = vi.hoisted(() => ({
+ isEnabled: true,
+ isLoading: false,
+ error: null as string | null,
+ reconnectNeeded: false,
+ clearError: vi.fn(),
+ openPicker: vi.fn(async () => []),
+}));
+const oneDrive = vi.hoisted(() => ({
+ isEnabled: true,
+ isLoading: false,
+ error: null as string | null,
+ reconnectNeeded: false,
+ clearError: vi.fn(),
+ openPicker: vi.fn(async () => []),
+}));
+vi.mock("@editor/hooks/useGoogleDrivePicker", () => ({
+ useGoogleDrivePicker: () => ({ ...google }),
+}));
+vi.mock("@editor/hooks/useOneDrivePicker", () => ({
+ useOneDrivePicker: () => ({ ...oneDrive }),
+}));
+
+beforeEach(() => {
+ google.isEnabled = true;
+ oneDrive.isEnabled = true;
+ oneDrive.reconnectNeeded = false;
+ google.openPicker.mockClear();
+});
+
+it("lists only the services the server enabled, in a stable order", () => {
+ oneDrive.isEnabled = false;
+ const { result, rerender } = renderHook(useCloudFilePickers);
+ expect(result.current.map((picker) => picker.id)).toEqual(["googledrive"]);
+
+ oneDrive.isEnabled = true;
+ rerender();
+ expect(result.current.map((picker) => picker.id)).toEqual([
+ "googledrive",
+ "onedrive",
+ ]);
+ expect(result.current.map((picker) => picker.testId)).toEqual([
+ "google-drive-button",
+ "onedrive-button",
+ ]);
+});
+
+it("passes one accept filter to whichever picker is opened", async () => {
+ const { result } = renderHook(useCloudFilePickers);
+ await result.current[0].openPicker({ multiple: false, accept: ".pdf" });
+ expect(google.openPicker).toHaveBeenCalledWith({
+ multiple: false,
+ mimeTypes: ".pdf",
+ });
+});
+
+it("only the OneDrive picker can ask the user to reconnect", () => {
+ oneDrive.reconnectNeeded = true;
+ const { result } = renderHook(useCloudFilePickers);
+ expect(result.current.map((picker) => picker.reconnectNeeded)).toEqual([
+ false,
+ true,
+ ]);
+});
diff --git a/frontend/src/editor/core/hooks/useCloudFilePickers.ts b/frontend/src/editor/core/hooks/useCloudFilePickers.ts
new file mode 100644
index 0000000000..64a7b78577
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useCloudFilePickers.ts
@@ -0,0 +1,86 @@
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import type { IconName } from "@editor/ui/Icon";
+import { useGoogleDrivePicker } from "@editor/hooks/useGoogleDrivePicker";
+import { useOneDrivePicker } from "@editor/hooks/useOneDrivePicker";
+
+export interface CloudPickOptions {
+ multiple?: boolean;
+ accept?: string;
+}
+
+export interface CloudFilePicker {
+ id: "googledrive" | "onedrive";
+ icon: IconName;
+ name: string;
+ actionLabel: string;
+ failedTitle: string;
+ testId: string;
+ isLoading: boolean;
+ error: string | null;
+ reconnectNeeded: boolean;
+ clearError: () => void;
+ openPicker: (options?: CloudPickOptions) => Promise<File[]>;
+}
+
+export function useCloudFilePickers(): CloudFilePicker[] {
+ const { t } = useTranslation();
+ const {
+ isEnabled: googleEnabled,
+ isLoading: googleLoading,
+ error: googleError,
+ clearError: clearGoogleError,
+ openPicker: openGooglePicker,
+ } = useGoogleDrivePicker();
+ const oneDrive = useOneDrivePicker();
+
+ return useMemo(() => {
+ const pickers: CloudFilePicker[] = [];
+ if (googleEnabled) {
+ pickers.push({
+ id: "googledrive",
+ icon: "googledrive",
+ name: "Google Drive",
+ actionLabel: t("fileSidebar.googleDrive", "Open from Google Drive"),
+ failedTitle: t(
+ "provider.googledrive.errors.pickerFailed",
+ "Failed to open Google Drive picker",
+ ),
+ testId: "google-drive-button",
+ isLoading: googleLoading,
+ error: googleError,
+ reconnectNeeded: false,
+ clearError: clearGoogleError,
+ openPicker: (options = {}) =>
+ openGooglePicker({
+ multiple: options.multiple,
+ mimeTypes: options.accept,
+ }),
+ });
+ }
+ if (oneDrive.isEnabled) {
+ pickers.push({
+ id: "onedrive",
+ icon: "onedrive",
+ name: "OneDrive",
+ actionLabel: t("fileSidebar.oneDrive", "Open from OneDrive"),
+ failedTitle: t("fileSidebar.oneDriveFailed", "Couldn't open OneDrive"),
+ testId: "onedrive-button",
+ isLoading: oneDrive.isLoading,
+ error: oneDrive.error,
+ reconnectNeeded: oneDrive.reconnectNeeded,
+ clearError: oneDrive.clearError,
+ openPicker: oneDrive.openPicker,
+ });
+ }
+ return pickers;
+ }, [
+ googleEnabled,
+ googleLoading,
+ googleError,
+ clearGoogleError,
+ openGooglePicker,
+ oneDrive,
+ t,
+ ]);
+}
diff --git a/frontend/src/editor/core/hooks/useGoogleDrivePicker.ts b/frontend/src/editor/core/hooks/useGoogleDrivePicker.ts
index 47baf7c0e7..11c2194456 100644
--- a/frontend/src/editor/core/hooks/useGoogleDrivePicker.ts
+++ b/frontend/src/editor/core/hooks/useGoogleDrivePicker.ts
@@ -1,6 +1,11 @@
import { useState, useCallback, useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useAppConfig } from "@editor/contexts/AppConfigContext";
+import {
+ ensureConnectedAccount,
+ useConnectedAccounts,
+} from "@editor/hooks/useConnectedAccounts";
+import { fetchAccessToken } from "@editor/services/connectedAccountsService";
import {
getGoogleDrivePickerService,
isGoogleDriveConfigured,
@@ -21,7 +26,6 @@ interface UseGoogleDrivePickerReturn {
openPicker: (options?: UseGoogleDrivePickerOptions) => Promise<File[]>;
}
-/** Initializes Drive lazily; failed picks resolve to [] and set error until cleared or retried. */
export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {
const { t } = useTranslation();
const { config } = useAppConfig();
@@ -30,6 +34,8 @@ export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {
const [error, setError] = useState<string | null>(null);
const clearError = useCallback(() => setError(null), []);
const [isInitialized, setIsInitialized] = useState(false);
+ const connected = useConnectedAccounts();
+ const useAccounts = connected.available("google");
// Unrelated app settings must not invalidate Drive's config or picker callbacks.
const googleDriveBackendConfig = useMemo(
@@ -84,15 +90,38 @@ export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {
setIsLoading(true);
setError(null);
+ let account;
+ if (useAccounts) {
+ const connection = await ensureConnectedAccount(
+ "google",
+ connected.connect,
+ );
+ if (!connection.account) {
+ if (connection.outcome === "error") {
+ setError(
+ t(
+ "provider.googledrive.errors.connectFailed",
+ "Couldn't connect your Google account. Try again from Settings > Connected accounts.",
+ ),
+ );
+ }
+ return [];
+ }
+ account = connection.account;
+ }
+
await initializeService();
const service = getGoogleDrivePickerService();
- const files = await service.openPicker({
+ const pickerOptions = {
multiple: options.multiple ?? true,
mimeTypes: options.mimeTypes,
- });
-
- return files;
+ };
+ if (account) {
+ const token = await fetchAccessToken(account.id, "drive");
+ return await service.openPickerWithToken(token, pickerOptions);
+ }
+ return await service.openPicker(pickerOptions);
} catch (err) {
const errorMessage =
err instanceof Error
@@ -108,7 +137,7 @@ export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {
setIsLoading(false);
}
},
- [isEnabled, initializeService, t],
+ [isEnabled, initializeService, useAccounts, connected.connect, t],
);
return {
diff --git a/frontend/src/editor/core/hooks/useOneDrivePicker.test.ts b/frontend/src/editor/core/hooks/useOneDrivePicker.test.ts
new file mode 100644
index 0000000000..3d56a9bae0
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useOneDrivePicker.test.ts
@@ -0,0 +1,206 @@
+import { act, renderHook } from "@testing-library/react";
+import { AxiosError, AxiosHeaders } from "axios";
+import { beforeEach, expect, it, vi } from "vitest";
+import { useOneDrivePicker } from "@editor/hooks/useOneDrivePicker";
+import { allowConsole } from "@editor/tests/failOnConsole";
+
+const service = vi.hoisted(() => ({
+ initialize: vi.fn().mockResolvedValue(undefined),
+ pick: vi.fn(),
+}));
+const appConfig = vi.hoisted(() => ({
+ config: {
+ microsoftEnabled: true,
+ microsoftClientId: "app-id",
+ microsoftTenant: "organizations",
+ } as Record<string, unknown>,
+}));
+const accounts = vi.hoisted(() => ({
+ available: false,
+ account: undefined as { id: number; personal: boolean } | undefined,
+ connect: vi.fn(),
+}));
+vi.mock("@editor/hooks/useConnectedAccounts", () => ({
+ useConnectedAccounts: () => ({
+ available: () => accounts.available,
+ connect: accounts.connect,
+ }),
+ ensureConnectedAccount: async (
+ provider: string,
+ connect: (provider: string) => Promise<string>,
+ ) => {
+ if (accounts.account) return { account: accounts.account };
+ const outcome = await connect(provider);
+ return { account: accounts.account, outcome };
+ },
+}));
+vi.mock("@editor/contexts/AppConfigContext", () => ({
+ useAppConfig: () => appConfig,
+}));
+vi.mock("@editor/services/oneDrivePickerService", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@editor/services/oneDrivePickerService")
+ >()),
+ getOneDrivePickerService: () => service,
+}));
+
+beforeEach(() => {
+ service.initialize.mockClear();
+ service.pick.mockReset();
+ accounts.available = false;
+ accounts.account = undefined;
+ accounts.connect.mockReset();
+});
+
+function renderPicker() {
+ const { result } = renderHook(useOneDrivePicker);
+ const pick = (options?: Parameters<typeof result.current.openPicker>[0]) =>
+ act(() => result.current.openPicker(options));
+ return { result, pick };
+}
+
+function httpFailure(status: number) {
+ return new AxiosError("failed", "ERR", undefined, undefined, {
+ status,
+ statusText: "Failed",
+ data: {},
+ headers: {},
+ config: { headers: new AxiosHeaders() },
+ });
+}
+
+it("prepares sign-in as soon as the server enables OneDrive", () => {
+ const { result } = renderPicker();
+ expect(result.current.isEnabled).toBe(true);
+ expect(service.initialize).toHaveBeenCalledWith({
+ clientId: "app-id",
+ tenant: "organizations",
+ graphUrl: "https://graph.microsoft.com/v1.0",
+ });
+});
+
+it("narrows the picker to the accepted extensions", async () => {
+ const file = new File(["PDF"], "Report.pdf");
+ service.pick.mockResolvedValue([file]);
+ const { pick } = renderPicker();
+
+ expect(
+ await pick({ multiple: false, accept: ".pdf,application/pdf,image/*" }),
+ ).toEqual([file]);
+ expect(service.pick).toHaveBeenCalledWith(
+ expect.objectContaining({ multiple: false, extensions: [".pdf"] }),
+ undefined,
+ );
+});
+
+it("reports a failed pick and recovers on retry", async () => {
+ allowConsole.error(/OneDrive picker error/);
+ service.pick
+ .mockRejectedValueOnce(new Error("AADSTS65001: consent required"))
+ .mockResolvedValueOnce([]);
+ const { result, pick } = renderPicker();
+
+ expect(await pick()).toEqual([]);
+ expect(result.current.error).toBe("AADSTS65001: consent required");
+
+ act(() => result.current.clearError());
+ await pick();
+ expect(result.current.error).toBeNull();
+ expect(result.current.isLoading).toBe(false);
+});
+
+it("explains a blocked sign-in window and stays quiet when the user closes it", async () => {
+ allowConsole.error(/OneDrive picker error/);
+ service.pick
+ .mockRejectedValueOnce(
+ Object.assign(new Error("popup_window_error: see docs"), {
+ errorCode: "popup_window_error",
+ }),
+ )
+ .mockRejectedValueOnce(
+ Object.assign(new Error("user_cancelled"), {
+ errorCode: "user_cancelled",
+ }),
+ );
+ const { result, pick } = renderPicker();
+
+ await pick();
+ expect(result.current.error).toBe("provider.onedrive.errors.popupBlocked");
+
+ act(() => result.current.clearError());
+ expect(await pick()).toEqual([]);
+ expect(result.current.error).toBeNull();
+});
+
+it("connects the Microsoft account on first use, then picks with it", async () => {
+ accounts.available = true;
+ accounts.connect.mockImplementation(async () => {
+ accounts.account = { id: 4, personal: false };
+ return "connected";
+ });
+ service.pick.mockResolvedValue([]);
+ const { pick } = renderPicker();
+
+ await pick();
+
+ expect(accounts.connect).toHaveBeenCalledWith("microsoft");
+ expect(service.pick).toHaveBeenCalledWith(expect.anything(), {
+ accountId: 4,
+ });
+});
+
+it("signs a personal account in through the browser instead", async () => {
+ accounts.available = true;
+ accounts.account = { id: 4, personal: true };
+ service.pick.mockResolvedValue([]);
+ const { pick } = renderPicker();
+
+ await pick();
+
+ expect(accounts.connect).not.toHaveBeenCalled();
+ expect(service.pick).toHaveBeenCalledWith(expect.anything(), undefined);
+});
+
+it("stops quietly when the user closes the connect window", async () => {
+ accounts.available = true;
+ accounts.connect.mockResolvedValue("closed");
+ const { result, pick } = renderPicker();
+
+ expect(await pick()).toEqual([]);
+ expect(service.pick).not.toHaveBeenCalled();
+ expect(result.current.error).toBeNull();
+});
+
+it("offers to reconnect when the server refuses the account's token", async () => {
+ allowConsole.error(/OneDrive picker error/);
+ accounts.available = true;
+ accounts.account = { id: 4, personal: false };
+ service.pick.mockRejectedValue(httpFailure(409));
+ const { result, pick } = renderPicker();
+
+ await pick();
+
+ expect(result.current.error).toBe("provider.onedrive.errors.reconnect");
+ expect(result.current.reconnectNeeded).toBe(true);
+ act(() => result.current.clearError());
+ expect(result.current.reconnectNeeded).toBe(false);
+});
+
+it.each([
+ [
+ "a network error",
+ new AxiosError("Network Error", "ERR_NETWORK"),
+ "unreachable",
+ ],
+ ["a failed fetch", new TypeError("Failed to fetch"), "unreachable"],
+ ["an HTTP 500", httpFailure(500), "serverError"],
+])("reports %s as %s", async (_label, failure, message) => {
+ allowConsole.error(/OneDrive picker error/);
+ service.pick.mockRejectedValue(failure);
+ const { result, pick } = renderPicker();
+
+ await pick();
+
+ expect(result.current.error).toBe(`provider.onedrive.errors.${message}`);
+ expect(result.current.reconnectNeeded).toBe(false);
+});
diff --git a/frontend/src/editor/core/hooks/useOneDrivePicker.ts b/frontend/src/editor/core/hooks/useOneDrivePicker.ts
new file mode 100644
index 0000000000..43b3a4bfdf
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useOneDrivePicker.ts
@@ -0,0 +1,146 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useAppConfig } from "@editor/contexts/AppConfigContext";
+import {
+ ensureConnectedAccount,
+ useConnectedAccounts,
+} from "@editor/hooks/useConnectedAccounts";
+import {
+ acceptToExtensions,
+ classifyOneDriveFailure,
+ getOneDriveConfig,
+ getOneDrivePickerService,
+ isUserCancelled,
+} from "@editor/services/oneDrivePickerService";
+import {
+ oneDriveConnectFailedMessage,
+ oneDriveFailureMessage,
+ oneDrivePickerLabels,
+} from "@editor/services/oneDriveMessages";
+
+interface UseOneDrivePickerOptions {
+ multiple?: boolean;
+ accept?: string;
+}
+
+interface UseOneDrivePickerReturn {
+ isEnabled: boolean;
+ isLoading: boolean;
+ error: string | null;
+ reconnectNeeded: boolean;
+ clearError: () => void;
+ openPicker: (options?: UseOneDrivePickerOptions) => Promise<File[]>;
+}
+
+export function useOneDrivePicker(): UseOneDrivePickerReturn {
+ const { t, i18n } = useTranslation();
+ const { config } = useAppConfig();
+ const connected = useConnectedAccounts();
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [reconnectNeeded, setReconnectNeeded] = useState(false);
+ const clearError = useCallback(() => {
+ setError(null);
+ setReconnectNeeded(false);
+ }, []);
+
+ const oneDriveConfig = useMemo(
+ () => getOneDriveConfig(config),
+ [
+ config?.microsoftEnabled,
+ config?.microsoftClientId,
+ config?.microsoftTenant,
+ config?.microsoftGraphUrl,
+ ],
+ );
+ const isEnabled = oneDriveConfig !== null;
+ const useAccounts = connected.available("microsoft");
+
+ useEffect(() => {
+ if (oneDriveConfig) {
+ getOneDrivePickerService()
+ .initialize(oneDriveConfig)
+ .catch((err: unknown) => console.error("OneDrive init failed:", err));
+ }
+ }, [oneDriveConfig]);
+
+ const openPicker = useCallback(
+ async (options: UseOneDrivePickerOptions = {}): Promise<File[]> => {
+ if (!oneDriveConfig) {
+ setError(
+ t(
+ "provider.onedrive.errors.notConfigured",
+ "OneDrive is not configured",
+ ),
+ );
+ return [];
+ }
+ try {
+ setIsLoading(true);
+ setError(null);
+ setReconnectNeeded(false);
+ let account;
+ if (useAccounts) {
+ const connection = await ensureConnectedAccount(
+ "microsoft",
+ connected.connect,
+ );
+ if (!connection.account) {
+ if (connection.outcome === "error") {
+ setError(oneDriveConnectFailedMessage(t));
+ }
+ return [];
+ }
+ account = connection.account;
+ }
+ const service = getOneDrivePickerService();
+ await service.initialize(oneDriveConfig);
+ return await service.pick(
+ {
+ multiple: options.multiple ?? true,
+ extensions: acceptToExtensions(options.accept),
+ locale: i18n?.language,
+ labels: oneDrivePickerLabels(
+ t,
+ t("provider.onedrive.pickerTitle", "Choose files from OneDrive"),
+ ),
+ },
+ account && !account.personal ? { accountId: account.id } : undefined,
+ );
+ } catch (err) {
+ if (isUserCancelled(err)) return [];
+ console.error("OneDrive picker error:", err);
+ const failure = classifyOneDriveFailure(err);
+ setReconnectNeeded(failure === "reconnect");
+ if (failure) {
+ setError(oneDriveFailureMessage(t, failure));
+ } else {
+ setError(
+ err instanceof Error
+ ? err.message
+ : t(
+ "provider.onedrive.errors.pickerFailed",
+ "Failed to open OneDrive",
+ ),
+ );
+ }
+ return [];
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [oneDriveConfig, useAccounts, connected.connect, i18n?.language, t],
+ );
+
+ return useMemo(
+ () => ({
+ isEnabled,
+ isLoading,
+ error,
+ reconnectNeeded,
+ clearError,
+ openPicker,
+ }),
+ [isEnabled, isLoading, error, reconnectNeeded, clearError, openPicker],
+ );
+}
diff --git a/frontend/src/editor/core/hooks/useOneDriveSave.test.ts b/frontend/src/editor/core/hooks/useOneDriveSave.test.ts
new file mode 100644
index 0000000000..2786a9d6da
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useOneDriveSave.test.ts
@@ -0,0 +1,216 @@
+import { act, renderHook } from "@testing-library/react";
+import { AxiosError, AxiosHeaders } from "axios";
+import { beforeEach, expect, it, vi } from "vitest";
+import {
+ CONNECTED_ACCOUNTS_SETTINGS_PATH,
+ useOneDriveSave,
+} from "@editor/hooks/useOneDriveSave";
+import { OneDriveSaveError } from "@editor/services/oneDriveSave";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+import type { CloudOrigin, FileId } from "@editor/types/file";
+
+const mocks = vi.hoisted(() => ({
+ alert: vi.fn((_options: Record<string, unknown>) => "toast-1"),
+ navigate: vi.fn(),
+ save: vi.fn(),
+ openExternal: vi.fn(),
+ pickFolder: vi.fn(),
+ account: { id: 9, personal: false } as
+ | { id: number; personal: boolean }
+ | undefined,
+ config: {} as Record<string, unknown>,
+}));
+
+vi.mock("@editor/components/toast", () => ({
+ alert: mocks.alert,
+ dismissToast: vi.fn(),
+}));
+vi.mock("react-router-dom", () => ({ useNavigate: () => mocks.navigate }));
+vi.mock("@editor/contexts/FileContext", () => ({
+ useFileActions: () => ({ actions: { updateStirlingFileStub: vi.fn() } }),
+}));
+vi.mock("@editor/hooks/useConnectedAccounts", () => ({
+ useConnectedAccounts: () => ({
+ available: () => true,
+ connect: vi.fn(),
+ accounts: [{ id: 9, provider: "microsoft", status: "CONNECTED" }],
+ accountFor: () => mocks.account,
+ }),
+ ensureConnectedAccount: async () => ({ account: mocks.account }),
+}));
+vi.mock("@editor/hooks/useOneDrivePicker", () => ({
+ useOneDrivePicker: () => ({ isEnabled: true }),
+}));
+vi.mock("@editor/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFile: async () => new File(["%PDF"], "Report.pdf"),
+ updateFileMetadata: async () => true,
+ },
+}));
+vi.mock("@editor/services/oneDriveSave", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@editor/services/oneDriveSave")>()),
+ saveToOneDrive: mocks.save,
+}));
+vi.mock("@editor/services/oneDrivePickerService", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@editor/services/oneDrivePickerService")
+ >()),
+ getOneDrivePickerService: () => ({ pickFolder: mocks.pickFolder }),
+}));
+vi.mock("@editor/platform/openExternal", () => ({
+ openExternal: mocks.openExternal,
+}));
+vi.mock("@editor/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: mocks.config }),
+}));
+
+const origin: CloudOrigin = {
+ provider: "onedrive",
+ accountId: 9,
+ driveId: "drive-1",
+ itemId: "item-1",
+ parentId: "folder-1",
+ name: "Report.pdf",
+ eTag: '"{E},1"',
+ webUrl: "https://contoso.sharepoint.com/Report.pdf",
+};
+
+const stub = {
+ id: "file-1" as FileId,
+ name: "Report.pdf",
+ cloudOrigin: origin,
+} as StirlingFileStub;
+
+function lastToast(): Record<string, unknown> {
+ return mocks.alert.mock.calls.at(-1)![0];
+}
+
+beforeEach(() => {
+ mocks.alert.mockClear();
+ mocks.navigate.mockReset();
+ mocks.save.mockReset();
+ mocks.openExternal.mockReset();
+ mocks.pickFolder.mockReset();
+ mocks.account = { id: 9, personal: false };
+ mocks.config = { microsoftEnabled: true, microsoftClientId: "client" };
+});
+
+it("offers a Reconnect button that opens the connected accounts settings", async () => {
+ mocks.save.mockRejectedValue(new OneDriveSaveError("reconnect", "sign in"));
+ const { result } = renderHook(useOneDriveSave);
+
+ await act(() => result.current.save(stub));
+
+ const toast = lastToast();
+ expect(toast.body).toBe("provider.onedrive.errors.reconnect");
+ expect(toast.buttonText).toBe("oneDriveSave.reconnect");
+ (toast.buttonCallback as () => void)();
+ expect(mocks.navigate).toHaveBeenCalledWith(CONNECTED_ACCOUNTS_SETTINGS_PATH);
+});
+
+it.each([
+ ["network", "unreachable"],
+ ["server", "serverError"],
+] as const)("words a %s failure as %s", async (code, message) => {
+ mocks.save.mockRejectedValue(new OneDriveSaveError(code, code));
+ const { result } = renderHook(useOneDriveSave);
+
+ await act(() => result.current.save(stub));
+
+ expect(lastToast().body).toBe(`provider.onedrive.errors.${message}`);
+ expect(lastToast().buttonText).toBeUndefined();
+});
+
+it("offers Reconnect when the folder picker's token is refused", async () => {
+ mocks.pickFolder.mockRejectedValue(
+ new AxiosError("refused", "ERR", undefined, undefined, {
+ status: 409,
+ statusText: "Conflict",
+ data: {},
+ headers: {},
+ config: { headers: new AxiosHeaders() },
+ }),
+ );
+ const { result } = renderHook(useOneDriveSave);
+
+ await act(() => result.current.saveToFolder(stub));
+
+ expect(lastToast().body).toBe("provider.onedrive.errors.reconnect");
+ expect(lastToast().buttonText).toBe("oneDriveSave.reconnect");
+ expect(mocks.save).not.toHaveBeenCalled();
+});
+
+it("opens the file's OneDrive page when it has one", () => {
+ const { result } = renderHook(useOneDriveSave);
+
+ act(() => result.current.openInOneDrive(stub));
+ expect(mocks.openExternal).toHaveBeenCalledWith(origin.webUrl);
+
+ mocks.openExternal.mockClear();
+ act(() =>
+ result.current.openInOneDrive({
+ ...stub,
+ cloudOrigin: { ...origin, webUrl: null },
+ }),
+ );
+ expect(mocks.openExternal).not.toHaveBeenCalled();
+});
+
+it("is a save target for files opened from OneDrive", () => {
+ const { result } = renderHook(useOneDriveSave);
+ const target = result.current.target!;
+ expect(target.handles(stub)).toBe(true);
+ expect(target.handles({ ...stub, cloudOrigin: undefined })).toBe(false);
+ expect(target.saveLabel(stub)).toBe("oneDriveSave.toolbar.replace");
+ expect(
+ target.isUnsaved({
+ ...stub,
+ cloudOrigin: { ...origin, savedFileId: "file-0" },
+ }),
+ ).toBe(true);
+ expect(
+ target.isUnsaved({
+ ...stub,
+ cloudOrigin: { ...origin, savedFileId: "file-1" },
+ }),
+ ).toBe(false);
+});
+
+it("saves a copy next to the original from Save a copy", async () => {
+ mocks.save.mockResolvedValue({
+ ...origin,
+ itemId: "item-2",
+ name: "Report (edited).pdf",
+ });
+ const { result } = renderHook(useOneDriveSave);
+ const saved = await act(() =>
+ result.current.saveCopy(stub, new File(["%PDF"], "Report.pdf")),
+ );
+ expect(saved).toBeTruthy();
+ expect(mocks.save).toHaveBeenCalledWith(
+ expect.any(File),
+ expect.objectContaining({ kind: "copy", name: "Report (edited).pdf" }),
+ );
+});
+
+it("is not a save target when the admin turns off editor saves", () => {
+ mocks.config = { ...mocks.config, microsoftAllowEditorSaves: false };
+ const { result } = renderHook(useOneDriveSave);
+ expect(result.current.target).toBeNull();
+ expect(result.current.available).toBe(false);
+});
+
+it.each([
+ ["a work or school account", { id: 9, personal: false }, true],
+ ["a personal account", { id: 9, personal: true }, false],
+ ["no connected account", undefined, false],
+])("offers a folder save only with %s", (_name, account, offered) => {
+ mocks.account = account;
+ const { result } = renderHook(useOneDriveSave);
+ const keys = result.current.target!.menuItems!(
+ stub,
+ async () => undefined,
+ ).map((item) => item.key);
+ expect(result.current.canSaveToFolder).toBe(offered);
+ expect(keys).toEqual(offered ? ["folder"] : []);
+});
diff --git a/frontend/src/editor/core/hooks/useOneDriveSave.ts b/frontend/src/editor/core/hooks/useOneDriveSave.ts
new file mode 100644
index 0000000000..8914e9ef2b
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useOneDriveSave.ts
@@ -0,0 +1,358 @@
+import { useCallback, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useNavigate } from "react-router-dom";
+import { alert, dismissToast } from "@editor/components/toast";
+import type { ToastOptions } from "@editor/components/toast/types";
+import { useFileActions } from "@editor/contexts/FileContext";
+import {
+ ensureConnectedAccount,
+ useConnectedAccounts,
+} from "@editor/hooks/useConnectedAccounts";
+import { useOneDrivePicker } from "@editor/hooks/useOneDrivePicker";
+import { useOneDriveSavesAvailable } from "@editor/hooks/useOneDriveSavesAvailable";
+import { fileStorage } from "@editor/services/fileStorage";
+import { enforceExportPolicies } from "@editor/services/policyExport";
+import {
+ classifyOneDriveFailure,
+ getOneDrivePickerService,
+ isUserCancelled,
+} from "@editor/services/oneDrivePickerService";
+import {
+ copyName,
+ hasUnsavedCloudChanges,
+ OneDriveSaveError,
+ saveToOneDrive,
+ withLiveAccount,
+ type OneDriveSaveTarget,
+} from "@editor/services/oneDriveSave";
+import {
+ oneDriveConnectFailedMessage,
+ oneDriveFailureMessage,
+ oneDrivePickerLabels,
+} from "@editor/services/oneDriveMessages";
+import { openExternal } from "@editor/platform/openExternal";
+import type { SaveTarget } from "@editor/services/saveTargets";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+import type { FileId } from "@editor/types/file";
+
+export interface OneDriveSave {
+ available: boolean;
+ saving: FileId | null;
+ /** Save's view of OneDrive; null when editor saves to OneDrive are off. */
+ target: SaveTarget | null;
+ save: (stub: StirlingFileStub, file?: File) => Promise<boolean>;
+ saveCopy: (stub: StirlingFileStub, file?: File) => Promise<boolean>;
+ canSaveToFolder: boolean;
+ saveToFolder: (stub: StirlingFileStub, file?: File) => Promise<void>;
+ openInOneDrive: (stub: StirlingFileStub) => void;
+}
+
+export const CONNECTED_ACCOUNTS_SETTINGS_PATH = "/settings/connectedAccounts";
+
+export function useOneDriveSave(): OneDriveSave {
+ const { t, i18n } = useTranslation();
+ const { actions } = useFileActions();
+ const connected = useConnectedAccounts();
+ useOneDrivePicker();
+ const navigate = useNavigate();
+ const [saving, setSaving] = useState<FileId | null>(null);
+ const available = useOneDriveSavesAvailable();
+ const folderAccount = connected.accountFor("microsoft");
+ const canSaveToFolder =
+ available && Boolean(folderAccount) && !folderAccount?.personal;
+
+ const reconnectAction = useCallback(
+ () => ({
+ buttonText: t("oneDriveSave.reconnect", "Reconnect"),
+ buttonCallback: () => navigate(CONNECTED_ACCOUNTS_SETTINGS_PATH),
+ }),
+ [navigate, t],
+ );
+
+ const saveFailed = useCallback(
+ (body: string, extra?: Partial<ToastOptions>): string =>
+ alert({
+ alertType: "error",
+ title: t("oneDriveSave.failedTitle", "Couldn't save to OneDrive"),
+ body,
+ expandable: false,
+ ...extra,
+ }),
+ [t],
+ );
+
+ const run = useCallback(
+ async (
+ stub: StirlingFileStub,
+ requested: OneDriveSaveTarget,
+ content?: File,
+ ): Promise<boolean> => {
+ const target = withLiveAccount(requested, connected.accounts);
+ if (!target) {
+ saveFailed(oneDriveFailureMessage(t, "reconnect"), reconnectAction());
+ return false;
+ }
+ const stored = content ?? (await fileStorage.getStirlingFile(stub.id));
+ if (!stored) {
+ saveFailed(
+ t(
+ "fileSidebar.dataLostBody",
+ "This browser lost this file's contents. Upload it again to keep working with it.",
+ ),
+ );
+ return false;
+ }
+ let file: File = stored;
+ // Callers that pass content have already run export policies on it.
+ if (!content) {
+ try {
+ [file] = await enforceExportPolicies([stored], [stub.id]);
+ } catch (error) {
+ saveFailed(error instanceof Error ? error.message : String(error));
+ return false;
+ }
+ }
+ setSaving(stub.id);
+ try {
+ const origin = {
+ ...(await saveToOneDrive(file, target)),
+ savedFileId: stub.id,
+ };
+ actions.updateStirlingFileStub(stub.id, { cloudOrigin: origin });
+ const remembered = await fileStorage.updateFileMetadata(stub.id, {
+ cloudOrigin: origin,
+ });
+ if (!remembered) {
+ alert({
+ alertType: "warning",
+ title: t("oneDriveSave.saved", "Saved to OneDrive"),
+ body: t(
+ "oneDriveSave.linkNotStored",
+ "This browser couldn't remember the link to the OneDrive file. After a reload, save it as a copy instead.",
+ ),
+ expandable: false,
+ });
+ return true;
+ }
+ alert({
+ alertType: "success",
+ title: t("oneDriveSave.saved", "Saved to OneDrive"),
+ body: origin.name,
+ expandable: false,
+ durationMs: 5000,
+ ...(origin.webUrl
+ ? {
+ buttonText: t("oneDriveSave.open", "Open in OneDrive"),
+ buttonCallback: () => void openExternal(origin.webUrl!),
+ }
+ : {}),
+ });
+ return true;
+ } catch (error) {
+ const code = error instanceof OneDriveSaveError ? error.code : "failed";
+ const copyTarget =
+ (code === "conflict" || code === "missing") &&
+ target.kind === "replace"
+ ? target.origin
+ : null;
+ const toastId: string = saveFailed(
+ code === "conflict"
+ ? t(
+ "oneDriveSave.conflict",
+ "This file has changed in OneDrive since this version was opened or saved. Save your version as a copy instead.",
+ )
+ : code === "missing"
+ ? t(
+ "oneDriveSave.missing",
+ "This file was moved or deleted in OneDrive. Save your version as a copy instead.",
+ )
+ : oneDriveFailureMessage(t, code),
+ copyTarget
+ ? {
+ isPersistentPopup: true,
+ buttonText: t(
+ "oneDriveSave.saveCopyToOneDrive",
+ "Save a copy in OneDrive",
+ ),
+ buttonCallback: () => {
+ dismissToast(toastId);
+ void run(
+ stub,
+ {
+ kind: "copy",
+ origin: copyTarget,
+ name: copyName(copyTarget.name),
+ },
+ file,
+ );
+ },
+ }
+ : code === "reconnect"
+ ? reconnectAction()
+ : {},
+ );
+ return false;
+ } finally {
+ setSaving(null);
+ }
+ },
+ [actions, connected.accounts, reconnectAction, saveFailed, t],
+ );
+
+ const save = useCallback(
+ async (stub: StirlingFileStub, file?: File) => {
+ const origin = stub.cloudOrigin;
+ return origin ? run(stub, { kind: "replace", origin }, file) : false;
+ },
+ [run],
+ );
+
+ const saveCopy = useCallback(
+ async (stub: StirlingFileStub, file?: File) => {
+ const origin = stub.cloudOrigin;
+ if (!origin) return false;
+ return run(
+ stub,
+ { kind: "copy", origin, name: copyName(origin.name) },
+ file,
+ );
+ },
+ [run],
+ );
+
+ const saveToFolder = useCallback(
+ async (stub: StirlingFileStub, file?: File) => {
+ const fail = (err: unknown) => {
+ if (isUserCancelled(err)) return;
+ const failure = classifyOneDriveFailure(err);
+ saveFailed(
+ oneDriveFailureMessage(t, failure),
+ failure === "reconnect" ? reconnectAction() : undefined,
+ );
+ };
+ let account;
+ try {
+ ({ account } = await ensureConnectedAccount(
+ "microsoft",
+ connected.connect,
+ ));
+ } catch (err) {
+ fail(err);
+ return;
+ }
+ if (!account) {
+ saveFailed(oneDriveConnectFailedMessage(t));
+ return;
+ }
+ if (account.personal) {
+ saveFailed(
+ t(
+ "oneDriveSave.personalUnsupported",
+ "Uploading to OneDrive needs a work or school Microsoft account.",
+ ),
+ );
+ return;
+ }
+ let folder;
+ try {
+ folder = await getOneDrivePickerService().pickFolder(
+ {
+ locale: i18n?.language,
+ labels: oneDrivePickerLabels(
+ t,
+ t(
+ "oneDriveSave.chooseFolder",
+ "Choose a OneDrive folder to upload to",
+ ),
+ ),
+ },
+ { accountId: account.id },
+ );
+ } catch (err) {
+ fail(err);
+ return;
+ }
+ if (!folder) return;
+ await run(
+ stub,
+ {
+ kind: "folder",
+ accountId: account.id,
+ driveId: folder.driveId,
+ folderId: folder.folderId,
+ name: stub.name,
+ },
+ file,
+ );
+ },
+ [connected.connect, i18n?.language, reconnectAction, run, saveFailed, t],
+ );
+
+ const openInOneDrive = useCallback((stub: StirlingFileStub) => {
+ const url = stub.cloudOrigin?.webUrl;
+ if (url) void openExternal(url);
+ }, []);
+
+ const target = useMemo<SaveTarget | null>(() => {
+ if (!available) return null;
+ return {
+ id: "onedrive",
+ handles: (stub) => Boolean(stub.cloudOrigin),
+ isUnsaved: hasUnsavedCloudChanges,
+ saveLabel: (stub) =>
+ t("oneDriveSave.toolbar.replace", "Update {{name}} in OneDrive", {
+ name: stub.cloudOrigin?.name ?? stub.name,
+ }),
+ saveAllLabel: () =>
+ t("oneDriveSave.toolbar.saveAll", "Update all in OneDrive"),
+ statusLabel: (unsaved) =>
+ unsaved
+ ? t(
+ "oneDriveSave.status.unsaved",
+ "Changes not saved to OneDrive yet",
+ )
+ : t("oneDriveSave.status.saved", "Saved to OneDrive"),
+ icon: "cloud-upload",
+ save: async (stub, file) =>
+ (await save(stub, file)) ? "saved" : "failed",
+ menuItems: (stub, file) =>
+ canSaveToFolder
+ ? [
+ {
+ key: "folder",
+ label: t(
+ "oneDriveSave.uploadToOneDrive",
+ "Upload to OneDrive...",
+ ),
+ icon: "folder-up",
+ onClick: () => void file().then((f) => saveToFolder(stub, f)),
+ },
+ ]
+ : [],
+ saving,
+ };
+ }, [available, canSaveToFolder, save, saveToFolder, saving, t]);
+
+ return useMemo(
+ () => ({
+ available,
+ saving,
+ target,
+ save,
+ saveCopy,
+ canSaveToFolder,
+ saveToFolder,
+ openInOneDrive,
+ }),
+ [
+ available,
+ saving,
+ target,
+ save,
+ saveCopy,
+ canSaveToFolder,
+ saveToFolder,
+ openInOneDrive,
+ ],
+ );
+}
diff --git a/frontend/src/editor/core/hooks/useOneDriveSaveBlockedHint.ts b/frontend/src/editor/core/hooks/useOneDriveSaveBlockedHint.ts
new file mode 100644
index 0000000000..2abd0c5ef1
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useOneDriveSaveBlockedHint.ts
@@ -0,0 +1,3 @@
+export function useOneDriveSaveBlockedHint(): string | null {
+ return null;
+}
diff --git a/frontend/src/editor/core/hooks/useOneDriveSavesAvailable.ts b/frontend/src/editor/core/hooks/useOneDriveSavesAvailable.ts
new file mode 100644
index 0000000000..8bacad28b6
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useOneDriveSavesAvailable.ts
@@ -0,0 +1,13 @@
+import { useAppConfig } from "@editor/contexts/AppConfigContext";
+import { useConnectedAccounts } from "@editor/hooks/useConnectedAccounts";
+import { getOneDriveConfig } from "@editor/services/oneDrivePickerService";
+
+export function useOneDriveSavesAvailable(): boolean {
+ const { config } = useAppConfig();
+ const connected = useConnectedAccounts();
+ return (
+ getOneDriveConfig(config) !== null &&
+ connected.available("microsoft") &&
+ config?.microsoftAllowEditorSaves !== false
+ );
+}
diff --git a/frontend/src/editor/core/hooks/useSaveTargets.ts b/frontend/src/editor/core/hooks/useSaveTargets.ts
index 5e7ee1b86a..1d5f9ff2ad 100644
--- a/frontend/src/editor/core/hooks/useSaveTargets.ts
+++ b/frontend/src/editor/core/hooks/useSaveTargets.ts
@@ -1,8 +1,11 @@
+import { useMemo } from "react";
+import { useOneDriveSave } from "@editor/hooks/useOneDriveSave";
import type { SaveTarget } from "@editor/services/saveTargets";
const NONE: SaveTarget[] = [];
/** Places Save can write back to besides disk and downloads. */
export function useSaveTargets(): SaveTarget[] {
- return NONE;
+ const { target } = useOneDriveSave();
+ return useMemo(() => (target ? [target] : NONE), [target]);
}
diff --git a/frontend/src/editor/core/pages/HomePage.tsx b/frontend/src/editor/core/pages/HomePage.tsx
index a67c2eeb69..d3ae694680 100644
--- a/frontend/src/editor/core/pages/HomePage.tsx
+++ b/frontend/src/editor/core/pages/HomePage.tsx
@@ -894,7 +894,7 @@ const MyFilesSidebarOverrides = forwardRef<HTMLDivElement, FileSidebarProps>(
ref={ref}
{...props}
onUploadFiles={handleUpload}
- onPickGoogleDriveFiles={handleUpload}
+ onPickCloudFiles={handleUpload}
extraActions={[
{
icon: <Icon name="folder-plus" />,
diff --git a/frontend/src/editor/core/services/cloudOrigin.ts b/frontend/src/editor/core/services/cloudOrigin.ts
new file mode 100644
index 0000000000..4cb81222f6
--- /dev/null
+++ b/frontend/src/editor/core/services/cloudOrigin.ts
@@ -0,0 +1,11 @@
+import type { CloudOrigin } from "@editor/types/file";
+
+const origins = new WeakMap<File, CloudOrigin>();
+
+export function rememberCloudOrigin(file: File, origin: CloudOrigin): void {
+ origins.set(file, origin);
+}
+
+export function cloudOriginOf(file: File): CloudOrigin | undefined {
+ return origins.get(file);
+}
diff --git a/frontend/src/editor/core/services/connectedAccountsService.ts b/frontend/src/editor/core/services/connectedAccountsService.ts
index bb4f69ecbc..0b5b5196da 100644
--- a/frontend/src/editor/core/services/connectedAccountsService.ts
+++ b/frontend/src/editor/core/services/connectedAccountsService.ts
@@ -52,6 +52,18 @@ export async function disconnectAccount(id: number): Promise<void> {
await apiClient.delete(`${BASE}/${id}`);
}
+export async function fetchAccessToken(
+ id: number,
+ resource: string,
+): Promise<string> {
+ const response = await apiClient.post<{ accessToken: string }>(
+ `${BASE}/${id}/access-token`,
+ { resource },
+ { suppressErrorToast: true },
+ );
+ return response.data.accessToken;
+}
+
export type ConnectOutcome = "connected" | "cancelled" | "error" | "closed";
export async function connectAccount(
diff --git a/frontend/src/editor/core/services/fileStorage.ts b/frontend/src/editor/core/services/fileStorage.ts
index 2dfa4dbe16..8cd5689eba 100644
--- a/frontend/src/editor/core/services/fileStorage.ts
+++ b/frontend/src/editor/core/services/fileStorage.ts
@@ -403,6 +403,7 @@ class FileStorageService {
remoteSharedViaLink: stub.remoteSharedViaLink,
remoteHasShareLinks: stub.remoteHasShareLinks,
remoteShareToken: stub.remoteShareToken,
+ cloudOrigin: stub.cloudOrigin,
// History data from stub
versionNumber: stub.versionNumber ?? 1,
@@ -821,6 +822,7 @@ class FileStorageService {
isDirty: record.isDirty,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
+ cloudOrigin: record.cloudOrigin,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
remoteOwnerUsername: record.remoteOwnerUsername,
remoteOwnedByCurrentUser: record.remoteOwnedByCurrentUser,
@@ -905,6 +907,7 @@ class FileStorageService {
isDirty: record.isDirty,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
+ cloudOrigin: record.cloudOrigin,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
remoteOwnerUsername: record.remoteOwnerUsername,
remoteOwnedByCurrentUser: record.remoteOwnedByCurrentUser,
@@ -1021,6 +1024,7 @@ class FileStorageService {
isDirty: record.isDirty,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
+ cloudOrigin: record.cloudOrigin,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
remoteOwnerUsername: record.remoteOwnerUsername,
remoteOwnedByCurrentUser: record.remoteOwnedByCurrentUser,
diff --git a/frontend/src/editor/core/services/googleDrivePickerService.ts b/frontend/src/editor/core/services/googleDrivePickerService.ts
index 6bf900e930..2d6d9e8e15 100644
--- a/frontend/src/editor/core/services/googleDrivePickerService.ts
+++ b/frontend/src/editor/core/services/googleDrivePickerService.ts
@@ -179,6 +179,18 @@ class GoogleDrivePickerService {
return this.createPicker(options);
}
+ async openPickerWithToken(
+ accessToken: string,
+ options: PickerOptions = {},
+ ): Promise<File[]> {
+ if (!this.config) {
+ throw new Error("Google Drive service not initialized");
+ }
+ this.accessToken = accessToken;
+ window.gapi.client.setToken({ access_token: accessToken });
+ return this.createPicker(options);
+ }
+
/**
* Request access token from Google
*/
diff --git a/frontend/src/editor/core/services/oneDriveMessages.ts b/frontend/src/editor/core/services/oneDriveMessages.ts
new file mode 100644
index 0000000000..960066dbf7
--- /dev/null
+++ b/frontend/src/editor/core/services/oneDriveMessages.ts
@@ -0,0 +1,51 @@
+import type { TFunction } from "i18next";
+import type {
+ OneDriveFailure,
+ OneDrivePickOptions,
+} from "@editor/services/oneDrivePickerService";
+
+export function oneDriveFailureMessage(
+ t: TFunction,
+ failure: OneDriveFailure | "failed" | null,
+): string {
+ switch (failure) {
+ case "popupBlocked":
+ return t(
+ "provider.onedrive.errors.popupBlocked",
+ "Your browser blocked the Microsoft sign-in window. Allow pop-ups for this site and try again.",
+ );
+ case "reconnect":
+ return t(
+ "provider.onedrive.errors.reconnect",
+ "Your Microsoft account needs to sign in again. Reconnect it in Settings > Connected accounts.",
+ );
+ case "network":
+ return t(
+ "provider.onedrive.errors.unreachable",
+ "Couldn't reach OneDrive. Check your connection and try again.",
+ );
+ default:
+ return t(
+ "provider.onedrive.errors.serverError",
+ "OneDrive or the Stirling server had a problem. Try again, or ask your administrator if it keeps happening.",
+ );
+ }
+}
+
+export function oneDrivePickerLabels(
+ t: TFunction,
+ title: string,
+): NonNullable<OneDrivePickOptions["labels"]> {
+ return {
+ title,
+ close: t("close", "Close"),
+ loading: t("provider.onedrive.pickerLoading", "Connecting to OneDrive..."),
+ };
+}
+
+export function oneDriveConnectFailedMessage(t: TFunction): string {
+ return t(
+ "provider.onedrive.errors.connectFailed",
+ "Couldn't connect your Microsoft account. Try again from Settings > Connected accounts.",
+ );
+}
diff --git a/frontend/src/editor/core/services/oneDrivePickerService.test.ts b/frontend/src/editor/core/services/oneDrivePickerService.test.ts
new file mode 100644
index 0000000000..1412c2d429
--- /dev/null
+++ b/frontend/src/editor/core/services/oneDrivePickerService.test.ts
@@ -0,0 +1,278 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ acceptToExtensions,
+ getOneDriveConfig,
+ getOneDrivePickerService,
+} from "@editor/services/oneDrivePickerService";
+
+const msal = vi.hoisted(() => {
+ class InteractionRequiredAuthError extends Error {}
+ const account = {
+ homeAccountId: "a",
+ tenantId: "tenant-guid",
+ username: "[email protected]",
+ };
+ const app = {
+ getActiveAccount: vi.fn(() => account),
+ getAllAccounts: vi.fn(() => [account]),
+ setActiveAccount: vi.fn(),
+ loginPopup: vi.fn(),
+ acquireTokenSilent: vi.fn(async ({ scopes }: { scopes: string[] }) => ({
+ accessToken: `token:${scopes.join(" ")}`,
+ })),
+ acquireTokenPopup: vi.fn(),
+ clearCache: vi.fn(),
+ };
+ return { InteractionRequiredAuthError, app, account };
+});
+const serverTokens = vi.hoisted(() => ({
+ fetchAccessToken: vi.fn(
+ async (_id: number, resource: string) => `server:${resource}`,
+ ),
+}));
+vi.mock("@editor/services/connectedAccountsService", () => serverTokens);
+vi.mock("@azure/msal-browser", () => ({
+ InteractionRequiredAuthError: msal.InteractionRequiredAuthError,
+ createStandardPublicClientApplication: vi.fn(async () => msal.app),
+}));
+
+const GRAPH_URL = "https://graph.microsoft.com/v1.0";
+
+describe("config helpers", () => {
+ it("needs the switch and a client id", () => {
+ expect(getOneDriveConfig({ microsoftEnabled: true })).toBeNull();
+ expect(getOneDriveConfig({ microsoftClientId: "id" })).toBeNull();
+ expect(
+ getOneDriveConfig({ microsoftEnabled: true, microsoftClientId: "id" }),
+ ).toEqual({
+ clientId: "id",
+ tenant: "common",
+ graphUrl: GRAPH_URL,
+ });
+ });
+
+ it("keeps only extensions from an accept string", () => {
+ expect(acceptToExtensions(".PDF, image/*,application/pdf,.docx")).toEqual([
+ ".pdf",
+ ".docx",
+ ]);
+ expect(acceptToExtensions(undefined)).toEqual([]);
+ });
+});
+
+describe("picker protocol", () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.spyOn(HTMLFormElement.prototype, "submit").mockImplementation(() => {});
+ fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url.endsWith("/me/drive?$select=webUrl")) {
+ return Response.json({
+ webUrl: "https://contoso-my.sharepoint.com/personal/pat/Documents",
+ });
+ }
+ if (url.includes("/drives/drive%201/items/item-1?")) {
+ expect(init?.headers).toEqual({
+ Authorization: "Bearer token:Files.Read.All",
+ });
+ return Response.json({
+ name: "Invoice.pdf",
+ file: { mimeType: "application/pdf" },
+ lastModifiedDateTime: "2026-10-01T10:00:00Z",
+ ...(new URL(url).searchParams
+ .get("$select")
+ ?.split(",")
+ .includes("content.downloadUrl")
+ ? {
+ "@microsoft.graph.downloadUrl":
+ "https://download.example/invoice",
+ }
+ : {}),
+ });
+ }
+ if (url === "https://download.example/invoice") {
+ expect(init).toBeUndefined();
+ return new Response("%PDF-1.7");
+ }
+ throw new Error(`unexpected fetch ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+ });
+
+ async function initializedService() {
+ const service = getOneDrivePickerService();
+ await service.initialize({
+ clientId: "app-id",
+ tenant: "common",
+ graphUrl: GRAPH_URL,
+ });
+ return service;
+ }
+
+ async function connectPicker(
+ origin = "https://contoso-my.sharepoint.com",
+ ): Promise<{
+ activated: () => Promise<void>;
+ replies: unknown[];
+ send: (id: string, data: unknown) => void;
+ tokenReply: (id: string, token: string) => Promise<void>;
+ }> {
+ await vi.waitFor(() =>
+ expect(
+ document.querySelector("[data-testid=onedrive-picker]"),
+ ).not.toBeNull(),
+ );
+ const frame = document.querySelector("iframe")!;
+ const form = HTMLFormElement.prototype.submit as unknown as {
+ mock: { contexts: HTMLFormElement[] };
+ };
+ const submitted = form.mock.contexts[0];
+ expect(submitted.action).toMatch(
+ /^https:\/\/contoso-my\.sharepoint\.com\/_layouts\/15\/FilePicker\.aspx\?/,
+ );
+ const options = JSON.parse(
+ new URL(submitted.action).searchParams.get("filePicker")!,
+ );
+ const channel = new MessageChannel();
+ const replies: unknown[] = [];
+ channel.port2.onmessage = (event) => replies.push(event.data);
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { type: "initialize", channelId: options.messaging.channelId },
+ origin,
+ source: frame.contentWindow,
+ ports: [channel.port1],
+ }),
+ );
+ return {
+ activated: () =>
+ vi.waitFor(() => expect(replies).toContainEqual({ type: "activate" })),
+ replies,
+ send: (id, data) =>
+ channel.port2.postMessage({ type: "command", id, data }),
+ tokenReply: (id, token) =>
+ vi.waitFor(() =>
+ expect(replies).toContainEqual({
+ type: "result",
+ id,
+ data: { result: "token", token },
+ }),
+ ),
+ };
+ }
+
+ it("creates one sign-in client for concurrent initialisations", async () => {
+ const msalModule = await import("@azure/msal-browser");
+ const create = vi.mocked(msalModule.createStandardPublicClientApplication);
+ create.mockClear();
+ const service = getOneDrivePickerService();
+ const config = {
+ clientId: "concurrent-app",
+ tenant: "organizations",
+ graphUrl: GRAPH_URL,
+ };
+
+ await Promise.all([
+ service.initialize(config),
+ service.initialize(config),
+ service.initialize(config),
+ ]);
+
+ expect(create).toHaveBeenCalledTimes(1);
+ });
+
+ it("answers token requests and downloads the picked files", async () => {
+ const service = await initializedService();
+ const picked = service.pick({ extensions: [".pdf"] });
+
+ const picker = await connectPicker();
+ await picker.activated();
+ picker.send("1", {
+ command: "authenticate",
+ resource: "https://contoso-my.sharepoint.com",
+ type: "SharePoint",
+ });
+ await picker.tokenReply(
+ "1",
+ "token:https://contoso-my.sharepoint.com/.default",
+ );
+ picker.send("2", {
+ command: "pick",
+ items: [
+ {
+ id: "item-1",
+ name: "Invoice.pdf",
+ parentReference: { driveId: "drive 1" },
+ },
+ ],
+ });
+
+ const files = await picked;
+ expect(files).toHaveLength(1);
+ expect(files[0].name).toBe("Invoice.pdf");
+ expect(files[0].type).toBe("application/pdf");
+ expect(files[0].lastModified).toBe(Date.parse("2026-10-01T10:00:00Z"));
+ expect(document.querySelector("[data-testid=onedrive-picker]")).toBeNull();
+ });
+
+ it("resolves to nothing when the picker is closed", async () => {
+ const service = await initializedService();
+ const picked = service.pick();
+
+ const picker = await connectPicker();
+ await picker.activated();
+ picker.send("1", { command: "close" });
+
+ expect(await picked).toEqual([]);
+ expect(document.querySelector("[data-testid=onedrive-picker]")).toBeNull();
+ });
+
+ it("uses a connected account's server-issued tokens without signing in here", async () => {
+ msal.app.loginPopup.mockClear();
+ msal.app.acquireTokenSilent.mockClear();
+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) => {
+ if (url.endsWith("/me/drive?$select=webUrl")) {
+ expect(init?.headers).toEqual({ Authorization: "Bearer server:graph" });
+ return Response.json({
+ webUrl: "https://contoso-my.sharepoint.com/personal/pat/Documents",
+ });
+ }
+ throw new Error(`unexpected fetch ${url}`);
+ });
+ const service = await initializedService();
+ const picked = service.pick({}, { accountId: 3 });
+
+ const picker = await connectPicker();
+ await picker.activated();
+ picker.send("1", {
+ command: "authenticate",
+ resource: "https://contoso-my.sharepoint.com/personal/pat",
+ });
+ await picker.tokenReply("1", "server:https://contoso-my.sharepoint.com");
+ picker.send("2", { command: "close" });
+
+ expect(await picked).toEqual([]);
+ expect(msal.app.loginPopup).not.toHaveBeenCalled();
+ expect(msal.app.acquireTokenSilent).not.toHaveBeenCalled();
+ expect(serverTokens.fetchAccessToken).toHaveBeenCalledWith(3, "graph");
+ });
+
+ it("ignores a channel offered by a page from another origin", async () => {
+ const service = await initializedService();
+ const picked = service.pick();
+
+ const intruder = await connectPicker("https://attacker.example");
+ const picker = await connectPicker();
+ await picker.activated();
+ expect(intruder.replies).toEqual([]);
+
+ picker.send("1", { command: "close" });
+ expect(await picked).toEqual([]);
+ });
+});
diff --git a/frontend/src/editor/core/services/oneDrivePickerService.ts b/frontend/src/editor/core/services/oneDrivePickerService.ts
new file mode 100644
index 0000000000..79361e206a
--- /dev/null
+++ b/frontend/src/editor/core/services/oneDrivePickerService.ts
@@ -0,0 +1,676 @@
+import type {
+ AccountInfo,
+ IPublicClientApplication,
+} from "@azure/msal-browser";
+import { absoluteWithBasePath } from "@editor/constants/app";
+import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from "@editor/styles/zIndex";
+import { generateId } from "@editor/utils/generateId";
+import { isAxiosError } from "axios";
+import {
+ fetchAccessToken,
+ isPopupBlocked,
+} from "@editor/services/connectedAccountsService";
+import type { AppConfig } from "@editor/types/appConfig";
+import { rememberCloudOrigin } from "@editor/services/cloudOrigin";
+
+export interface OneDriveConfig {
+ clientId: string;
+ tenant: string;
+ graphUrl: string;
+}
+
+interface PickerTokens {
+ personal: boolean;
+ graph(): Promise<string>;
+ forResource(resource: string | undefined): Promise<string>;
+}
+
+export interface OneDrivePickOptions {
+ multiple?: boolean;
+ extensions?: string[];
+ locale?: string;
+ labels?: { title: string; close: string; loading: string };
+ folders?: boolean;
+}
+
+interface PickerCommand {
+ command: string;
+ resource?: string;
+ type?: string;
+ items?: PickedItem[];
+}
+
+interface PickedItem {
+ id: string;
+ name?: string;
+ parentReference: { driveId: string };
+}
+
+export interface PickedFolder {
+ driveId: string;
+ folderId: string;
+ name: string;
+}
+
+interface DriveItemDownload {
+ id: string;
+ eTag?: string;
+ webUrl?: string;
+ parentReference?: { driveId?: string; id?: string };
+ name: string;
+ file?: { mimeType?: string };
+ lastModifiedDateTime?: string;
+ "@microsoft.graph.downloadUrl"?: string;
+}
+
+const DEFAULT_GRAPH_URL = "https://graph.microsoft.com/v1.0";
+const PICKER_SETTLE_MS = 1200;
+const PICKER_REVEAL_FALLBACK_MS = 15000;
+const GRAPH_READ_SCOPES = ["Files.Read.All"];
+const PERSONAL_PICKER_URL = "https://onedrive.live.com/picker";
+const PERSONAL_PICKER_SCOPES = ["OneDrive.ReadOnly"];
+const PERSONAL_ACCOUNTS_TENANT = "9188040d-6c67-4c5b-b112-36a304b66dad";
+export const ONEDRIVE_REDIRECT_PATH = "msal-redirect.html";
+
+class OneDrivePickerService {
+ private app: IPublicClientApplication | null = null;
+ private appKey: string | null = null;
+ private interactionRequired:
+ | typeof import("@azure/msal-browser").InteractionRequiredAuthError
+ | null = null;
+ private open = false;
+ private pending: { key: string; promise: Promise<void> } | null = null;
+ private graphUrl = DEFAULT_GRAPH_URL;
+
+ async initialize(config: OneDriveConfig): Promise<void> {
+ this.graphUrl = config.graphUrl.replace(/\/$/, "");
+ const key = `${config.clientId}|${config.tenant}`;
+ if (this.app && this.appKey === key) {
+ return;
+ }
+ if (this.pending?.key !== key) {
+ const promise = this.createApp(config, key).finally(() => {
+ if (this.pending?.promise === promise) this.pending = null;
+ });
+ this.pending = { key, promise };
+ }
+ return this.pending.promise;
+ }
+
+ private async createApp(config: OneDriveConfig, key: string): Promise<void> {
+ const msal = await import("@azure/msal-browser");
+ this.interactionRequired = msal.InteractionRequiredAuthError;
+ this.app = await msal.createStandardPublicClientApplication({
+ auth: {
+ clientId: config.clientId,
+ authority: `https://login.microsoftonline.com/${encodeURIComponent(config.tenant)}`,
+ redirectUri: absoluteWithBasePath(ONEDRIVE_REDIRECT_PATH),
+ },
+ cache: { cacheLocation: "sessionStorage" },
+ });
+ this.appKey = key;
+ }
+
+ async pick(
+ options: OneDrivePickOptions = {},
+ connected?: { accountId: number },
+ ): Promise<File[]> {
+ if (this.open) {
+ return [];
+ }
+ this.open = true;
+ try {
+ const tokens = connected
+ ? this.accountTokens(connected.accountId)
+ : await this.msalTokens();
+ const baseUrl = tokens.personal
+ ? PERSONAL_PICKER_URL
+ : await this.businessPickerBaseUrl(tokens);
+ const items = await this.showPicker(tokens, baseUrl, options);
+ if (items.length === 0) {
+ return [];
+ }
+ const graphToken = await tokens.graph();
+ return await Promise.all(
+ items.map(async (item) => {
+ const { file, details } = await this.download(item, graphToken);
+ if (connected) {
+ rememberCloudOrigin(file, {
+ provider: "onedrive",
+ accountId: connected.accountId,
+ driveId:
+ details.parentReference?.driveId ??
+ item.parentReference.driveId,
+ itemId: details.id ?? item.id,
+ parentId: details.parentReference?.id ?? null,
+ name: details.name,
+ eTag: details.eTag ?? null,
+ webUrl: details.webUrl ?? null,
+ });
+ }
+ return file;
+ }),
+ );
+ } finally {
+ this.open = false;
+ }
+ }
+
+ async pickFolder(
+ options: OneDrivePickOptions,
+ connected: { accountId: number },
+ ): Promise<PickedFolder | null> {
+ if (this.open) {
+ return null;
+ }
+ this.open = true;
+ try {
+ const tokens = this.accountTokens(connected.accountId);
+ const baseUrl = await this.businessPickerBaseUrl(tokens);
+ const [folder] = await this.showPicker(tokens, baseUrl, {
+ ...options,
+ multiple: false,
+ folders: true,
+ });
+ if (!folder) {
+ return null;
+ }
+ return {
+ driveId: folder.parentReference.driveId,
+ folderId: folder.id,
+ name: folder.name ?? "",
+ };
+ } finally {
+ this.open = false;
+ }
+ }
+
+ signOut(): void {
+ const account = this.app?.getActiveAccount();
+ if (this.app && account) {
+ void this.app.clearCache({ account });
+ }
+ }
+
+ private accountTokens(accountId: number): PickerTokens {
+ return {
+ personal: false,
+ graph: () => fetchAccessToken(accountId, "graph"),
+ forResource: (resource) =>
+ fetchAccessToken(accountId, resourceOrigin(resource)),
+ };
+ }
+
+ private async msalTokens(): Promise<PickerTokens> {
+ const account = await this.signIn();
+ const personal = account.tenantId === PERSONAL_ACCOUNTS_TENANT;
+ return {
+ personal,
+ graph: () => this.token(account, GRAPH_READ_SCOPES),
+ forResource: (resource) =>
+ this.token(account, this.pickerScopes(personal, resource)),
+ };
+ }
+
+ private requireApp(): IPublicClientApplication {
+ if (!this.app) {
+ throw new Error("OneDrive is not initialized");
+ }
+ return this.app;
+ }
+
+ private async signIn(): Promise<AccountInfo> {
+ const app = this.requireApp();
+ const existing = app.getActiveAccount() ?? app.getAllAccounts()[0];
+ if (existing) {
+ app.setActiveAccount(existing);
+ return existing;
+ }
+ const result = await app.loginPopup({
+ scopes: GRAPH_READ_SCOPES,
+ prompt: "select_account",
+ });
+ app.setActiveAccount(result.account);
+ return result.account;
+ }
+
+ private async token(account: AccountInfo, scopes: string[]): Promise<string> {
+ const app = this.requireApp();
+ try {
+ return (await app.acquireTokenSilent({ scopes, account })).accessToken;
+ } catch (error) {
+ if (
+ this.interactionRequired &&
+ error instanceof this.interactionRequired
+ ) {
+ return (await app.acquireTokenPopup({ scopes, account })).accessToken;
+ }
+ throw error;
+ }
+ }
+
+ private async businessPickerBaseUrl(tokens: PickerTokens): Promise<string> {
+ const graphToken = await tokens.graph();
+ for (const path of [
+ "/me/drive?$select=webUrl",
+ "/sites/root?$select=webUrl",
+ ]) {
+ const response = await fetch(`${this.graphUrl}${path}`, {
+ headers: { Authorization: `Bearer ${graphToken}` },
+ });
+ if (response.ok) {
+ const { webUrl } = (await response.json()) as { webUrl?: string };
+ if (webUrl) {
+ return new URL(webUrl).origin;
+ }
+ }
+ }
+ throw new Error(
+ "Could not find a OneDrive or SharePoint site for this account",
+ );
+ }
+
+ private pickerScopes(
+ personal: boolean,
+ resource: string | undefined,
+ ): string[] {
+ return personal
+ ? PERSONAL_PICKER_SCOPES
+ : [`${resourceOrigin(resource)}/.default`];
+ }
+
+ private async showPicker(
+ tokens: PickerTokens,
+ baseUrl: string,
+ options: OneDrivePickOptions,
+ ): Promise<PickedItem[]> {
+ const personal = tokens.personal;
+ const initialToken = await tokens.forResource(baseUrl);
+ const channelId = generateId();
+ const pickerOptions = {
+ sdk: "8.0",
+ entry: { oneDrive: { files: {} } },
+ authentication: {},
+ messaging: { origin: window.location.origin, channelId },
+ selection: { mode: options.multiple === false ? "single" : "multiple" },
+ theme:
+ document.documentElement.dataset.theme === "dark" ? "dark" : "default",
+ accessibility: { enableFocusTrap: true },
+ typesAndSources: {
+ mode: options.folders ? "folders" : "files",
+ ...(!options.folders &&
+ options.extensions &&
+ options.extensions.length > 0
+ ? { filters: options.extensions }
+ : {}),
+ pivots: { oneDrive: true, recent: true, sharedLibraries: !personal },
+ },
+ };
+ const query = new URLSearchParams({
+ filePicker: JSON.stringify(pickerOptions),
+ locale: (options.locale ?? "en-us").toLowerCase(),
+ });
+
+ const overlay = createOverlay(
+ options.labels ?? {
+ title: "OneDrive",
+ close: "Close",
+ loading: "Connecting to OneDrive...",
+ },
+ );
+ const pickerUrl = personal
+ ? `${baseUrl}?${query}`
+ : `${baseUrl}/_layouts/15/FilePicker.aspx?${query}`;
+ const pickerOrigin = new URL(pickerUrl).origin;
+
+ return new Promise<PickedItem[]>((resolve, reject) => {
+ let port: MessagePort | null = null;
+ let settled = false;
+
+ let revealTimer: ReturnType<typeof setTimeout> | undefined;
+ const reveal = (delayMs: number) => {
+ clearTimeout(revealTimer);
+ revealTimer = setTimeout(() => {
+ overlay.frame.style.opacity = "1";
+ }, delayMs);
+ };
+
+ const finish = (items: PickedItem[] | Error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(revealTimer);
+ window.removeEventListener("message", onWindowMessage);
+ document.removeEventListener("keydown", onKeyDown, true);
+ port?.close();
+ overlay.root.remove();
+ if (items instanceof Error) reject(items);
+ else resolve(items);
+ };
+
+ const reply = (id: string, data: Record<string, unknown>) =>
+ port?.postMessage({ type: "result", id, data });
+
+ const onCommand = async (id: string, command: PickerCommand) => {
+ port?.postMessage({ type: "acknowledge", id });
+ switch (command.command) {
+ case "authenticate":
+ try {
+ const token = await tokens.forResource(command.resource);
+ reply(id, { result: "token", token });
+ reveal(PICKER_SETTLE_MS);
+ } catch (error) {
+ reply(id, {
+ result: "error",
+ error: {
+ code: "unableToObtainToken",
+ message:
+ error instanceof Error ? error.message : String(error),
+ },
+ });
+ }
+ break;
+ case "pick":
+ reply(id, { result: "success" });
+ finish(command.items ?? []);
+ break;
+ case "close":
+ finish([]);
+ break;
+ default:
+ reply(id, {
+ result: "error",
+ error: { code: "unsupportedCommand", message: command.command },
+ });
+ }
+ };
+
+ const onWindowMessage = (event: MessageEvent) => {
+ if (
+ event.source !== overlay.frame.contentWindow ||
+ event.origin !== pickerOrigin
+ )
+ return;
+ const message = event.data as { type?: string; channelId?: string };
+ if (message?.type !== "initialize" || message.channelId !== channelId) {
+ return;
+ }
+ port = event.ports[0];
+ reveal(PICKER_REVEAL_FALLBACK_MS);
+ port.addEventListener("message", (portEvent: MessageEvent) => {
+ const payload = portEvent.data as {
+ type?: string;
+ id?: string;
+ data?: PickerCommand;
+ };
+ if (payload.type === "command" && payload.id && payload.data) {
+ void onCommand(payload.id, payload.data);
+ }
+ });
+ port.start();
+ port.postMessage({ type: "activate" });
+ };
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ finish([]);
+ }
+ };
+
+ window.addEventListener("message", onWindowMessage);
+ document.addEventListener("keydown", onKeyDown, true);
+ overlay.closeButton.addEventListener("click", () => finish([]));
+ overlay.root.addEventListener("click", (event) => {
+ if (event.target === overlay.root) finish([]);
+ });
+
+ try {
+ submitIntoFrame(overlay.frame, pickerUrl, initialToken);
+ } catch (error) {
+ finish(error instanceof Error ? error : new Error(String(error)));
+ }
+ });
+ }
+
+ private async download(
+ item: PickedItem,
+ graphToken: string,
+ ): Promise<{ file: File; details: DriveItemDownload }> {
+ const driveId = encodeURIComponent(item.parentReference.driveId);
+ const itemId = encodeURIComponent(item.id);
+ const metadata = await fetch(
+ `${this.graphUrl}/drives/${driveId}/items/${itemId}?$select=id,name,eTag,webUrl,parentReference,file,lastModifiedDateTime,content.downloadUrl`,
+ { headers: { Authorization: `Bearer ${graphToken}` } },
+ );
+ if (!metadata.ok) {
+ throw new Error(
+ `Could not read ${item.name ?? "the file"} from OneDrive (HTTP ${metadata.status})`,
+ );
+ }
+ const details = (await metadata.json()) as DriveItemDownload;
+ const downloadUrl = details["@microsoft.graph.downloadUrl"];
+ if (!downloadUrl) {
+ throw new Error(`${details.name} cannot be downloaded`);
+ }
+ const content = await fetch(downloadUrl);
+ if (!content.ok) {
+ throw new Error(
+ `Could not download ${details.name} (HTTP ${content.status})`,
+ );
+ }
+ const bytes = await content.arrayBuffer();
+ const file = new File([bytes], details.name, {
+ type: details.file?.mimeType ?? content.headers.get("content-type") ?? "",
+ lastModified: details.lastModifiedDateTime
+ ? Date.parse(details.lastModifiedDateTime)
+ : Date.now(),
+ });
+ return { file, details };
+ }
+}
+
+function resourceOrigin(resource: string | undefined): string {
+ if (!resource) {
+ throw new Error("The picker asked for a token without naming a resource");
+ }
+ return new URL(resource).origin;
+}
+
+interface PickerOverlay {
+ root: HTMLDivElement;
+ frame: HTMLIFrameElement;
+ closeButton: HTMLButtonElement;
+}
+
+function createOverlay(labels: {
+ title: string;
+ close: string;
+ loading: string;
+}): PickerOverlay {
+ const root = document.createElement("div");
+ root.dataset.testid = "onedrive-picker";
+ Object.assign(root.style, {
+ position: "fixed",
+ inset: "0",
+ zIndex: String(Z_INDEX_OVER_FILE_MANAGER_MODAL),
+ background: "var(--c-overlay)",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ padding: "16px",
+ });
+
+ const panel = document.createElement("div");
+ Object.assign(panel.style, {
+ display: "flex",
+ flexDirection: "column",
+ width: "min(1080px, 100%)",
+ height: "min(724px, 100%)",
+ borderRadius: "var(--radius-lg, 12px)",
+ overflow: "hidden",
+ background: "var(--c-modal-surface, var(--c-surface))",
+ boxShadow: "var(--shadow-xl)",
+ });
+
+ const header = document.createElement("div");
+ Object.assign(header.style, {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ flex: "0 0 44px",
+ padding: "0 8px 0 16px",
+ borderBottom: "1px solid var(--c-border-subtle)",
+ color: "var(--c-text)",
+ fontSize: "14px",
+ fontWeight: "600",
+ });
+ const title = document.createElement("span");
+ title.textContent = labels.title;
+
+ const closeButton = document.createElement("button");
+ closeButton.type = "button";
+ closeButton.setAttribute("aria-label", labels.close);
+ closeButton.textContent = "×";
+ Object.assign(closeButton.style, {
+ width: "32px",
+ height: "32px",
+ border: "0",
+ borderRadius: "50%",
+ background: "transparent",
+ color: "var(--c-text-muted)",
+ fontSize: "22px",
+ lineHeight: "1",
+ cursor: "pointer",
+ });
+ header.append(title, closeButton);
+
+ const body = document.createElement("div");
+ Object.assign(body.style, { position: "relative", flex: "1 1 auto" });
+
+ const frame = document.createElement("iframe");
+ frame.name = `onedrive-picker-${generateId()}`;
+ frame.title = labels.title;
+ Object.assign(frame.style, {
+ position: "absolute",
+ inset: "0",
+ width: "100%",
+ height: "100%",
+ border: "0",
+ background: "transparent",
+ opacity: "0",
+ transition: "opacity 150ms ease-in",
+ });
+
+ const loading = document.createElement("div");
+ loading.dataset.testid = "onedrive-picker-loading";
+ loading.setAttribute("role", "status");
+ Object.assign(loading.style, {
+ position: "absolute",
+ inset: "0",
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ justifyContent: "center",
+ gap: "12px",
+ background: "var(--c-modal-surface, var(--c-surface))",
+ color: "var(--c-text-muted)",
+ fontSize: "14px",
+ });
+ const spinner = document.createElement("div");
+ Object.assign(spinner.style, {
+ width: "28px",
+ height: "28px",
+ borderRadius: "50%",
+ border: "3px solid var(--c-border)",
+ borderTopColor: "var(--c-primary)",
+ });
+ spinner.animate?.(
+ [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
+ { duration: 900, iterations: Infinity },
+ );
+ const message = document.createElement("span");
+ message.textContent = labels.loading;
+ loading.append(spinner, message);
+
+ body.append(loading, frame);
+ panel.append(header, body);
+ root.append(panel);
+ document.body.append(root);
+ return { root, frame, closeButton };
+}
+
+function submitIntoFrame(
+ frame: HTMLIFrameElement,
+ url: string,
+ accessToken: string,
+): void {
+ const form = document.createElement("form");
+ form.method = "POST";
+ form.action = url;
+ form.target = frame.name;
+ form.style.display = "none";
+ const token = document.createElement("input");
+ token.type = "hidden";
+ token.name = "access_token";
+ token.value = accessToken;
+ form.append(token);
+ document.body.append(form);
+ form.submit();
+ form.remove();
+}
+
+let serviceInstance: OneDrivePickerService | null = null;
+
+export function getOneDrivePickerService(): OneDrivePickerService {
+ if (!serviceInstance) {
+ serviceInstance = new OneDrivePickerService();
+ }
+ return serviceInstance;
+}
+
+export function getOneDriveConfig(
+ appConfig: AppConfig | null | undefined,
+): OneDriveConfig | null {
+ if (!appConfig?.microsoftEnabled || !appConfig.microsoftClientId) {
+ return null;
+ }
+ return {
+ clientId: appConfig.microsoftClientId,
+ tenant: appConfig.microsoftTenant || "common",
+ graphUrl: appConfig.microsoftGraphUrl || DEFAULT_GRAPH_URL,
+ };
+}
+
+export function acceptToExtensions(accept?: string): string[] {
+ if (!accept) return [];
+ return accept
+ .split(",")
+ .map((part) => part.trim().toLowerCase())
+ .filter((part) => part.startsWith("."));
+}
+
+export type OneDriveFailure =
+ | "popupBlocked"
+ | "reconnect"
+ | "network"
+ | "server";
+
+export function classifyOneDriveFailure(
+ error: unknown,
+): OneDriveFailure | null {
+ if (isPopupBlocked(error)) return "popupBlocked";
+ if (isAxiosError(error)) {
+ const status = error.response?.status;
+ if (status === undefined) return "network";
+ if (status === 401 || status === 403 || status === 409) return "reconnect";
+ return "server";
+ }
+ if (error instanceof TypeError) return "network";
+ return null;
+}
+
+export function isUserCancelled(error: unknown): boolean {
+ return (
+ (error as { errorCode?: string } | null)?.errorCode === "user_cancelled"
+ );
+}
diff --git a/frontend/src/editor/core/services/oneDriveSave.test.ts b/frontend/src/editor/core/services/oneDriveSave.test.ts
new file mode 100644
index 0000000000..c21bc048bf
--- /dev/null
+++ b/frontend/src/editor/core/services/oneDriveSave.test.ts
@@ -0,0 +1,181 @@
+// @vitest-environment node
+import { AxiosError, AxiosHeaders } from "axios";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { CloudOrigin } from "@editor/types/file";
+
+const post = vi.fn();
+vi.mock("@editor/services/apiClient", () => ({ default: { post } }));
+
+const { saveToOneDrive, copyName, withLiveAccount } =
+ await import("@editor/services/oneDriveSave");
+
+const origin: CloudOrigin = {
+ provider: "onedrive",
+ accountId: 33,
+ driveId: "drive-1",
+ itemId: "item-1",
+ parentId: "folder-1",
+ name: "Report.pdf",
+ eTag: '"{E},1"',
+ webUrl: null,
+};
+
+const saved = {
+ driveId: "drive-1",
+ itemId: "item-2",
+ parentId: "folder-1",
+ name: "Report.pdf",
+ eTag: '"{E},2"',
+ webUrl: "https://contoso/Report.pdf",
+};
+
+function sent(): Record<string, FormDataEntryValue> {
+ const form = post.mock.calls[0][1] as FormData;
+ return Object.fromEntries(form.entries());
+}
+
+function failure(status: number, data: object | string = {}) {
+ return new AxiosError("failed", "ERR", undefined, undefined, {
+ status,
+ statusText: "Failed",
+ data,
+ headers: {},
+ config: { headers: new AxiosHeaders() },
+ });
+}
+
+const file = new File(["%PDF-1.7"], "Report.pdf", { type: "application/pdf" });
+
+describe("saveToOneDrive", () => {
+ beforeEach(() => {
+ post.mockReset();
+ });
+
+ it("refuses to replace a file whose OneDrive version is unknown", async () => {
+ await expect(
+ saveToOneDrive(file, {
+ kind: "replace",
+ origin: { ...origin, eTag: null },
+ }),
+ ).rejects.toMatchObject({ code: "conflict" });
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it("replaces the picked item, sending the eTag it was opened with", async () => {
+ post.mockResolvedValue({ data: saved });
+
+ const next = await saveToOneDrive(file, { kind: "replace", origin });
+
+ expect(post.mock.calls[0][0]).toBe(
+ "/api/v1/connected-accounts/33/drive/save",
+ );
+ expect(sent()).toMatchObject({
+ driveId: "drive-1",
+ itemId: "item-1",
+ eTag: '"{E},1"',
+ });
+ expect(next).toMatchObject({
+ itemId: "item-2",
+ eTag: '"{E},2"',
+ stirlingCopy: false,
+ });
+ });
+
+ it("saves a copy into the folder the file came from", async () => {
+ post.mockResolvedValue({ data: saved });
+
+ const next = await saveToOneDrive(file, {
+ kind: "copy",
+ origin,
+ name: copyName(origin.name),
+ });
+ expect(next.stirlingCopy).toBe(true);
+
+ expect(sent()).toMatchObject({
+ driveId: "drive-1",
+ parentId: "folder-1",
+ name: "Report (edited).pdf",
+ });
+ expect(sent().itemId).toBeUndefined();
+ });
+
+ it.each([
+ ["a changed file", failure(409, { code: "conflict" }), "conflict"],
+ [
+ "a file deleted in OneDrive",
+ failure(410, { code: "missing" }),
+ "missing",
+ ],
+ [
+ "a changed file whose body is raw text",
+ failure(409, '{"code":"conflict","message":"changed"}'),
+ "conflict",
+ ],
+ [
+ "a deleted file whose body is raw text",
+ failure(410, '{"code":"missing"}'),
+ "missing",
+ ],
+ ["a 410 whose body is not JSON", failure(410, "Gone"), "server"],
+ ["an account that must sign in again", failure(409), "reconnect"],
+ ["a rejected account", failure(401), "reconnect"],
+ [
+ "a lost connection",
+ new AxiosError("Network Error", "ERR_NETWORK"),
+ "network",
+ ],
+ ["a server failure", failure(502), "server"],
+ ["an unexpected error", new Error("boom"), "server"],
+ ])("reports %s as %s", async (_label, error, code) => {
+ post.mockRejectedValue(error);
+
+ await expect(
+ saveToOneDrive(file, { kind: "replace", origin }),
+ ).rejects.toMatchObject({ code });
+ });
+});
+
+describe("withLiveAccount", () => {
+ const account = (id: number, status: "CONNECTED" | "NEEDS_RECONNECT") => ({
+ id,
+ provider: "microsoft" as const,
+ email: null,
+ displayName: null,
+ status,
+ personal: false,
+ lastError: null,
+ createdAt: null,
+ });
+
+ it("keeps the account the file was opened with while it is connected", () => {
+ const target = { kind: "replace" as const, origin };
+ expect(withLiveAccount(target, [account(33, "CONNECTED")])).toBe(target);
+ });
+
+ it("moves a file to the reconnected account when its old one is gone", () => {
+ const next = withLiveAccount({ kind: "replace", origin }, [
+ account(34, "CONNECTED"),
+ ]);
+ expect(next).toEqual({
+ kind: "replace",
+ origin: { ...origin, accountId: 34 },
+ });
+ });
+
+ it("refuses to guess between several connected accounts", () => {
+ expect(
+ withLiveAccount({ kind: "replace", origin }, [
+ account(34, "CONNECTED"),
+ account(35, "CONNECTED"),
+ ]),
+ ).toBeNull();
+ });
+
+ it("asks for a reconnect when no account is connected", () => {
+ expect(
+ withLiveAccount({ kind: "replace", origin }, [
+ account(33, "NEEDS_RECONNECT"),
+ ]),
+ ).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/services/oneDriveSave.ts b/frontend/src/editor/core/services/oneDriveSave.ts
new file mode 100644
index 0000000000..1d3270face
--- /dev/null
+++ b/frontend/src/editor/core/services/oneDriveSave.ts
@@ -0,0 +1,179 @@
+import type { StirlingFileStub } from "@editor/types/fileContext";
+import { isAxiosError } from "axios";
+import apiClient from "@editor/services/apiClient";
+import type { CloudOrigin } from "@editor/types/file";
+import type { ConnectedAccount } from "@editor/services/connectedAccountsService";
+
+export type OneDriveSaveTarget =
+ | { kind: "replace"; origin: CloudOrigin }
+ | { kind: "copy"; origin: CloudOrigin; name: string }
+ | {
+ kind: "folder";
+ accountId: number;
+ driveId: string;
+ folderId: string;
+ name: string;
+ };
+
+export class OneDriveSaveError extends Error {
+ constructor(
+ readonly code:
+ | "conflict"
+ | "missing"
+ | "reconnect"
+ | "network"
+ | "server"
+ | "failed",
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+interface SavedItem {
+ driveId: string;
+ itemId: string;
+ parentId: string | null;
+ name: string;
+ eTag: string | null;
+ webUrl: string | null;
+}
+
+function targetAccountId(target: OneDriveSaveTarget): number {
+ return target.kind === "folder" ? target.accountId : target.origin.accountId;
+}
+
+export function withLiveAccount(
+ target: OneDriveSaveTarget,
+ accounts: readonly ConnectedAccount[],
+): OneDriveSaveTarget | null {
+ const live = accounts.filter(
+ (account) =>
+ account.provider === "microsoft" && account.status === "CONNECTED",
+ );
+ const accountId = targetAccountId(target);
+ if (live.some((account) => account.id === accountId)) return target;
+ if (live.length !== 1) return null;
+ if (target.kind === "folder") return { ...target, accountId: live[0].id };
+ return { ...target, origin: { ...target.origin, accountId: live[0].id } };
+}
+
+export async function saveToOneDrive(
+ file: File,
+ target: OneDriveSaveTarget,
+): Promise<CloudOrigin> {
+ const accountId = targetAccountId(target);
+ const form = new FormData();
+ form.append("fileInput", file);
+ if (target.kind === "replace") {
+ if (!target.origin.eTag) {
+ throw new OneDriveSaveError(
+ "conflict",
+ "The OneDrive version of this file is unknown, so it was not replaced.",
+ );
+ }
+ form.append("driveId", target.origin.driveId);
+ form.append("itemId", target.origin.itemId);
+ form.append("eTag", target.origin.eTag);
+ } else if (target.kind === "copy") {
+ if (!target.origin.parentId) {
+ throw new OneDriveSaveError(
+ "failed",
+ "The OneDrive folder of this file is unknown.",
+ );
+ }
+ form.append("driveId", target.origin.driveId);
+ form.append("parentId", target.origin.parentId);
+ form.append("name", target.name);
+ } else {
+ form.append("driveId", target.driveId);
+ form.append("parentId", target.folderId);
+ form.append("name", target.name);
+ }
+ try {
+ const response = await apiClient.post<SavedItem>(
+ `/api/v1/connected-accounts/${accountId}/drive/save`,
+ form,
+ { suppressErrorToast: true },
+ );
+ const saved = response.data;
+ return {
+ provider: "onedrive",
+ accountId,
+ driveId: saved.driveId,
+ itemId: saved.itemId,
+ parentId: saved.parentId,
+ name: saved.name,
+ eTag: saved.eTag,
+ webUrl: saved.webUrl,
+ stirlingCopy:
+ target.kind !== "replace" || Boolean(target.origin.stirlingCopy),
+ };
+ } catch (error) {
+ throw saveError(error);
+ }
+}
+
+function saveError(error: unknown): OneDriveSaveError {
+ const server = new OneDriveSaveError(
+ "server",
+ "OneDrive or the Stirling server had a problem saving the file.",
+ );
+ if (!isAxiosError(error)) return server;
+ const response = error.response;
+ if (!response) {
+ return new OneDriveSaveError(
+ "network",
+ "Couldn't reach OneDrive. Check your connection and try again.",
+ );
+ }
+ const code = errorCode(response.data);
+ if (response.status === 409 && code === "conflict") {
+ return new OneDriveSaveError(
+ "conflict",
+ "The file changed in OneDrive since you opened it.",
+ );
+ }
+ if (response.status === 410 && code === "missing") {
+ return new OneDriveSaveError(
+ "missing",
+ "The file was moved or deleted in OneDrive.",
+ );
+ }
+ if ([401, 403, 409].includes(response.status)) {
+ return new OneDriveSaveError(
+ "reconnect",
+ "Your Microsoft account needs to sign in again.",
+ );
+ }
+ return server;
+}
+
+/** Some transports hand an error body over as its raw text rather than parsed JSON. */
+function errorCode(data: unknown): string | undefined {
+ let body = data;
+ if (typeof body === "string") {
+ try {
+ body = JSON.parse(body);
+ } catch {
+ return undefined;
+ }
+ }
+ if (typeof body !== "object" || body === null || !("code" in body)) {
+ return undefined;
+ }
+ return typeof body.code === "string" ? body.code : undefined;
+}
+
+export function copyName(name: string): string {
+ const dot = name.lastIndexOf(".");
+ return dot > 0
+ ? `${name.slice(0, dot)} (edited)${name.slice(dot)}`
+ : `${name} (edited)`;
+}
+
+/** True when this version differs from the one last saved to OneDrive. */
+export function hasUnsavedCloudChanges(stub: StirlingFileStub): boolean {
+ const origin = stub.cloudOrigin;
+ return Boolean(origin?.savedFileId && origin.savedFileId !== stub.id);
+}
diff --git a/frontend/src/editor/core/services/saveTargets.ts b/frontend/src/editor/core/services/saveTargets.ts
index 420b740c2b..4a10436dd1 100644
--- a/frontend/src/editor/core/services/saveTargets.ts
+++ b/frontend/src/editor/core/services/saveTargets.ts
@@ -24,7 +24,7 @@ export interface SaveTarget {
isUnsaved: (stub: StirlingFileStub) => boolean;
/** What Save does for this file, e.g. "Update Report.pdf in OneDrive". */
saveLabel: (stub: StirlingFileStub) => string;
- /** Label for several files, e.g. "Save all to OneDrive". */
+ /** Label for several files, e.g. "Update all in OneDrive". */
saveAllLabel: () => string;
statusLabel: (unsaved: boolean) => string;
icon: IconName;
diff --git a/frontend/src/editor/core/tests/stubbed/onedrive-save.spec.ts b/frontend/src/editor/core/tests/stubbed/onedrive-save.spec.ts
new file mode 100644
index 0000000000..b91bc90ae7
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/onedrive-save.spec.ts
@@ -0,0 +1,403 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Locator, Page, Request, Route } from "@playwright/test";
+import path from "path";
+import { uploadFiles } from "@editor/tests/helpers/ui-helpers";
+
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+const SHOTS = process.env.ONEDRIVE_SAVE_SHOTS;
+
+interface SaveCall {
+ itemId: string | null;
+ parentId: string | null;
+ name: string | null;
+}
+
+interface MicrosoftConfig {
+ allowEditorSaves?: boolean;
+ personal?: boolean;
+}
+
+async function stubMicrosoft(
+ page: Page,
+ config: MicrosoftConfig = {},
+): Promise<SaveCall[]> {
+ await page.route("**/api/v1/config/app-config", (route: Route) =>
+ route.fulfill({
+ json: {
+ enableLogin: false,
+ isAdmin: false,
+ languages: ["en-US"],
+ defaultLocale: "en-US",
+ microsoftEnabled: true,
+ microsoftClientId: "00000000-0000-0000-0000-000000000000",
+ microsoftTenant: "organizations",
+ microsoftAccountConnections: true,
+ microsoftAllowEditorSaves: config.allowEditorSaves ?? true,
+ },
+ }),
+ );
+ await page.route("**/api/v1/connected-accounts", (route: Route) =>
+ route.fulfill({
+ json: {
+ providers: { microsoft: true, google: false },
+ accounts: [
+ {
+ id: 9,
+ provider: "microsoft",
+ email: "[email protected]",
+ displayName: "Pat",
+ status: "CONNECTED",
+ personal: config.personal ?? false,
+ lastError: null,
+ createdAt: null,
+ },
+ ],
+ },
+ }),
+ );
+ const calls: SaveCall[] = [];
+ await page.route("**/api/v1/connected-accounts/9/drive/save", (route) => {
+ const call = parseSave(route.request());
+ calls.push(call);
+ const copy = call.itemId === null;
+ return route.fulfill({
+ json: {
+ driveId: "drive-1",
+ itemId: copy ? `copy-${calls.length}` : call.itemId,
+ parentId: "folder-1",
+ name: call.name ?? "Report.pdf",
+ eTag: `"{E},${calls.length + 1}"`,
+ webUrl: "https://contoso.sharepoint.com/Report.pdf",
+ },
+ });
+ });
+ return calls;
+}
+
+function parseSave(request: Request): SaveCall {
+ const body = request.postDataBuffer()?.toString("latin1") ?? "";
+ const field = (name: string) =>
+ body.match(new RegExp(`name="${name}"\\r\\n\\r\\n([^\\r]*)`))?.[1] ?? null;
+ return {
+ itemId: field("itemId"),
+ parentId: field("parentId"),
+ name: field("name"),
+ };
+}
+
+/** Marks the uploaded file as opened from OneDrive, then reloads. */
+async function openFromOneDrive(page: Page, unsaved: boolean): Promise<void> {
+ await uploadFiles(page, SAMPLE_PDF);
+ await page.evaluate(
+ (dirty) =>
+ new Promise<void>((resolve, reject) => {
+ const open = indexedDB.open("stirling-pdf-files");
+ open.onsuccess = () => {
+ const store = open.result
+ .transaction("files", "readwrite")
+ .objectStore("files");
+ const all = store.getAll();
+ all.onsuccess = () => {
+ for (const record of all.result) {
+ record.cloudOrigin = {
+ provider: "onedrive",
+ accountId: 9,
+ driveId: "drive-1",
+ itemId: "item-1",
+ parentId: "folder-1",
+ name: "Report.pdf",
+ eTag: '"{E},1"',
+ webUrl: "https://contoso.sharepoint.com/Report.pdf",
+ savedFileId: dirty ? "older-version" : record.id,
+ };
+ store.put(record);
+ }
+ store.transaction.oncomplete = () => resolve();
+ };
+ all.onerror = () => reject(all.error);
+ };
+ open.onerror = () => reject(open.error);
+ }),
+ unsaved,
+ );
+ await page.reload();
+ await expect(page.getByTestId("file-onedrive-badge").first()).toBeVisible({
+ timeout: 15_000,
+ });
+}
+
+async function startWithOneDriveFile(
+ page: Page,
+ { unsaved, ...config }: MicrosoftConfig & { unsaved: boolean },
+): Promise<SaveCall[]> {
+ const calls = await stubMicrosoft(page, config);
+ await page.goto("/editor");
+ await openFromOneDrive(page, unsaved);
+ return calls;
+}
+
+async function openInViewer(page: Page): Promise<void> {
+ const item = page.locator(".file-sidebar-file-item").first();
+ await item.hover();
+ // The reload keeps the viewed-file marker but not the workbench, so reopen it.
+ const close = item.getByRole("button", { name: "Close viewer" });
+ if (await close.count()) await close.click();
+ await item.getByRole("button", { name: "Open in viewer" }).click();
+ await expect(
+ page.getByRole("button", { name: /Close PDF/ }).first(),
+ ).toBeVisible({ timeout: 15_000 });
+ // Save exports through the viewer, which can only do so once the document loaded.
+ await expect(page.getByText("/ 1", { exact: true })).toBeVisible({
+ timeout: 15_000,
+ });
+ await page.waitForFunction(() =>
+ document.querySelector("canvas, img[src^='blob:']"),
+ );
+}
+
+async function openFileCards(page: Page): Promise<Locator> {
+ // The segmented control's radio sits off-screen; its label takes the click.
+ const radio = page.getByRole("radio", { name: /Active Files/i });
+ const id = await radio.getAttribute("id");
+ await page.locator(`label[for="${id}"]`).click();
+ const card = page.getByTestId("file-thumbnail").first();
+ await expect(card).toBeVisible({ timeout: 15_000 });
+ await card.hover();
+ return card;
+}
+
+async function nthSave(calls: SaveCall[], n: number): Promise<SaveCall> {
+ await expect.poll(() => calls.length).toBe(n);
+ return calls[n - 1];
+}
+
+async function expectOtherDestinations(page: Page): Promise<void> {
+ await expect(
+ page.getByRole("menuitem", { name: "Download", exact: true }),
+ ).toBeVisible();
+ await expect(
+ page.getByRole("menuitem", { name: /Upload to OneDrive/ }),
+ ).toBeVisible();
+}
+
+function toolbarUnsavedDot(page: Page): Locator {
+ return page.locator(".workbench-bar-unsaved-dot");
+}
+
+function sidebarUnsavedDot(page: Page): Locator {
+ return page
+ .getByTestId("file-onedrive-badge")
+ .locator(".file-sidebar-cloud-badge-dot");
+}
+
+async function shot(page: Page, name: string): Promise<void> {
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `${name}.png`) });
+}
+
+test.describe("Saving files opened from OneDrive", () => {
+ test.use({ autoGoto: false });
+
+ test("Save updates the original in OneDrive by default", async ({ page }) => {
+ const calls = await startWithOneDriveFile(page, { unsaved: true });
+ await openInViewer(page);
+
+ const save = page.getByRole("button", {
+ name: "Update Report.pdf in OneDrive",
+ });
+ await expect(save).toBeVisible();
+ await expect(toolbarUnsavedDot(page)).toBeVisible();
+ await shot(page, "1-replace-unsaved");
+ await save.click();
+
+ expect(await nthSave(calls, 1)).toMatchObject({ itemId: "item-1" });
+ await expect(page.getByText("Saved to OneDrive").first()).toBeVisible();
+ await expect(toolbarUnsavedDot(page)).toHaveCount(0);
+ });
+
+ test("the menu offers the other destinations", async ({ page }) => {
+ await startWithOneDriveFile(page, { unsaved: true });
+ await openInViewer(page);
+
+ const more = page.getByRole("button", { name: "More save options" });
+ await more.hover();
+ await expect(page.getByRole("tooltip")).toHaveText("More save options");
+ await more.click();
+ await expectOtherDestinations(page);
+ await expect(
+ page.getByRole("menuitem", { name: /Update Report\.pdf/ }),
+ ).toHaveCount(0);
+ await shot(page, "3-save-menu");
+ await page.keyboard.press("Escape");
+
+ await expect(page.getByRole("menu")).toHaveCount(0);
+ await expect(more).toBeFocused();
+ await expect(page.getByRole("tooltip")).toHaveCount(0);
+ });
+
+ test("a personal account is not offered a folder save", async ({ page }) => {
+ await startWithOneDriveFile(page, { unsaved: false, personal: true });
+ await openInViewer(page);
+
+ await page.getByRole("button", { name: "More save options" }).click();
+ await expect(
+ page.getByRole("menuitem", { name: "Download", exact: true }),
+ ).toBeVisible();
+ await expect(
+ page.getByRole("menuitem", { name: /Upload to OneDrive/ }),
+ ).toHaveCount(0);
+ await page.keyboard.press("Escape");
+ await expect(page.getByRole("menu")).toHaveCount(0);
+
+ const item = page.locator(".file-sidebar-file-item").first();
+ await item.hover();
+ await item.getByRole("button", { name: "More actions" }).click();
+ await expect(page.getByTestId("file-save-onedrive")).toBeVisible();
+ await expect(page.getByTestId("file-save-onedrive-folder")).toHaveCount(0);
+ });
+
+ test("the file menu's OneDrive rows fit on one line", async ({ page }) => {
+ await startWithOneDriveFile(page, { unsaved: true });
+ const item = page.locator(".file-sidebar-file-item").first();
+ await item.hover();
+ await item.getByRole("button", { name: "More actions" }).click();
+ const rows = [
+ page
+ .getByTestId("file-save-onedrive")
+ .locator(".file-sidebar-kebab-item-stack > span")
+ .first(),
+ page.getByTestId("file-save-onedrive-target"),
+ page.getByTestId("file-save-onedrive-copy"),
+ page.getByTestId("file-save-onedrive-folder"),
+ page.getByTestId("file-open-onedrive"),
+ ];
+ for (const row of rows) {
+ await expect(row).toBeVisible();
+ const lines = await row.evaluate((el) => {
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ let most = 0;
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const range = document.createRange();
+ range.selectNodeContents(node);
+ const tops = [...range.getClientRects()]
+ .filter((r) => r.width > 0)
+ .map((r) => Math.round(r.top));
+ most = Math.max(most, new Set(tops).size);
+ }
+ return most;
+ });
+ expect(lines, await row.innerText()).toBe(1);
+ }
+ });
+
+ test("the result of a tool offers the same save menu", async ({ page }) => {
+ await page.route("**/api/v1/general/rotate-pdf", (route: Route) =>
+ route.fulfill({
+ path: SAMPLE_PDF,
+ headers: {
+ "content-type": "application/pdf",
+ "content-disposition": 'attachment; filename="Report.pdf"',
+ },
+ }),
+ );
+ const calls = await startWithOneDriveFile(page, { unsaved: false });
+ await openInViewer(page);
+
+ await page.getByText("Rotate", { exact: true }).first().click();
+ await page.getByRole("button", { name: "Rotate Clockwise" }).click();
+ await page.getByRole("button", { name: /Apply Rotation/ }).click();
+ await expect(page.getByTestId("download-result-button")).toHaveText(
+ "Update Report.pdf in OneDrive",
+ { timeout: 15_000 },
+ );
+
+ await page.getByTestId("download-result-menu").click();
+ await expectOtherDestinations(page);
+ await shot(page, "7-result-save-menu");
+ await page.keyboard.press("Escape");
+ await page.getByTestId("download-result-button").click();
+
+ expect(await nthSave(calls, 1)).toMatchObject({ itemId: "item-1" });
+ });
+
+ test("turning off editor saves hides OneDrive saving", async ({ page }) => {
+ const calls = await startWithOneDriveFile(page, {
+ unsaved: true,
+ allowEditorSaves: false,
+ });
+ await openInViewer(page);
+
+ await expect(
+ page.getByRole("button", { name: "More save options" }),
+ ).toHaveCount(0);
+ await expect(toolbarUnsavedDot(page)).toHaveCount(0);
+ const download = page.waitForEvent("download");
+ await page.getByRole("button", { name: "Download", exact: true }).click();
+ await download;
+ expect(calls).toHaveLength(0);
+ });
+
+ test("a file card saves to OneDrive like the toolbar", async ({ page }) => {
+ const calls = await startWithOneDriveFile(page, { unsaved: true });
+ const card = await openFileCards(page);
+
+ await expect(card.getByTestId("file-card-save-status")).toBeVisible();
+ await expect(
+ card.getByRole("button", { name: "Download", exact: true }),
+ ).toBeVisible();
+ await expect(sidebarUnsavedDot(page)).toBeVisible();
+ await shot(page, "5-file-card");
+ await card
+ .getByRole("button", { name: "Update Report.pdf in OneDrive" })
+ .click();
+
+ expect(await nthSave(calls, 1)).toMatchObject({ itemId: "item-1" });
+ await expect(card.getByTestId("file-card-save-status")).toHaveCount(0);
+ await expect(sidebarUnsavedDot(page)).toHaveCount(0);
+ });
+
+ test("Save in the page editor sends its unsaved edits to OneDrive", async ({
+ page,
+ }) => {
+ const calls = await startWithOneDriveFile(page, { unsaved: false });
+ await openFileCards(page);
+ await page
+ .locator('[data-tour="view-switcher"]')
+ .first()
+ .locator(".mantine-SegmentedControl-label", { hasText: "Page Editor" })
+ .click();
+ const track = page.getByTestId("page-tracks").locator("section").first();
+ const firstPage = track.locator("[data-page-id]").first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+ await firstPage.hover();
+ await firstPage.getByRole("button", { name: "Rotate right" }).click();
+ await expect(track).toContainText("edited");
+
+ await page
+ .getByRole("button", { name: "Update Report.pdf in OneDrive" })
+ .click();
+
+ expect(await nthSave(calls, 1)).toMatchObject({ itemId: "item-1" });
+ await expect(track).toContainText("v2", { timeout: 30_000 });
+ await expect(track).not.toContainText("edited");
+ await expect(toolbarUnsavedDot(page)).toHaveCount(0);
+ });
+
+ test("closing a card with unsaved OneDrive edits offers to save them", async ({
+ page,
+ }) => {
+ const calls = await startWithOneDriveFile(page, { unsaved: true });
+ const card = await openFileCards(page);
+
+ await card.getByRole("button", { name: "Close", exact: true }).click();
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toContainText("This file has unsaved changes.");
+ await shot(page, "6-close-unsaved");
+ await dialog.getByRole("button", { name: /Save and close/i }).click();
+
+ await nthSave(calls, 1);
+ await expect(page.getByTestId("file-thumbnail")).toHaveCount(0);
+ });
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-library-cleanup.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-library-cleanup.spec.ts
index 0187ce7e9f..5693c32a40 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-library-cleanup.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-library-cleanup.spec.ts
@@ -59,21 +59,13 @@ test.describe("PDF Library cleanup", () => {
await expect(page.getByTestId("google-drive-button")).toHaveCount(0);
});
- test("shows the Google Drive button beside the add button", async ({
- page,
- }) => {
+ test("offers Google Drive from the add menu", async ({ page }) => {
await stubGoogleDriveConfigured(page);
await page.goto("/editor");
- const drive = page.getByTestId("google-drive-button");
- await expect(drive).toBeVisible();
-
- const driveBox = await drive.boundingBox();
- const addBox = await page
- .getByTestId("pdf-library-add-files")
- .boundingBox();
- expect(driveBox).not.toBeNull();
- expect(addBox).not.toBeNull();
- expect(driveBox!.y).toBeCloseTo(addBox!.y, 0);
- expect(addBox!.x - (driveBox!.x + driveBox!.width)).toBeLessThan(12);
+ await page.getByTestId("pdf-library-add-files").click();
+ await expect(page.getByTestId("google-drive-button")).toBeVisible();
+ await expect(
+ page.getByTestId("pdf-library-add-from-computer"),
+ ).toBeVisible();
});
});
diff --git a/frontend/src/editor/core/types/appConfig.ts b/frontend/src/editor/core/types/appConfig.ts
index 0d62423828..89b1d89992 100644
--- a/frontend/src/editor/core/types/appConfig.ts
+++ b/frontend/src/editor/core/types/appConfig.ts
@@ -77,7 +77,12 @@ export interface AppConfig {
googleDriveApiKey?: string;
googleDriveAppId?: string;
googleDriveAccountConnections?: boolean;
+ microsoftEnabled?: boolean;
+ microsoftClientId?: string;
+ microsoftTenant?: string;
+ microsoftGraphUrl?: string;
microsoftAccountConnections?: boolean;
+ microsoftAllowEditorSaves?: boolean;
timestampDefaultTsaUrl?: string;
timestampCustomTsaUrls?: string[];
timestampTsaPresets?: { label: string; url: string }[];
diff --git a/frontend/src/editor/core/types/file.ts b/frontend/src/editor/core/types/file.ts
index fac43fd86e..110081ad56 100644
--- a/frontend/src/editor/core/types/file.ts
+++ b/frontend/src/editor/core/types/file.ts
@@ -88,6 +88,22 @@ export interface BaseFileMetadata {
remoteHasShareLinks?: boolean; // True when owner has shared this file
remoteHasUserShares?: boolean; // True when owner has invited specific users
remoteShareToken?: string; // Share token when file is from a share link
+ cloudOrigin?: CloudOrigin;
+}
+
+export interface CloudOrigin {
+ provider: "onedrive";
+ accountId: number;
+ driveId: string;
+ itemId: string;
+ parentId: string | null;
+ name: string;
+ eTag: string | null;
+ webUrl: string | null;
+ /** Stirling created this item (a copy or a folder save), so Save may update it. */
+ stirlingCopy?: boolean;
+ /** The file version last read from or saved to OneDrive. */
+ savedFileId?: string;
}
/**
diff --git a/frontend/src/editor/core/utils/inMemoryUpload.ts b/frontend/src/editor/core/utils/inMemoryUpload.ts
index b420d9d335..7bfb8784b7 100644
--- a/frontend/src/editor/core/utils/inMemoryUpload.ts
+++ b/frontend/src/editor/core/utils/inMemoryUpload.ts
@@ -33,8 +33,8 @@ export function copyBudgetBytes(maxTouchPoints: number): number {
/**
* A copy of `form` with files read into memory, in entry order, until their combined size would
* pass `budgetBytes`. Files past the budget are re-wrapped instead of copied: the WebKit bug
- * thread reports a fresh File over the same bytes uploading correctly, which costs no memory but
- * has not been confirmed here. String fields are kept as they are.
+ * thread reports a fresh File over the same bytes uploading correctly, which costs no memory.
+ * String fields are kept as they are.
*/
export async function inMemoryFormData(
form: FormData,
diff --git a/frontend/src/editor/desktop/hooks/useOneDriveSaveBlockedHint.test.ts b/frontend/src/editor/desktop/hooks/useOneDriveSaveBlockedHint.test.ts
new file mode 100644
index 0000000000..423ae50899
--- /dev/null
+++ b/frontend/src/editor/desktop/hooks/useOneDriveSaveBlockedHint.test.ts
@@ -0,0 +1,37 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({ savesAvailable: false, connected: false }));
+
+vi.mock("@editor/hooks/useOneDriveSavesAvailable", () => ({
+ useOneDriveSavesAvailable: () => state.savesAvailable,
+}));
+vi.mock("@editor/hooks/useConnectedServer", () => ({
+ useConnectedServer: () => state.connected,
+}));
+
+import { useOneDriveSaveBlockedHint } from "@editor/hooks/useOneDriveSaveBlockedHint";
+
+describe("useOneDriveSaveBlockedHint", () => {
+ beforeEach(() => {
+ state.savesAvailable = false;
+ state.connected = false;
+ });
+
+ it("asks to sign in when no server is connected", () => {
+ const { result } = renderHook(useOneDriveSaveBlockedHint);
+ expect(result.current).toBe("oneDriveSave.signInToSave");
+ });
+
+ it("says nothing when Save can reach OneDrive", () => {
+ state.savesAvailable = true;
+ const { result } = renderHook(useOneDriveSaveBlockedHint);
+ expect(result.current).toBeNull();
+ });
+
+ it("says nothing when signed in to a server that has OneDrive saves off", () => {
+ state.connected = true;
+ const { result } = renderHook(useOneDriveSaveBlockedHint);
+ expect(result.current).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/desktop/hooks/useOneDriveSaveBlockedHint.ts b/frontend/src/editor/desktop/hooks/useOneDriveSaveBlockedHint.ts
new file mode 100644
index 0000000000..dbe6a6a048
--- /dev/null
+++ b/frontend/src/editor/desktop/hooks/useOneDriveSaveBlockedHint.ts
@@ -0,0 +1,14 @@
+import { useTranslation } from "react-i18next";
+import { useConnectedServer } from "@editor/hooks/useConnectedServer";
+import { useOneDriveSavesAvailable } from "@editor/hooks/useOneDriveSavesAvailable";
+
+export function useOneDriveSaveBlockedHint(): string | null {
+ const { t } = useTranslation();
+ const savesAvailable = useOneDriveSavesAvailable();
+ const connectedServer = useConnectedServer();
+ if (savesAvailable || connectedServer) return null;
+ return t(
+ "oneDriveSave.signInToSave",
+ "Sign in to your server to save to OneDrive.",
+ );
+}
diff --git a/frontend/src/editor/desktop/services/tauriHttpClient.test.ts b/frontend/src/editor/desktop/services/tauriHttpClient.test.ts
index 92862a37ec..7036d008c1 100644
--- a/frontend/src/editor/desktop/services/tauriHttpClient.test.ts
+++ b/frontend/src/editor/desktop/services/tauriHttpClient.test.ts
@@ -145,3 +145,53 @@ describe("tauriHttpClient — Content-Type handling", () => {
expect(ct).toBe("application/json");
});
});
+
+describe("tauriHttpClient - FormData uploads", () => {
+ const WEBKIT =
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
+ const WEBVIEW2 =
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0";
+
+ const original = new File(["%PDF-2.0 bytes"], "Report.pdf", {
+ type: "application/pdf",
+ lastModified: 1234,
+ });
+
+ async function send(userAgent: string): Promise<FormData> {
+ vi.stubGlobal("navigator", { userAgent, maxTouchPoints: 0 });
+ const form = new FormData();
+ form.append("fileInput", original);
+ form.append("accountId", "33");
+ await create({ baseURL: "https://api.test" }).post(
+ "/api/v1/rights-management/open",
+ form,
+ );
+ return fetchMock.mock.calls[0][1].body as FormData;
+ }
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValue(okJson());
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ test("sends in-memory copies from WebKit, keeping fields, names and bytes", async () => {
+ const sent = await send(WEBKIT);
+
+ const file = sent.get("fileInput") as File;
+ expect(file).not.toBe(original);
+ expect(file.name).toBe("Report.pdf");
+ expect(file.type).toBe("application/pdf");
+ expect(file.lastModified).toBe(1234);
+ expect(await file.text()).toBe("%PDF-2.0 bytes");
+ expect(sent.get("accountId")).toBe("33");
+ });
+
+ test("streams the original file from other engines", async () => {
+ const sent = await send(WEBVIEW2);
+
+ expect(sent.get("fileInput")).toBe(original);
+ expect(sent.get("accountId")).toBe("33");
+ });
+});
diff --git a/frontend/src/editor/desktop/services/tauriHttpClient.ts b/frontend/src/editor/desktop/services/tauriHttpClient.ts
index e594d26274..69d9528fde 100644
--- a/frontend/src/editor/desktop/services/tauriHttpClient.ts
+++ b/frontend/src/editor/desktop/services/tauriHttpClient.ts
@@ -1,6 +1,7 @@
/* oxlint-disable typescript/no-explicit-any -- Axios-compatible API requires matching axios's `any` signatures */
import { fetch } from "@tauri-apps/plugin-http";
import { enforceDocumentPrivacy } from "@editor/services/documentPrivacyService";
+import { uploadSafeFormData } from "@editor/utils/inMemoryUpload";
import {
shouldUseFastLocalTransport,
fetchViaLocalProxy,
@@ -227,8 +228,7 @@ class TauriHttpClient {
if (finalConfig.data) {
if (finalConfig.data instanceof FormData) {
- // FormData can be passed directly
- body = finalConfig.data;
+ body = await uploadSafeFormData(finalConfig.data);
// Drop any caller-supplied Content-Type so the native fetch generates
// multipart/form-data WITH its boundary (matches axios's FormData
// handling). A boundary-less "multipart/form-data" header makes the
diff --git a/frontend/src/editor/proprietary/components/shared/config/configNavSections.tsx b/frontend/src/editor/proprietary/components/shared/config/configNavSections.tsx
index 57799774c0..f82aa673af 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configNavSections.tsx
+++ b/frontend/src/editor/proprietary/components/shared/config/configNavSections.tsx
@@ -101,7 +101,7 @@ export const useConfigNavSections = (
label: t("settings.connectedAccounts.title", "Connected accounts"),
description: t(
"settings.connectedAccounts.description",
- "Your own OneDrive, SharePoint and Google Drive, for your pipelines.",
+ "Your own OneDrive, SharePoint and Google Drive, for opening files and for your pipelines.",
),
icon: "cloud",
component: <ConnectedAccountsSection />,
diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.test.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.test.ts
index 0228207d04..d8f1ca10d6 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.test.ts
+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.test.ts
@@ -67,3 +67,27 @@ describe("SSO auto-login security setting", () => {
});
});
});
+
+describe("Microsoft editor saves", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it.each([true, false])(
+ "loads %s from the server and saves it back unchanged",
+ async (allowEditorSaves) => {
+ vi.mocked(apiClient.get).mockImplementation(async (url) => ({
+ data: url.endsWith("/premium")
+ ? { proFeatures: { microsoft: { allowEditorSaves } } }
+ : {},
+ }));
+
+ const settings = await fetchConnectionsSettings();
+
+ expect(settings.microsoft?.allowEditorSaves).toBe(allowEditorSaves);
+ expect(
+ saveConnectionsSettings(settings).deltaSettings[
+ "premium.proFeatures.microsoft.allowEditorSaves"
+ ],
+ ).toBe(allowEditorSaves);
+ },
+ );
+});
diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts
index 34a883bb9c..af08fa69d1 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts
+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts
@@ -193,6 +193,8 @@ export async function fetchConnectionsSettings(): Promise<
clientSecret: premiumData.proFeatures?.microsoft?.clientSecret || "",
allowAccountConnections:
premiumData.proFeatures?.microsoft?.allowAccountConnections !== false,
+ allowEditorSaves:
+ premiumData.proFeatures?.microsoft?.allowEditorSaves !== false,
},
};
diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts
index 8c958a2af7..8e65e74fce 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts
+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts
@@ -112,6 +112,7 @@ export interface MicrosoftSettings {
tenant?: string;
clientSecret?: string;
allowAccountConnections?: boolean;
+ allowEditorSaves?: boolean;
}
export interface OAuth2GenericSettings {
diff --git a/frontend/src/msalRedirect.ts b/frontend/src/msalRedirect.ts
new file mode 100644
index 0000000000..e91a50be91
--- /dev/null
+++ b/frontend/src/msalRedirect.ts
@@ -0,0 +1,3 @@
+import { broadcastResponseToMainFrame } from "@azure/msal-browser/redirect-bridge";
+
+void broadcastResponseToMainFrame();
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index e8171268b8..32b8b1feba 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -703,6 +703,10 @@ export default defineConfig(async ({ mode, command }) => {
// Minifies better than esbuild for this esnext target.
cssMinify: "lightningcss" as const,
rollupOptions: {
+ input: {
+ index: path.resolve(__dirname, "index.html"),
+ "msal-redirect": path.resolve(__dirname, "msal-redirect.html"),
+ },
output: {
assetFileNames: mjsToJsAssetFileNames,
manualChunks(id: string, meta: ManualChunkMeta) {