@patrickdk77/office-defuse 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +278 -36
  2. package/dist/biff.d.ts +62 -0
  3. package/dist/biff.js +95 -0
  4. package/dist/cfb-writer.d.ts +25 -0
  5. package/dist/cfb-writer.js +314 -0
  6. package/dist/cfb.d.ts +58 -0
  7. package/dist/cfb.js +456 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +357 -0
  10. package/dist/contained.d.ts +46 -0
  11. package/dist/contained.js +152 -0
  12. package/dist/context.d.ts +140 -17
  13. package/dist/context.js +135 -37
  14. package/dist/crc32.d.ts +8 -2
  15. package/dist/crc32.js +44 -4
  16. package/dist/engine.d.ts +12 -1
  17. package/dist/engine.js +336 -42
  18. package/dist/errors.d.ts +17 -0
  19. package/dist/errors.js +27 -1
  20. package/dist/fields.d.ts +36 -0
  21. package/dist/fields.js +139 -0
  22. package/dist/findings.d.ts +2 -1
  23. package/dist/findings.js +44 -9
  24. package/dist/flat.d.ts +33 -0
  25. package/dist/flat.js +486 -0
  26. package/dist/formats.d.ts +7 -0
  27. package/dist/formats.js +5 -1
  28. package/dist/formulas.d.ts +27 -0
  29. package/dist/formulas.js +157 -1
  30. package/dist/index.d.ts +3 -2
  31. package/dist/index.js +8 -1
  32. package/dist/index.mjs +1 -1
  33. package/dist/io.d.ts +62 -1
  34. package/dist/io.js +245 -1
  35. package/dist/links.d.ts +27 -0
  36. package/dist/links.js +106 -1
  37. package/dist/msg.d.ts +8 -0
  38. package/dist/msg.js +251 -0
  39. package/dist/objects.d.ts +45 -0
  40. package/dist/objects.js +204 -0
  41. package/dist/odf.d.ts +66 -2
  42. package/dist/odf.js +181 -64
  43. package/dist/offcrypto.d.ts +54 -0
  44. package/dist/offcrypto.js +647 -0
  45. package/dist/ole.d.ts +12 -0
  46. package/dist/ole.js +139 -0
  47. package/dist/oleobj.d.ts +85 -0
  48. package/dist/oleobj.js +215 -0
  49. package/dist/ooxml.d.ts +83 -2
  50. package/dist/ooxml.js +358 -145
  51. package/dist/package.d.ts +3 -0
  52. package/dist/package.js +21 -0
  53. package/dist/plan.d.ts +104 -0
  54. package/dist/plan.js +73 -0
  55. package/dist/plugins.d.ts +8 -0
  56. package/dist/plugins.js +60 -0
  57. package/dist/ppt.d.ts +8 -0
  58. package/dist/ppt.js +281 -0
  59. package/dist/rewrite-cfb.d.ts +14 -0
  60. package/dist/rewrite-cfb.js +52 -0
  61. package/dist/rewrite-rtf.d.ts +9 -0
  62. package/dist/rewrite-rtf.js +45 -0
  63. package/dist/rewrite-xml.d.ts +36 -0
  64. package/dist/rewrite-xml.js +341 -0
  65. package/dist/rewrite-zip.d.ts +8 -0
  66. package/dist/rewrite-zip.js +498 -0
  67. package/dist/rtf.d.ts +8 -0
  68. package/dist/rtf.js +712 -0
  69. package/dist/rtfcomp.d.ts +7 -0
  70. package/dist/rtfcomp.js +80 -0
  71. package/dist/score.js +1 -1
  72. package/dist/sniff.d.ts +5 -0
  73. package/dist/sniff.js +38 -0
  74. package/dist/types.d.ts +66 -2
  75. package/dist/types.js +33 -0
  76. package/dist/vsd.d.ts +13 -0
  77. package/dist/vsd.js +689 -0
  78. package/dist/word.d.ts +9 -0
  79. package/dist/word.js +194 -0
  80. package/dist/xls.d.ts +27 -0
  81. package/dist/xls.js +208 -0
  82. package/dist/xml.d.ts +30 -0
  83. package/dist/xml.js +45 -23
  84. package/dist/zip-writer.d.ts +4 -0
  85. package/dist/zip-writer.js +20 -7
  86. package/dist/zip.d.ts +9 -2
  87. package/dist/zip.js +61 -4
  88. package/package.json +6 -3
