@file-viewer/renderer-spreadsheet 3.3.5 → 3.3.7

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.
@@ -34,6 +34,8 @@ const BORDER_STYLE_PRIORITY = {
34
34
  const HEADER_FONT = `bold 12px ${TABLE_FONT_FAMILY}`;
35
35
  const BODY_FONT = `${TABLE_FONT_SIZE}px ${TABLE_FONT_FAMILY}`;
36
36
  const MAX_OVERFLOW_SCAN_COLS = 32;
37
+ const MIN_SCROLLABLE_PANE_WIDTH = 24;
38
+ const VERTICAL_SCROLLBAR_TRACK_WIDTH = 14;
37
39
  let measureCanvas;
38
40
  const textWidthCache = new Map();
39
41
  const normalizeZoomScale = (scale = 1) => {
@@ -270,9 +272,10 @@ export const detectIndexOffset = (ws, mode = 'source') => {
270
272
  return 1;
271
273
  };
272
274
  export const buildColumns = (ws, mode = 'source') => {
273
- var _a;
275
+ var _a, _b, _c;
274
276
  const columnsMeta = getSheetColumnsMeta(ws);
275
277
  const colWidths = getSheetColWidths(ws);
278
+ const frozenColumns = ((_b = (_a = ws.structure) === null || _a === void 0 ? void 0 : _a.freeze) === null || _b === void 0 ? void 0 : _b.columns) || 0;
276
279
  const columns = [{
277
280
  key: INDEX_COLUMN_KEY,
278
281
  title: mode === 'legacy-records' ? '#' : '',
@@ -290,7 +293,7 @@ export const buildColumns = (ws, mode = 'source') => {
290
293
  overflowTooltipHeaderShow: false
291
294
  }];
292
295
  const dataKeys = [];
293
- for (let index = 0; index < (((_a = ws.meta) === null || _a === void 0 ? void 0 : _a.totalCols) || 0); index += 1) {
296
+ for (let index = 0; index < (((_c = ws.meta) === null || _c === void 0 ? void 0 : _c.totalCols) || 0); index += 1) {
294
297
  const key = getDataKey(index);
295
298
  const column = columnsMeta === null || columnsMeta === void 0 ? void 0 : columnsMeta[index];
296
299
  const width = getColumnWidth(colWidths, index, ws.defaults.colWidth);
@@ -302,6 +305,7 @@ export const buildColumns = (ws, mode = 'source') => {
302
305
  title: (column === null || column === void 0 ? void 0 : column.title) || `${index + 1}`,
303
306
  width: hidden ? 0 : Math.max(Math.ceil(width), 1),
304
307
  hide: hidden,
308
+ ...(index < frozenColumns ? { fixed: 'left' } : {}),
305
309
  widthFillDisable: true,
306
310
  renderType: 'both',
307
311
  headerAlign: 'center',
@@ -344,6 +348,28 @@ export const getDisplayColumns = (columns, zoomScale = 1) => {
344
348
  }
345
349
  return columns.map(column => scaleColumn(column, normalizedScale));
346
350
  };
351
+ export const getSpreadsheetDisplayColumns = (columns, zoomScale, viewportWidth) => {
352
+ const display = getDisplayColumns(columns, zoomScale);
353
+ const available = viewportWidth > 0
354
+ ? Math.max(0, viewportWidth - VERTICAL_SCROLLBAR_TRACK_WIDTH - MIN_SCROLLABLE_PANE_WIDTH)
355
+ : Infinity;
356
+ let fixedWidth = getRenderColumnWidth(display[0]);
357
+ let frozenColumns = 0;
358
+ for (let index = 1; index < display.length; index += 1) {
359
+ const column = display[index];
360
+ if (column.fixed !== 'left')
361
+ break;
362
+ const nextWidth = fixedWidth + (column.hide ? 0 : getRenderColumnWidth(column));
363
+ if (frozenColumns === index - 1 && nextWidth <= available) {
364
+ fixedWidth = nextWidth;
365
+ frozenColumns = index;
366
+ }
367
+ else {
368
+ delete column.fixed;
369
+ }
370
+ }
371
+ return { columns: display, frozenColumns };
372
+ };
347
373
  export const getSearchColumnLeft = (columns, key) => {
348
374
  let left = 0;
349
375
  const visit = (list) => {
@@ -517,11 +543,15 @@ const isBlankOverflowTarget = (virtualState, row, rowIndex, dataColIndex) => {
517
543
  }
518
544
  return !hasRenderableValue(row[getDataKey(dataColIndex)]);
519
545
  };
546
+ const getFrozenColumnCount = (state) => { var _a, _b, _c; return (_c = (_a = state.visibleFrozenColumns) !== null && _a !== void 0 ? _a : (_b = state.freeze) === null || _b === void 0 ? void 0 : _b.columns) !== null && _c !== void 0 ? _c : 0; };
520
547
  const collectOverflowRoom = (virtualState, row, rowIndex, dataColIndex, direction) => {
521
548
  let room = 0;
549
+ const freeze = getFrozenColumnCount(virtualState);
550
+ const insideFrozenPane = dataColIndex < freeze;
522
551
  for (let step = 1; step <= MAX_OVERFLOW_SCAN_COLS; step += 1) {
523
552
  const nextColIndex = dataColIndex + step * direction;
524
- if (nextColIndex < 0 || nextColIndex >= virtualState.totalCols) {
553
+ if (nextColIndex < 0 || nextColIndex >= virtualState.totalCols ||
554
+ (nextColIndex < freeze) !== insideFrozenPane) {
525
555
  break;
526
556
  }
527
557
  if (!isBlankOverflowTarget(virtualState, row, rowIndex, nextColIndex)) {
@@ -582,9 +612,11 @@ const getLeftOverflowMirror = (virtualState, row, rowIndex, targetDataColIndex,
582
612
  if (!targetWidth) {
583
613
  return undefined;
584
614
  }
615
+ const freeze = getFrozenColumnCount(virtualState);
616
+ const firstPaneColumn = targetDataColIndex < freeze ? 0 : freeze;
585
617
  for (let step = 1; step <= MAX_OVERFLOW_SCAN_COLS; step += 1) {
586
618
  const sourceDataColIndex = targetDataColIndex - step;
587
- if (sourceDataColIndex < 0) {
619
+ if (sourceDataColIndex < firstPaneColumn) {
588
620
  break;
589
621
  }
590
622
  const sourceColumn = virtualState.columns[sourceDataColIndex + 1];
@@ -908,14 +940,21 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
908
940
  const scaledCellWidth = scaleNumber(sheetDefaults.colWidth, normalizedScale);
909
941
  const headerStyle = getIndexCellStyle(normalizedScale, darkMode);
910
942
  const loadingStyle = getLoadingCellStyle(normalizedScale, darkMode);
911
- let firstVisibleColumn = 1;
943
+ const frozenColumns = getFrozenColumnCount(virtualState);
944
+ let firstVisibleColumn = frozenColumns + 1;
912
945
  const getProjectedMerge = (rowIndex, colIndex, column) => {
913
946
  const cellKey = getCellCacheKey(rowIndex, colIndex, column);
914
- const anchorKey = virtualState.mergeCoveredMap.get(cellKey);
915
- const merge = anchorKey ? virtualState.mergeStartMap.get(anchorKey) : undefined;
947
+ const anchorKey = virtualState.mergeCoveredMap.get(cellKey) || cellKey;
948
+ const merge = virtualState.mergeStartMap.get(anchorKey);
916
949
  const displayCol = getDataColumnIndex(column, colIndex) + 1;
917
- if (!merge || merge.row !== rowIndex || displayCol !== firstVisibleColumn ||
918
- merge.col >= displayCol || displayCol >= merge.col + merge.colspan) {
950
+ if (!merge || merge.row !== rowIndex) {
951
+ return undefined;
952
+ }
953
+ const mergeEnd = merge.col + merge.colspan;
954
+ const frozenSegment = displayCol === merge.col && merge.col <= frozenColumns && mergeEnd > frozenColumns + 1;
955
+ const scrollingSegment = displayCol === firstVisibleColumn && displayCol > frozenColumns &&
956
+ merge.col < displayCol && displayCol < mergeEnd;
957
+ if (!frozenSegment && !scrollingSegment) {
919
958
  return undefined;
920
959
  }
921
960
  let width = 0;
@@ -927,11 +966,12 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
927
966
  if (col < displayCol)
928
967
  offsetLeft += scaledWidth;
929
968
  }
930
- return { merge, anchorKey: anchorKey, width, offsetLeft, colspan: merge.col + merge.colspan - displayCol };
969
+ const segmentEnd = frozenSegment ? frozenColumns + 1 : mergeEnd;
970
+ return { merge, anchorKey, width, offsetLeft, colspan: segmentEnd - displayCol, frozenSegment };
931
971
  };
932
972
  const spanMethod = ({ rowIndex, colIndex, column, visibleLeafColumns }) => {
933
973
  if (visibleLeafColumns === null || visibleLeafColumns === void 0 ? void 0 : visibleLeafColumns.length) {
934
- const visibleDataColumns = visibleLeafColumns.filter(item => item.key !== INDEX_COLUMN_KEY && isVisibleDataColumn(item));
974
+ const visibleDataColumns = visibleLeafColumns.filter(item => item.key !== INDEX_COLUMN_KEY && !item.fixed && isVisibleDataColumn(item));
935
975
  if (visibleDataColumns.length) {
936
976
  firstVisibleColumn = Math.min(...visibleDataColumns.map(item => getDataColumnIndex(item, 1) + 1));
937
977
  }
@@ -994,7 +1034,8 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
994
1034
  : undefined;
995
1035
  const match = searchCell === null || searchCell === void 0 ? void 0 : searchCell(rowIndex, dataColIndex);
996
1036
  const renderText = shouldRenderTextInOverlay(style, column) || !!overflowLayout || !!mirror || !!match;
997
- const comment = commentsByCell.get(cellKey);
1037
+ const hasFrozenAnchor = projected && !projected.frozenSegment && projected.merge.col <= frozenColumns;
1038
+ const comment = hasFrozenAnchor ? undefined : commentsByCell.get(cellKey);
998
1039
  if (!hasBorder(style) && !renderText && !comment) {
999
1040
  return undefined;
1000
1041
  }
@@ -1009,7 +1050,9 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
1009
1050
  const collapsedStyle = hasBorder(style)
1010
1051
  ? getCollapsedBorderStyle(virtualState, rowIndex, dataColIndex, baseStyle, normalizedScale)
1011
1052
  : baseStyle;
1012
- renderCellOverlay(cellEl, projected ? { ...collapsedStyle, borderLeft: undefined } : collapsedStyle, (mirror === null || mirror === void 0 ? void 0 : mirror.style) || collapsedStyle, mirror ? mirror.value : renderValue, renderText, (mirror === null || mirror === void 0 ? void 0 : mirror.overflowLayout) || overflowLayout, normalizedScale);
1053
+ renderCellOverlay(cellEl, (projected === null || projected === void 0 ? void 0 : projected.frozenSegment)
1054
+ ? { ...collapsedStyle, borderRight: undefined }
1055
+ : projected ? { ...collapsedStyle, borderLeft: undefined } : collapsedStyle, (mirror === null || mirror === void 0 ? void 0 : mirror.style) || collapsedStyle, mirror ? mirror.value : renderValue, renderText, (mirror === null || mirror === void 0 ? void 0 : mirror.overflowLayout) || overflowLayout, normalizedScale);
1013
1056
  if (comment) {
1014
1057
  cellEl.style.pointerEvents = 'auto';
1015
1058
  const indicator = cellEl.ownerDocument.createElement('button');
@@ -1076,6 +1119,7 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
1076
1119
  EDIT_BG_COLOR: darkMode ? '#18212f' : '#ffffff',
1077
1120
  PLACEHOLDER_COLOR: darkMode ? '#94a3b8' : '#8a94a3',
1078
1121
  SCROLLER_COLOR: darkMode ? '#475569' : '#c1c7d0',
1122
+ SCROLLER_TRACK_SIZE: VERTICAL_SCROLLBAR_TRACK_WIDTH,
1079
1123
  SCROLLER_FOCUS_COLOR: darkMode ? '#64748b' : '#9aa0a6',
1080
1124
  SELECT_ROW_COL_BG_COLOR: EXCEL_GREEN_SOFT,
1081
1125
  SELECT_AREA_COLOR: 'rgba(33, 163, 102, 0.14)',
@@ -775,12 +775,16 @@ class SheetJsModel {
775
775
  });
776
776
  }
777
777
  getStructure() {
778
- var _a;
778
+ var _a, _b, _c, _d;
779
+ const layout = this.ws['!fileViewerLayout'];
780
+ const rows = Math.min((_b = (_a = layout === null || layout === void 0 ? void 0 : layout.freeze) === null || _a === void 0 ? void 0 : _a.rows) !== null && _b !== void 0 ? _b : 0, this.totalRows);
781
+ const columns = Math.min((_d = (_c = layout === null || layout === void 0 ? void 0 : layout.freeze) === null || _c === void 0 ? void 0 : _c.columns) !== null && _d !== void 0 ? _d : 0, this.totalCols);
779
782
  return {
780
783
  merge: this.getAllMerge(),
781
784
  colWidths: this.getColWidths(),
782
785
  rowHeights: this.getAllRowHeights(),
783
- rowSizing: (_a = this.ws['!fileViewerLayout']) === null || _a === void 0 ? void 0 : _a.rowSizing,
786
+ rowSizing: layout === null || layout === void 0 ? void 0 : layout.rowSizing,
787
+ ...(rows || columns ? { freeze: { rows, columns } } : {}),
784
788
  columns: this.getColumns(),
785
789
  images: this.getImages(),
786
790
  charts: this.getCharts()
@@ -0,0 +1,6 @@
1
+ export type SpreadsheetEncryptionErrorCode = 'encrypted' | 'invalid-password' | 'unsupported-encryption';
2
+ export declare class SpreadsheetEncryptionError extends Error {
3
+ readonly code: SpreadsheetEncryptionErrorCode;
4
+ constructor(code: SpreadsheetEncryptionErrorCode);
5
+ }
6
+ export declare function decryptSpreadsheetPackage(data: ArrayBuffer, fileType: string | undefined, password?: string, signal?: AbortSignal): Promise<ArrayBuffer>;
@@ -0,0 +1,455 @@
1
+ import { CFB } from 'styled-exceljs';
2
+ import { DOMParser } from '@xmldom/xmldom';
3
+ export class SpreadsheetEncryptionError extends Error {
4
+ constructor(code) {
5
+ super(code);
6
+ this.code = code;
7
+ }
8
+ }
9
+ const encryptionNamespace = 'http://schemas.microsoft.com/office/2006/encryption';
10
+ const passwordNamespace = 'http://schemas.microsoft.com/office/2006/keyEncryptor/password';
11
+ const officeHeader = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
12
+ const openXmlTypes = new Set(['xlsx', 'xlsm', 'xlsb', 'xltx', 'xltm']);
13
+ const hashBits = { 'SHA-1': 160, 'SHA-256': 256, 'SHA-384': 384, 'SHA-512': 512 };
14
+ const blocks = {
15
+ verifier: Uint8Array.of(0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, 0x79),
16
+ verifierHash: Uint8Array.of(0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, 0x4e),
17
+ key: Uint8Array.of(0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, 0xd6),
18
+ integrityKey: Uint8Array.of(0x5f, 0xb2, 0xad, 0x01, 0x0c, 0xb9, 0xe1, 0xf6),
19
+ integrityValue: Uint8Array.of(0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, 0x33),
20
+ };
21
+ const aesBlockSize = 16;
22
+ const segmentSize = 4096;
23
+ const encryptedByteBudget = 256 * 1024 * 1024;
24
+ const padSize = (size) => Math.ceil(size / aesBlockSize) * aesBlockSize;
25
+ const requireBytes = (condition) => {
26
+ if (!condition)
27
+ throw new Error('Malformed encrypted spreadsheet.');
28
+ };
29
+ const unsupported = () => { throw new SpreadsheetEncryptionError('unsupported-encryption'); };
30
+ function concat(left, right) {
31
+ const bytes = new Uint8Array(left.byteLength + right.byteLength);
32
+ bytes.set(left);
33
+ bytes.set(right, left.byteLength);
34
+ return bytes;
35
+ }
36
+ function compoundBytes(content) {
37
+ if (content instanceof Uint8Array && content.buffer instanceof ArrayBuffer) {
38
+ return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
39
+ }
40
+ return Uint8Array.from(content);
41
+ }
42
+ function uint32(value) {
43
+ const bytes = new Uint8Array(4);
44
+ new DataView(bytes.buffer).setUint32(0, value, true);
45
+ return bytes;
46
+ }
47
+ function utf16le(value) {
48
+ const bytes = new Uint8Array(value.length * 2);
49
+ const view = new DataView(bytes.buffer);
50
+ for (let index = 0; index < value.length; index++) {
51
+ view.setUint16(index * 2, value.charCodeAt(index), true);
52
+ }
53
+ return bytes;
54
+ }
55
+ function sameBytes(left, right) {
56
+ if (left.byteLength !== right.byteLength)
57
+ return false;
58
+ let difference = 0;
59
+ for (let index = 0; index < left.byteLength; index++)
60
+ difference |= left[index] ^ right[index];
61
+ return difference === 0;
62
+ }
63
+ async function hash(subtle, algorithm, bytes) {
64
+ return new Uint8Array(await subtle.digest(algorithm, bytes));
65
+ }
66
+ async function passwordHash(subtle, algorithm, salt, password, spins, signal) {
67
+ const input = concat(salt, utf16le(password));
68
+ let result = await hash(subtle, algorithm, input);
69
+ input.fill(0);
70
+ const iterated = new Uint8Array(4 + result.byteLength);
71
+ const counter = new DataView(iterated.buffer);
72
+ for (let index = 0; index < spins; index++) {
73
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
74
+ counter.setUint32(0, index, true);
75
+ iterated.set(result, 4);
76
+ result = await hash(subtle, algorithm, iterated);
77
+ }
78
+ iterated.fill(0);
79
+ return result;
80
+ }
81
+ function sized(bytes, size) {
82
+ if (bytes.byteLength >= size)
83
+ return bytes.slice(0, size);
84
+ const expanded = new Uint8Array(size).fill(0x36);
85
+ expanded.set(bytes);
86
+ return expanded;
87
+ }
88
+ const aesKey = (subtle, raw) => subtle.importKey('raw', raw, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
89
+ async function decryptBlocks(subtle, key, iv, cipher) {
90
+ requireBytes(cipher.byteLength > 0 && cipher.byteLength % aesBlockSize === 0);
91
+ const padding = await subtle.encrypt({ name: 'AES-CBC', iv: cipher.subarray(-aesBlockSize) }, key, new Uint8Array(0));
92
+ return new Uint8Array(await subtle.decrypt({ name: 'AES-CBC', iv }, key, concat(cipher, new Uint8Array(padding))));
93
+ }
94
+ async function decryptEcb(subtle, key, cipher) {
95
+ const decoded = await decryptBlocks(subtle, key, new Uint8Array(aesBlockSize), cipher);
96
+ for (let index = aesBlockSize; index < decoded.byteLength; index++) {
97
+ decoded[index] ^= cipher[index - aesBlockSize];
98
+ }
99
+ return decoded;
100
+ }
101
+ function streamSize(encrypted) {
102
+ requireBytes(encrypted.byteLength >= 8 + aesBlockSize);
103
+ const header = new DataView(encrypted.buffer, encrypted.byteOffset, 8);
104
+ const length = header.getUint32(4, true) * 0x100000000 + header.getUint32(0, true);
105
+ requireBytes(Number.isSafeInteger(length) && length > 0 && length <= encrypted.byteLength - 8);
106
+ requireBytes(padSize(length) === encrypted.byteLength - 8);
107
+ return length;
108
+ }
109
+ function base64Attribute(element, name) {
110
+ const value = element.getAttribute(name);
111
+ requireBytes(typeof value === 'string' && value.length > 0 && value.length <= 512);
112
+ return Uint8Array.from(atob(value), char => char.charCodeAt(0));
113
+ }
114
+ function readAgileParameters(element) {
115
+ var _a;
116
+ const algorithm = (_a = element.getAttribute('hashAlgorithm')) === null || _a === void 0 ? void 0 : _a.toUpperCase().replace(/^SHA(?=\d)/, 'SHA-');
117
+ const keyBytes = Number(element.getAttribute('keyBits')) / 8;
118
+ if (element.getAttribute('cipherAlgorithm') !== 'AES' ||
119
+ element.getAttribute('cipherChaining') !== 'ChainingModeCBC' ||
120
+ element.getAttribute('blockSize') !== '16' ||
121
+ ![16, 24, 32].includes(keyBytes) || !Object.prototype.hasOwnProperty.call(hashBits, algorithm))
122
+ unsupported();
123
+ const hashBytes = hashBits[algorithm] / 8;
124
+ requireBytes(Number(element.getAttribute('hashSize')) === hashBytes);
125
+ const salt = base64Attribute(element, 'saltValue');
126
+ requireBytes(salt.byteLength > 0 && salt.byteLength === Number(element.getAttribute('saltSize')));
127
+ return { algorithm, keyBytes, hashBytes, salt };
128
+ }
129
+ function agileReader(info) {
130
+ var _a;
131
+ requireBytes(info.byteLength > 8 && info.byteLength <= 65536);
132
+ const xml = new TextDecoder('utf-8', { fatal: true }).decode(info.subarray(8));
133
+ requireBytes(!/<!DOCTYPE|<!ENTITY/i.test(xml));
134
+ const document = new DOMParser({ onError: () => { throw new Error('Malformed encrypted spreadsheet.'); } })
135
+ .parseFromString(xml, 'application/xml');
136
+ const root = document.documentElement;
137
+ requireBytes((root === null || root === void 0 ? void 0 : root.namespaceURI) === encryptionNamespace && root.localName === 'encryption');
138
+ const keys = document.getElementsByTagNameNS(passwordNamespace, 'encryptedKey');
139
+ if (keys.length !== 1)
140
+ unsupported();
141
+ const payloadKeys = document.getElementsByTagNameNS(encryptionNamespace, 'keyData');
142
+ const integrityFields = document.getElementsByTagNameNS(encryptionNamespace, 'dataIntegrity');
143
+ requireBytes(payloadKeys.length === 1 && integrityFields.length === 1);
144
+ const keyData = payloadKeys.item(0);
145
+ const integrity = integrityFields.item(0);
146
+ const encryptor = keys.item(0);
147
+ const passwordParameters = readAgileParameters(encryptor);
148
+ const payloadParameters = readAgileParameters(keyData);
149
+ const spinsText = (_a = encryptor.getAttribute('spinCount')) !== null && _a !== void 0 ? _a : '';
150
+ const spins = Number(spinsText);
151
+ if (!/^\d+$/.test(spinsText) || !Number.isSafeInteger(spins) || spins > 1000000)
152
+ unsupported();
153
+ const verifier = base64Attribute(encryptor, 'encryptedVerifierHashInput');
154
+ const verifierHash = base64Attribute(encryptor, 'encryptedVerifierHashValue');
155
+ const encryptedKey = base64Attribute(encryptor, 'encryptedKeyValue');
156
+ const integrityKey = base64Attribute(integrity, 'encryptedHmacKey');
157
+ const integrityValue = base64Attribute(integrity, 'encryptedHmacValue');
158
+ return async (subtle, encrypted, password, signal) => {
159
+ const size = streamSize(encrypted);
160
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
161
+ const { algorithm, keyBytes, hashBytes, salt } = passwordParameters;
162
+ const iterated = await passwordHash(subtle, algorithm, salt, password, spins, signal);
163
+ const iv = sized(salt, aesBlockSize);
164
+ const decryptField = async (field, block) => {
165
+ const raw = sized(await hash(subtle, algorithm, concat(iterated, block)), keyBytes);
166
+ const key = await aesKey(subtle, raw);
167
+ raw.fill(0);
168
+ return decryptBlocks(subtle, key, iv, field);
169
+ };
170
+ const [input, verification] = await Promise.all([
171
+ decryptField(verifier, blocks.verifier),
172
+ decryptField(verifierHash, blocks.verifierHash),
173
+ ]);
174
+ const actual = await hash(subtle, algorithm, input.subarray(0, salt.byteLength));
175
+ if (!sameBytes(actual, verification.subarray(0, hashBytes))) {
176
+ iterated.fill(0);
177
+ throw new SpreadsheetEncryptionError('invalid-password');
178
+ }
179
+ const raw = await decryptField(encryptedKey, blocks.key);
180
+ iterated.fill(0);
181
+ const key = await aesKey(subtle, raw.subarray(0, payloadParameters.keyBytes));
182
+ raw.fill(0);
183
+ const payloadIv = async (part) => sized(await hash(subtle, payloadParameters.algorithm, concat(payloadParameters.salt, part)), aesBlockSize);
184
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
185
+ const [keyIv, valueIv] = await Promise.all([payloadIv(blocks.integrityKey), payloadIv(blocks.integrityValue)]);
186
+ const [hmacKey, value] = await Promise.all([
187
+ decryptBlocks(subtle, key, keyIv, integrityKey),
188
+ decryptBlocks(subtle, key, valueIv, integrityValue),
189
+ ]);
190
+ const hmac = await subtle.importKey('raw', hmacKey, { name: 'HMAC', hash: payloadParameters.algorithm }, false, ['verify']);
191
+ hmacKey.fill(0);
192
+ if (!await subtle.verify('HMAC', hmac, value.subarray(0, payloadParameters.hashBytes), encrypted)) {
193
+ throw new Error('Encrypted spreadsheet integrity check failed.');
194
+ }
195
+ const decoded = new Uint8Array(size);
196
+ for (let offset = 0, segment = 0; offset < size; offset += segmentSize, segment++) {
197
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
198
+ const length = Math.min(segmentSize, size - offset);
199
+ const cipher = encrypted.subarray(8 + offset, 8 + offset + padSize(length));
200
+ const plain = await decryptBlocks(subtle, key, await payloadIv(uint32(segment)), cipher);
201
+ decoded.set(plain.subarray(0, length), offset);
202
+ }
203
+ return decoded;
204
+ };
205
+ }
206
+ function standardReader(info) {
207
+ requireBytes(info.byteLength >= 12 + 32);
208
+ const view = new DataView(info.buffer, info.byteOffset, info.byteLength);
209
+ const flags = view.getUint32(4, true);
210
+ if ((flags & 0x3c) !== 0x24 || flags !== view.getUint32(12, true) || view.getUint32(16, true) !== 0)
211
+ unsupported();
212
+ const algorithm = view.getUint32(20, true);
213
+ const keyBytes = view.getUint32(28, true) / 8;
214
+ const keySizes = new Map([[0x660e, 16], [0x660f, 24], [0x6610, 32]]);
215
+ if (keySizes.get(algorithm) !== keyBytes || view.getUint32(24, true) !== 0x8004)
216
+ unsupported();
217
+ const verifierOffset = 12 + view.getUint32(8, true);
218
+ requireBytes(verifierOffset >= 44 && verifierOffset + 72 <= info.byteLength);
219
+ requireBytes(view.getUint32(verifierOffset, true) === 16 && view.getUint32(verifierOffset + 36, true) === 20);
220
+ const salt = info.subarray(verifierOffset + 4, verifierOffset + 20);
221
+ const verifier = info.subarray(verifierOffset + 20, verifierOffset + 36);
222
+ const verifierHash = info.subarray(verifierOffset + 40, verifierOffset + 72);
223
+ return async (subtle, encrypted, password, signal) => {
224
+ const size = streamSize(encrypted);
225
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
226
+ const iterations = await passwordHash(subtle, 'SHA-1', salt, password, 50000, signal);
227
+ const final = await hash(subtle, 'SHA-1', concat(iterations, uint32(0)));
228
+ iterations.fill(0);
229
+ const fold = async (byte) => {
230
+ const padding = new Uint8Array(64).fill(byte);
231
+ for (let index = 0; index < final.byteLength; index++)
232
+ padding[index] ^= final[index];
233
+ return hash(subtle, 'SHA-1', padding);
234
+ };
235
+ const [first, second] = await Promise.all([fold(0x36), fold(0x5c)]);
236
+ final.fill(0);
237
+ const key = await aesKey(subtle, concat(first, second).subarray(0, keyBytes));
238
+ const [input, verification] = await Promise.all([
239
+ decryptEcb(subtle, key, verifier),
240
+ decryptEcb(subtle, key, verifierHash),
241
+ ]);
242
+ const actual = await hash(subtle, 'SHA-1', input);
243
+ if (!sameBytes(actual, verification.subarray(0, 20))) {
244
+ throw new SpreadsheetEncryptionError('invalid-password');
245
+ }
246
+ const plain = new Uint8Array(size);
247
+ const chunkSize = 64 * 1024;
248
+ for (let offset = 0; offset < size; offset += chunkSize) {
249
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
250
+ const length = Math.min(chunkSize, size - offset);
251
+ const chunk = await decryptEcb(subtle, key, encrypted.subarray(8 + offset, 8 + offset + padSize(length)));
252
+ plain.set(chunk.subarray(0, length), offset);
253
+ }
254
+ return plain;
255
+ };
256
+ }
257
+ function biffFilePass(workbook) {
258
+ const view = new DataView(workbook.buffer, workbook.byteOffset, workbook.byteLength);
259
+ for (let offset = 0; offset + 4 <= view.byteLength;) {
260
+ const type = view.getUint16(offset, true);
261
+ const size = view.getUint16(offset + 2, true);
262
+ if (type === 0x002f) {
263
+ requireBytes(offset + 4 + size <= workbook.byteLength);
264
+ return workbook.subarray(offset + 4, offset + 4 + size);
265
+ }
266
+ if (type === 0x000a)
267
+ break;
268
+ offset += 4 + size;
269
+ }
270
+ return null;
271
+ }
272
+ const clearBiffRecords = new Set([0x0809, 0x0194, 0x0195, 0x00e1, 0x0196, 0x0138]);
273
+ function restoreBiffHeaders(workbook, plain) {
274
+ const view = new DataView(workbook.buffer, workbook.byteOffset, workbook.byteLength);
275
+ for (let offset = 0; offset + 4 <= view.byteLength;) {
276
+ const type = view.getUint16(offset, true);
277
+ const size = view.getUint16(offset + 2, true);
278
+ const start = offset + 4;
279
+ const end = start + size;
280
+ requireBytes(end <= workbook.byteLength);
281
+ plain.set(workbook.subarray(offset, start), offset);
282
+ if (type === 0x002f) {
283
+ plain.fill(0, offset, offset + 2);
284
+ plain.fill(0, start, end);
285
+ }
286
+ else if (clearBiffRecords.has(type)) {
287
+ plain.set(workbook.subarray(start, end), start);
288
+ }
289
+ else if (type === 0x0085) {
290
+ plain.set(workbook.subarray(start, Math.min(start + 4, end)), start);
291
+ }
292
+ offset = end;
293
+ }
294
+ return plain;
295
+ }
296
+ function decryptBiffXor(workbook, filePass, password) {
297
+ if (password.length < 1 || password.length > 15 || !/^[\x01-\x7f]+$/.test(password)) {
298
+ throw new SpreadsheetEncryptionError('invalid-password');
299
+ }
300
+ const chars = Uint8Array.from(password, character => character.charCodeAt(0));
301
+ const verifierData = concat(Uint8Array.of(chars.byteLength), chars);
302
+ let verifier = 0;
303
+ for (let index = verifierData.byteLength - 1; index >= 0; index--) {
304
+ verifier = (((verifier << 1) | (verifier >>> 14)) & 0x7fff) ^ verifierData[index];
305
+ }
306
+ let xorKey = 0xffff;
307
+ for (const character of chars) {
308
+ xorKey ^= character << 8;
309
+ for (let bit = 0; bit < 8; bit++) {
310
+ xorKey = ((xorKey << 1) ^ (xorKey & 0x8000 ? 0x1021 : 0)) & 0xffff;
311
+ }
312
+ }
313
+ if ((verifier ^ 0xce4b) !== filePass.getUint16(4, true) || xorKey !== filePass.getUint16(2, true)) {
314
+ throw new SpreadsheetEncryptionError('invalid-password');
315
+ }
316
+ const padding = Uint8Array.of(0xbb, 0xff, 0xff, 0xba, 0xff, 0xff, 0xb9, 0x80, 0x00, 0xbe, 0x0f, 0x00, 0xbf, 0x0f, 0x00);
317
+ const xorBytes = concat(chars, padding.subarray(0, 16 - chars.byteLength));
318
+ for (let index = 0; index < xorBytes.byteLength; index++) {
319
+ const byte = xorBytes[index] ^ ((xorKey >>> ((index % 2) * 8)) & 255);
320
+ xorBytes[index] = (byte >>> 1) | (byte << 7);
321
+ }
322
+ const plain = workbook.slice();
323
+ const source = new DataView(workbook.buffer, workbook.byteOffset, workbook.byteLength);
324
+ for (let offset = 0; offset + 4 <= source.byteLength;) {
325
+ const type = source.getUint16(offset, true);
326
+ const length = source.getUint16(offset + 2, true);
327
+ const end = offset + 4 + length;
328
+ requireBytes(end <= source.byteLength);
329
+ if (type !== 0x002f && !clearBiffRecords.has(type)) {
330
+ const prefix = type === 0x0085 ? 4 : 0;
331
+ for (let index = offset + 4 + prefix, key = end + prefix; index < end; index++, key++) {
332
+ const byte = workbook[index] ^ xorBytes[key % 16];
333
+ plain[index] = (byte >>> 5) | (byte << 3);
334
+ }
335
+ }
336
+ offset = end;
337
+ }
338
+ xorBytes.fill(0);
339
+ return restoreBiffHeaders(workbook, plain);
340
+ }
341
+ function rc4(bytes, key) {
342
+ const state = Uint8Array.from({ length: 256 }, (_, index) => index);
343
+ let right = 0;
344
+ for (let left = 0; left < 256; left++) {
345
+ right = (right + state[left] + key[left % key.byteLength]) & 255;
346
+ [state[left], state[right]] = [state[right], state[left]];
347
+ }
348
+ right = 0;
349
+ return bytes.map((byte, index) => {
350
+ const left = (index + 1) & 255;
351
+ right = (right + state[left]) & 255;
352
+ [state[left], state[right]] = [state[right], state[left]];
353
+ return byte ^ state[(state[left] + state[right]) & 255];
354
+ });
355
+ }
356
+ async function decryptBiffCryptoApi(subtle, workbook, filePass, keyBits, password, signal) {
357
+ const view = new DataView(filePass.buffer, filePass.byteOffset, filePass.byteLength);
358
+ const verifierOffset = 14 + view.getUint32(10, true);
359
+ requireBytes(verifierOffset >= 46 && verifierOffset + 60 <= filePass.byteLength);
360
+ requireBytes(view.getUint32(verifierOffset, true) === 16 && view.getUint32(verifierOffset + 36, true) === 20);
361
+ const salt = filePass.subarray(verifierOffset + 4, verifierOffset + 20);
362
+ const initial = await hash(subtle, 'SHA-1', concat(salt, utf16le(password)));
363
+ const forBlock = async (block) => {
364
+ const digest = await hash(subtle, 'SHA-1', concat(initial, uint32(block)));
365
+ if (keyBits !== 40)
366
+ return digest.subarray(0, keyBits / 8);
367
+ const key = new Uint8Array(16);
368
+ key.set(digest.subarray(0, 5));
369
+ return key;
370
+ };
371
+ const verifier = filePass.subarray(verifierOffset + 20, verifierOffset + 36);
372
+ const verifierHash = filePass.subarray(verifierOffset + 40, verifierOffset + 60);
373
+ const decoded = rc4(concat(verifier, verifierHash), await forBlock(0));
374
+ if (!sameBytes(await hash(subtle, 'SHA-1', decoded.subarray(0, 16)), decoded.subarray(16))) {
375
+ throw new SpreadsheetEncryptionError('invalid-password');
376
+ }
377
+ const result = new Uint8Array(workbook.byteLength);
378
+ const biffBlockSize = 1024;
379
+ for (let offset = 0, block = 0; offset < workbook.byteLength; offset += biffBlockSize, block++) {
380
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
381
+ result.set(rc4(workbook.subarray(offset, offset + biffBlockSize), await forBlock(block)), offset);
382
+ }
383
+ initial.fill(0);
384
+ return restoreBiffHeaders(workbook, result);
385
+ }
386
+ async function decryptLegacyBiff(workbook, filePass, password, signal) {
387
+ var _a;
388
+ const bof = new DataView(workbook.buffer, workbook.byteOffset, 6);
389
+ const view = new DataView(filePass.buffer, filePass.byteOffset, filePass.byteLength);
390
+ if (bof.getUint16(0, true) !== 0x0809 || bof.getUint16(4, true) !== 0x0600 || filePass.byteLength < 6) {
391
+ return unsupported();
392
+ }
393
+ const type = view.getUint16(0, true);
394
+ if (type === 0 && filePass.byteLength === 6) {
395
+ if (password === undefined)
396
+ throw new SpreadsheetEncryptionError('encrypted');
397
+ return decryptBiffXor(workbook, view, password);
398
+ }
399
+ const isCryptoApi = type === 1 && filePass.byteLength >= 46
400
+ && [2, 3, 4].includes(view.getUint16(2, true)) && view.getUint16(4, true) === 2;
401
+ const subtle = (_a = globalThis.crypto) === null || _a === void 0 ? void 0 : _a.subtle;
402
+ if (!subtle || !isCryptoApi)
403
+ return unsupported();
404
+ const keyBits = view.getUint32(30, true) || 40;
405
+ if (view.getUint32(22, true) !== 0x6801 || view.getUint32(26, true) !== 0x8004 || keyBits < 40 || keyBits > 128 || keyBits % 8) {
406
+ return unsupported();
407
+ }
408
+ if (password === undefined)
409
+ throw new SpreadsheetEncryptionError('encrypted');
410
+ return decryptBiffCryptoApi(subtle, workbook, filePass, keyBits, password, signal);
411
+ }
412
+ export async function decryptSpreadsheetPackage(data, fileType, password, signal) {
413
+ var _a, _b, _c, _d;
414
+ const bytes = new Uint8Array(data);
415
+ if (!officeHeader.every((byte, index) => bytes[index] === byte))
416
+ return data;
417
+ const cfb = CFB.read(bytes, { type: 'array' });
418
+ const infoContent = (_a = CFB.find(cfb, '/EncryptionInfo')) === null || _a === void 0 ? void 0 : _a.content;
419
+ const packageContent = (_b = CFB.find(cfb, '/EncryptedPackage')) === null || _b === void 0 ? void 0 : _b.content;
420
+ if (!infoContent && !packageContent) {
421
+ const entry = CFB.find(cfb, '/Workbook') || CFB.find(cfb, '/Book');
422
+ const workbook = ((_c = entry === null || entry === void 0 ? void 0 : entry.content) === null || _c === void 0 ? void 0 : _c.length) ? compoundBytes(entry.content) : undefined;
423
+ const filePass = workbook && biffFilePass(workbook);
424
+ if (workbook && filePass) {
425
+ if (workbook.byteLength > encryptedByteBudget)
426
+ unsupported();
427
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
428
+ entry.content = await decryptLegacyBiff(workbook, filePass, password, signal);
429
+ return Uint8Array.from(CFB.write(cfb, { type: 'array' })).buffer;
430
+ }
431
+ return data;
432
+ }
433
+ if (!infoContent || !packageContent || infoContent.length < 8 || infoContent.length > 65536) {
434
+ throw new Error('Malformed encrypted spreadsheet.');
435
+ }
436
+ if (packageContent.length > encryptedByteBudget)
437
+ unsupported();
438
+ if (fileType && !openXmlTypes.has(fileType.toLowerCase()))
439
+ unsupported();
440
+ const info = compoundBytes(infoContent);
441
+ const version = new DataView(info.buffer, info.byteOffset, info.byteLength);
442
+ const major = version.getUint16(0, true);
443
+ const minor = version.getUint16(2, true);
444
+ const reader = major === 4 && minor === 4 && version.getUint32(4, true) === 0x40 ? agileReader(info)
445
+ : minor === 2 && [2, 3, 4].includes(major) ? standardReader(info)
446
+ : unsupported();
447
+ const subtle = (_d = globalThis.crypto) === null || _d === void 0 ? void 0 : _d.subtle;
448
+ if (!subtle)
449
+ unsupported();
450
+ if (password === undefined)
451
+ throw new SpreadsheetEncryptionError('encrypted');
452
+ const plain = await reader(subtle, compoundBytes(packageContent), password, signal);
453
+ requireBytes(plain[0] === 0x50 && plain[1] === 0x4b);
454
+ return plain.buffer;
455
+ }