@file-viewer/renderer-email 3.1.1 → 3.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.
- package/README.en.md +3 -36
- package/README.md +3 -36
- package/dist/email.d.ts +7 -0
- package/dist/email.js +216 -105
- package/dist/emailHtml.d.ts +3 -0
- package/dist/emailHtml.js +191 -0
- package/dist/msg.d.ts +60 -0
- package/dist/msg.js +229 -0
- package/dist/msgCfb.d.ts +4 -0
- package/dist/msgCfb.js +171 -0
- package/dist/msgEncoding.d.ts +2 -0
- package/dist/msgEncoding.js +52 -0
- package/dist/msgMessages.d.ts +5 -0
- package/dist/msgMessages.js +32 -0
- package/dist/msgRtf.d.ts +7 -0
- package/dist/msgRtf.js +234 -0
- package/package.json +29 -19
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
export const normalizeEmailResourceId = (value) => {
|
|
2
|
+
const isUri = /^cid:/i.test(value.trim());
|
|
3
|
+
let result = value.trim().replace(/^cid:/i, '').replace(/^<|>$/g, '');
|
|
4
|
+
if (isUri) {
|
|
5
|
+
try {
|
|
6
|
+
result = decodeURIComponent(result);
|
|
7
|
+
}
|
|
8
|
+
catch { }
|
|
9
|
+
}
|
|
10
|
+
return result;
|
|
11
|
+
};
|
|
12
|
+
export function createEmailImageResource(buffer, mimeType, objectUrls) {
|
|
13
|
+
if (typeof URL.createObjectURL === 'function') {
|
|
14
|
+
const url = URL.createObjectURL(new Blob([buffer], { type: mimeType }));
|
|
15
|
+
if (!url.startsWith('blob:null/')) {
|
|
16
|
+
objectUrls.push(url);
|
|
17
|
+
return url;
|
|
18
|
+
}
|
|
19
|
+
URL.revokeObjectURL(url);
|
|
20
|
+
}
|
|
21
|
+
const bytes = new Uint8Array(buffer);
|
|
22
|
+
const parts = [];
|
|
23
|
+
for (let offset = 0; offset < bytes.length; offset += 24576) {
|
|
24
|
+
parts.push(btoa(String.fromCharCode(...bytes.subarray(offset, offset + 24576))));
|
|
25
|
+
}
|
|
26
|
+
return `data:${mimeType};base64,${parts.join('')}`;
|
|
27
|
+
}
|
|
28
|
+
const ALLOWED_TAGS = new Set('a abbr address article aside b bdi bdo big blockquote br caption center cite code col colgroup dd del details div dl dt em figcaption figure font footer h1 h2 h3 h4 h5 h6 header hr i img ins kbd label li main mark ol p pre q rp rt ruby s samp section small span strike strong style sub summary sup table tbody td tfoot th thead time title tr tt u ul var wbr'.split(' '));
|
|
29
|
+
const DROP_CONTENT = new Set('script iframe frame frameset object embed applet svg math template noscript audio video source track input link meta base'.split(' '));
|
|
30
|
+
const ALLOWED_ATTRS = new Set('alt title class id style width height align valign bgcolor color face size border cellpadding cellspacing colspan rowspan dir lang role aria-label scope start type value open name text'.split(' '));
|
|
31
|
+
const SAFE_IMAGE = /^data:image\/(?:png|jpeg|gif|webp|avif|bmp);base64,[a-z0-9+/=\r\n]+$/i;
|
|
32
|
+
export function createEmailHtmlDocument(html, resources, darkMode = false, documentRef = document) {
|
|
33
|
+
var _a, _b;
|
|
34
|
+
if (html.length > 32 * 1024 * 1024)
|
|
35
|
+
throw new Error('Email HTML exceeds the safety limit.');
|
|
36
|
+
const template = documentRef.createElement('template');
|
|
37
|
+
const inertDocument = template.content.ownerDocument;
|
|
38
|
+
if (inertDocument.defaultView)
|
|
39
|
+
throw new Error('Email parsing requires an inert template document.');
|
|
40
|
+
const parsed = inertDocument.createElement('html');
|
|
41
|
+
parsed.innerHTML = html;
|
|
42
|
+
const rootAttributes = (_a = /^\s*(?:<!doctype[^>]*>\s*)?<html\b((?:[^>"']|"[^"]*"|'[^']*')*)>/i.exec(html.slice(0, 16384))) === null || _a === void 0 ? void 0 : _a[1];
|
|
43
|
+
if (rootAttributes) {
|
|
44
|
+
const probe = inertDocument.createElement('div');
|
|
45
|
+
probe.innerHTML = `<div${rootAttributes}></div>`;
|
|
46
|
+
for (const name of ['lang', 'dir']) {
|
|
47
|
+
const value = (_b = probe.firstElementChild) === null || _b === void 0 ? void 0 : _b.getAttribute(name);
|
|
48
|
+
if (value)
|
|
49
|
+
parsed.setAttribute(name, value);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const head = parsed.querySelector('head') || inertDocument.createElement('head');
|
|
53
|
+
const body = parsed.querySelector('body') || inertDocument.createElement('body');
|
|
54
|
+
const ownedUrls = new Set(resources.values());
|
|
55
|
+
const lookup = (value) => {
|
|
56
|
+
const trimmed = value.trim();
|
|
57
|
+
if (ownedUrls.has(trimmed) && /^blob:/.test(trimmed))
|
|
58
|
+
return trimmed;
|
|
59
|
+
if (SAFE_IMAGE.test(trimmed))
|
|
60
|
+
return trimmed;
|
|
61
|
+
const key = normalizeEmailResourceId(trimmed);
|
|
62
|
+
let exact = resources.get(key);
|
|
63
|
+
if (!exact && !/^cid:/i.test(trimmed)) {
|
|
64
|
+
try {
|
|
65
|
+
exact = resources.get(decodeURIComponent(key));
|
|
66
|
+
}
|
|
67
|
+
catch { }
|
|
68
|
+
}
|
|
69
|
+
if (exact && (/^blob:/.test(exact) || SAFE_IMAGE.test(exact)))
|
|
70
|
+
return exact;
|
|
71
|
+
if (/^cid:/i.test(trimmed)) {
|
|
72
|
+
const matches = [...resources].filter(([id]) => id.toLowerCase() === key.toLowerCase());
|
|
73
|
+
if (matches.length === 1 && (/^blob:/.test(matches[0][1]) || SAFE_IMAGE.test(matches[0][1])))
|
|
74
|
+
return matches[0][1];
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
};
|
|
78
|
+
let expandedResourceCharacters = 0;
|
|
79
|
+
const resource = (value) => {
|
|
80
|
+
const resolved = lookup(value);
|
|
81
|
+
if (resolved) {
|
|
82
|
+
expandedResourceCharacters += resolved.length;
|
|
83
|
+
if (expandedResourceCharacters > 48 * 1024 * 1024)
|
|
84
|
+
throw new Error('Email inline resource expansion limit exceeded.');
|
|
85
|
+
}
|
|
86
|
+
return resolved;
|
|
87
|
+
};
|
|
88
|
+
const css = (value) => value
|
|
89
|
+
.replace(/@import\s+(?:url\([^)]*\)|[^;]*);?/gi, '')
|
|
90
|
+
.replace(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/gi, (_match, double, single, bare) => {
|
|
91
|
+
var _a, _b;
|
|
92
|
+
const resolved = resource(String((_b = (_a = double !== null && double !== void 0 ? double : single) !== null && _a !== void 0 ? _a : bare) !== null && _b !== void 0 ? _b : ''));
|
|
93
|
+
return resolved ? `url("${resolved.replace(/["\\\r\n]/g, '')}")` : 'none';
|
|
94
|
+
});
|
|
95
|
+
const attributes = (element) => {
|
|
96
|
+
const tag = element.localName.toLowerCase();
|
|
97
|
+
for (const attribute of Array.from(element.attributes)) {
|
|
98
|
+
const name = attribute.name.toLowerCase();
|
|
99
|
+
if (tag === 'img' && name === 'src') {
|
|
100
|
+
const resolved = resource(attribute.value);
|
|
101
|
+
if (resolved)
|
|
102
|
+
element.setAttribute('src', resolved);
|
|
103
|
+
else
|
|
104
|
+
element.removeAttribute(attribute.name);
|
|
105
|
+
}
|
|
106
|
+
else if (name === 'background') {
|
|
107
|
+
const resolved = resource(attribute.value);
|
|
108
|
+
if (resolved)
|
|
109
|
+
element.setAttribute('background', resolved);
|
|
110
|
+
else
|
|
111
|
+
element.removeAttribute(attribute.name);
|
|
112
|
+
}
|
|
113
|
+
else if (tag === 'a' && name === 'href') {
|
|
114
|
+
if (!/^#[a-z0-9_:.\-]+$/i.test(attribute.value))
|
|
115
|
+
element.removeAttribute(attribute.name);
|
|
116
|
+
}
|
|
117
|
+
else if (name === 'style')
|
|
118
|
+
element.setAttribute('style', css(attribute.value));
|
|
119
|
+
else if (!ALLOWED_ATTRS.has(name))
|
|
120
|
+
element.removeAttribute(attribute.name);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
let count = 0;
|
|
124
|
+
const clean = (parent) => {
|
|
125
|
+
const pending = [...parent.children];
|
|
126
|
+
while (pending.length) {
|
|
127
|
+
const element = pending.pop();
|
|
128
|
+
if (++count > 100000)
|
|
129
|
+
throw new Error('Email HTML node limit exceeded.');
|
|
130
|
+
const tag = element.localName.toLowerCase();
|
|
131
|
+
if (DROP_CONTENT.has(tag)) {
|
|
132
|
+
element.remove();
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (!ALLOWED_TAGS.has(tag)) {
|
|
136
|
+
const children = [...element.children];
|
|
137
|
+
element.replaceWith(...Array.from(element.childNodes));
|
|
138
|
+
pending.push(...children);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
attributes(element);
|
|
142
|
+
if (tag === 'style')
|
|
143
|
+
element.textContent = css(element.textContent || '');
|
|
144
|
+
pending.push(...element.children);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
clean(head);
|
|
148
|
+
clean(body);
|
|
149
|
+
attributes(parsed);
|
|
150
|
+
attributes(body);
|
|
151
|
+
if (body.getAttribute('bgcolor') && !body.style.backgroundColor)
|
|
152
|
+
body.style.backgroundColor = body.getAttribute('bgcolor');
|
|
153
|
+
if (body.getAttribute('text') && !body.style.color)
|
|
154
|
+
body.style.color = body.getAttribute('text');
|
|
155
|
+
if (body.getAttribute('background') && !body.style.backgroundImage)
|
|
156
|
+
body.style.backgroundImage = `url("${body.getAttribute('background').replace(/["\\\r\n]/g, '')}")`;
|
|
157
|
+
const escapedLength = (value, attribute = false) => {
|
|
158
|
+
let size = value.length;
|
|
159
|
+
for (let index = 0; index < value.length; index++) {
|
|
160
|
+
const code = value.charCodeAt(index);
|
|
161
|
+
if (code === 38)
|
|
162
|
+
size += 4;
|
|
163
|
+
else if (code === 60 || code === 62)
|
|
164
|
+
size += 3;
|
|
165
|
+
else if (attribute && code === 34)
|
|
166
|
+
size += 5;
|
|
167
|
+
}
|
|
168
|
+
return size;
|
|
169
|
+
};
|
|
170
|
+
const nodes = [parsed];
|
|
171
|
+
let estimated = 0;
|
|
172
|
+
while (nodes.length) {
|
|
173
|
+
const node = nodes.pop();
|
|
174
|
+
if (node.nodeType === 3)
|
|
175
|
+
estimated += escapedLength(node.nodeValue || '');
|
|
176
|
+
else if (node.nodeType === 1) {
|
|
177
|
+
estimated += 32;
|
|
178
|
+
for (const attr of Array.from(node.attributes))
|
|
179
|
+
estimated += attr.name.length + escapedLength(attr.value, true) + 8;
|
|
180
|
+
}
|
|
181
|
+
if (estimated > 64 * 1024 * 1024)
|
|
182
|
+
throw new Error('Email HTML serialization limit exceeded.');
|
|
183
|
+
nodes.push(...Array.from(node.childNodes));
|
|
184
|
+
}
|
|
185
|
+
const escape = (value) => value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
|
186
|
+
const serializeAttributes = (element) => Array.from(element.attributes).map(attr => ` ${attr.name}="${escape(attr.value)}"`).join('');
|
|
187
|
+
const background = darkMode ? '#111827' : '#fff';
|
|
188
|
+
const foreground = darkMode ? '#e5e7eb' : '#172033';
|
|
189
|
+
const csp = "default-src 'none'; script-src 'none'; connect-src 'none'; img-src blob: data:; style-src 'unsafe-inline'; font-src 'none'; media-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'";
|
|
190
|
+
return `<!doctype html><html${serializeAttributes(parsed)}><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${csp}"><meta name="referrer" content="no-referrer"><style>:root{color-scheme:${darkMode ? 'dark' : 'light'}}body{margin:0;padding:18px;font-family:Aptos,"Segoe UI",sans-serif;line-height:1.6;overflow-wrap:anywhere;background:${background};color:${foreground}}img{max-width:100%;height:auto}table{max-width:100%}</style>${head.innerHTML}</head><body${serializeAttributes(body)}>${body.innerHTML}</body></html>`;
|
|
191
|
+
}
|
package/dist/msg.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { ParsedEmailView } from './email.js';
|
|
2
|
+
export interface MsgFields {
|
|
3
|
+
dataType?: string;
|
|
4
|
+
error?: unknown;
|
|
5
|
+
subject?: string;
|
|
6
|
+
senderName?: string;
|
|
7
|
+
senderEmail?: string;
|
|
8
|
+
senderSmtpAddress?: string;
|
|
9
|
+
sentRepresentingSmtpAddress?: string;
|
|
10
|
+
sentRepresentingName?: string;
|
|
11
|
+
sentRepresentingEmail?: string;
|
|
12
|
+
displayTo?: string;
|
|
13
|
+
displayCc?: string;
|
|
14
|
+
displayBcc?: string;
|
|
15
|
+
body?: string;
|
|
16
|
+
bodyHtml?: string;
|
|
17
|
+
html?: Uint8Array | ArrayBuffer | string;
|
|
18
|
+
headers?: string;
|
|
19
|
+
compressedRtf?: Uint8Array;
|
|
20
|
+
internetCodepage?: number;
|
|
21
|
+
messageCodepage?: number;
|
|
22
|
+
clientSubmitTime?: string;
|
|
23
|
+
messageDeliveryTime?: string;
|
|
24
|
+
creationTime?: string;
|
|
25
|
+
recipients?: MsgFields[];
|
|
26
|
+
attachments?: MsgFields[];
|
|
27
|
+
name?: string;
|
|
28
|
+
email?: string;
|
|
29
|
+
smtpAddress?: string;
|
|
30
|
+
recipType?: string | number;
|
|
31
|
+
fileName?: string;
|
|
32
|
+
fileNameShort?: string;
|
|
33
|
+
extension?: string;
|
|
34
|
+
contentLength?: number;
|
|
35
|
+
pidContentId?: string;
|
|
36
|
+
contentLocation?: string;
|
|
37
|
+
attachMimeTag?: string;
|
|
38
|
+
attachmentHidden?: boolean;
|
|
39
|
+
innerMsgContent?: boolean;
|
|
40
|
+
innerMsgContentFields?: MsgFields;
|
|
41
|
+
messageClass?: string;
|
|
42
|
+
messageId?: string;
|
|
43
|
+
[key: string]: unknown;
|
|
44
|
+
}
|
|
45
|
+
export interface MsgReaderLike {
|
|
46
|
+
parserConfig?: {
|
|
47
|
+
ansiEncoding?: string;
|
|
48
|
+
propertyObserver?: (fields: MsgFields, tag: number, raw: Uint8Array | null) => void;
|
|
49
|
+
};
|
|
50
|
+
getFileData(): MsgFields;
|
|
51
|
+
getAttachment(attachment: MsgFields): {
|
|
52
|
+
fileName: string;
|
|
53
|
+
content: Uint8Array;
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export type MsgReaderConstructor = new (buffer: ArrayBuffer) => MsgReaderLike;
|
|
57
|
+
export declare function safeMsgAttachmentName(value: unknown, fallback: string): string;
|
|
58
|
+
export declare function normalizeMsg(reader: MsgReaderLike, fields: MsgFields, filename: string, objectUrls: string[], cidUrls: Map<string, string>, signal?: AbortSignal): Promise<ParsedEmailView>;
|
|
59
|
+
export declare function captureMsgProperty(fields: MsgFields, tag: number, raw: Uint8Array | null, codepage?: number): void;
|
|
60
|
+
export declare function parseMsg(buffer: ArrayBuffer, filename: string, objectUrls: string[], cidUrls: Map<string, string>, signal?: AbortSignal): Promise<ParsedEmailView>;
|
package/dist/msg.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { inspectMsgContainer, MAX_MSG_BYTES } from './msgCfb.js';
|
|
2
|
+
import { createEmailImageResource, normalizeEmailResourceId } from './emailHtml.js';
|
|
3
|
+
import { decompressMsgRtf, extractMsgRtf } from './msgRtf.js';
|
|
4
|
+
import { decodeEmailHtmlBytes, msgCodepageLabel } from './msgEncoding.js';
|
|
5
|
+
const MAX_ATTACHMENTS = 1024;
|
|
6
|
+
const MAX_RECIPIENTS = 4096;
|
|
7
|
+
const MAX_BODY_CHARS = 32 * 1024 * 1024;
|
|
8
|
+
const MAX_INLINE_BYTES = 32 * 1024 * 1024;
|
|
9
|
+
const MAX_NESTED_MESSAGES = 24;
|
|
10
|
+
const MIME = {
|
|
11
|
+
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
|
|
12
|
+
webp: 'image/webp', avif: 'image/avif', bmp: 'image/bmp', tif: 'image/tiff', tiff: 'image/tiff',
|
|
13
|
+
svg: 'image/svg+xml', pdf: 'application/pdf', txt: 'text/plain', csv: 'text/csv',
|
|
14
|
+
html: 'text/html', htm: 'text/html', rtf: 'application/rtf', msg: 'application/vnd.ms-outlook',
|
|
15
|
+
eml: 'message/rfc822', zip: 'application/zip',
|
|
16
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
17
|
+
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
18
|
+
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
19
|
+
};
|
|
20
|
+
const RASTER_MIME = /^image\/(?:png|jpeg|gif|webp|avif|bmp|x-ms-bmp)$/i;
|
|
21
|
+
const string = (value, max = MAX_BODY_CHARS) => {
|
|
22
|
+
if (typeof value !== 'string')
|
|
23
|
+
return '';
|
|
24
|
+
if (value.length > max)
|
|
25
|
+
throw new Error('Outlook MSG text exceeds the safety limit.');
|
|
26
|
+
return value.replace(/\0+$/, '');
|
|
27
|
+
};
|
|
28
|
+
export function safeMsgAttachmentName(value, fallback) {
|
|
29
|
+
const name = string(value, 32768).split(/[\\/]/).pop().replace(/[\x00-\x1f\x7f\u202a-\u202e\u2066-\u2069]/g, '').replace(/[<>:"|?*]/g, '_').replace(/[. ]+$/, '').trim();
|
|
30
|
+
return !name || name === '.' || name === '..' ? fallback : name;
|
|
31
|
+
}
|
|
32
|
+
const recipient = (item) => ({ name: string(item.name, 32768), address: string(item.smtpAddress || item.email, 32768) });
|
|
33
|
+
const addressText = (items) => items.map(item => item.name && item.address ? `${item.name} <${item.address}>` : item.address || item.name || '').join(', ');
|
|
34
|
+
const copy = (value) => {
|
|
35
|
+
const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
|
|
36
|
+
if (!(bytes instanceof Uint8Array) || bytes.length > MAX_MSG_BYTES)
|
|
37
|
+
throw new Error('Invalid or oversized MSG attachment.');
|
|
38
|
+
return new Uint8Array(bytes).buffer;
|
|
39
|
+
};
|
|
40
|
+
function assertFieldTree(root) {
|
|
41
|
+
var _a, _b;
|
|
42
|
+
const seen = new Set();
|
|
43
|
+
const pending = [{ item: root, depth: 0 }];
|
|
44
|
+
let count = 0;
|
|
45
|
+
while (pending.length) {
|
|
46
|
+
const { item, depth } = pending.pop();
|
|
47
|
+
if (depth > MAX_NESTED_MESSAGES || seen.has(item) || ++count > 32768)
|
|
48
|
+
throw new Error('Outlook MSG nesting limit exceeded.');
|
|
49
|
+
seen.add(item);
|
|
50
|
+
if ((((_a = item.attachments) === null || _a === void 0 ? void 0 : _a.length) || 0) > MAX_ATTACHMENTS || (((_b = item.recipients) === null || _b === void 0 ? void 0 : _b.length) || 0) > MAX_RECIPIENTS)
|
|
51
|
+
throw new Error('Outlook MSG recipient/attachment limit exceeded.');
|
|
52
|
+
for (const attachment of item.attachments || []) {
|
|
53
|
+
if (attachment.innerMsgContentFields)
|
|
54
|
+
pending.push({ item: attachment.innerMsgContentFields, depth: depth + 1 });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export async function normalizeMsg(reader, fields, filename, objectUrls, cidUrls, signal) {
|
|
59
|
+
var _a, _b;
|
|
60
|
+
signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
|
|
61
|
+
if (fields.error || fields.dataType !== 'msg')
|
|
62
|
+
throw new Error(string(fields.error) || 'The file does not contain a readable Outlook message.');
|
|
63
|
+
assertFieldTree(fields);
|
|
64
|
+
const warnings = [];
|
|
65
|
+
const actualSender = { name: string(fields.senderName, 32768), address: string(fields.senderSmtpAddress || fields.senderEmail, 32768) };
|
|
66
|
+
const represented = { name: string(fields.sentRepresentingName, 32768), address: string(fields.sentRepresentingSmtpAddress || fields.sentRepresentingEmail, 32768) };
|
|
67
|
+
const hasRepresentation = !!(represented.name || represented.address);
|
|
68
|
+
const from = [hasRepresentation ? represented : actualSender].filter(item => item.name || item.address);
|
|
69
|
+
const sender = hasRepresentation && (actualSender.address || actualSender.name) &&
|
|
70
|
+
(actualSender.address !== represented.address || actualSender.name !== represented.name) ? [actualSender] : [];
|
|
71
|
+
const to = [];
|
|
72
|
+
const cc = [];
|
|
73
|
+
const bcc = [];
|
|
74
|
+
for (const item of fields.recipients || []) {
|
|
75
|
+
const address = recipient(item);
|
|
76
|
+
if (!address.name && !address.address)
|
|
77
|
+
continue;
|
|
78
|
+
const kind = String((_a = item.recipType) !== null && _a !== void 0 ? _a : 'to').toLowerCase();
|
|
79
|
+
(kind === 'cc' || kind === '2' ? cc : kind === 'bcc' || kind === '3' ? bcc : to).push(address);
|
|
80
|
+
}
|
|
81
|
+
if (!to.length && fields.displayTo)
|
|
82
|
+
to.push({ name: string(fields.displayTo, 32768) });
|
|
83
|
+
if (!cc.length && fields.displayCc)
|
|
84
|
+
cc.push({ name: string(fields.displayCc, 32768) });
|
|
85
|
+
if (!bcc.length && fields.displayBcc)
|
|
86
|
+
bcc.push({ name: string(fields.displayBcc, 32768) });
|
|
87
|
+
let html = string(fields.bodyHtml);
|
|
88
|
+
if (!html && fields.html)
|
|
89
|
+
html = decodeEmailHtmlBytes(fields.html, fields.internetCodepage, fields.messageCodepage);
|
|
90
|
+
let text = string(fields.body);
|
|
91
|
+
let rtf;
|
|
92
|
+
if ((_b = fields.compressedRtf) === null || _b === void 0 ? void 0 : _b.length) {
|
|
93
|
+
try {
|
|
94
|
+
const uncompressed = decompressMsgRtf(fields.compressedRtf);
|
|
95
|
+
const extracted = extractMsgRtf(uncompressed, fields.messageCodepage);
|
|
96
|
+
text || (text = extracted.text);
|
|
97
|
+
html || (html = extracted.html || '');
|
|
98
|
+
rtf = copy(uncompressed);
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (!html && !text)
|
|
102
|
+
throw error;
|
|
103
|
+
warnings.push('email.msg.rtfUnavailable');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
|
|
107
|
+
let inlineBytes = 0;
|
|
108
|
+
const attachments = (fields.attachments || []).map((attachment, index) => {
|
|
109
|
+
const fallback = `attachment-${index + 1}`;
|
|
110
|
+
let name = safeMsgAttachmentName(attachment.fileName || attachment.fileNameShort || attachment.name, fallback);
|
|
111
|
+
const extension = string(attachment.extension, 128).replace(/^\./, '');
|
|
112
|
+
if (attachment.innerMsgContent && !/\.msg$/i.test(name))
|
|
113
|
+
name += '.msg';
|
|
114
|
+
else if (!name.includes('.') && /^[a-z0-9]{1,16}$/i.test(extension))
|
|
115
|
+
name += `.${extension}`;
|
|
116
|
+
const hint = string(attachment.attachMimeTag, 256).split(';')[0].trim().toLowerCase();
|
|
117
|
+
const mimeType = attachment.innerMsgContent ? MIME.msg : (/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(hint) ? hint : MIME[name.split('.').pop().toLowerCase()] || 'application/octet-stream');
|
|
118
|
+
const size = Number.isSafeInteger(attachment.contentLength) && attachment.contentLength >= 0 ? attachment.contentLength : -1;
|
|
119
|
+
if (size > MAX_MSG_BYTES)
|
|
120
|
+
throw new Error('Outlook MSG attachment exceeds the size limit.');
|
|
121
|
+
const contentId = string(attachment.pidContentId, 32768);
|
|
122
|
+
const contentLocation = string(attachment.contentLocation, 32768);
|
|
123
|
+
const result = {
|
|
124
|
+
id: `msg-${index}`,
|
|
125
|
+
name, size, mimeType, contentId, contentLocation,
|
|
126
|
+
inline: !!attachment.attachmentHidden || !!contentId,
|
|
127
|
+
async load() {
|
|
128
|
+
signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
|
|
129
|
+
const extracted = reader.getAttachment(attachment);
|
|
130
|
+
if (!extracted || !(extracted.content instanceof Uint8Array))
|
|
131
|
+
throw new Error(`Attachment data is not embedded: ${name}`);
|
|
132
|
+
const buffer = copy(extracted.content);
|
|
133
|
+
result.size = buffer.byteLength;
|
|
134
|
+
signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
|
|
135
|
+
return buffer;
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
return result;
|
|
139
|
+
});
|
|
140
|
+
for (const attachment of attachments) {
|
|
141
|
+
const referenced = !!(attachment.contentId || attachment.contentLocation || attachment.inline || html.includes(attachment.name));
|
|
142
|
+
if (!referenced || !RASTER_MIME.test(attachment.mimeType || ''))
|
|
143
|
+
continue;
|
|
144
|
+
signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
|
|
145
|
+
try {
|
|
146
|
+
if (inlineBytes + Math.max(0, attachment.size) > MAX_INLINE_BYTES)
|
|
147
|
+
throw new Error('Inline image size limit exceeded.');
|
|
148
|
+
const bytes = await attachment.load();
|
|
149
|
+
inlineBytes += bytes.byteLength;
|
|
150
|
+
if (inlineBytes > MAX_INLINE_BYTES)
|
|
151
|
+
throw new Error('Inline image size limit exceeded.');
|
|
152
|
+
signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
|
|
153
|
+
const cid = normalizeEmailResourceId(attachment.contentId || '');
|
|
154
|
+
const keys = [cid, attachment.contentLocation].filter((key) => !!key);
|
|
155
|
+
if (attachments.filter(item => item.name === attachment.name).length === 1)
|
|
156
|
+
keys.push(attachment.name);
|
|
157
|
+
const available = keys.map(normalizeEmailResourceId).filter(key => !cidUrls.has(key));
|
|
158
|
+
if (available.length) {
|
|
159
|
+
const url = createEmailImageResource(bytes, attachment.mimeType, objectUrls);
|
|
160
|
+
available.forEach(key => cidUrls.set(key, url));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (signal === null || signal === void 0 ? void 0 : signal.aborted)
|
|
165
|
+
throw error;
|
|
166
|
+
if (!warnings.includes('email.msg.inlineUnavailable'))
|
|
167
|
+
warnings.push('email.msg.inlineUnavailable');
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const subject = string(fields.subject, 32768) || filename;
|
|
171
|
+
const date = string(fields.clientSubmitTime || fields.messageDeliveryTime || fields.creationTime, 4096);
|
|
172
|
+
const rawHeaders = string(fields.headers, 2 * 1024 * 1024);
|
|
173
|
+
const headerLine = (key, value) => value ? `${key}: ${value.replace(/[\r\n\0]/g, ' ')}` : '';
|
|
174
|
+
const headers = rawHeaders || [
|
|
175
|
+
'X-File-Viewer-Source: Outlook MAPI properties (not transport headers)',
|
|
176
|
+
headerLine('Subject', subject), headerLine('From', addressText(from)), headerLine('Sender', addressText(sender)),
|
|
177
|
+
headerLine('To', addressText(to)), headerLine('Cc', addressText(cc)),
|
|
178
|
+
headerLine('Bcc', addressText(bcc)), headerLine('Date', date),
|
|
179
|
+
headerLine('Message-ID', string(fields.messageId, 32768)),
|
|
180
|
+
headerLine('Message-Class', string(fields.messageClass, 32768)),
|
|
181
|
+
].filter(Boolean).join('\r\n');
|
|
182
|
+
if (!html && !text && !rtf)
|
|
183
|
+
warnings.push('email.msg.noBody');
|
|
184
|
+
if (/\.smime(?:\.|$)|rpmsg|protected/i.test(string(fields.messageClass, 32768)))
|
|
185
|
+
warnings.push('email.msg.protected');
|
|
186
|
+
return { kind: 'msg', subject, from, sender, to, cc, bcc, date, text, html, rtf, headers, attachments, warnings };
|
|
187
|
+
}
|
|
188
|
+
export function captureMsgProperty(fields, tag, raw, codepage) {
|
|
189
|
+
const name = { 0x0042: 'sentRepresentingName', 0x0065: 'sentRepresentingEmail',
|
|
190
|
+
0x0e04: 'displayTo', 0x0e03: 'displayCc', 0x0e02: 'displayBcc',
|
|
191
|
+
0x3713: 'contentLocation' }[tag >>> 16];
|
|
192
|
+
const type = tag & 0xffff;
|
|
193
|
+
if (!name || !raw || (type !== 0x001f && type !== 0x001e))
|
|
194
|
+
return;
|
|
195
|
+
if (raw.length > 65536)
|
|
196
|
+
throw new Error('Outlook MSG metadata exceeds the safety limit.');
|
|
197
|
+
const value = decodeEmailHtmlBytes(raw, type === 0x001f ? 1200 : codepage || 1252);
|
|
198
|
+
if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))
|
|
199
|
+
return;
|
|
200
|
+
fields[name] = value;
|
|
201
|
+
}
|
|
202
|
+
export async function parseMsg(buffer, filename, objectUrls, cidUrls, signal) {
|
|
203
|
+
signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
|
|
204
|
+
const { messageCodepage } = inspectMsgContainer(buffer);
|
|
205
|
+
const module = await import('@kenjiuno/msgreader');
|
|
206
|
+
signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
|
|
207
|
+
const exported = module.default;
|
|
208
|
+
const constructor = typeof exported === 'function' ? exported : exported === null || exported === void 0 ? void 0 : exported.default;
|
|
209
|
+
if (typeof constructor !== 'function')
|
|
210
|
+
throw new Error('Outlook MSG parser failed to load.');
|
|
211
|
+
const localBuffer = buffer instanceof ArrayBuffer ? buffer : new Uint8Array(buffer).slice().buffer;
|
|
212
|
+
const reader = new constructor(localBuffer);
|
|
213
|
+
const label = msgCodepageLabel(messageCodepage);
|
|
214
|
+
reader.parserConfig = {
|
|
215
|
+
...(messageCodepage ? { ansiEncoding: { 949: 'cp949', 936: 'cp936', 932: 'cp932', 950: 'cp950' }[messageCodepage] || label || `cp${messageCodepage}` } : {}),
|
|
216
|
+
propertyObserver: (fields, tag, raw) => captureMsgProperty(fields, tag, raw, messageCodepage),
|
|
217
|
+
};
|
|
218
|
+
const initialUrls = objectUrls.length;
|
|
219
|
+
const initialCids = new Map(cidUrls);
|
|
220
|
+
try {
|
|
221
|
+
return await normalizeMsg(reader, reader.getFileData(), filename, objectUrls, cidUrls, signal);
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
objectUrls.splice(initialUrls).forEach(url => URL.revokeObjectURL(url));
|
|
225
|
+
cidUrls.clear();
|
|
226
|
+
initialCids.forEach((url, cid) => cidUrls.set(cid, url));
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
}
|
package/dist/msgCfb.d.ts
ADDED
package/dist/msgCfb.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
export const MAX_MSG_BYTES = 128 * 1024 * 1024;
|
|
2
|
+
const END = 0xfffffffe;
|
|
3
|
+
const FREE = 0xffffffff;
|
|
4
|
+
const MAX_DIRECTORY_ENTRIES = 32768;
|
|
5
|
+
const MAX_STORAGE_DEPTH = 24;
|
|
6
|
+
const MAGIC = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
|
|
7
|
+
export function inspectMsgContainer(buffer) {
|
|
8
|
+
const fail = (reason) => { throw new Error(`Invalid Outlook MSG: ${reason}`); };
|
|
9
|
+
if (buffer.byteLength < 512 || buffer.byteLength > MAX_MSG_BYTES)
|
|
10
|
+
fail('source size limit');
|
|
11
|
+
const bytes = new Uint8Array(buffer);
|
|
12
|
+
const view = new DataView(buffer);
|
|
13
|
+
if (!MAGIC.every((value, index) => bytes[index] === value))
|
|
14
|
+
fail('missing CFB signature');
|
|
15
|
+
const version = view.getUint16(26, true);
|
|
16
|
+
const shift = view.getUint16(30, true);
|
|
17
|
+
if (view.getUint16(28, true) !== 0xfffe || !((version === 3 && shift === 9) || (version === 4 && shift === 12)) || view.getUint16(32, true) !== 6)
|
|
18
|
+
fail('unsupported CFB header');
|
|
19
|
+
const sectorSize = 2 ** shift;
|
|
20
|
+
if (bytes.length % sectorSize || bytes.length < sectorSize * 2)
|
|
21
|
+
fail('truncated sector');
|
|
22
|
+
const sectorCount = bytes.length / sectorSize - 1;
|
|
23
|
+
const sectorOffset = (sector) => {
|
|
24
|
+
if (!Number.isInteger(sector) || sector < 0 || sector >= sectorCount)
|
|
25
|
+
fail('sector out of bounds');
|
|
26
|
+
return (sector + 1) * sectorSize;
|
|
27
|
+
};
|
|
28
|
+
const fatCount = view.getUint32(44, true);
|
|
29
|
+
const difatCount = view.getUint32(72, true);
|
|
30
|
+
if (!fatCount || fatCount > sectorCount || difatCount > sectorCount)
|
|
31
|
+
fail('invalid allocation table count');
|
|
32
|
+
const reserved = new Set();
|
|
33
|
+
const fatSectors = [];
|
|
34
|
+
const addFat = (sector) => {
|
|
35
|
+
if (sector === FREE)
|
|
36
|
+
return;
|
|
37
|
+
sectorOffset(sector);
|
|
38
|
+
if (reserved.has(sector))
|
|
39
|
+
fail('duplicate FAT/DIFAT sector');
|
|
40
|
+
reserved.add(sector);
|
|
41
|
+
fatSectors.push(sector);
|
|
42
|
+
};
|
|
43
|
+
for (let index = 0; index < 109; index++)
|
|
44
|
+
addFat(view.getUint32(76 + index * 4, true));
|
|
45
|
+
let difat = view.getUint32(68, true);
|
|
46
|
+
for (let index = 0; index < difatCount; index++) {
|
|
47
|
+
const start = sectorOffset(difat);
|
|
48
|
+
if (reserved.has(difat))
|
|
49
|
+
fail('cyclic DIFAT');
|
|
50
|
+
reserved.add(difat);
|
|
51
|
+
for (let offset = 0; offset < sectorSize - 4; offset += 4)
|
|
52
|
+
addFat(view.getUint32(start + offset, true));
|
|
53
|
+
difat = view.getUint32(start + sectorSize - 4, true);
|
|
54
|
+
}
|
|
55
|
+
if (difatCount && difat !== END)
|
|
56
|
+
fail('unterminated DIFAT');
|
|
57
|
+
if (fatSectors.length !== fatCount || fatCount * (sectorSize / 4) < sectorCount)
|
|
58
|
+
fail('incomplete FAT');
|
|
59
|
+
const fat = new Uint32Array(fatCount * (sectorSize / 4));
|
|
60
|
+
fatSectors.forEach((sector, index) => {
|
|
61
|
+
const start = sectorOffset(sector);
|
|
62
|
+
for (let offset = 0; offset < sectorSize / 4; offset++)
|
|
63
|
+
fat[index * (sectorSize / 4) + offset] = view.getUint32(start + offset * 4, true);
|
|
64
|
+
});
|
|
65
|
+
const claimed = new Set(reserved);
|
|
66
|
+
const chain = (start, table, limit, owners, maxLength = limit) => {
|
|
67
|
+
const result = [];
|
|
68
|
+
for (let sector = start; sector !== END;) {
|
|
69
|
+
if (sector >= limit || sector >= table.length || owners.has(sector) || result.length >= maxLength)
|
|
70
|
+
fail('cyclic, shared or out-of-range allocation chain');
|
|
71
|
+
owners.add(sector);
|
|
72
|
+
result.push(sector);
|
|
73
|
+
sector = table[sector];
|
|
74
|
+
}
|
|
75
|
+
return result;
|
|
76
|
+
};
|
|
77
|
+
const directory = chain(view.getUint32(48, true), fat, sectorCount, claimed, Math.ceil(MAX_DIRECTORY_ENTRIES * 128 / sectorSize));
|
|
78
|
+
if (!directory.length)
|
|
79
|
+
fail('missing directory');
|
|
80
|
+
const dirBytes = new Uint8Array(directory.length * sectorSize);
|
|
81
|
+
directory.forEach((sector, index) => dirBytes.set(bytes.subarray(sectorOffset(sector), sectorOffset(sector) + sectorSize), index * sectorSize));
|
|
82
|
+
const dir = new DataView(dirBytes.buffer);
|
|
83
|
+
const count = dirBytes.length / 128;
|
|
84
|
+
const decoder = new TextDecoder('utf-16le');
|
|
85
|
+
const entries = Array.from({ length: count }, (_, id) => {
|
|
86
|
+
const offset = id * 128;
|
|
87
|
+
const type = dir.getUint8(offset + 66);
|
|
88
|
+
const length = dir.getUint16(offset + 64, true);
|
|
89
|
+
if (type && (!([1, 2, 5].includes(type)) || length < 2 || length > 64 || length % 2))
|
|
90
|
+
fail('invalid directory entry');
|
|
91
|
+
const low = dir.getUint32(offset + 120, true);
|
|
92
|
+
const high = version === 4 ? dir.getUint32(offset + 124, true) : 0;
|
|
93
|
+
const size = low + high * 2 ** 32;
|
|
94
|
+
if ((type === 2 || type === 5) && size > MAX_MSG_BYTES)
|
|
95
|
+
fail('stream size limit');
|
|
96
|
+
return {
|
|
97
|
+
id, type, size,
|
|
98
|
+
name: type ? decoder.decode(dirBytes.subarray(offset, offset + length - 2)) : '',
|
|
99
|
+
left: dir.getUint32(offset + 68, true),
|
|
100
|
+
right: dir.getUint32(offset + 72, true),
|
|
101
|
+
child: dir.getUint32(offset + 76, true),
|
|
102
|
+
start: dir.getUint32(offset + 116, true),
|
|
103
|
+
};
|
|
104
|
+
});
|
|
105
|
+
const root = entries[0];
|
|
106
|
+
if (root.type !== 5)
|
|
107
|
+
fail('missing root storage');
|
|
108
|
+
const miniCount = view.getUint32(64, true);
|
|
109
|
+
if (miniCount > sectorCount || view.getUint32(56, true) !== 4096)
|
|
110
|
+
fail('invalid MiniFAT header');
|
|
111
|
+
const miniFatChain = miniCount ? chain(view.getUint32(60, true), fat, sectorCount, claimed) : [];
|
|
112
|
+
if (miniFatChain.length !== miniCount)
|
|
113
|
+
fail('incomplete MiniFAT');
|
|
114
|
+
const miniFat = new Uint32Array(miniCount * (sectorSize / 4));
|
|
115
|
+
miniFatChain.forEach((sector, index) => {
|
|
116
|
+
const start = sectorOffset(sector);
|
|
117
|
+
for (let offset = 0; offset < sectorSize / 4; offset++)
|
|
118
|
+
miniFat[index * (sectorSize / 4) + offset] = view.getUint32(start + offset * 4, true);
|
|
119
|
+
});
|
|
120
|
+
const miniStream = root.size ? chain(root.start, fat, sectorCount, claimed) : [];
|
|
121
|
+
if (miniStream.length * sectorSize < root.size)
|
|
122
|
+
fail('truncated mini stream');
|
|
123
|
+
const miniClaimed = new Set();
|
|
124
|
+
const visited = new Set([0]);
|
|
125
|
+
const stack = [{ id: root.child, depth: 1, parent: 0 }];
|
|
126
|
+
let properties;
|
|
127
|
+
while (stack.length) {
|
|
128
|
+
const next = stack.pop();
|
|
129
|
+
if (next.id === FREE)
|
|
130
|
+
continue;
|
|
131
|
+
if (next.id >= count || visited.has(next.id) || next.depth > MAX_STORAGE_DEPTH)
|
|
132
|
+
fail('cyclic directory or nested storage limit');
|
|
133
|
+
visited.add(next.id);
|
|
134
|
+
const item = entries[next.id];
|
|
135
|
+
if (item.type !== 1 && item.type !== 2)
|
|
136
|
+
fail('invalid child entry');
|
|
137
|
+
stack.push({ ...next, id: item.left }, { ...next, id: item.right });
|
|
138
|
+
if (item.type === 1) {
|
|
139
|
+
stack.push({ id: item.child, depth: next.depth + 1, parent: item.id });
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
const small = item.size < 4096;
|
|
143
|
+
const sectors = item.size ? chain(item.start, small ? miniFat : fat, small ? Math.ceil(root.size / 64) : sectorCount, small ? miniClaimed : claimed) : [];
|
|
144
|
+
const width = small ? 64 : sectorSize;
|
|
145
|
+
if (sectors.length * width < item.size)
|
|
146
|
+
fail('truncated property or attachment stream');
|
|
147
|
+
if (small && sectors.some((sector, index) => sector * 64 + Math.min(64, Math.max(0, item.size - index * 64)) > root.size))
|
|
148
|
+
fail('property exceeds mini stream');
|
|
149
|
+
if (next.parent === 0 && item.name === '__properties_version1.0') {
|
|
150
|
+
if (item.size < 32 || item.size > 2 * 1024 * 1024 || (item.size - 32) % 16)
|
|
151
|
+
fail('invalid message property stream');
|
|
152
|
+
properties = new Uint8Array(item.size);
|
|
153
|
+
sectors.forEach((sector, index) => {
|
|
154
|
+
const offset = small
|
|
155
|
+
? sectorOffset(miniStream[Math.floor(sector * 64 / sectorSize)]) + (sector * 64 % sectorSize)
|
|
156
|
+
: sectorOffset(sector);
|
|
157
|
+
const length = Math.min(width, item.size - index * width);
|
|
158
|
+
if (length > 0)
|
|
159
|
+
properties.set(bytes.subarray(offset, offset + length), index * width);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (!properties)
|
|
164
|
+
fail('CFB is not an Outlook message');
|
|
165
|
+
const props = new DataView(properties.buffer);
|
|
166
|
+
for (let offset = 32; offset + 16 <= props.byteLength; offset += 16) {
|
|
167
|
+
if (props.getUint32(offset, true) === 0x3ffd0003)
|
|
168
|
+
return { messageCodepage: props.getUint32(offset + 8, true) };
|
|
169
|
+
}
|
|
170
|
+
return {};
|
|
171
|
+
}
|