package/dist/word.js ADDED
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wordRules = wordRules;
4
+ const errors_1 = require("./errors");
5
+ const fields_1 = require("./fields");
6
+ const io_1 = require("./io");
7
+ const offcrypto_1 = require("./offcrypto");
8
+ const oleobj_1 = require("./oleobj");
9
+ const types_1 = require("./types");
10
+ /** wIdent of Word 97 and later, and of Word 6.0 and 95 (MS-DOC 2.5.2). */
11
+ const WORD8 = 0xa5ec;
12
+ const WORD6 = 0xa5dc;
13
+ /** FibRgFcLcb97 pairs (MS-DOC 2.5.6): the attached template's table and the piece table. */
14
+ const FC_STTBF_ASSOC = 32;
15
+ const FC_CLX = 33;
16
+ /** In a Word 6.0 or 95 FIB, the length of the macro table that holds WordBasic macros. Word writes 2 for an empty one. */
17
+ const WORD6_MACROS = 0x11c;
18
+ /** In a Word 6.0 or 95 FIB, fcClx and lcbClx: where the piece table of a file saved fast lies in the WordDocument stream. */
19
+ const WORD6_CLX = 0x160;
20
+ /** Text is read in pieces of at most this many characters. */
21
+ const PIECE = 65536;
22
+ const u16 = (b, at) => b[at] | (b[at + 1] << 8);
23
+ /** A stream read through its decryption. */
24
+ const decrypted = (src, decrypt) => ({
25
+ size: () => src.size(),
26
+ read: async (offset, length) => decrypt(offset, await src.read(offset, length)),
27
+ });
28
+ const u32 = (b, at) => (b[at] | (b[at + 1] << 8) | (b[at + 2] << 16) | (b[at + 3] << 24)) >>> 0;
29
+ /**
30
+ * Inspects a Word 6.0 to 2003 document: its FIB, whether it is encrypted, the fields in its text and the template it
31
+ * attaches. Returns whether it is a template, or undefined for an `optional` stream that holds no FIB.
32
+ */
33
+ async function wordRules(ctx, cfb, stream, optional = false) {
34
+ let source = cfb.source(stream);
35
+ let fib = await source.read(0, 1024);
36
+ const ident = fib.length >= 32 ? u16(fib, 0) : 0;
37
+ if (ident !== WORD8 && ident !== WORD6) {
38
+ if (optional)
39
+ return undefined;
40
+ throw new errors_1.StopError(types_1.OfficeCategory.Package, types_1.OfficeDetail.Unrecognized, 'The WordDocument stream does not start with a Word FIB', { reason: 'a WordDocument stream without a FIB' });
41
+ }
42
+ const flags = u16(fib, 10);
43
+ const tableEntry = cfb.child(cfb.root, flags & 0x0200 ? '1Table' : '0Table');
44
+ let tableSource = tableEntry?.kind === 'stream' ? cfb.source(tableEntry) : undefined;
45
+ // fEncrypted, set for RC4, RC4 CryptoAPI and XOR obfuscation alike. Word 97 to 2003 documents are read through the
46
+ // decryption. A Word 6.0 or 95 document's encryption is another, which this reader does not undo.
47
+ if (flags & 0x0100) {
48
+ if (ident === WORD6 || !tableSource)
49
+ throw new errors_1.StopError(types_1.OfficeCategory.Encrypted, types_1.OfficeDetail.PasswordRequired, 'The document is encrypted', { stream: stream.name });
50
+ const key = await (0, offcrypto_1.unlockDocument)(ctx, fib, tableSource, stream.name);
51
+ source = decrypted(source, key.word);
52
+ tableSource = decrypted(tableSource, key.table);
53
+ fib = await source.read(0, 1024);
54
+ }
55
+ const location = stream.name;
56
+ const fields = new fields_1.FieldStack(ctx, location);
57
+ // Word marks a field's start, separator and end with 0x13, 0x14 and 0x15 in the text. Other control characters in
58
+ // a field's code, such as the 0x01 of a hyperlink's data, are not part of what it says.
59
+ const text = (s) => {
60
+ for (const ch of s) {
61
+ if (ch === '\x13')
62
+ fields.begin();
63
+ else if (ch === '\x14')
64
+ fields.separate();
65
+ else if (ch === '\x15')
66
+ fields.end();
67
+ else if (ch >= ' ' || ch === '\t') {
68
+ if (fields.inCode)
69
+ fields.text(ch);
70
+ else
71
+ fields.result(ch);
72
+ }
73
+ }
74
+ };
75
+ const reader = new io_1.Reader(source, stream.size, 65536, 8);
76
+ if (ident === WORD6) {
77
+ // Word 6.0 and 95 keep their text as 8-bit characters. A file saved fast (fComplex) adds pieces to the end, and its
78
+ // piece table, in the WordDocument stream itself at fcClx (FIB offset 0x160), gives their order. Any other file,
79
+ // or one whose piece table does not read, is read from fcMin to fcMac, every byte between, as msodde does.
80
+ const clxAt = u32(fib, WORD6_CLX);
81
+ const clxSize = u32(fib, WORD6_CLX + 4);
82
+ const list = flags & 0x0004 && clxSize > 0 && clxAt + clxSize <= stream.size ? pieces(await reader.read(clxAt, clxSize)).filter(p => !p.compressed && p.fc + p.length <= stream.size) : [];
83
+ if (list.length) {
84
+ for (const p of list) {
85
+ for (let cp = 0; cp < p.length; cp += PIECE) {
86
+ (0, errors_1.checkTime)(ctx.settings.deadline);
87
+ text(latin(await reader.read(p.fc + cp, Math.min(PIECE, p.length - cp))));
88
+ }
89
+ }
90
+ }
91
+ else {
92
+ const from = u32(fib, 0x18);
93
+ const to = Math.min(u32(fib, 0x1c), stream.size);
94
+ for (let at = from; at < to; at += PIECE) {
95
+ (0, errors_1.checkTime)(ctx.settings.deadline);
96
+ text(latin(await reader.read(at, Math.min(PIECE, to - at))));
97
+ }
98
+ }
99
+ if (fib.length >= WORD6_MACROS + 4 && u32(fib, WORD6_MACROS) > 2)
100
+ ctx.report(types_1.OfficeCategory.Macro, types_1.OfficeDetail.WordBasic, location, { stream: location, bytes: u32(fib, WORD6_MACROS) });
101
+ }
102
+ else {
103
+ const pairs = fcLcb(fib);
104
+ const table = tableEntry;
105
+ if (table?.kind === 'stream' && tableSource) {
106
+ const clx = pairs[FC_CLX];
107
+ if (clx && clx.lcb > 0 && clx.fc + clx.lcb <= table.size) {
108
+ for (const p of pieces(await tableSource.read(clx.fc, clx.lcb))) {
109
+ for (let cp = 0; cp < p.length; cp += PIECE) {
110
+ (0, errors_1.checkTime)(ctx.settings.deadline);
111
+ const n = Math.min(PIECE, p.length - cp);
112
+ if (p.compressed)
113
+ text(latin(await reader.read(p.fc + cp, n)));
114
+ else
115
+ text((0, oleobj_1.utf16)(await reader.read(p.fc + cp * 2, n * 2)));
116
+ }
117
+ }
118
+ }
119
+ const assoc = pairs[FC_STTBF_ASSOC];
120
+ if (assoc && assoc.lcb > 0 && assoc.fc + assoc.lcb <= table.size) {
121
+ // The attached template is string 1 of SttbfAssoc (MS-DOC 2.9.271).
122
+ const template = sttb(await tableSource.read(assoc.fc, Math.min(assoc.lcb, 65536)))[1] ?? '';
123
+ if (template.trim())
124
+ ctx.external(types_1.OfficeDetail.Template, template, location, { source: 'SttbfAssoc' }, 'template');
125
+ }
126
+ }
127
+ }
128
+ fields.finish();
129
+ return { template: (flags & 1) === 1 };
130
+ }
131
+ /** The fc and lcb pairs of a Word 97 FIB, after its variable-length arrays of 16- and 32-bit values. */
132
+ function fcLcb(fib) {
133
+ const r = new oleobj_1.ByteReader(fib);
134
+ const out = [];
135
+ return (0, oleobj_1.bounded)(() => {
136
+ r.skip(32);
137
+ r.skip(r.u16() * 2);
138
+ r.skip(r.u16() * 4);
139
+ const n = r.u16();
140
+ for (let i = 0; i < n; i++)
141
+ out.push({ fc: r.u32(), lcb: r.u32() });
142
+ return out;
143
+ }, () => out);
144
+ }
145
+ /** The pieces of a Clx (MS-DOC 2.9.38): where each run of text is, and whether it is stored 8 bits a character. */
146
+ function pieces(clx) {
147
+ const r = new oleobj_1.ByteReader(clx);
148
+ const out = [];
149
+ return (0, oleobj_1.bounded)(() => {
150
+ // Prc entries of formatting come first, each with its size.
151
+ while (r.left > 0 && clx[r.pos] === 0x01) {
152
+ r.skip(1);
153
+ r.skip(r.u16());
154
+ }
155
+ if (r.u8() !== 0x02)
156
+ return out;
157
+ const lcb = r.u32();
158
+ const n = Math.floor((lcb - 4) / 12);
159
+ const plc = new oleobj_1.ByteReader(r.bytes(Math.min(lcb, r.left)));
160
+ const cps = [];
161
+ for (let i = 0; i <= n; i++)
162
+ cps.push(plc.u32());
163
+ for (let i = 0; i < n; i++) {
164
+ plc.skip(2);
165
+ const fc = plc.u32();
166
+ plc.skip(2);
167
+ const length = cps[i + 1] - cps[i];
168
+ if (length <= 0)
169
+ continue;
170
+ const compressed = (fc & 0x40000000) !== 0;
171
+ out.push({ fc: compressed ? (fc & 0x3fffffff) / 2 : fc, length, compressed });
172
+ }
173
+ return out;
174
+ }, () => []);
175
+ }
176
+ /** The strings of an STTB (MS-DOC 2.2.4), in 16-bit characters when it starts with 0xFFFF, as Word 97 writes one. */
177
+ function sttb(b) {
178
+ const r = new oleobj_1.ByteReader(b);
179
+ const out = [];
180
+ return (0, oleobj_1.bounded)(() => {
181
+ const wide = r.u16() === 0xffff;
182
+ if (!wide)
183
+ r.pos = 0;
184
+ const count = r.u16();
185
+ const extra = r.u16();
186
+ for (let i = 0; i < count; i++) {
187
+ const n = wide ? r.u16() : r.u8();
188
+ out.push(wide ? (0, oleobj_1.utf16)(r.bytes(n * 2)) : latin(r.bytes(n)));
189
+ r.skip(extra);
190
+ }
191
+ return out;
192
+ }, () => out);
193
+ }
194
+ const latin = (b) => Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString('latin1');
package/dist/xls.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { type BiffRecord } from './biff';
2
+ import type { CfbEntry, CompoundFile } from './cfb';
3
+ import { type RunContext } from './context';
4
+ /** Turns an encrypted record body into its plain bytes. Without encryption the body is as stored. */
5
+ export type Decrypt = (r: BiffRecord) => Uint8Array;
6
+ /**
7
+ * Opens a workbook encrypted by its FILEPASS record, or says it cannot. Set by the decryption module, so this module
8
+ * reads workbooks without knowing how they are encrypted.
9
+ */
10
+ export type Unlock = (ctx: RunContext, filePass: BiffRecord, stream: string) => Decrypt | Promise<Decrypt>;
11
+ /**
12
+ * Inspects an Excel 5.0 to 2003 workbook stream. Excel reads the globals substream from the start of the stream,
13
+ * then each sheet from where its BoundSheet record says the sheet starts. The globals give the macro sheets, the
14
+ * names Excel runs as macros, and the DDE, OLE and workbook links. The sheets give shapes that run macros and
15
+ * hyperlinks. An encrypted workbook goes through `unlock`.
16
+ */
17
+ export declare function excelRules(ctx: RunContext, cfb: CompoundFile, stream: CfbEntry, unlock: Unlock): Promise<{
18
+ template: boolean;
19
+ addIn: boolean;
20
+ }>;
21
+ /**
22
+ * A VirtualPath (MS-XLS 2.5.277) written out. One that starts with U+0001 is encoded: its control characters name a
23
+ * volume, the root, a folder, a step up, a URL's volume or Excel's startup folders.
24
+ */
25
+ export declare function virtualPath(p: string): string;
26
+ /** The target of an HLink record: its Hyperlink Object (MS-OSHARED 2.3.7.1) after the cell range and class id. */
27
+ export declare function hyperlink(b: Uint8Array): string;
package/dist/xls.js ADDED
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.excelRules = excelRules;
4
+ exports.virtualPath = virtualPath;
5
+ exports.hyperlink = hyperlink;
6
+ const biff_1 = require("./biff");
7
+ const context_1 = require("./context");
8
+ const errors_1 = require("./errors");
9
+ const formulas_1 = require("./formulas");
10
+ const links_1 = require("./links");
11
+ const oleobj_1 = require("./oleobj");
12
+ const types_1 = require("./types");
13
+ const STATES = ['visible', 'hidden', 'very hidden', 'hidden'];
14
+ /** Record types of cell formulas (MS-XLS 2.4.127, 2.4.260 and 2.4.4): FORMULA, SHRFMLA and ARRAY. */
15
+ const FORMULA = 0x0006;
16
+ const SHRFMLA = 0x04bc;
17
+ const ARRAY = 0x0221;
18
+ /** Where the parsed formula starts in each: its cce, then its rgce. */
19
+ const FORMULA_AT = new Map([
20
+ [FORMULA, 20],
21
+ [SHRFMLA, 8],
22
+ [ARRAY, 12],
23
+ ]);
24
+ /**
25
+ * Inspects an Excel 5.0 to 2003 workbook stream. Excel reads the globals substream from the start of the stream,
26
+ * then each sheet from where its BoundSheet record says the sheet starts. The globals give the macro sheets, the
27
+ * names Excel runs as macros, and the DDE, OLE and workbook links. The sheets give shapes that run macros and
28
+ * hyperlinks. An encrypted workbook goes through `unlock`.
29
+ */
30
+ async function excelRules(ctx, cfb, stream, unlock) {
31
+ const location = stream.name;
32
+ const records = new biff_1.RecordReader(cfb, stream, 0, ctx.settings.deadline);
33
+ const first = await records.next();
34
+ if (first?.type !== biff_1.R.bof || first.body.length < 4)
35
+ throw new errors_1.StopError(types_1.OfficeCategory.Package, types_1.OfficeDetail.Unrecognized, `The ${stream.name} stream does not start with a BOF record`, { reason: 'a workbook stream without a BOF record' });
36
+ const biff8 = (first.body[0] | (first.body[1] << 8)) === 0x0600;
37
+ let decrypt = r => r.body;
38
+ const sheets = [];
39
+ const books = [];
40
+ const names = [];
41
+ /** The SupBook each XTI of the ExternSheet record names. */
42
+ const xti = [];
43
+ const flags = { template: false, addIn: false };
44
+ for (let r = await records.next(); r && r.type !== biff_1.R.eof; r = await records.next()) {
45
+ if (r.type === biff_1.R.filePass) {
46
+ decrypt = await unlock(ctx, r, location);
47
+ continue;
48
+ }
49
+ const body = decrypt(r);
50
+ if (r.type === biff_1.R.boundSheet)
51
+ sheets.push((0, biff_1.parseBoundSheet)(body, biff8));
52
+ else if (r.type === biff_1.R.template)
53
+ flags.template = true;
54
+ else if (r.type === biff_1.R.addIn)
55
+ flags.addIn = true;
56
+ else if (r.type === biff_1.R.lbl) {
57
+ const name = (0, biff_1.parseLbl)(body, biff8);
58
+ names.push(name.name);
59
+ const auto = (0, biff_1.autoName)(name.name);
60
+ if (auto)
61
+ ctx.report(types_1.OfficeCategory.Macro, auto.onOpen ? types_1.OfficeDetail.EventOnOpen : types_1.OfficeDetail.Event, location, { event: auto.event, name: (0, context_1.clip)(name.name) });
62
+ }
63
+ else if (r.type === biff_1.R.supBook && body.length >= 4) {
64
+ const cch = body[2] | (body[3] << 8);
65
+ books.push({ ctab: body[0] | (body[1] << 8), cch, path: cch > 0 && cch <= 0xff ? (0, biff_1.xlString)(body, 4, cch).text : '', ole: false, dde: false, names: [] });
66
+ }
67
+ else if (r.type === biff_1.R.externSheet && biff8 && body.length >= 2) {
68
+ const n = body[0] | (body[1] << 8);
69
+ for (let k = 0; k < n && 2 + k * 6 + 2 <= body.length; k++)
70
+ xti.push(body[2 + k * 6] | (body[3 + k * 6] << 8));
71
+ }
72
+ else if (r.type === biff_1.R.externName && body.length >= 2 && books.length) {
73
+ if (biff8 && body.length >= 7)
74
+ books[books.length - 1].names.push((0, biff_1.xlString)(body, 7, body[6]).text);
75
+ // fOle and fOleLink mark an OLE object's name. Excel writes StdDocumentName with fOle beside the items of a DDE
76
+ // link, so a link with any DDE item is a DDE link.
77
+ if ((body[0] | (body[1] << 8)) & 0x18)
78
+ books[books.length - 1].ole = true;
79
+ else
80
+ books[books.length - 1].dde = true;
81
+ }
82
+ }
83
+ for (const b of books)
84
+ linkRules(ctx, b, location);
85
+ const nameOf = (ref) => (ref.kind === 'name' ? names[ref.index - 1] : books[xti[ref.ixti] ?? -1]?.names[ref.index - 1]);
86
+ for (const s of sheets)
87
+ await sheetRules(ctx, cfb, stream, s, decrypt, location, biff8 ? nameOf : undefined);
88
+ return flags;
89
+ }
90
+ /** A SupBook record, read as MS-XLS 2.4.271 and oletools tell its kinds apart. */
91
+ function linkRules(ctx, b, location) {
92
+ if (b.cch === 0x401 || b.cch === 0x3a01 || b.path === ' ' || b.path === '\0' || !b.path)
93
+ return;
94
+ if (b.ctab === 0) {
95
+ // A DDE or OLE data source: the application or class, U+0003, and the topic or file.
96
+ const [application, topic = ''] = b.path.split('\x03');
97
+ if (b.ole && !b.dde) {
98
+ const data = { source: 'SupBook', className: (0, context_1.clip)(application) };
99
+ if (topic)
100
+ ctx.external(types_1.OfficeDetail.Object, topic, location, data, 'linked object');
101
+ else
102
+ ctx.report(types_1.OfficeCategory.External, types_1.OfficeDetail.Object, location, data);
103
+ }
104
+ else
105
+ ctx.report(types_1.OfficeCategory.Dde, types_1.OfficeDetail.Link, location, { application: (0, context_1.clip)(application), topic: (0, context_1.clip)(topic) });
106
+ return;
107
+ }
108
+ ctx.external(types_1.OfficeDetail.Workbook, virtualPath(b.path), location, { source: 'SupBook' }, 'external workbook');
109
+ }
110
+ /**
111
+ * A VirtualPath (MS-XLS 2.5.277) written out. One that starts with U+0001 is encoded: its control characters name a
112
+ * volume, the root, a folder, a step up, a URL's volume or Excel's startup folders.
113
+ */
114
+ function virtualPath(p) {
115
+ if (p.charCodeAt(0) !== 1)
116
+ return p;
117
+ let out = '';
118
+ for (let i = 1; i < p.length; i++) {
119
+ const c = p.charCodeAt(i);
120
+ if (c === 1) {
121
+ // A drive letter, or @ for a UNC host. A U+0003 after it starts the path.
122
+ const v = p[i + 1] ?? '';
123
+ i++;
124
+ out += v === '@' ? '\\\\' : `${v}:`;
125
+ }
126
+ else if (c === 2 || c === 3)
127
+ out += '\\';
128
+ else if (c === 4)
129
+ out += '..\\';
130
+ // A long volume, such as a URL, after a character that counts it.
131
+ else if (c === 5)
132
+ i++;
133
+ else if (c >= 6 && c <= 8)
134
+ out += 'XLSTART\\';
135
+ else
136
+ out += p[i];
137
+ }
138
+ return out;
139
+ }
140
+ /** One sheet's substream, with any chart substreams inside it: Obj records that run macros, and hyperlinks. */
141
+ async function sheetRules(ctx, cfb, stream, s, decrypt, location, nameOf) {
142
+ const records = new biff_1.RecordReader(cfb, stream, s.position, ctx.settings.deadline);
143
+ const bof = await records.next();
144
+ if (bof?.type !== biff_1.R.bof || bof.body.length < 4)
145
+ return;
146
+ const bofType = bof.body[2] | (bof.body[3] << 8);
147
+ // The sheet's own BOF says what it is, and so does its BoundSheet record. Either one makes a macro sheet.
148
+ const macroSheet = s.type === 1 || bofType === 0x0040;
149
+ if (macroSheet)
150
+ ctx.report(types_1.OfficeCategory.Macro, types_1.OfficeDetail.XlmMacrosheet, location, { sheet: (0, context_1.clip)(s.name), state: STATES[s.state] });
151
+ let depth = 1;
152
+ for (let r = await records.next(); r && depth > 0; r = await records.next()) {
153
+ if (r.type === biff_1.R.bof)
154
+ depth++;
155
+ else if (r.type === biff_1.R.eof)
156
+ depth--;
157
+ else if (r.type === biff_1.R.obj) {
158
+ if (objMacro(decrypt(r)))
159
+ ctx.report(types_1.OfficeCategory.Macro, types_1.OfficeDetail.Link, location, { sheet: (0, context_1.clip)(s.name) });
160
+ }
161
+ else if (r.type === biff_1.R.hlink) {
162
+ const target = hyperlink(decrypt(r));
163
+ if (target.trim() && !(0, links_1.isFragment)(target))
164
+ ctx.link(target, location, { sheet: (0, context_1.clip)(s.name), source: 'HLink record' });
165
+ }
166
+ else if (nameOf && !macroSheet && FORMULA_AT.has(r.type)) {
167
+ // A macro sheet's formulas are its macros, which its own finding covers.
168
+ const b = decrypt(r);
169
+ const at = FORMULA_AT.get(r.type) ?? 0;
170
+ if (b.length < at + 2)
171
+ continue;
172
+ const cce = b[at] | (b[at + 1] << 8);
173
+ for (const [fn, kind] of (0, formulas_1.biffCalls)(b.subarray(at + 2, at + 2 + cce), nameOf))
174
+ ctx.report(kind === 'fetch' ? types_1.OfficeCategory.External : types_1.OfficeCategory.Macro, types_1.OfficeDetail.Formula, location, { sheet: (0, context_1.clip)(s.name), function: (0, context_1.clip)(fn) });
175
+ }
176
+ }
177
+ }
178
+ /** Whether an Obj record (MS-XLS 2.4.181) holds an FtMacro subrecord, the macro a click runs. */
179
+ function objMacro(b) {
180
+ let at = 0;
181
+ while (at + 4 <= b.length) {
182
+ const ft = b[at] | (b[at + 1] << 8);
183
+ const cb = b[at + 2] | (b[at + 3] << 8);
184
+ // FtEnd ends the list, and FtLbsData's length does not count all its data, so the walk stops there.
185
+ if (ft === 0x00 || ft === 0x13)
186
+ return false;
187
+ if (ft === 0x04)
188
+ return cb > 0;
189
+ at += 4 + cb;
190
+ }
191
+ return false;
192
+ }
193
+ /** The target of an HLink record: its Hyperlink Object (MS-OSHARED 2.3.7.1) after the cell range and class id. */
194
+ function hyperlink(b) {
195
+ const r = new oleobj_1.ByteReader(b);
196
+ return (0, oleobj_1.bounded)(() => {
197
+ r.skip(8 + 16 + 4);
198
+ const flags = r.u32();
199
+ const string = () => (0, oleobj_1.utf16)(r.bytes(r.u32() * 2)).replace(/\0+$/, '');
200
+ if (flags & 0x10)
201
+ string();
202
+ if (flags & 0x80)
203
+ string();
204
+ if (!(flags & 0x01))
205
+ return '';
206
+ return flags & 0x100 ? string() : (0, oleobj_1.readMoniker)(r).target;
207
+ }, () => '');
208
+ }
package/dist/xml.d.ts CHANGED
@@ -32,6 +32,17 @@ export interface XmlElement {
32
32
  */
33
33
  start: number;
34
34
  end: number;
35
+ /** The element's position among the elements of the part, from 0, counting those in entity text. */
36
+ index: number;
37
+ /** The namespace declarations of the start tag, as prefix ('' for the default namespace) and URI, defaults included. */
38
+ namespaces: Array<[string, string]>;
39
+ /** Written as an empty-element tag. */
40
+ empty: boolean;
41
+ /**
42
+ * The start tag does not say on its own what the attributes are: a value refers to an entity the internal subset
43
+ * declares, or an attribute-list declaration added a default or normalized a value.
44
+ */
45
+ rewritten: boolean;
35
46
  }
