@bevel-software/platform-core-frontend 0.11.2 → 0.12.1
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.
- package/THIRD-PARTY-NOTICES.md +670 -395
- package/package.json +6 -2
- package/src/lib/__tests__/api.test.ts +95 -0
- package/src/lib/api.ts +30 -2
- package/src/lib/clipboard.ts +25 -0
- package/src/modules/access/__tests__/useFileAccess.test.tsx +47 -0
- package/src/modules/access/hooks/useFileAccess.ts +23 -5
- package/src/modules/git/__tests__/GitSyncFailedBanner.test.tsx +181 -0
- package/src/modules/git/components/GitSyncFailedBanner.tsx +106 -0
- package/src/modules/library/utils/clipboard.ts +4 -20
- package/src/modules/secrets-vault/components/SecretsPage.tsx +313 -313
- package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +82 -82
- package/src/modules/workspace/components/FileExplorer.tsx +6 -14
- package/src/modules/workspace/components/FileViewer.tsx +20 -4
- package/src/modules/workspace/components/KbPageHeader.tsx +1 -1
- package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +3 -1
- package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +17 -0
- package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +15 -0
- package/src/modules/workspace/components/renderers/DocxRenderer.tsx +11 -2
- package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +88 -0
- package/src/modules/workspace/components/renderers/EmailRenderer.tsx +309 -0
- package/src/modules/workspace/components/renderers/LegacyOfficeRenderer.tsx +60 -0
- package/src/modules/workspace/components/renderers/PdfRenderer.tsx +261 -33
- package/src/modules/workspace/components/renderers/PptxRenderer.tsx +184 -0
- package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +195 -45
- package/src/modules/workspace/components/renderers/__tests__/DownloadFileButton.test.tsx +48 -0
- package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.test.tsx +176 -0
- package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +214 -76
- package/src/modules/workspace/components/renderers/__tests__/PptxRenderer.test.tsx +125 -0
- package/src/modules/workspace/components/renderers/__tests__/XlsxRenderer.test.tsx +245 -0
- package/src/modules/workspace/components/renderers/__tests__/emailBody.test.ts +117 -0
- package/src/modules/workspace/components/renderers/__tests__/emailMessage.test.ts +404 -0
- package/src/modules/workspace/components/renderers/__tests__/pptxOutline.test.ts +448 -0
- package/src/modules/workspace/components/renderers/__tests__/readBodyCapped.test.ts +117 -0
- package/src/modules/workspace/components/renderers/__tests__/rendererLayout.test.ts +73 -7
- package/src/modules/workspace/components/renderers/__tests__/rendererSelection.test.tsx +107 -0
- package/src/modules/workspace/components/renderers/downloadFile.ts +33 -0
- package/src/modules/workspace/components/renderers/emailBody.ts +168 -0
- package/src/modules/workspace/components/renderers/emailMessage.ts +223 -0
- package/src/modules/workspace/components/renderers/emlMessage.ts +91 -0
- package/src/modules/workspace/components/renderers/htmlSandbox.ts +9 -2
- package/src/modules/workspace/components/renderers/index.ts +82 -6
- package/src/modules/workspace/components/renderers/lazyRenderer.tsx +9 -2
- package/src/modules/workspace/components/renderers/msgMessage.ts +219 -0
- package/src/modules/workspace/components/renderers/pptxOutline.ts +317 -0
- package/src/modules/workspace/components/renderers/readBodyCapped.ts +97 -0
- package/src/modules/workspace/components/renderers/xmlReading.ts +0 -0
- package/src/url-suffix-imports.d.ts +12 -0
|
@@ -1,19 +1,91 @@
|
|
|
1
|
-
import { useEffect, useState } from 'react';
|
|
1
|
+
import { useEffect, useMemo, useState } from 'react';
|
|
2
2
|
import * as XLSX from 'xlsx';
|
|
3
3
|
import { useWorkspace } from '../../state/workspace.context';
|
|
4
4
|
import { authFetch } from '../../../../lib/api';
|
|
5
|
+
import { DownloadFileButton } from './DownloadFileButton';
|
|
6
|
+
import { readBodyCapped } from './readBodyCapped';
|
|
5
7
|
import type { FileRendererProps } from './types';
|
|
6
8
|
|
|
9
|
+
/**
|
|
10
|
+
* Where the grid stops. A KB spreadsheet is read for orientation — what the
|
|
11
|
+
* columns are, roughly what is in them — and a million-row export rendered as
|
|
12
|
+
* a million `<td>`s locks the tab long before it answers either question. The
|
|
13
|
+
* caps keep the DOM bounded; the note under the grid says exactly what was
|
|
14
|
+
* cut, and the Download affordance is the path to the whole sheet.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* The largest workbook this viewer will parse. SheetJS has no streaming or
|
|
18
|
+
* metadata-only mode: `read` materializes every cell of every sheet, so a dense
|
|
19
|
+
* file freezes the main thread long before the row and column caps below get a
|
|
20
|
+
* chance to bound the VIEW.
|
|
21
|
+
*/
|
|
22
|
+
const MAX_WORKBOOK_BYTES = 25 * 1024 * 1024; // 25 MB
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The largest DECLARED uncompressed total this viewer will inflate. The
|
|
26
|
+
* transfer cap above cannot rule out a ZIP bomb: an .xlsx is a ZIP, and a
|
|
27
|
+
* file well under 25 MB on the wire can declare gigabytes of XML that
|
|
28
|
+
* `XLSX.read` would materialize in full before any row or column cap runs.
|
|
29
|
+
*/
|
|
30
|
+
const MAX_UNCOMPRESSED_BYTES = 100 * 1024 * 1024; // 100 MB
|
|
31
|
+
|
|
32
|
+
const MAX_ROWS = 1000;
|
|
33
|
+
const MAX_COLS = 100;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Sum of the uncompressed entry sizes a ZIP archive declares in its central
|
|
37
|
+
* directory — or `null` when the bytes are not a readable ZIP, so a renamed
|
|
38
|
+
* or truncated file falls through to `XLSX.read`'s own parse error instead
|
|
39
|
+
* of a misleading "too large" message. A ZIP64 entry (size field saturated
|
|
40
|
+
* at 0xffffffff) reports Infinity: its real size is over any cap here.
|
|
41
|
+
*/
|
|
42
|
+
function zipDeclaredSize(buffer: ArrayBuffer): number | null {
|
|
43
|
+
const view = new DataView(buffer);
|
|
44
|
+
// End-of-central-directory record: 22 bytes at the tail, preceded by at
|
|
45
|
+
// most 64 KB of archive comment. Scan back for its signature.
|
|
46
|
+
const stop = Math.max(0, buffer.byteLength - 22 - 0xffff);
|
|
47
|
+
let eocd = -1;
|
|
48
|
+
for (let i = buffer.byteLength - 22; i >= stop; i--) {
|
|
49
|
+
if (view.getUint32(i, true) !== 0x06054b50) continue;
|
|
50
|
+
// The signature is four ordinary bytes and may appear INSIDE the archive
|
|
51
|
+
// comment. The real record is the one whose declared comment length ends
|
|
52
|
+
// exactly at the file's end — a planted one almost never does, and a
|
|
53
|
+
// fake directory would otherwise be parsed and the size guard skipped.
|
|
54
|
+
if (i + 22 + view.getUint16(i + 20, true) !== buffer.byteLength) continue;
|
|
55
|
+
eocd = i;
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
if (eocd < 0) return null;
|
|
59
|
+
const entryCount = view.getUint16(eocd + 10, true);
|
|
60
|
+
let offset = view.getUint32(eocd + 16, true);
|
|
61
|
+
let total = 0;
|
|
62
|
+
for (let n = 0; n < entryCount; n++) {
|
|
63
|
+
if (offset + 46 > buffer.byteLength || view.getUint32(offset, true) !== 0x02014b50) return null;
|
|
64
|
+
const size = view.getUint32(offset + 24, true);
|
|
65
|
+
if (size === 0xffffffff) return Number.POSITIVE_INFINITY;
|
|
66
|
+
total += size;
|
|
67
|
+
// Fixed header + file name + extra field + comment.
|
|
68
|
+
offset +=
|
|
69
|
+
46 +
|
|
70
|
+
view.getUint16(offset + 28, true) +
|
|
71
|
+
view.getUint16(offset + 30, true) +
|
|
72
|
+
view.getUint16(offset + 32, true);
|
|
73
|
+
}
|
|
74
|
+
return total;
|
|
75
|
+
}
|
|
76
|
+
|
|
7
77
|
interface SheetView {
|
|
8
78
|
name: string;
|
|
9
79
|
rows: string[][];
|
|
80
|
+
/** Real dimensions before the caps — what the truncation note reports. */
|
|
81
|
+
totalRows: number;
|
|
82
|
+
totalCols: number;
|
|
10
83
|
}
|
|
11
84
|
|
|
12
85
|
/**
|
|
13
86
|
* Inline .xlsx viewer. Fetches the binary from `/api/workspace/:id/file/raw`,
|
|
14
87
|
* parses it with SheetJS, and renders each sheet as an HTML table with a
|
|
15
|
-
* tab strip across the top. Multi-sheet workbooks show one tab per sheet
|
|
16
|
-
* single-sheet workbooks hide the tab strip.
|
|
88
|
+
* tab strip across the top. Multi-sheet workbooks show one tab per sheet.
|
|
17
89
|
*
|
|
18
90
|
* View-only: there is no edit mode for binary office formats. The renderer
|
|
19
91
|
* ignores `onSave` / `onValueChange` / `readOnly`.
|
|
@@ -24,46 +96,64 @@ interface SheetView {
|
|
|
24
96
|
*/
|
|
25
97
|
export function XlsxRenderer({ filePath }: FileRendererProps) {
|
|
26
98
|
const { workspaceId } = useWorkspace();
|
|
27
|
-
const [
|
|
99
|
+
const [workbook, setWorkbook] = useState<XLSX.WorkBook | null>(null);
|
|
28
100
|
const [activeSheet, setActiveSheet] = useState(0);
|
|
29
101
|
const [error, setError] = useState<string | null>(null);
|
|
30
102
|
|
|
31
103
|
useEffect(() => {
|
|
32
|
-
|
|
104
|
+
setWorkbook(null);
|
|
33
105
|
setActiveSheet(0);
|
|
34
106
|
setError(null);
|
|
35
107
|
if (!workspaceId) return;
|
|
36
108
|
|
|
37
109
|
let cancelled = false;
|
|
110
|
+
// Cleanup ABORTS, not just flags: flipping `cancelled` alone left an
|
|
111
|
+
// abandoned viewer downloading and buffering the whole workbook.
|
|
112
|
+
const controller = new AbortController();
|
|
38
113
|
(async () => {
|
|
39
114
|
try {
|
|
40
115
|
const res = await authFetch(
|
|
41
116
|
`/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(filePath)}`,
|
|
117
|
+
{ signal: controller.signal },
|
|
42
118
|
);
|
|
43
119
|
if (cancelled) return;
|
|
44
120
|
if (!res.ok) {
|
|
45
121
|
setError(`Failed to load spreadsheet (HTTP ${res.status})`);
|
|
46
122
|
return;
|
|
47
123
|
}
|
|
48
|
-
|
|
124
|
+
// SheetJS parses EVERY cell of every sheet before this component can
|
|
125
|
+
// apply its row and column caps, so those caps bound what is DISPLAYED,
|
|
126
|
+
// never what is parsed. The byte bound is what keeps a dense workbook
|
|
127
|
+
// from freezing the tab, and it has to come before the buffer:
|
|
128
|
+
// `readBodyCapped` refuses an over-cap Content-Length without reading a
|
|
129
|
+
// byte (and aborts the request, so an oversized workbook stops arriving
|
|
130
|
+
// instead of streaming on behind the error) and abandons an undeclared
|
|
131
|
+
// or understated body the moment it crosses the cap.
|
|
132
|
+
const buffer = await readBodyCapped(res, MAX_WORKBOOK_BYTES, controller);
|
|
49
133
|
if (cancelled) return;
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
134
|
+
if (buffer === null) {
|
|
135
|
+
setError('This spreadsheet is too large to preview. Download it to open in a spreadsheet app.');
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
// The byte bounds above are TRANSFER sizes; a ZIP bomb sails under
|
|
139
|
+
// both. Reject on the uncompressed total the archive itself declares,
|
|
140
|
+
// before `XLSX.read` inflates any of it. (Non-ZIP bytes fall through
|
|
141
|
+
// to the parse error below, where they belong.)
|
|
142
|
+
const declaredInflated = zipDeclaredSize(buffer);
|
|
143
|
+
if (declaredInflated !== null && declaredInflated > MAX_UNCOMPRESSED_BYTES) {
|
|
144
|
+
setError('This spreadsheet is too large to preview. Download it to open in a spreadsheet app.');
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
let parsed: XLSX.WorkBook;
|
|
148
|
+
try {
|
|
149
|
+
parsed = XLSX.read(new Uint8Array(buffer), { type: 'array' });
|
|
150
|
+
} catch (parseErr) {
|
|
151
|
+
console.warn('[XlsxRenderer] parse failed:', parseErr);
|
|
152
|
+
if (!cancelled) setError('This file could not be parsed as a spreadsheet.');
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
65
155
|
if (cancelled) return;
|
|
66
|
-
|
|
156
|
+
setWorkbook(parsed);
|
|
67
157
|
} catch (e) {
|
|
68
158
|
if (cancelled) return;
|
|
69
159
|
setError(e instanceof Error ? e.message : String(e));
|
|
@@ -72,18 +162,61 @@ export function XlsxRenderer({ filePath }: FileRendererProps) {
|
|
|
72
162
|
|
|
73
163
|
return () => {
|
|
74
164
|
cancelled = true;
|
|
165
|
+
controller.abort();
|
|
75
166
|
};
|
|
76
167
|
}, [workspaceId, filePath]);
|
|
77
168
|
|
|
169
|
+
// Convert ONLY the sheet on screen, when it is on screen. `XLSX.read` has
|
|
170
|
+
// already materialized every cell (SheetJS has no partial parse), but
|
|
171
|
+
// stringifying up to MAX_ROWS × MAX_COLS cells per sheet for EVERY sheet up
|
|
172
|
+
// front would multiply that work by the sheet count before the first grid
|
|
173
|
+
// could paint. A tab revisit re-converts — work bounded by the caps.
|
|
174
|
+
const sheet = useMemo<SheetView | null>(() => {
|
|
175
|
+
if (!workbook || workbook.SheetNames.length === 0) return null;
|
|
176
|
+
const name = workbook.SheetNames[Math.min(activeSheet, workbook.SheetNames.length - 1)]!;
|
|
177
|
+
const ws = workbook.Sheets[name];
|
|
178
|
+
const ref = ws?.['!ref'];
|
|
179
|
+
if (!ws || !ref) return { name, rows: [], totalRows: 0, totalCols: 0 };
|
|
180
|
+
// Cap the conversion range BEFORE materializing anything:
|
|
181
|
+
// `sheet_to_json` walks every cell of the range it is given, so a
|
|
182
|
+
// sparse sheet whose declared range is `A1:XFD1048576` (one stray
|
|
183
|
+
// cell at the far corner) would materialize 16k × 1M cells and
|
|
184
|
+
// freeze the tab. The honest "N of M" totals for the truncation
|
|
185
|
+
// note come from the DECLARED `!ref` itself — no full parse needed.
|
|
186
|
+
const range = XLSX.utils.decode_range(ref);
|
|
187
|
+
const totalRows = range.e.r - range.s.r + 1;
|
|
188
|
+
const totalCols = range.e.c - range.s.c + 1;
|
|
189
|
+
const bounded = {
|
|
190
|
+
s: range.s,
|
|
191
|
+
e: {
|
|
192
|
+
r: Math.min(range.e.r, range.s.r + MAX_ROWS - 1),
|
|
193
|
+
c: Math.min(range.e.c, range.s.c + MAX_COLS - 1),
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
const rows = XLSX.utils.sheet_to_json(ws, {
|
|
197
|
+
header: 1,
|
|
198
|
+
raw: false,
|
|
199
|
+
defval: '',
|
|
200
|
+
range: XLSX.utils.encode_range(bounded),
|
|
201
|
+
}) as unknown[][];
|
|
202
|
+
return {
|
|
203
|
+
name,
|
|
204
|
+
totalRows,
|
|
205
|
+
totalCols,
|
|
206
|
+
rows: rows.map((row) => row.map((cell) => (cell == null ? '' : String(cell)))),
|
|
207
|
+
};
|
|
208
|
+
}, [workbook, activeSheet]);
|
|
209
|
+
|
|
78
210
|
if (error) {
|
|
79
211
|
return (
|
|
80
|
-
<div className="flex items-center justify-center
|
|
81
|
-
{error}
|
|
212
|
+
<div className="flex h-full flex-col items-center justify-center gap-3 text-center">
|
|
213
|
+
<p className="text-sm text-danger">{error}</p>
|
|
214
|
+
<DownloadFileButton filePath={filePath} />
|
|
82
215
|
</div>
|
|
83
216
|
);
|
|
84
217
|
}
|
|
85
218
|
|
|
86
|
-
if (
|
|
219
|
+
if (workbook === null) {
|
|
87
220
|
return (
|
|
88
221
|
<div className="flex items-center justify-center h-full text-ink-muted text-sm">
|
|
89
222
|
Loading spreadsheet...
|
|
@@ -91,7 +224,7 @@ export function XlsxRenderer({ filePath }: FileRendererProps) {
|
|
|
91
224
|
);
|
|
92
225
|
}
|
|
93
226
|
|
|
94
|
-
if (
|
|
227
|
+
if (sheet === null) {
|
|
95
228
|
return (
|
|
96
229
|
<div className="flex items-center justify-center h-full text-ink-muted text-sm">
|
|
97
230
|
The workbook has no sheets.
|
|
@@ -99,28 +232,32 @@ export function XlsxRenderer({ filePath }: FileRendererProps) {
|
|
|
99
232
|
);
|
|
100
233
|
}
|
|
101
234
|
|
|
102
|
-
const
|
|
235
|
+
const truncated = sheet.totalRows > MAX_ROWS || sheet.totalCols > MAX_COLS;
|
|
103
236
|
|
|
104
237
|
return (
|
|
105
238
|
<div className="flex flex-col h-full">
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
239
|
+
<div className="flex items-center gap-1 border-b border-line px-1 pb-1 shrink-0">
|
|
240
|
+
{workbook.SheetNames.length > 1 && (
|
|
241
|
+
<div className="flex min-w-0 items-center gap-1 overflow-x-auto">
|
|
242
|
+
{workbook.SheetNames.map((name, i) => (
|
|
243
|
+
<button
|
|
244
|
+
key={name}
|
|
245
|
+
type="button"
|
|
246
|
+
onClick={() => setActiveSheet(i)}
|
|
247
|
+
className={`px-2 py-1 rounded-xs text-xs font-medium whitespace-nowrap transition-colors ${
|
|
248
|
+
i === activeSheet
|
|
249
|
+
? 'bg-sunken text-ink'
|
|
250
|
+
: 'text-ink-muted hover:text-ink hover:bg-hover'
|
|
251
|
+
}`}
|
|
252
|
+
>
|
|
253
|
+
{name}
|
|
254
|
+
</button>
|
|
255
|
+
))}
|
|
256
|
+
</div>
|
|
257
|
+
)}
|
|
258
|
+
<span className="flex-1" />
|
|
259
|
+
<DownloadFileButton filePath={filePath} />
|
|
260
|
+
</div>
|
|
124
261
|
<div className="flex-1 overflow-auto">
|
|
125
262
|
{sheet.rows.length === 0 ? (
|
|
126
263
|
<div className="flex items-center justify-center h-full text-ink-muted text-sm">
|
|
@@ -152,6 +289,19 @@ export function XlsxRenderer({ filePath }: FileRendererProps) {
|
|
|
152
289
|
</table>
|
|
153
290
|
)}
|
|
154
291
|
</div>
|
|
292
|
+
{truncated && (
|
|
293
|
+
<div role="note" className="shrink-0 border-t border-line px-1 pt-1.5 text-detail text-ink-muted">
|
|
294
|
+
Truncated view: showing
|
|
295
|
+
{sheet.totalRows > MAX_ROWS
|
|
296
|
+
? ` the first ${MAX_ROWS.toLocaleString()} of ${sheet.totalRows.toLocaleString()} rows`
|
|
297
|
+
: ''}
|
|
298
|
+
{sheet.totalRows > MAX_ROWS && sheet.totalCols > MAX_COLS ? ' and' : ''}
|
|
299
|
+
{sheet.totalCols > MAX_COLS
|
|
300
|
+
? ` the first ${MAX_COLS.toLocaleString()} of ${sheet.totalCols.toLocaleString()} columns`
|
|
301
|
+
: ''}
|
|
302
|
+
. Download the file for the full sheet.
|
|
303
|
+
</div>
|
|
304
|
+
)}
|
|
155
305
|
</div>
|
|
156
306
|
);
|
|
157
307
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { render, screen } from '@testing-library/react';
|
|
3
|
+
|
|
4
|
+
const apiMock = vi.hoisted(() => ({ authFetch: vi.fn() }));
|
|
5
|
+
vi.mock('../../../../../lib/api', () => ({ authFetch: apiMock.authFetch }));
|
|
6
|
+
vi.mock('../../../state/workspace.context', async (importOriginal) => ({
|
|
7
|
+
...(await importOriginal<object>()),
|
|
8
|
+
useWorkspace: () => ({ workspaceId: 'ws-1', kbDirName: 'knowledge-base' }),
|
|
9
|
+
}));
|
|
10
|
+
|
|
11
|
+
import { CanDownloadContext, DownloadFileButton } from '../DownloadFileButton';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The button reflects the per-path `download:` verb the backend resolves —
|
|
15
|
+
* FileViewer provides the verdict through CanDownloadContext. The backend's
|
|
16
|
+
* raw endpoint stays the authoritative gate; this is about not offering a
|
|
17
|
+
* click that can only 403.
|
|
18
|
+
*/
|
|
19
|
+
describe('DownloadFileButton — download permission', () => {
|
|
20
|
+
const renderWith = (canDownload: boolean | null) =>
|
|
21
|
+
render(
|
|
22
|
+
<CanDownloadContext.Provider value={canDownload}>
|
|
23
|
+
<DownloadFileButton filePath="knowledge-base/Plugins/GTM/deck.pptx" />
|
|
24
|
+
</CanDownloadContext.Provider>,
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
it('is disabled with an explanation when the download verb says no', () => {
|
|
28
|
+
renderWith(false);
|
|
29
|
+
const button = screen.getByRole('button', { name: 'Download' });
|
|
30
|
+
expect(button).toBeDisabled();
|
|
31
|
+
expect(button).toHaveAttribute(
|
|
32
|
+
'title',
|
|
33
|
+
'You do not have download permission for this file.',
|
|
34
|
+
);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('stays clickable on an explicit yes', () => {
|
|
38
|
+
renderWith(true);
|
|
39
|
+
expect(screen.getByRole('button', { name: 'Download' })).toBeEnabled();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('stays optimistic while the verdict is unknown — the backend still gates', () => {
|
|
43
|
+
// null = lookup in flight (or rendered outside FileViewer). Mirrors the
|
|
44
|
+
// editor: no flicker into disabled while the answer loads.
|
|
45
|
+
renderWith(null);
|
|
46
|
+
expect(screen.getByRole('button', { name: 'Download' })).toBeEnabled();
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
import { render, screen } from '@testing-library/react';
|
|
3
|
+
import * as XLSX from 'xlsx';
|
|
4
|
+
import {
|
|
5
|
+
WorkspaceContext,
|
|
6
|
+
type WorkspaceContextValue,
|
|
7
|
+
} from '../../../state/workspace.context';
|
|
8
|
+
|
|
9
|
+
const apiMock = vi.hoisted(() => ({ authFetch: vi.fn() }));
|
|
10
|
+
vi.mock('../../../../../lib/api', () => ({ authFetch: apiMock.authFetch }));
|
|
11
|
+
|
|
12
|
+
import { EmailRenderer } from '../EmailRenderer';
|
|
13
|
+
import { MAX_EMAIL_BYTES } from '../emailMessage';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The viewer over real message bytes (hand-written MIME; a real CFB container
|
|
17
|
+
* for `.msg`): parsing is `emailMessage.test.ts`'s job; this proves the model
|
|
18
|
+
* reaches the screen in the promised shape — labelled header fields, the body
|
|
19
|
+
* as plain text (never HTML), attachments listed with the names-only note,
|
|
20
|
+
* the up-front honesty strip, and Download on the happy and the failed path.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const EML_BYTES = new TextEncoder().encode(
|
|
24
|
+
[
|
|
25
|
+
'From: Ada Lovelace <ada@example.com>',
|
|
26
|
+
'To: bob@example.com',
|
|
27
|
+
'Subject: Quarterly numbers',
|
|
28
|
+
'Date: Mon, 5 Jan 2026 10:00:00 +0000',
|
|
29
|
+
'MIME-Version: 1.0',
|
|
30
|
+
'Content-Type: multipart/mixed; boundary="b1"',
|
|
31
|
+
'',
|
|
32
|
+
'--b1',
|
|
33
|
+
'Content-Type: text/html; charset=utf-8',
|
|
34
|
+
'',
|
|
35
|
+
'<p>Please see <b>attached</b>.</p><script>alert(1)</script>',
|
|
36
|
+
'--b1',
|
|
37
|
+
'Content-Type: application/pdf; name="report.pdf"',
|
|
38
|
+
'Content-Disposition: attachment; filename="report.pdf"',
|
|
39
|
+
'Content-Transfer-Encoding: base64',
|
|
40
|
+
'',
|
|
41
|
+
'JVBERi0xLjQ=',
|
|
42
|
+
'--b1--',
|
|
43
|
+
'',
|
|
44
|
+
].join('\r\n'),
|
|
45
|
+
).buffer as ArrayBuffer;
|
|
46
|
+
|
|
47
|
+
interface CfbUtilsModule {
|
|
48
|
+
utils: { cfb_new(): unknown; cfb_add(cfb: unknown, path: string, bytes: Uint8Array): void };
|
|
49
|
+
write(cfb: unknown, opts: { type: 'array' }): Uint8Array | number[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function utf16(s: string): Uint8Array {
|
|
53
|
+
const out = new Uint8Array(s.length * 2);
|
|
54
|
+
for (let i = 0; i < s.length; i++) {
|
|
55
|
+
const c = s.charCodeAt(i);
|
|
56
|
+
out[i * 2] = c & 0xff;
|
|
57
|
+
out[i * 2 + 1] = c >> 8;
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A real (minimal) `.msg`: subject + plain body in a CFB container. */
|
|
63
|
+
function msgFixture(): ArrayBuffer {
|
|
64
|
+
const CFB = XLSX.CFB as unknown as CfbUtilsModule;
|
|
65
|
+
const cfb = CFB.utils.cfb_new();
|
|
66
|
+
CFB.utils.cfb_add(cfb, '/__substg1.0_0037001F', utf16('From Outlook'));
|
|
67
|
+
CFB.utils.cfb_add(cfb, '/__substg1.0_1000001F', utf16('Body from the item.'));
|
|
68
|
+
const written = CFB.write(cfb, { type: 'array' });
|
|
69
|
+
const u8 = written instanceof Uint8Array ? written : Uint8Array.from(written);
|
|
70
|
+
return u8.slice().buffer as ArrayBuffer;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function renderEmail(filePath: string) {
|
|
74
|
+
return render(
|
|
75
|
+
<WorkspaceContext.Provider
|
|
76
|
+
value={{ workspaceId: 'ws-1' } as unknown as WorkspaceContextValue}
|
|
77
|
+
>
|
|
78
|
+
<EmailRenderer filePath={filePath} content="" onSave={async () => {}} />
|
|
79
|
+
</WorkspaceContext.Provider>,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
beforeEach(() => {
|
|
84
|
+
apiMock.authFetch.mockReset();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
describe('EmailRenderer', () => {
|
|
88
|
+
it('renders a .eml: labelled headers, HTML body stripped to text, attachments with the names-only note', async () => {
|
|
89
|
+
apiMock.authFetch.mockResolvedValue({ ok: true, arrayBuffer: async () => EML_BYTES });
|
|
90
|
+
|
|
91
|
+
renderEmail('Inbox/offer.eml');
|
|
92
|
+
|
|
93
|
+
expect(await screen.findByText('Ada Lovelace <ada@example.com>')).toBeInTheDocument();
|
|
94
|
+
expect(screen.getByText('From')).toBeInTheDocument();
|
|
95
|
+
expect(screen.getByText('To')).toBeInTheDocument();
|
|
96
|
+
expect(screen.getByText('Subject')).toBeInTheDocument();
|
|
97
|
+
expect(screen.getByText('Quarterly numbers')).toBeInTheDocument();
|
|
98
|
+
expect(screen.getByText('2026-01-05T10:00:00.000Z')).toBeInTheDocument();
|
|
99
|
+
// CHANGED: a message carrying an HTML alternative now RENDERS it, the way a
|
|
100
|
+
// mail client does — in a frame that cannot run scripts or fetch anything.
|
|
101
|
+
const frame = screen.getByTitle('Message body') as HTMLIFrameElement;
|
|
102
|
+
expect(frame.getAttribute('sandbox')).toBe('');
|
|
103
|
+
expect(frame.srcdoc).toContain('Please see');
|
|
104
|
+
expect(frame.srcdoc).toContain("default-src 'none'");
|
|
105
|
+
expect(frame.srcdoc).toContain('img-src data:');
|
|
106
|
+
expect(document.querySelector('b')).toBeNull();
|
|
107
|
+
expect(document.querySelector('script')).toBeNull();
|
|
108
|
+
// Attachments: named, and honestly not downloadable one by one.
|
|
109
|
+
expect(screen.getByText('report.pdf (application/pdf, 8 bytes)')).toBeInTheDocument();
|
|
110
|
+
expect(screen.getByText(/listed by name only/)).toBeInTheDocument();
|
|
111
|
+
// The honest strip + the way to the real thing.
|
|
112
|
+
expect(screen.getByText(/shown without remote content/)).toBeInTheDocument();
|
|
113
|
+
expect(screen.getByRole('button', { name: /Download/ })).toBeInTheDocument();
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('renders a .msg (real CFB bytes) through the same view', async () => {
|
|
117
|
+
apiMock.authFetch.mockResolvedValue({ ok: true, arrayBuffer: async () => msgFixture() });
|
|
118
|
+
|
|
119
|
+
renderEmail('Inbox/thread.msg');
|
|
120
|
+
|
|
121
|
+
expect(await screen.findByText('From Outlook')).toBeInTheDocument();
|
|
122
|
+
expect(screen.getByText('Subject')).toBeInTheDocument();
|
|
123
|
+
expect(screen.getByText('Body from the item.')).toBeInTheDocument();
|
|
124
|
+
expect(screen.getByRole('button', { name: /Download/ })).toBeInTheDocument();
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('says the file could not be parsed as a .msg and still offers Download', async () => {
|
|
128
|
+
const bytes = new TextEncoder().encode('renamed file that is not a CFB').buffer as ArrayBuffer;
|
|
129
|
+
apiMock.authFetch.mockResolvedValue({ ok: true, arrayBuffer: async () => bytes });
|
|
130
|
+
|
|
131
|
+
renderEmail('Inbox/broken.msg');
|
|
132
|
+
|
|
133
|
+
expect(
|
|
134
|
+
await screen.findByText(/This file could not be parsed as a \.msg/),
|
|
135
|
+
).toBeInTheDocument();
|
|
136
|
+
expect(screen.getByRole('button', { name: /Download/ })).toBeInTheDocument();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('says the file could not be parsed as a .eml for headerless bytes', async () => {
|
|
140
|
+
const bytes = new Uint8Array([0xd0, 0xcf, 0x11, 0xe0, 0x01, 0xff, 0xfe]).buffer as ArrayBuffer;
|
|
141
|
+
apiMock.authFetch.mockResolvedValue({ ok: true, arrayBuffer: async () => bytes });
|
|
142
|
+
|
|
143
|
+
renderEmail('Inbox/broken.eml');
|
|
144
|
+
|
|
145
|
+
expect(
|
|
146
|
+
await screen.findByText(/This file could not be parsed as a \.eml \(no email headers found\)/),
|
|
147
|
+
).toBeInTheDocument();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('reports a transport failure as a load error', async () => {
|
|
151
|
+
apiMock.authFetch.mockResolvedValue({ ok: false, status: 403 });
|
|
152
|
+
|
|
153
|
+
renderEmail('Inbox/offer.eml');
|
|
154
|
+
|
|
155
|
+
expect(await screen.findByText(/Failed to load email \(HTTP 403\)/)).toBeInTheDocument();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('rejects an oversized declared Content-Length and ABORTS the transfer', async () => {
|
|
159
|
+
// Returning without aborting would leave the connection streaming a body
|
|
160
|
+
// nobody will read for as long as the view stays mounted.
|
|
161
|
+
let signal: AbortSignal | undefined;
|
|
162
|
+
apiMock.authFetch.mockImplementation(async (_url: string, init?: { signal?: AbortSignal }) => {
|
|
163
|
+
signal = init?.signal;
|
|
164
|
+
return {
|
|
165
|
+
ok: true,
|
|
166
|
+
headers: { get: (name: string) => (name === 'content-length' ? String(MAX_EMAIL_BYTES + 1) : null) },
|
|
167
|
+
arrayBuffer: async () => EML_BYTES,
|
|
168
|
+
};
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
renderEmail('Inbox/huge.eml');
|
|
172
|
+
|
|
173
|
+
expect(await screen.findByText('This email is too large to display.')).toBeInTheDocument();
|
|
174
|
+
expect(signal?.aborted).toBe(true);
|
|
175
|
+
});
|
|
176
|
+
});
|