@file-viewer/renderer-spreadsheet 3.3.6 → 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.
@@ -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
+ }
@@ -26,6 +26,8 @@ export interface SpreadsheetParserContext {
26
26
  }
27
27
  export interface SpreadsheetWorkbookSource extends SpreadsheetTextSource {
28
28
  includeEmptySheets?: boolean;
29
+ password?: string;
30
+ signal?: AbortSignal;
29
31
  }
30
32
  export interface SpreadsheetWorkerRequest {
31
33
  type: string;
@@ -74,7 +76,7 @@ export declare const classifySpreadsheetCell: (value: unknown, defaultFont?: obj
74
76
  export declare const getWorksheetDisplayBounds: (worksheet: WorksheetRangeLike | undefined, charts: SheetChartDefinition[] | undefined, _comments?: SheetComment[], options?: {
75
77
  defaultFont?: object;
76
78
  }) => WorksheetDisplayBounds;
77
- export declare const parseSpreadsheetWorkbook: (context: SpreadsheetParserContext, data: ArrayBuffer, source?: SpreadsheetWorkbookSource) => Promise<SpreadsheetWorkerResponse[]>;
79
+ export declare const parseSpreadsheetWorkbook: (context: SpreadsheetParserContext, sourceBytes: ArrayBuffer, source?: SpreadsheetWorkbookSource) => Promise<SpreadsheetWorkerResponse[]>;
78
80
  export declare const parseSpreadsheetSheet: (context: SpreadsheetParserContext, payload?: Record<string, any>) => SpreadsheetWorkerResponse[];
79
81
  export declare const parseSpreadsheetRegion: (context: SpreadsheetParserContext, payload?: Record<string, any>) => SpreadsheetWorkerResponse[];
80
82
  export declare const indexOccupiedRegions: (worksheet: WorkSheet, budget?: {
@@ -105,5 +107,5 @@ export declare const discoverSpreadsheetSource: (worksheet: WorkSheet, sources?:
105
107
  sourceDiscovery: SheetSourceDiscovery;
106
108
  };
107
109
  export declare const searchSpreadsheetWorkbook: (context: SpreadsheetParserContext, query: string, options?: SpreadsheetSearchOptions) => SpreadsheetSearchMatch[];
108
- export declare const handleSpreadsheetWorkerRequest: (context: SpreadsheetParserContext, request: SpreadsheetWorkerRequest) => SpreadsheetWorkerResponse[] | Promise<SpreadsheetWorkerResponse[]>;
110
+ export declare const handleSpreadsheetWorkerRequest: (context: SpreadsheetParserContext, request: SpreadsheetWorkerRequest, signal?: AbortSignal) => SpreadsheetWorkerResponse[] | Promise<SpreadsheetWorkerResponse[]>;
109
111
  export {};
@@ -8,6 +8,7 @@ import { prepareSpreadsheetReadInput, } from './textEncoding.js';
8
8
  import { parseSpreadsheetCellImages } from './richDataParser.js';
9
9
  import { recoverUncachedFormulaValues } from './formulaValues.js';
10
10
  import { readWorkbookDefaultFont } from './workbookFont.js';
11
+ import { decryptSpreadsheetPackage, SpreadsheetEncryptionError } from './encryption.js';
11
12
  const readOptions = {
12
13
  type: 'array',
13
14
  dense: true,
@@ -111,6 +112,7 @@ const toErrorResponse = (error, payload = {}) => ({
111
112
  payload: {
112
113
  ...payload,
113
114
  message: error instanceof Error ? error.message : String(error),
115
+ ...(error instanceof SpreadsheetEncryptionError ? { code: error.code } : {}),
114
116
  },
115
117
  });
116
118
  const legalSourcePoint = (point) => Number.isSafeInteger(point === null || point === void 0 ? void 0 : point.row)
@@ -389,8 +391,9 @@ const parseSheets = (context, includeEmptySheets = false) => {
389
391
  }, []);
390
392
  return [{ type: 'sheets', payload: { sheets: context.sheets, commentsError: context.commentsError } }];
391
393
  };
392
- export const parseSpreadsheetWorkbook = async (context, data, source = {}) => {
394
+ export const parseSpreadsheetWorkbook = async (context, sourceBytes, source = {}) => {
393
395
  try {
396
+ const data = await decryptSpreadsheetPackage(sourceBytes, source.fileType, source.password, source.signal);
394
397
  const input = prepareSpreadsheetReadInput(data, source);
395
398
  context.workbook = readWorkbookWithMergeRecovery(input);
396
399
  const workbook = context.workbook;
@@ -874,8 +877,8 @@ export const searchSpreadsheetWorkbook = (context, query, options = {}) => {
874
877
  }
875
878
  return matches;
876
879
  };
877
- export const handleSpreadsheetWorkerRequest = (context, request) => {
878
- var _a, _b, _c, _d, _e, _f, _g, _h;
880
+ export const handleSpreadsheetWorkerRequest = (context, request, signal) => {
881
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
879
882
  switch (request.type) {
880
883
  case 'parseWorkbook':
881
884
  return parseSpreadsheetWorkbook(context, (_a = request.payload) === null || _a === void 0 ? void 0 : _a.workbook, {
@@ -883,6 +886,8 @@ export const handleSpreadsheetWorkerRequest = (context, request) => {
883
886
  filename: (_c = request.payload) === null || _c === void 0 ? void 0 : _c.filename,
884
887
  textEncoding: (_d = request.payload) === null || _d === void 0 ? void 0 : _d.textEncoding,
885
888
  includeEmptySheets: (_e = request.payload) === null || _e === void 0 ? void 0 : _e.includeEmptySheets,
889
+ password: (_f = request.payload) === null || _f === void 0 ? void 0 : _f.password,
890
+ signal,
886
891
  });
887
892
  case 'parseSheet':
888
893
  return parseSpreadsheetSheet(context, request.payload);
@@ -892,9 +897,9 @@ export const handleSpreadsheetWorkerRequest = (context, request) => {
892
897
  return [{
893
898
  type: 'searchWorkbook',
894
899
  payload: {
895
- requestId: (_f = request.payload) === null || _f === void 0 ? void 0 : _f.requestId,
896
- query: ((_g = request.payload) === null || _g === void 0 ? void 0 : _g.query) || '',
897
- matches: searchSpreadsheetWorkbook(context, ((_h = request.payload) === null || _h === void 0 ? void 0 : _h.query) || '', request.payload),
900
+ requestId: (_g = request.payload) === null || _g === void 0 ? void 0 : _g.requestId,
901
+ query: ((_h = request.payload) === null || _h === void 0 ? void 0 : _h.query) || '',
902
+ matches: searchSpreadsheetWorkbook(context, ((_j = request.payload) === null || _j === void 0 ? void 0 : _j.query) || '', request.payload),
898
903
  },
899
904
  }];
900
905
  default:
@@ -1,11 +1,13 @@
1
1
  import type JSZip from 'jszip';
2
2
  import type { WorkBook } from 'styled-exceljs';
3
+ import type { SheetFreezePane } from '../type.js';
3
4
  import type { StoredRowSizing } from './rowSizing.js';
4
5
  export interface StoredSheetLayout {
5
6
  columnWidth?: number;
6
7
  rowHeightPt?: number;
7
8
  rowSizing?: StoredRowSizing;
8
9
  maximumDigitWidth?: number;
10
+ freeze?: SheetFreezePane;
9
11
  }
10
12
  export declare const readWorkbookDigitWidth: (workbook?: WorkBook | null) => number;
11
13
  export declare const readStoredSheetLayout: (zip: JSZip, part: string) => Promise<StoredSheetLayout>;
@@ -1,4 +1,5 @@
1
1
  import { DOMParser } from '@xmldom/xmldom';
2
+ import { EXCEL_SOURCE_EXTENT } from '../../sourceRegion.js';
2
3
  export const readWorkbookDigitWidth = (workbook) => {
3
4
  var _a, _b, _c, _d, _e, _f, _g, _h;
4
5
  const styles = workbook === null || workbook === void 0 ? void 0 : workbook.Styles;
@@ -12,8 +13,33 @@ export const readWorkbookDigitWidth = (workbook) => {
12
13
  }
13
14
  return 7;
14
15
  };
16
+ const sheetChildren = (element, name) => {
17
+ var _a;
18
+ return Array.from((_a = element === null || element === void 0 ? void 0 : element.childNodes) !== null && _a !== void 0 ? _a : []).filter((node) => node.nodeType === 1 && node.localName === name
19
+ && node.namespaceURI === (element === null || element === void 0 ? void 0 : element.namespaceURI));
20
+ };
21
+ const readFrozenPane = (views) => {
22
+ var _a;
23
+ const sheetViews = sheetChildren(views, 'sheetView');
24
+ const view = (_a = sheetViews.find(candidate => candidate.getAttribute('workbookViewId') === '0')) !== null && _a !== void 0 ? _a : sheetViews[0];
25
+ const [pane] = sheetChildren(view, 'pane');
26
+ const state = pane === null || pane === void 0 ? void 0 : pane.getAttribute('state');
27
+ if (state !== 'frozen' && state !== 'frozenSplit')
28
+ return undefined;
29
+ const count = (attribute, max) => {
30
+ var _a, _b;
31
+ const raw = (_b = (_a = pane.getAttribute(attribute)) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
32
+ if (!/^\+?(?:\d+\.?\d*|\.\d+)(?:[Ee][+-]?\d+)?$/.test(raw))
33
+ return 0;
34
+ const value = Number(raw);
35
+ return Number.isSafeInteger(value) ? Math.min(value, max) : 0;
36
+ };
37
+ const rows = count('ySplit', EXCEL_SOURCE_EXTENT.rows - 1);
38
+ const columns = count('xSplit', EXCEL_SOURCE_EXTENT.cols - 1);
39
+ return rows || columns ? { rows, columns } : undefined;
40
+ };
15
41
  export const readStoredSheetLayout = async (zip, part) => {
16
- var _a, _b, _c, _d;
42
+ var _a, _b, _c, _d, _e, _f;
17
43
  const file = zip.file(part);
18
44
  if (!file)
19
45
  return {};
@@ -44,17 +70,25 @@ export const readStoredSheetLayout = async (zip, part) => {
44
70
  stream.resume();
45
71
  });
46
72
  const tag = (_a = /<(?:[\w.-]+:)?sheetFormatPr\b[^>]*>/.exec(header)) === null || _a === void 0 ? void 0 : _a[0];
47
- if (!tag)
73
+ const views = (_b = /<((?:[\w.-]+:)?sheetViews)\b[^>]*>[\s\S]*?<\/\1\s*>/.exec(header)) === null || _b === void 0 ? void 0 : _b[0];
74
+ if (!tag && !views)
48
75
  return {};
49
- const root = ((_b = /<(?:[\w.-]+:)?worksheet\b[^>]*>/.exec(header)) === null || _b === void 0 ? void 0 : _b[0]) || '';
50
- const namespaces = ((_c = root.match(/\sxmlns(?::[\w.-]+)?\s*=\s*(?:"[^"]*"|'[^']*')/g)) === null || _c === void 0 ? void 0 : _c.join('')) || '';
51
- const element = (_d = new DOMParser().parseFromString(`<layout${namespaces}>${tag.replace(/\/?>(?:\s*)$/, '/>')}</layout>`, 'application/xml').documentElement) === null || _d === void 0 ? void 0 : _d.getElementsByTagName('*')[0];
76
+ const root = ((_c = /<(?:[\w.-]+:)?worksheet\b[^>]*>/.exec(header)) === null || _c === void 0 ? void 0 : _c[0]) || '';
77
+ const namespaces = ((_d = root.match(/\sxmlns(?::[\w.-]+)?\s*=\s*(?:"[^"]*"|'[^']*')/g)) === null || _d === void 0 ? void 0 : _d.join('')) || '';
78
+ const parser = new DOMParser();
79
+ const layout = tag ? (_e = parser.parseFromString(`<layout${namespaces}>${tag.replace(/\/?>(?:\s*)$/, '/>')}</layout>`, 'application/xml').documentElement) === null || _e === void 0 ? void 0 : _e.getElementsByTagName('*')[0] : undefined;
52
80
  const bounded = (name, max) => {
53
- const raw = element === null || element === void 0 ? void 0 : element.getAttribute(name);
81
+ const raw = layout === null || layout === void 0 ? void 0 : layout.getAttribute(name);
54
82
  if (raw == null || raw.trim() === '')
55
83
  return undefined;
56
84
  const value = Number(raw);
57
85
  return Number.isFinite(value) && value > 0 && value <= max ? value : undefined;
58
86
  };
59
- return { columnWidth: bounded('defaultColWidth', 255), rowHeightPt: bounded('defaultRowHeight', 409.5) };
87
+ const viewRoot = views ? (_f = parser.parseFromString(`<layout${namespaces}>${views}</layout>`, 'application/xml').documentElement) === null || _f === void 0 ? void 0 : _f.getElementsByTagName('*')[0] : undefined;
88
+ const freeze = viewRoot ? readFrozenPane(viewRoot) : undefined;
89
+ return {
90
+ columnWidth: bounded('defaultColWidth', 255),
91
+ rowHeightPt: bounded('defaultRowHeight', 409.5),
92
+ ...(freeze ? { freeze } : {})
93
+ };
60
94
  };
@@ -129,7 +129,12 @@ export interface SheetRowSizing {
129
129
  fixedRows: number[];
130
130
  autoHeightDisabled?: boolean;
131
131
  }
132
+ export interface SheetFreezePane {
133
+ rows: number;
134
+ columns: number;
135
+ }
132
136
  export interface SheetStructure {
137
+ freeze?: SheetFreezePane;
133
138
  rowSizing?: SheetRowSizing;
134
139
  merge?: CellMerge[];
135
140
  colWidths?: number | number[];
@@ -7,6 +7,7 @@ type EVirtTableInstance = {
7
7
  };
8
8
  scrollX?: number;
9
9
  scrollY?: number;
10
+ fixedLeftWidth?: number;
10
11
  containerElement: HTMLElement;
11
12
  isTarget(event: Event): boolean;
12
13
  selector?: {