Skip to content

Commit 40770c1

Browse files
fix(web): correct bounded Office preview loading
1 parent ba76144 commit 40770c1

7 files changed

Lines changed: 394 additions & 41 deletions

File tree

‎apps/server/src/assets/AssetAccess.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -717,6 +717,40 @@ describe("AssetAccess", () => {
717717
}).pipe(Effect.provide(layerTest)),
718718
);
719719

720+
it.effect("keeps Office files out of directory-scoped browser-document grants", () =>
721+
Effect.gen(function* () {
722+
const fs = yield* FileSystem.FileSystem;
723+
const path = yield* Path.Path;
724+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-office-browser-grant-" });
725+
yield* fs.makeDirectory(path.join(root, "nested"));
726+
yield* fs.writeFileString(path.join(root, "style.css"), "body { color: red; }");
727+
for (const name of ["private.xlsx", "private.xls", "private.pptx", "nested/private.XLSX"]) {
728+
yield* fs.writeFileString(path.join(root, name), "Office file bytes");
729+
}
730+
for (const name of ["report.html", "report.pdf"]) {
731+
yield* fs.writeFileString(path.join(root, name), "browser document bytes");
732+
for (const resource of [
733+
{ _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: name },
734+
{ _tag: "draft-workspace-file" as const, cwd: root, path: name },
735+
]) {
736+
const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
737+
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
738+
const token = suffix.slice(0, suffix.indexOf("/"));
739+
expect(yield* resolveAsset(token, name)).toMatchObject({ kind: "file" });
740+
expect(yield* resolveAsset(token, "style.css")).toMatchObject({ kind: "file" });
741+
for (const sibling of [
742+
"private.xlsx",
743+
"private.xls",
744+
"private.pptx",
745+
"nested/private.XLSX",
746+
]) {
747+
expect(yield* resolveAsset(token, sibling)).toBeNull();
748+
}
749+
}
750+
}
751+
}).pipe(Effect.provide(layerTest)),
752+
);
753+
720754
it.effect("rejects workspace files outside the authorized root", () =>
721755
Effect.gen(function* () {
722756
const fileSystem = yield* FileSystem.FileSystem;

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,6 @@ const inlinePreviewMimeTypeForExtension = (extension: string) =>
9393
const PREVIEW_ASSET_EXTENSIONS = new Set([
9494
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
9595
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
96-
".xlsx",
97-
".xls",
98-
".pptx",
9996
".css",
10097
".js",
10198
".mjs",

‎apps/web/src/components/files/OfficeDocumentPreview.tsx‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,10 @@ function DocumentContents({ document }: { readonly document: OfficeDocument }) {
7777
)
7878
) : slide ? (
7979
<div
80-
className="relative w-full overflow-hidden border shadow-sm"
80+
className="@container relative w-full overflow-hidden border text-black shadow-sm"
8181
style={{
8282
aspectRatio: `${slide.width} / ${slide.height}`,
83-
containerType: "inline-size",
8483
backgroundColor: slide.background ?? "#ffffff",
85-
color: "#000000",
8684
}}
8785
>
8886
{layers?.map(({ element, layer }) => {

‎apps/web/src/components/files/OfficePreview.integration.test.tsx‎

Lines changed: 226 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,6 @@ vi.mock("~/assets/assetUrls", () => ({
2424
useAssetUrlRefresh: () => mocks.refresh,
2525
useAssetUrlState: () => ({ _tag: "Success", url: mocks.url }),
2626
}));
27-
vi.mock("~/hooks/useWorkspaceMutationRefresh", () => ({
28-
useWorkspaceMutationRefresh: () => undefined,
29-
}));
3027
vi.mock("~/hooks/useCopyToClipboard", () => ({
3128
useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), isCopied: false }),
3229
}));
@@ -51,16 +48,26 @@ vi.mock("./fileSurfaceChrome", () => ({
5148
FileSurfaceAction: ({ label, onPress }: { label: string; onPress: () => void }) => (
5249
<button aria-label={label} onClick={onPress} />
5350
),
54-
FileSurfaceFailure: ({ message }: { message: string }) => <div role="alert">{message}</div>,
51+
FileSurfaceFailure: ({ message, onRetry }: { message: string; onRetry?: () => void }) => (
52+
<div role="alert">
53+
{message}
54+
{onRetry ? <button onClick={onRetry}>Try again</button> : null}
55+
</div>
56+
),
5557
FileSurfaceLoading: () => <div role="status">Loading</div>,
5658
FileSurfaceNotice: ({ children }: { children: ReactNode }) => <div>{children}</div>,
5759
}));
5860

5961
/** Only the browser worker transport is replaced: its request is parsed by the real decoder. */
6062
class ParserWorker extends EventTarget {
63+
static instances: ParserWorker[] = [];
6164
static posted: ((worker: ParserWorker) => void) | undefined;
6265
request: OfficeWorkerRequest | undefined;
6366
terminate = vi.fn();
67+
constructor() {
68+
super();
69+
ParserWorker.instances.push(this);
70+
}
6471
postMessage(request: OfficeWorkerRequest) {
6572
this.request = request;
6673
ParserWorker.posted?.(this);
@@ -75,6 +82,9 @@ class ParserWorker extends EventTarget {
7582
}),
7683
);
7784
}
85+
fail() {
86+
this.dispatchEvent(new Event("error"));
87+
}
7888
}
7989

8090
function workbookBytes(bookType: "xlsx" | "biff8" = "xlsx", value = "ねこ / real workbook") {
@@ -111,6 +121,7 @@ beforeEach(() => {
111121
mocks.url = "https://environment.test/api/assets/signed/book.xlsx";
112122
mocks.refresh.mockReset().mockImplementation(async () => mocks.url);
113123
ParserWorker.posted = undefined;
124+
ParserWorker.instances = [];
114125
vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:office-local");
115126
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => undefined);
116127
vi.stubGlobal(
@@ -126,20 +137,229 @@ afterEach(async () => {
126137
vi.unstubAllGlobals();
127138
});
128139

129-
const workspace = (name = "/workspace/book.xlsx", reloadRevision = 0) => (
140+
const workspace = (
141+
name = "/workspace/book.xlsx",
142+
reloadRevision = 0,
143+
workspaceMutationId: string | null = null,
144+
) => (
130145
<WorkspaceOfficePreview
131146
environmentId={environmentId}
132147
threadRef={threadRef}
133148
draft={false}
134149
absolutePath={name}
135150
workspaceRoot="/workspace"
136151
format="xlsx"
137-
workspaceMutationId={null}
152+
workspaceMutationId={workspaceMutationId}
138153
reloadRevision={reloadRevision}
139154
/>
140155
);
141156

157+
function pendingAuthorization() {
158+
let complete: ((url: string | null) => void) | undefined;
159+
const promise = new Promise<string | null>((resolve) => {
160+
complete = resolve;
161+
});
162+
mocks.refresh.mockReturnValueOnce(promise);
163+
return { promise, complete: (url: string | null) => complete?.(url) };
164+
}
165+
142166
describe("Office entry points with the real document client and parser", () => {
167+
it("waits for reauthorization before starting one download per open for a cached completed mutation", async () => {
168+
const firstAuthorization = pendingAuthorization();
169+
const firstPosted = nextWorker();
170+
await act(() => root.render(workspace("/workspace/book.xlsx", 0, "mutation-a")));
171+
expect(mocks.refresh).toHaveBeenCalledOnce();
172+
expect(fetch).not.toHaveBeenCalled();
173+
expect(ParserWorker.instances).toHaveLength(0);
174+
await act(async () => {
175+
firstAuthorization.complete("https://environment.test/authorized-first.xlsx");
176+
await firstAuthorization.promise;
177+
});
178+
const first = await firstPosted;
179+
await act(() => first.finish());
180+
await act(() => root.render(null));
181+
const secondAuthorization = pendingAuthorization();
182+
const secondPosted = nextWorker();
183+
await act(() => root.render(workspace("/workspace/book.xlsx", 0, "mutation-a")));
184+
expect(mocks.refresh).toHaveBeenCalledTimes(2);
185+
expect(fetch).toHaveBeenCalledOnce();
186+
expect(ParserWorker.instances).toHaveLength(1);
187+
await act(async () => {
188+
secondAuthorization.complete("https://environment.test/authorized-second.xlsx");
189+
await secondAuthorization.promise;
190+
});
191+
const second = await secondPosted;
192+
await act(() => second.finish());
193+
expect(fetch).toHaveBeenCalledTimes(2);
194+
expect(vi.mocked(fetch).mock.calls.map(([url]) => String(url))).toEqual([
195+
"https://environment.test/authorized-first.xlsx?workspace-revision=mutation-a%3A0",
196+
"https://environment.test/authorized-second.xlsx?workspace-revision=mutation-a%3A0",
197+
]);
198+
expect(first.terminate).toHaveBeenCalledOnce();
199+
expect(second.terminate).toHaveBeenCalledOnce();
200+
expect(container.querySelector("tbody")?.textContent).toContain("ねこ / real workbook");
201+
});
202+
203+
it("gates new workspace mutations and manual reloads until each authorization completes", async () => {
204+
const initialPosted = nextWorker();
205+
await act(() => root.render(workspace()));
206+
await act(async () => {
207+
(await initialPosted).finish();
208+
});
209+
const mutationAuthorization = pendingAuthorization();
210+
const changedPosted = nextWorker();
211+
await act(() => root.render(workspace("/workspace/book.xlsx", 0, "mutation-new")));
212+
expect(fetch).toHaveBeenCalledOnce();
213+
expect(ParserWorker.instances).toHaveLength(1);
214+
expect(container.querySelector("table")).toBeNull();
215+
vi.mocked(fetch).mockImplementation(
216+
async () => new Response(workbookBytes("xlsx", "mutation value")),
217+
);
218+
await act(async () => {
219+
mutationAuthorization.complete(mocks.url);
220+
await mutationAuthorization.promise;
221+
});
222+
await act(async () => {
223+
(await changedPosted).finish();
224+
});
225+
expect(container.querySelector("tbody")?.textContent).toContain("mutation value");
226+
const manualAuthorization = pendingAuthorization();
227+
const manualPosted = nextWorker();
228+
await act(() => root.render(workspace("/workspace/book.xlsx", 1, "mutation-new")));
229+
expect(fetch).toHaveBeenCalledTimes(2);
230+
expect(ParserWorker.instances).toHaveLength(2);
231+
vi.mocked(fetch).mockImplementation(
232+
async () => new Response(workbookBytes("xlsx", "manual value")),
233+
);
234+
await act(async () => {
235+
manualAuthorization.complete(mocks.url);
236+
await manualAuthorization.promise;
237+
});
238+
await act(async () => {
239+
(await manualPosted).finish();
240+
});
241+
expect(container.querySelector("tbody")?.textContent).toContain("manual value");
242+
expect(mocks.refresh).toHaveBeenCalledTimes(2);
243+
expect(fetch).toHaveBeenCalledTimes(3);
244+
expect(ParserWorker.instances).toHaveLength(3);
245+
});
246+
247+
it("reauthorizes a failed preview before retrying its reader", async () => {
248+
const initialPosted = nextWorker();
249+
await act(() => root.render(workspace()));
250+
const first = await initialPosted;
251+
await act(() => first.fail());
252+
expect(container.querySelector('[role="alert"]')).not.toBeNull();
253+
const retryAuthorization = pendingAuthorization();
254+
const retryPosted = nextWorker();
255+
await act(() => container.querySelector<HTMLButtonElement>('[role="alert"] button')!.click());
256+
expect(mocks.refresh).toHaveBeenCalledOnce();
257+
expect(fetch).toHaveBeenCalledOnce();
258+
expect(ParserWorker.instances).toHaveLength(1);
259+
await act(async () => {
260+
retryAuthorization.complete("https://environment.test/renewed.xlsx");
261+
await retryAuthorization.promise;
262+
});
263+
await act(async () => {
264+
(await retryPosted).finish();
265+
});
266+
expect(vi.mocked(fetch).mock.calls.map(([url]) => String(url))).toEqual([
267+
mocks.url,
268+
"https://environment.test/renewed.xlsx",
269+
]);
270+
expect(ParserWorker.instances).toHaveLength(2);
271+
expect(container.querySelector("tbody")?.textContent).toContain("ねこ / real workbook");
272+
});
273+
274+
it("ignores an older resource authorization that resolves after the current preview", async () => {
275+
const oldAuthorization = pendingAuthorization();
276+
await act(() => root.render(workspace("/workspace/old.xlsx", 0, "mutation-a")));
277+
const currentAuthorization = pendingAuthorization();
278+
const posted = nextWorker();
279+
await act(() => root.render(workspace("/workspace/current.xlsx", 0, "mutation-a")));
280+
await act(async () => {
281+
currentAuthorization.complete("https://environment.test/current.xlsx");
282+
await currentAuthorization.promise;
283+
});
284+
await act(async () => {
285+
(await posted).finish();
286+
});
287+
await act(async () => {
288+
oldAuthorization.complete("https://environment.test/old.xlsx");
289+
await oldAuthorization.promise;
290+
});
291+
expect(fetch).toHaveBeenCalledExactlyOnceWith(
292+
"https://environment.test/current.xlsx?workspace-revision=mutation-a%3A0",
293+
{ signal: expect.any(AbortSignal) },
294+
);
295+
expect(ParserWorker.instances).toHaveLength(1);
296+
expect(container.querySelector("tbody")?.textContent).toContain("ねこ / real workbook");
297+
});
298+
299+
it("waits for a new authorization when returning to a previously authorized resource", async () => {
300+
const firstPosted = nextWorker();
301+
await act(() => root.render(workspace("/workspace/a.xlsx", 0, "mutation-a")));
302+
const first = await firstPosted;
303+
await act(() => first.finish());
304+
const otherAuthorization = pendingAuthorization();
305+
await act(() => root.render(workspace("/workspace/b.xlsx", 0, "mutation-a")));
306+
const returnAuthorization = pendingAuthorization();
307+
const returnedPosted = nextWorker();
308+
await act(() => root.render(workspace("/workspace/a.xlsx", 0, "mutation-a")));
309+
expect(fetch).toHaveBeenCalledOnce();
310+
expect(ParserWorker.instances).toHaveLength(1);
311+
expect(container.querySelector("table")).toBeNull();
312+
await act(async () => {
313+
otherAuthorization.complete("https://environment.test/stale-b.xlsx");
314+
await otherAuthorization.promise;
315+
});
316+
expect(fetch).toHaveBeenCalledOnce();
317+
await act(async () => {
318+
returnAuthorization.complete("https://environment.test/returned-a.xlsx");
319+
await returnAuthorization.promise;
320+
});
321+
const returned = await returnedPosted;
322+
await act(() => returned.finish());
323+
expect(fetch).toHaveBeenCalledTimes(2);
324+
expect(ParserWorker.instances).toHaveLength(2);
325+
expect(vi.mocked(fetch).mock.calls[1]?.[0]).toBe(
326+
"https://environment.test/returned-a.xlsx?workspace-revision=mutation-a%3A0",
327+
);
328+
expect(container.querySelector("tbody")?.textContent).toContain("ねこ / real workbook");
329+
});
330+
331+
it("recovers from authorization failure and ignores an authorization completed after closing", async () => {
332+
const failedAuthorization = pendingAuthorization();
333+
await act(() => root.render(workspace("/workspace/book.xlsx", 0, "mutation-a")));
334+
await act(async () => {
335+
failedAuthorization.complete(null);
336+
await failedAuthorization.promise;
337+
});
338+
expect(container.querySelector('[role="alert"]')).not.toBeNull();
339+
expect(fetch).not.toHaveBeenCalled();
340+
const retryAuthorization = pendingAuthorization();
341+
const retryPosted = nextWorker();
342+
await act(() => container.querySelector<HTMLButtonElement>('[role="alert"] button')!.click());
343+
expect(fetch).not.toHaveBeenCalled();
344+
await act(async () => {
345+
retryAuthorization.complete("https://environment.test/recovered.xlsx");
346+
await retryAuthorization.promise;
347+
});
348+
const retry = await retryPosted;
349+
await act(() => retry.finish());
350+
expect(container.querySelector("tbody")?.textContent).toContain("ねこ / real workbook");
351+
const closingAuthorization = pendingAuthorization();
352+
await act(() => root.render(workspace("/workspace/book.xlsx", 1, "mutation-a")));
353+
await act(() => root.render(null));
354+
await act(async () => {
355+
closingAuthorization.complete("https://environment.test/closed.xlsx");
356+
await closingAuthorization.promise;
357+
});
358+
expect(fetch).toHaveBeenCalledOnce();
359+
expect(ParserWorker.instances).toHaveLength(1);
360+
expect(container.textContent).toBe("");
361+
});
362+
143363
it("reloads changed bytes on a manual revision even when the signed URL is unchanged", async () => {
144364
const firstPosted = nextWorker();
145365
await act(() => root.render(workspace()));

0 commit comments

Comments
 (0)