36
47
  export interface XmlHandler {
37
48
  start?(el: XmlElement): void;
@@ -87,6 +98,12 @@ export interface XmlExternalReference {
87
98
  export interface XmlNotes {
88
99
  doctype?(d: XmlDoctype): void;
89
100
  externalEntity?(r: XmlExternalReference): void;
101
+ /**
102
+ * A reference to an internal entity in content, outside any other entity's text, at these offsets. The events of
103
+ * its text come between this call and `referenceEnd`.
104
+ */
105
+ referenceStart?(start: number, end: number): void;
106
+ referenceEnd?(): void;
90
107
  }
91
108
  export interface XmlOptions {
92
109
  /** Reads the dialect Office writes in VML drawing parts. See XmlTokenizer. */
@@ -99,6 +116,15 @@ export interface XmlOptions {
99
116
  export declare function attr(el: XmlElement, ns: string, local: string): string | undefined;
100
117
  /** An XML name without a colon. */
101
118
  export declare const isNcName: (s: string) => boolean;
119
+ export type XmlEncoding = 'utf-8' | 'utf-16le' | 'utf-16be';
120
+ /**
121
+ * The encoding of an XML part from its first four bytes, as XML 1.0 Appendix F tells it, and the length of its byte
122
+ * order mark. Undefined for UTF-32, which no Office application reads.
123
+ */
124
+ export declare function detectEncoding(b: Uint8Array): {
125
+ encoding: XmlEncoding;
126
+ bom: number;
127
+ } | undefined;
102
128
  /**
103
129
  * A streaming XML 1.0 tokenizer with namespaces. It refuses references to entities nothing declares, encodings other
104
130
  * than UTF-8 and UTF-16, and anything not well-formed. It holds one markup token at a time; text goes to the handler
@@ -133,6 +159,10 @@ export declare class XmlTokenizer {
133
159
  /** The XML declaration says standalone="yes". */
134
160
  private standalone;
135
161
  private encoding;
162
+ /** Start tags read so far, which numbers the elements. */
163
+ private elements;
164
+ /** An attribute value of the tag being read referred to an entity of the internal subset. */
165
+ private generalReference;
136
166
  /** The last text piece ended in CR, so an LF that starts the next piece belongs to the same line end. */
137
167
  private lastCr;
138
168
  private scan?;
package/dist/xml.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.XmlTokenizer = exports.isNcName = exports.unknownEntity = exports.showReferences = exports.UNKNOWN = exports.XMLNS_NS = exports.XML_NS = void 0;
4
4
  exports.attr = attr;
5
+ exports.detectEncoding = detectEncoding;
5
6
  const node_util_1 = require("node:util");
6
7
  const errors_1 = require("./errors");
7
8
  const types_1 = require("./types");
@@ -53,6 +54,26 @@ const NAME_END = /[\s>[\]"'%;&<]/;
53
54
  /** Attribute types other than CDATA, whose values are normalized further. NOTATION and enumerations are read apart. */
54
55
  const TOKENIZED_TYPES = new Set(['ID', 'IDREF', 'IDREFS', 'ENTITY', 'ENTITIES', 'NMTOKEN', 'NMTOKENS']);
55
56
  const LIMIT_DETAILS = new Set([types_1.OfficeDetail.XmlDepth, types_1.OfficeDetail.XmlTokenSize, types_1.OfficeDetail.XmlEntityDepth, types_1.OfficeDetail.XmlEntityExpansions, types_1.OfficeDetail.XmlEntitySize]);
57
+ /**
58
+ * The encoding of an XML part from its first four bytes, as XML 1.0 Appendix F tells it, and the length of its byte
59
+ * order mark. Undefined for UTF-32, which no Office application reads.
60
+ */
61
+ function detectEncoding(b) {
62
+ const at = (i) => (i < b.length ? b[i] : -1);
63
+ if ((at(0) === 0 && at(1) === 0) || (at(0) === 0xff && at(1) === 0xfe && at(2) === 0 && at(3) === 0) || (at(0) === 0x3c && at(1) === 0 && at(2) === 0 && at(3) === 0))
64
+ return undefined;
65
+ if (at(0) === 0xef && at(1) === 0xbb && at(2) === 0xbf)
66
+ return { encoding: 'utf-8', bom: 3 };
67
+ if (at(0) === 0xff && at(1) === 0xfe)
68
+ return { encoding: 'utf-16le', bom: 2 };
69
+ if (at(0) === 0xfe && at(1) === 0xff)
70
+ return { encoding: 'utf-16be', bom: 2 };
71
+ if (at(0) === 0x3c && at(1) === 0 && at(2) === 0x3f && at(3) === 0)
72
+ return { encoding: 'utf-16le', bom: 0 };
73
+ if (at(0) === 0 && at(1) === 0x3c && at(2) === 0 && at(3) === 0x3f)
74
+ return { encoding: 'utf-16be', bom: 0 };
75
+ return { encoding: 'utf-8', bom: 0 };
76
+ }
56
77
  const isSpace = (c) => c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d;
57
78
  /** A character XML 1.0 allows. The decoders leave no lone surrogates, so the halves of a pair pass here. */
58
79
  const isXmlChar = (c) => c === 0x09 || c === 0x0a || c === 0x0d || (c >= 0x20 && c !== 0xfffe && c !== 0xffff);
@@ -169,6 +190,10 @@ class XmlTokenizer {
169
190
  /** The XML declaration says standalone="yes". */
170
191
  standalone = false;
171
192
  encoding = 'utf-8';
193
+ /** Start tags read so far, which numbers the elements. */
194
+ elements = 0;
195
+ /** An attribute value of the tag being read referred to an entity of the internal subset. */
196
+ generalReference = false;
172
197
  /** The last text piece ended in CR, so an LF that starts the next piece belongs to the same line end. */
173
198
  lastCr = false;
174
199
  scan;
@@ -227,29 +252,14 @@ class XmlTokenizer {
227
252
  /** Picks the encoding from the first bytes, as XML 1.0 Appendix F does, and reads the bytes held so far. */
228
253
  begin() {
229
254
  const b = this.head;
230
- const at = (i) => (i < b.length ? b[i] : -1);
231
- if ((at(0) === 0 && at(1) === 0) || (at(0) === 0xff && at(1) === 0xfe && at(2) === 0 && at(3) === 0) || (at(0) === 0x3c && at(1) === 0 && at(2) === 0 && at(3) === 0)) {
232
- this.stop(types_1.OfficeDetail.Encoding, 'UTF-32 is not an encoding Office reads');
233
- }
234
- let skip = 0;
235
- if (at(0) === 0xef && at(1) === 0xbb && at(2) === 0xbf)
236
- skip = 3;
237
- else if (at(0) === 0xff && at(1) === 0xfe) {
238
- this.encoding = 'utf-16le';
239
- skip = 2;
240
- }
241
- else if (at(0) === 0xfe && at(1) === 0xff) {
242
- this.encoding = 'utf-16be';
243
- skip = 2;
244
- }
245
- else if (at(0) === 0x3c && at(1) === 0 && at(2) === 0x3f && at(3) === 0)
246
- this.encoding = 'utf-16le';
247
- else if (at(0) === 0 && at(1) === 0x3c && at(2) === 0 && at(3) === 0x3f)
248
- this.encoding = 'utf-16be';
255
+ const found = detectEncoding(b);
256
+ if (!found)
257
+ return this.stop(types_1.OfficeDetail.Encoding, 'UTF-32 is not an encoding Office reads');
258
+ this.encoding = found.encoding;
249
259
  const decoder = new node_util_1.TextDecoder(this.encoding, { fatal: true, ignoreBOM: true });
250
260
  this.decoder = decoder;
251
261
  this.head = new Uint8Array(0);
252
- this.feed(this.decode(decoder, b.subarray(skip), true), false);
262
+ this.feed(this.decode(decoder, b.subarray(found.bom), true), false);
253
263
  return decoder;
254
264
  }
255
265
  decode(decoder, bytes, more) {
@@ -467,6 +477,8 @@ class XmlTokenizer {
467
477
  return;
468
478
  }
469
479
  this.enter(name, e.text);
480
+ if (!this.span)
481
+ this.notes.referenceStart?.(start, end);
470
482
  const { buf, pos, base, floor, span: outer } = this;
471
483
  this.buf = e.text;
472
484
  this.pos = 0;
@@ -482,6 +494,8 @@ class XmlTokenizer {
482
494
  this.floor = floor;
483
495
  this.span = outer;
484
496
  this.active.pop();
497
+ if (!outer)
498
+ this.notes.referenceEnd?.();
485
499
  }
486
500
  /** A reference to a general entity in an attribute value. Its text is normalized into the value. */
487
501
  attributeReference(name) {
@@ -489,6 +503,7 @@ class XmlTokenizer {
489
503
  if (!('text' in e))
490
504
  this.malformed(`A reference to external entity "${name}" in an attribute value`);
491
505
  this.enter(name, e.text);
506
+ this.generalReference = true;
492
507
  const value = this.attributeValue(e.text, true);
493
508
  this.active.pop();
494
509
  return value;
@@ -981,6 +996,7 @@ class XmlTokenizer {
981
996
  const qname = body.slice(0, i);
982
997
  const raw = [];
983
998
  let selfClosing = this.vml && qname.toLowerCase() === 'br';
999
+ this.generalReference = false;
984
1000
  for (;;) {
985
1001
  const before = i;
986
1002
  while (i < n && isSpace(body.charCodeAt(i)))
@@ -1017,18 +1033,24 @@ class XmlTokenizer {
1017
1033
  // Attribute-list declarations normalize the attributes they type, and add the defaults the tag leaves out. Each
1018
1034
  // default added counts against the entity limits, so declarations cannot multiply the work of a long part.
1019
1035
  const declared = this.declared.get(qname);
1036
+ let rewritten = this.generalReference;
1020
1037
  if (declared) {
1021
1038
  const given = new Set();
1022
1039
  for (const a of raw) {
1023
1040
  given.add(a[0]);
1024
- if (declared.tokenized.has(a[0]))
1025
- a[1] = tokenize(a[1]);
1041
+ if (!declared.tokenized.has(a[0]))
1042
+ continue;
1043
+ const v = tokenize(a[1]);
1044
+ if (v !== a[1])
1045
+ rewritten = true;
1046
+ a[1] = v;
1026
1047
  }
1027
1048
  for (const [name, value] of declared.defaults) {
1028
1049
  if (given.has(name))
1029
1050
  continue;
1030
1051
  this.charge(value.length);
1031
1052
  raw.push([name, value]);
1053
+ rewritten = true;
1032
1054
  }
1033
1055
  }
1034
1056
  const scope = new Map();
@@ -1061,7 +1083,7 @@ class XmlTokenizer {
1061
1083
  const depth = this.stack.length + 1;
1062
1084
  if (depth > this.limits.depth)
1063
1085
  this.stop(types_1.OfficeDetail.XmlDepth, `Elements nest deeper than ${this.limits.depth}`);
1064
- const el = { ns: '', local: '', qname, attributes: [], depth, start, end };
1086
+ const el = { ns: '', local: '', qname, attributes: [], depth, start, end, index: this.elements++, namespaces: [...scope], empty: selfClosing, rewritten };
1065
1087
  const open = { el, scope: scope.size ? scope : undefined };
1066
1088
  this.stack.push(open);
1067
1089
  const [prefix, local] = this.split(qname);
@@ -24,6 +24,8 @@ export declare class ZipWriter {
24
24
  constructor(sink: ByteSink, options?: {
25
25
  forceZip64?: boolean;
26
26
  });
27
+ /** Bytes written so far: where the next entry's local header goes. */
28
+ get position(): number;
27
29
  private put;
28
30
  /** Adds an entry from bytes in memory, deflated unless `compress` is false. A name ending in "/" is a directory. */
29
31
  add(name: string, data: Uint8Array, options?: {
@@ -31,6 +33,8 @@ export declare class ZipWriter {
31
33
  dosTime?: number;
32
34
  dosDate?: number;
33
35
  }): Promise<void>;
36
+ /** The local header `copy` writes for an entry. */
37
+ localHeader(info: CopiedEntry): Uint8Array;
34
38
  /** Adds an entry whose compressed bytes come from `chunks` unchanged, such as an entry of the archive being rewritten. */
35
39
  copy(info: CopiedEntry, chunks: AsyncIterable<Uint8Array>): Promise<void>;
36
40
  /** Writes the central directory and the end records. The caller closes the sink. */