Replaced added postal-mime for custom mime parser due to PGP verify requirements

This commit is contained in:
the-djmaze 2022-02-10 15:37:05 +01:00
parent 9188a8bcd2
commit 292e21bae1
11 changed files with 177 additions and 2224 deletions

131
dev/Mime/Parser.js Normal file
View file

@ -0,0 +1,131 @@
const
// RFC2045
QPDecodeIn = /=([0-9A-F]{2})/g,
QPDecodeOut = (...args) => String.fromCharCode(parseInt(args[1], 16));
export function ParseMime(text)
{
class MimePart
{
header(name) {
return this.headers && this.headers[name];
}
headerValue(name) {
return (this.header(name) || {value:null}).value;
}
get raw() {
return text.slice(this.start, this.end);
}
get bodyRaw() {
return text.slice(this.body_start, this.body_end);
}
get body() {
let body = this.bodyRaw,
encoding = this.headerValue('content-transfer-encoding');
if ('quoted-printable' == encoding) {
body = body.replace(/=\r?\n/g, '').replace(QPDecodeIn, QPDecodeOut);
} else if ('base64' == encoding) {
body = atob(body.replace(/\r?\n/g, ''));
}
return body;
}
get dataUrl() {
let body = this.bodyRaw,
encoding = this.headerValue('content-transfer-encoding');
if ('base64' == encoding) {
body = body.replace(/\r?\n/g, '');
} else {
if ('quoted-printable' == encoding) {
body = body.replace(/=\r?\n/g, '').replace(QPDecodeIn, QPDecodeOut);
}
body = btoa(body);
}
return 'data:' + this.headerValue('content-type') + ';base64,' + body;
}
forEach(fn) {
fn(this);
if (this.parts) {
this.parts.forEach(part => part.forEach(fn));
}
}
getByContentType(type) {
if (type == this.headerValue('content-type')) {
return this;
}
if (this.parts) {
let i = 0, p = this.parts, part;
for (i; i < p.length; ++i) {
if ((part = p[i].getByContentType(type))) {
return part;
}
}
}
}
}
const ParsePart = (mimePart, start_pos = 0, id = '') =>
{
let part = new MimePart;
if (id) {
part.id = id;
part.start = start_pos;
part.end = start_pos + mimePart.length;
}
// get headers
let head = mimePart.match(/^[\s\S]+?\r?\n\r?\n/);
if (head) {
head = head[0];
let headers = {};
head.replace(/\r?\n\s+/g, ' ').split(/\r?\n/).forEach(header => {
let match = header.match(/^([^:]+):\s*([^;]+)/),
params = {};
[...header.matchAll(/;\s*([^;=]+)=\s*"?([^;"]+)"?/g)].forEach(param =>
params[param[1].trim().toLowerCase()] = param[2].trim()
);
headers[match[1].trim().toLowerCase()] = {
value: match[2].trim(),
params: params
};
});
part.headers = headers;
// get body
part.body_start = start_pos + head.length;
part.body_end = start_pos + mimePart.length;
let boundary = headers['content-type'].params.boundary;
if (boundary) {
part.boundary = boundary;
part.parts = [];
let regex = new RegExp('(?:^|\r?\n)--' + boundary + '(?:--)?(?:\r?\n|$)', 'g'),
body = mimePart.slice(head.length),
bodies = body.split(regex),
pos = part.body_start;
[...body.matchAll(regex)].forEach(([boundary], index) => {
if (!index) {
part.body_text = bodies[0];
}
pos += bodies[index].length;
pos += boundary.length;
part.parts.push(ParsePart(bodies[1+index], pos, ((id ? id + '.' : '') + (1+index))));
if ('--' == boundary.trim().slice(-2)) {
// end
}
});
}
}
return part;
};
return ParsePart(text);
}

View file

@ -52,7 +52,7 @@ import { AbstractViewRight } from 'Knoin/AbstractViews';
import { PgpUserStore } from 'Stores/User/Pgp';
import PostalMime from '../../../../vendors/postal-mime/src/postal-mime.js';
import { ParseMime } from 'Mime/Parser';
import { AttachmentModel } from 'Model/Attachment';
const
@ -61,44 +61,57 @@ const
currentMessage = () => MessageUserStore.message(),
mimeToMessage = (data, message) => {
// TODO: Check multipart/signed application/pgp-signature application/pgp-keys
const headers = data.split(/\r?\n\r?\n/)[0];
if (/Content-Type:/i.test(headers)) {
// https://github.com/postalsys/postal-mime
(new PostalMime).parse(data).then(result => {
// TODO: multipart/signed
let html = result.html,
regex = /^<+|>+$/g;
result.attachments.forEach(data => {
const struct = ParseMime(data),
text = struct.getByContentType('text/plain');
let html = struct.getByContentType('text/html');
html = html ? html.body : '';
// TODO: Check multipart/signed application/pgp-signature application/pgp-keys
struct.forEach(part => {
let cd = part.header('content-disposition'),
cid = part.header('content-id'),
type = part.header('content-type');
if (cid || cd) {
// if (cd && 'attachment' === cd.value) {
let attachment = new AttachmentModel;
attachment.mimeType = data.mimeType;
attachment.fileName = data.filename;
attachment.content = data.content; // ArrayBuffer
attachment.cid = data.contentId || '';
// Parse inline attachments from result.attachments
if (attachment.cid) {
if (html) {
let cid = 'cid:' + attachment.cid.replace(regex, ''),
b64 = 'data:' + data.mimeType + ';base64,' + btoa(String.fromCharCode(...new Uint8Array(data.content)));
html = html
.replace('src="' + cid + '"', 'src="' + b64 + '"')
.replace("src='" + cid + "'", "src='" + b64 + "'");
}
attachment.mimeType = type.value;
attachment.fileName = (type.name || (cd && cd.params.filename));
attachment.url = part.dataUrl;
/*
attachment.fileNameExt = '';
attachment.fileType = FileType.Unknown;
attachment.friendlySize = '';
attachment.isLinked = false;
attachment.isThumbnail = false;
attachment.contentLocation = '';
attachment.download = '';
attachment.folder = '';
attachment.uid = '';
attachment.mimeIndex = part.id;
attachment.framed = false;
*/
attachment.cid = cid ? cid.value : '';
if (cid && html) {
let cid = 'cid:' + attachment.contentId();
attachment.isInline = html.includes(cid);
html = html
.replace('src="' + cid + '"', 'src="' + attachment.url + '"')
.replace("src='" + cid + "'", "src='" + attachment.url + "'");
} else {
message.attachments.push(attachment);
}
// data.disposition
// data.related = true;
message.attachments.push(attachment);
});
message.hasAttachments(message.attachments().hasVisible());
// result.headers;
message.plain(result.text || '');
if (html) {
message.html(html.replace(/<\/?script[\s\S]*?>/gi, '') || '');
message.viewHtml();
} else {
message.viewPlain();
}
});
message.plain(text ? text.body : '');
if (html) {
message.html(html.replace(/<\/?script[\s\S]*?>/gi, ''));
message.viewHtml();
} else {
message.viewPlain();
}
return;
}
message.plain(data);

View file

@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View file

@ -1,140 +0,0 @@
# postal-mime
Email parser for browser environments.
PostalMime can be run in the main web thread or from Web Workers.
PostalMime can be bundled using WebPack. In fact the distribution file is also built with WebPack.
## Source
Source code is available from [Github](https://github.com/postalsys/postal-mime).
## Demo
See this [example](https://kreata.ee/postal-mime/example/).
## Usage
### Free, AGPL-licensed version
First install the module from npm:
```
$ npm install postal-mime
```
next import the PostalMime class into your script:
```js
const { PostalMime } = require('postal-mime');
```
or when using as a global
```html
<script src="/path/to/postal-mime.js"></script>
<script>
const PostalMime = postalMime.default;
</script>
```
### MIT version
MIT-licensed version is available for [Postal Systems subscribers](https://postalsys.com/).
First install the module from Postal Systems private registry:
```
$ npm install @postalsys/postal-mime
```
next import the postal-mime class into your script:
```js
const { PostalMime } = require('@postalsys/postal-mime');
```
If you have already built your application using the free version of postal-mime and do not want to modify require statements in your code, you can install the MIT-licensed version as an alias for "postal-mime".
```
$ npm install postal-mime@npm:@postalsys/postal-mime
```
This way you can keep using the old module name
```js
const { PostalMime } = require('postal-mime');
```
### Promises
All postal-mime methods use Promises, so you need to wait using `await` or wait for the `then()` method to fire until you get the response.
```js
const { PostalMime } = require('postal-mime');
const parser = new PostalMime();
const email = await parser.parse(email);
console.log(email.subject);
console.log(email.html);
```
### Node.js
Even though PostalMime is built for the browser environment you can also use it in Node.js with a few tweaks. Notably you'd need to register a global _Blob_ class that is not available by default in Node.
```js
// Set up global Blob
// $ npm install cross-blob
globalThis.Blob = require('cross-blob');
// Require Node.js version of the library
const PostalMime = require('postal-mime/dist/node').postalMime.default;
// Use PostalMime as you'd normally do
new PostalMime().parse('Subject: test').then(res => console.log(res));
```
#### parser.parse()
```js
parser.parse(email) -> Promise
```
Where
- **email** is the rfc822 formatted email. Either a string, an ArrayBuffer, a Blob object or a Node.js Buffer
> **NB** you can call `parse()` only once. If you need to parse another message, create a new _PostalMime_ object.
This method parses an email message into a structured object with the following properties:
- **headers** is an array of headers in the same order as found from the message (topmost headers first).
- **headers[].key** is lowercase key of the header line, eg. `"dkim-signature"`
- **headers[].value** is the unprocessed value of the header line
- **from**, **sender**, **replyTo** includes a processed object for the corresponding headers
- **from.name** is decoded name (empty string if not set)
- **from.address** is the email address
- **deliveredTo**, **returnPath** is the email address from the corresponding header
- **to**, **cc**, **bcc** includes an array of processed objects for the corresponding headers
- **to[].name** is decoded name (empty string if not set)
- **to[].address** is the email address
- **subject** is the email subject line
- **messageId**, **inReplyTo**, **references** includes the value as found from the corresponding header without any processing
- **date** is the email sending time formatted as an ISO date string (unless parsing failed and in this case the original value is used)
- **html** is the HTML content of the message as a string
- **text** is the plaintext content of the message as a string
- **attachments** is an array that includes message attachments
- **attachment[].filename** is the file name if provided
- **attachment[].mimeType** is the MIME type of the attachment
- **attachment[].disposition** is either "attachment", "inline" or `null` if disposition was not provided
- **attachment[].related** is a boolean value that indicats if this attachment should be treated as embedded image
- **attachment[].contentId** is the ID from Content-ID header
- **attachment[].content** is an ArrayBuffer that contains the attachment file
## License
&copy; 2021 Andris Reinman
Licensed under GNU Affero General Public License v3.0 or later.
MIT-licensed version of postal-mime is available for [Postal Systems subscribers](https://postalsys.com/).

View file

@ -1,48 +0,0 @@
import { decodeBase64 } from './decode-strings';
export default class Base64Decoder {
constructor() {
this.decoder = new TextDecoder();
this.maxChunkSize = 100 * 1024;
this.chunks = [];
this.remainder = '';
}
update(buffer) {
let str = this.decoder.decode(buffer);
if (/[^a-zA-Z0-9+/]/.test(str)) {
str = str.replace(/[^a-zA-Z0-9+/]+/g, '');
}
this.remainder += str;
if (this.remainder.length >= this.maxChunkSize) {
let allowedBytes = Math.floor(this.remainder.length / 4) * 4;
let base64Str;
if (allowedBytes === this.remainder.length) {
base64Str = this.remainder;
this.remainder = '';
} else {
base64Str = this.remainder.substr(0, allowedBytes);
this.remainder = this.remainder.substr(allowedBytes);
}
if (base64Str.length) {
this.chunks.push(decodeBase64(base64Str));
}
}
}
finalize() {
if (this.remainder && !/^=+$/.test(this.remainder)) {
this.chunks.push(decodeBase64(this.remainder));
}
return this.chunks;
}
}

View file

@ -1,268 +0,0 @@
export const textEncoder = new TextEncoder();
const decoders = new Map();
const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
const base64Lookup = new Uint8Array(256);
for (var i = 0; i < base64Chars.length; i++) {
base64Lookup[base64Chars.charCodeAt(i)] = i;
}
export function decodeBase64(base64) {
let bufferLength = Math.ceil(base64.length / 4) * 3;
const len = base64.length;
let p = 0;
if (base64.length % 4 === 3) {
bufferLength--;
} else if (base64.length % 4 === 2) {
bufferLength -= 2;
} else if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
const arrayBuffer = new ArrayBuffer(bufferLength);
const bytes = new Uint8Array(arrayBuffer);
for (let i = 0; i < len; i += 4) {
let encoded1 = base64Lookup[base64.charCodeAt(i)];
let encoded2 = base64Lookup[base64.charCodeAt(i + 1)];
let encoded3 = base64Lookup[base64.charCodeAt(i + 2)];
let encoded4 = base64Lookup[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arrayBuffer;
}
export function getDecoder(charset) {
charset = charset || 'utf8';
if (decoders.has(charset)) {
return decoders.get(charset);
}
let decoder;
try {
decoder = new TextDecoder(charset);
} catch (err) {
if (charset === 'utf8') {
// is this even possible?
throw err;
}
// use default
return getDecoder();
}
decoders.set(charset, decoder);
return decoder;
}
/**
* Converts a Blob into an ArrayBuffer
* @param {Blob} blob Blob to convert
* @returns {ArrayBuffer} Converted value
*/
export async function blobToArrayBuffer(blob) {
if ('arrayBuffer' in blob) {
return await blob.arrayBuffer();
}
const fr = new FileReader();
return new Promise((resolve, reject) => {
fr.onload = function (e) {
resolve(e.target.result);
};
fr.onerror = function (e) {
reject(fr.error);
};
fr.readAsArrayBuffer(blob);
});
}
export function getHex(c) {
if ((c >= 0x30 /* 0 */ && c <= 0x39) /* 9 */ || (c >= 0x61 /* a */ && c <= 0x66) /* f */ || (c >= 0x41 /* A */ && c <= 0x46) /* F */) {
return String.fromCharCode(c);
}
return false;
}
/**
* Decode a complete mime word encoded string
*
* @param {String} str Mime word encoded string
* @return {String} Decoded unicode string
*/
export function decodeWord(charset, encoding, str) {
// RFC2231 added language tag to the encoding
// see: https://tools.ietf.org/html/rfc2231#section-5
// this implementation silently ignores this tag
let splitPos = charset.indexOf('*');
if (splitPos >= 0) {
charset = charset.substr(0, splitPos);
}
encoding = encoding.toUpperCase();
let byteStr;
if (encoding === 'Q') {
str = str
// remove spaces between = and hex char, this might indicate invalidly applied line splitting
.replace(/=\s+([0-9a-fA-F])/g, '=$1')
// convert all underscores to spaces
.replace(/[_\s]/g, ' ');
let buf = textEncoder.encode(str);
let encodedBytes = [];
for (let i = 0, len = buf.length; i < len; i++) {
let c = buf[i];
if (i <= len - 2 && c === 0x3d /* = */) {
let c1 = getHex(buf[i + 1]);
let c2 = getHex(buf[i + 2]);
if (c1 && c2) {
let c = parseInt(c1 + c2, 16);
encodedBytes.push(c);
i += 2;
continue;
}
}
encodedBytes.push(c);
}
byteStr = new ArrayBuffer(encodedBytes.length);
let dataView = new DataView(byteStr);
for (let i = 0, len = encodedBytes.length; i < len; i++) {
dataView.setUint8(i, encodedBytes[i]);
}
} else if (encoding === 'B') {
byteStr = decodeBase64(str.replace(/[^a-zA-Z0-9\+\/=]+/g, ''));
} else {
// keep as is, convert ArrayBuffer to unicode string, assume utf8
byteStr = textEncoder.encode(str);
}
return getDecoder(charset).decode(byteStr);
}
export function decodeWords(str) {
return (
(str || '')
.toString()
// find base64 words that can be joined
.replace(/(=\?([^?]+)\?[Bb]\?[^?]*\?=)\s*(?==\?([^?]+)\?[Bb]\?[^?]*\?=)/g, (match, left, chLeft, chRight) => {
// only mark b64 chunks to be joined if charsets match
if (chLeft === chRight) {
// set a joiner marker
return left + '__\x00JOIN\x00__';
}
return match;
})
// find QP words that can be joined
.replace(/(=\?([^?]+)\?[Qq]\?[^?]*\?=)\s*(?==\?([^?]+)\?[Qq]\?[^?]*\?=)/g, (match, left, chLeft, chRight) => {
// only mark QP chunks to be joined if charsets match
if (chLeft === chRight) {
// set a joiner marker
return left + '__\x00JOIN\x00__';
}
return match;
})
// join base64 encoded words
.replace(/(\?=)?__\x00JOIN\x00__(=\?([^?]+)\?[QqBb]\?)?/g, '')
// remove spaces between mime encoded words
.replace(/(=\?[^?]+\?[QqBb]\?[^?]*\?=)\s+(?==\?[^?]+\?[QqBb]\?[^?]*\?=)/g, '$1')
// decode words
.replace(/=\?([\w_\-*]+)\?([QqBb])\?([^?]*)\?=/g, (m, charset, encoding, text) => decodeWord(charset, encoding, text))
);
}
export function decodeURIComponentWithCharset(encodedStr, charset) {
charset = charset || 'utf-8';
let encodedBytes = [];
for (let i = 0; i < encodedStr.length; i++) {
let c = encodedStr.charAt(i);
if (c === '%' && /^[a-f0-9]{2}/i.test(encodedStr.substr(i + 1, 2))) {
// encoded sequence
let byte = encodedStr.substr(i + 1, 2);
i += 2;
encodedBytes.push(parseInt(byte, 16));
} else if (c.charCodeAt(0) > 126) {
c = textEncoder.encode(c);
for (let j = 0; j < c.length; j++) {
encodedBytes.push(c[j]);
}
} else {
// "normal" char
encodedBytes.push(c.charCodeAt(0));
}
}
const byteStr = new ArrayBuffer(encodedBytes.length);
const dataView = new DataView(byteStr);
for (let i = 0, len = encodedBytes.length; i < len; i++) {
dataView.setUint8(i, encodedBytes[i]);
}
return getDecoder(charset).decode(byteStr);
}
export function decodeParameterValueContinuations(header) {
// handle parameter value continuations
// https://tools.ietf.org/html/rfc2231#section-3
// preprocess values
let paramKeys = new Map();
Object.keys(header.params).forEach(key => {
let match = key.match(/\*((\d+)\*?)?$/);
if (!match) {
// nothing to do here, does not seem like a continuation param
return;
}
let actualKey = key.substr(0, match.index).toLowerCase();
let nr = Number(match[2]) || 0;
let paramVal;
if (!paramKeys.has(actualKey)) {
paramVal = {
charset: false,
values: []
};
paramKeys.set(actualKey, paramVal);
} else {
paramVal = paramKeys.get(actualKey);
}
let value = header.params[key];
if (nr === 0 && match[0].charAt(match[0].length - 1) === '*' && (match = value.match(/^([^']*)'[^']*'(.*)$/))) {
paramVal.charset = match[1] || 'utf-8';
value = match[2];
}
paramVal.values.push({ nr, value });
// remove the old reference
delete header.params[key];
});
paramKeys.forEach((paramVal, key) => {
header.params[key] = decodeURIComponentWithCharset(
paramVal.values
.sort((a, b) => a.nr - b.nr)
.map(a => a.value)
.join(''),
paramVal.charset
);
});
}

View file

@ -1,270 +0,0 @@
import { getDecoder, decodeParameterValueContinuations, textEncoder, blobToArrayBuffer } from './decode-strings';
import PassThroughDecoder from './pass-through-decoder';
import Base64Decoder from './base64-decoder';
import QPDecoder from './qp-decoder';
export default class MimeNode {
constructor(opts) {
opts = opts || {};
this.postalMime = opts.postalMime;
this.root = !!opts.parentNode;
this.childNodes = [];
if (opts.parentNode) {
opts.parentNode.childNodes.push(this);
}
this.state = 'header';
this.headerLines = [];
this.decoders = new Map();
this.contentType = {
value: 'text/plain'
};
this.contentTransferEncoding = {
value: '8bit'
};
this.contentDisposition = {
value: ''
};
this.headers = [];
this.contentDecoder = false;
}
setupContentDecoder(transferEncoding) {
if (/base64/i.test(transferEncoding)) {
this.contentDecoder = new Base64Decoder();
} else if (/quoted-printable/i.test(transferEncoding)) {
this.contentDecoder = new QPDecoder({ decoder: getDecoder(this.contentType.parsed.params.charset) });
} else {
this.contentDecoder = new PassThroughDecoder();
}
}
async finalize() {
if (this.state === 'finished') {
return;
}
if (this.state === 'header') {
this.processHeaders();
}
// remove self from boundary listing
let boundaries = this.postalMime.boundaries;
for (let i = boundaries.length - 1; i >= 0; i--) {
let boundary = boundaries[i];
if (boundary.node === this) {
boundaries.splice(i, 1);
break;
}
}
await this.finalizeChildNodes();
this.content = this.contentDecoder
? await blobToArrayBuffer(new Blob(this.contentDecoder.finalize(), { type: 'application/octet-stream' }))
: null;
this.state = 'finished';
}
async finalizeChildNodes() {
for (let childNode of this.childNodes) {
await childNode.finalize();
}
}
parseStructuredHeader(str) {
let response = {
value: false,
params: {}
};
let key = false;
let value = '';
let stage = 'value';
let quote = false;
let escaped = false;
let chr;
for (let i = 0, len = str.length; i < len; i++) {
chr = str.charAt(i);
switch (stage) {
case 'key':
if (chr === '=') {
key = value.trim().toLowerCase();
stage = 'value';
value = '';
break;
}
value += chr;
break;
case 'value':
if (escaped) {
value += chr;
} else if (chr === '\\') {
escaped = true;
continue;
} else if (quote && chr === quote) {
quote = false;
} else if (!quote && chr === '"') {
quote = chr;
} else if (!quote && chr === ';') {
if (key === false) {
response.value = value.trim();
} else {
response.params[key] = value.trim();
}
stage = 'key';
value = '';
} else {
value += chr;
}
escaped = false;
break;
}
}
// finalize remainder
value = value.trim();
if (stage === 'value') {
if (key === false) {
// default value
response.value = value;
} else {
// subkey value
response.params[key] = value;
}
} else if (value) {
// treat as key without value, see emptykey:
// Header-Key: somevalue; key=value; emptykey
response.params[value.toLowerCase()] = '';
}
if (response.value) {
response.value = response.value.toLowerCase();
}
// convert Parameter Value Continuations into single strings
decodeParameterValueContinuations(response);
return response;
}
decodeFlowedText(str, delSp) {
return (
str
.split(/\r?\n/)
// remove soft linebreaks
// soft linebreaks are added after space symbols
.reduce((previousValue, currentValue) => {
if (/ $/.test(previousValue) && !/(^|\n)-- $/.test(previousValue)) {
if (delSp) {
// delsp adds space to text to be able to fold it
// these spaces can be removed once the text is unfolded
return previousValue.slice(0, -1) + currentValue;
} else {
return previousValue + currentValue;
}
} else {
return previousValue + '\n' + currentValue;
}
})
// remove whitespace stuffing
// http://tools.ietf.org/html/rfc3676#section-4.4
.replace(/^ /gm, '')
);
}
getTextContent() {
if (!this.content) {
return '';
}
let str = getDecoder(this.contentType.parsed.params.charset).decode(this.content);
if (/^flowed$/i.test(this.contentType.parsed.params.format)) {
str = this.decodeFlowedText(str, /^yes$/i.test(this.contentType.parsed.params.delsp));
}
return str;
}
processHeaders() {
for (let i = this.headerLines.length - 1; i >= 0; i--) {
let line = this.headerLines[i];
if (i && /^\s/.test(line)) {
this.headerLines[i - 1] += '\n' + line;
this.headerLines.splice(i, 1);
} else {
// remove folding and extra WS
line = line.replace(/\s+/g, ' ');
let sep = line.indexOf(':');
let key = sep < 0 ? line.trim() : line.substr(0, sep).trim();
let value = sep < 0 ? '' : line.substr(sep + 1).trim();
this.headers.push({ key: key.toLowerCase(), originalKey: key, value });
switch (key.toLowerCase()) {
case 'content-type':
this.contentType = { value, parsed: {} };
break;
case 'content-transfer-encoding':
this.contentTransferEncoding = { value, parsed: {} };
break;
case 'content-disposition':
this.contentDisposition = { value, parsed: {} };
break;
case 'content-id':
this.contentId = value;
break;
}
}
}
this.contentType.parsed = this.parseStructuredHeader(this.contentType.value);
this.contentType.multipart = /^multipart\//i.test(this.contentType.parsed.value)
? this.contentType.parsed.value.substr(this.contentType.parsed.value.indexOf('/') + 1)
: false;
if (this.contentType.multipart && this.contentType.parsed.params.boundary) {
// add self to boundary terminator listing
this.postalMime.boundaries.push({
value: textEncoder.encode(this.contentType.parsed.params.boundary),
node: this
});
}
this.contentDisposition.parsed = this.parseStructuredHeader(this.contentDisposition.value);
this.contentTransferEncoding.encoding = this.contentTransferEncoding.value
.toLowerCase()
.split(/[^\w-]/)
.shift();
this.setupContentDecoder(this.contentTransferEncoding.encoding);
}
feed(line) {
switch (this.state) {
case 'header':
if (!line.length) {
this.state = 'body';
return this.processHeaders();
}
this.headerLines.push(getDecoder().decode(line));
break;
case 'body': {
// add line to body
this.contentDecoder.update(line);
}
}
}
}

View file

@ -1,14 +0,0 @@
export default class PassThroughDecoder {
constructor() {
this.chunks = [];
}
update(line) {
this.chunks.push(line);
this.chunks.push('\n');
}
finalize() {
return this.chunks;
}
}

View file

@ -1,395 +0,0 @@
import MimeNode from './mime-node';
import { textToHtml, htmlToText, formatTextHeader, formatHtmlHeader } from './text-format';
//import addressParser from './address-parser';
import { decodeWords, textEncoder, blobToArrayBuffer } from './decode-strings';
export default class PostalMime {
constructor() {
this.root = this.currentNode = new MimeNode({
postalMime: this
});
this.boundaries = [];
this.textContent = {};
this.attachments = [];
this.started = false;
}
async finalize() {
// close all pending nodes
await this.root.finalize();
}
async processLine(line, isFinal) {
let boundaries = this.boundaries;
// check if this is a mime boundary
if (boundaries.length && line.length > 2 && line[0] === 0x2d && line[1] === 0x2d) {
// could be a boundary marker
for (let i = boundaries.length - 1; i >= 0; i--) {
let boundary = boundaries[i];
if (line.length !== boundary.value.length + 2 && line.length !== boundary.value.length + 4) {
continue;
}
let isTerminator = line.length === boundary.value.length + 4;
if (isTerminator && (line[line.length - 2] !== 0x2d || line[line.length - 1] !== 0x2d)) {
continue;
}
let boudaryMatches = true;
for (let i = 0; i < boundary.value.length; i++) {
if (line[i + 2] !== boundary.value[i]) {
boudaryMatches = false;
break;
}
}
if (!boudaryMatches) {
continue;
}
if (isTerminator) {
await boundary.node.finalize();
this.currentNode = boundary.node.parentNode || this.root;
} else {
// finalize any open child nodes (should be just one though)
await boundary.node.finalizeChildNodes();
this.currentNode = new MimeNode({
postalMime: this,
parentNode: boundary.node
});
}
if (isFinal) {
return this.finalize();
}
return;
}
}
this.currentNode.feed(line);
if (isFinal) {
return this.finalize();
}
}
readLine() {
let startPos = this.readPos;
let endPos = this.readPos;
let res = () => {
return {
bytes: new Uint8Array(this.buf, startPos, endPos - startPos),
done: this.readPos >= this.av.length
};
};
while (this.readPos < this.av.length) {
const c = this.av[this.readPos++];
if (c !== 0x0d && c !== 0x0a) {
endPos = this.readPos;
}
if (c === 0x0a) {
return res();
}
}
return res();
}
async processNodeTree() {
// get text nodes
let textContent = {};
let textTypes = new Set();
let textMap = (this.textMap = new Map());
let walk = async (node, alternative, related) => {
alternative = alternative || false;
related = related || false;
if (!node.contentType.multipart) {
// regular node
// is it inline message/rfc822
if (node.contentType.parsed.value === 'message/rfc822' && node.contentDisposition.parsed.value !== 'attachment') {
const subParser = new PostalMime();
node.subMessage = await subParser.parse(node.content);
if (!textMap.has(node)) {
textMap.set(node, {});
}
let textEntry = textMap.get(node);
// default to text if there is no content
if (node.subMessage.text || !node.subMessage.html) {
textEntry.plain = textEntry.plain || [];
textEntry.plain.push({ type: 'subMessage', value: node.subMessage });
textTypes.add('plain');
}
if (node.subMessage.html) {
textEntry.html = textEntry.html || [];
textEntry.html.push({ type: 'subMessage', value: node.subMessage });
textTypes.add('html');
}
if (subParser.textMap) {
subParser.textMap.forEach((subTextEntry, subTextNode) => {
textMap.set(subTextNode, subTextEntry);
});
}
for (let attachment of node.subMessage.attachments || []) {
this.attachments.push(attachment);
}
}
// is it text?
else if (
(/^text\//i.test(node.contentType.parsed.value) || node.contentType.parsed.value === 'message/delivery-status') &&
node.contentDisposition.parsed.value !== 'attachment'
) {
let textType = node.contentType.parsed.value.substr(node.contentType.parsed.value.indexOf('/') + 1);
if (node.contentType.parsed.value === 'message/delivery-status') {
textType = 'plain';
}
let selectorNode = alternative || node;
if (!textMap.has(selectorNode)) {
textMap.set(selectorNode, {});
}
let textEntry = textMap.get(selectorNode);
textEntry[textType] = textEntry[textType] || [];
textEntry[textType].push({ type: 'text', value: node.getTextContent() });
textTypes.add(textType);
}
// is it an attachment
else if (node.content) {
let filename = node.contentDisposition.parsed.params.filename || node.contentType.parsed.params.name || null;
let attachment = {
filename: decodeWords(filename),
mimeType: node.contentType.parsed.value,
disposition: node.contentDisposition.parsed.value || null
};
if (related && node.contentId) {
attachment.related = true;
}
if (node.contentId) {
attachment.contentId = node.contentId;
}
attachment.content = node.content;
this.attachments.push(attachment);
}
} else if (node.contentType.multipart === 'alternative') {
alternative = node;
} else if (node.contentType.multipart === 'related') {
related = node;
}
for (let childNode of node.childNodes) {
await walk(childNode, alternative, related);
}
};
await walk(this.root, false, []);
textMap.forEach(mapEntry => {
textTypes.forEach(textType => {
if (!textContent[textType]) {
textContent[textType] = [];
}
if (mapEntry[textType]) {
mapEntry[textType].forEach(textEntry => {
switch (textEntry.type) {
case 'text':
textContent[textType].push(textEntry.value);
break;
case 'subMessage':
{
switch (textType) {
case 'html':
textContent[textType].push(formatHtmlHeader(textEntry.value));
break;
case 'plain':
textContent[textType].push(formatTextHeader(textEntry.value));
break;
}
}
break;
}
});
} else {
let alternativeType;
switch (textType) {
case 'html':
alternativeType = 'plain';
break;
case 'plain':
alternativeType = 'html';
break;
}
(mapEntry[alternativeType] || []).forEach(textEntry => {
switch (textEntry.type) {
case 'text':
switch (textType) {
case 'html':
textContent[textType].push(textToHtml(textEntry.value));
break;
case 'plain':
textContent[textType].push(htmlToText(textEntry.value));
break;
}
break;
case 'subMessage':
{
switch (textType) {
case 'html':
textContent[textType].push(formatHtmlHeader(textEntry.value));
break;
case 'plain':
textContent[textType].push(formatTextHeader(textEntry.value));
break;
}
}
break;
}
});
}
});
});
Object.keys(textContent).forEach(textType => {
textContent[textType] = textContent[textType].join('\n');
});
this.textContent = textContent;
}
async parse(buf) {
if (this.started) {
throw new Error('Can not reuse parser, create a new PostalMime object');
}
this.started = true;
// should it thrown on empty value instead?
buf = buf || ArrayBuffer(0);
if (typeof buf === 'string') {
// cast string input to ArrayBuffer
buf = textEncoder.encode(buf);
}
if (buf instanceof Blob || Object.prototype.toString.call(buf) === '[object Blob]') {
// can't process blob directly, cast to ArrayBuffer
buf = await blobToArrayBuffer(buf);
}
if (buf.buffer instanceof ArrayBuffer) {
// Node.js Buffer object or Uint8Array
buf = new Uint8Array(buf).buffer;
}
this.buf = buf;
this.av = new Uint8Array(buf);
this.readPos = 0;
while (this.readPos < this.av.length) {
const line = this.readLine();
await this.processLine(line.bytes, line.done);
}
await this.processNodeTree();
let message = {
headers: this.root.headers.map(entry => ({ key: entry.key, value: entry.value })).reverse()
};
/*
for (let key of ['from', 'sender', 'reply-to']) {
let addressHeader = this.root.headers.find(line => line.key === key);
if (addressHeader && addressHeader.value) {
let addresses = addressParser(addressHeader.value);
if (addresses && addresses.length) {
message[key.replace(/\-(.)/g, (o, c) => c.toUpperCase())] = addresses[0];
}
}
}
for (let key of ['delivered-to', 'return-path']) {
let addressHeader = this.root.headers.find(line => line.key === key);
if (addressHeader && addressHeader.value) {
let addresses = addressParser(addressHeader.value);
if (addresses && addresses.length && addresses[0].address) {
message[key.replace(/\-(.)/g, (o, c) => c.toUpperCase())] = addresses[0].address;
}
}
}
for (let key of ['to', 'cc', 'bcc']) {
let addressHeaders = this.root.headers.filter(line => line.key === key);
let addresses = [];
addressHeaders
.filter(entry => entry && entry.value)
.map(entry => addressParser(entry.value))
.forEach(parsed => (addresses = addresses.concat(parsed || [])));
if (addresses && addresses.length) {
message[key] = addresses;
}
}
for (let key of ['subject', 'message-id', 'in-reply-to', 'references']) {
let header = this.root.headers.find(line => line.key === key);
if (header && header.value) {
message[key.replace(/\-(.)/g, (o, c) => c.toUpperCase())] = decodeWords(header.value);
}
}
let dateHeader = this.root.headers.find(line => line.key === 'date');
if (dateHeader) {
let date = new Date(dateHeader.value);
if (!date || date.toString() === 'Invalid Date') {
date = dateHeader.value;
} else {
// enforce ISO format if seems to be a valid date
date = date.toISOString();
}
message.date = date;
}
*/
if (this.textContent && this.textContent.html) {
message.html = this.textContent.html;
}
if (this.textContent && this.textContent.plain) {
message.text = this.textContent.plain;
}
message.attachments = this.attachments;
return message;
}
}

View file

@ -1,93 +0,0 @@
export default class QPDecoder {
constructor(opts) {
opts = opts || {};
this.decoder = opts.decoder || new TextDecoder();
this.maxChunkSize = 100 * 1024;
this.remainder = '';
this.chunks = [];
}
decodeQPBytes(encodedBytes) {
let buf = new ArrayBuffer(encodedBytes.length);
let dataView = new DataView(buf);
for (let i = 0, len = encodedBytes.length; i < len; i++) {
dataView.setUint8(i, parseInt(encodedBytes[i], 16));
}
return buf;
}
decodeChunks(str) {
// unwrap newlines
str = str.replace(/=\r?\n/g, '');
let list = str.split(/(?==)/);
let encodedBytes = [];
for (let part of list) {
if (part.charAt(0) !== '=') {
if (encodedBytes.length) {
this.chunks.push(this.decodeQPBytes(encodedBytes));
encodedBytes = [];
}
this.chunks.push(part);
continue;
}
if (part.length === 3) {
encodedBytes.push(part.substr(1));
continue;
}
if (part.length > 3) {
encodedBytes.push(part.substr(1, 2));
this.chunks.push(this.decodeQPBytes(encodedBytes));
encodedBytes = [];
part = part.substr(3);
this.chunks.push(part);
}
}
if (encodedBytes.length) {
this.chunks.push(this.decodeQPBytes(encodedBytes));
encodedBytes = [];
}
}
update(buffer) {
// expect full lines, so add line terminator as well
let str = this.decoder.decode(buffer) + '\n';
str = this.remainder + str;
if (str.length < this.maxChunkSize) {
this.remainder = str;
return;
}
this.remainder = '';
let partialEnding = str.match(/=[a-fA-F0-9]?$/);
if (partialEnding) {
if (partialEnding.index === 0) {
this.remainder = str;
return;
}
this.remainder = str.substr(partialEnding.index);
str = str.substr(0, partialEnding.index);
}
this.decodeChunks(str);
}
finalize() {
if (this.remainder.length) {
this.decodeChunks(this.remainder);
this.remainder = '';
}
return this.chunks;
}
}

View file

@ -1,302 +0,0 @@
const element = document.createElement('div');
export function escapeHtml(str) {
return str.trim().replace(/[<>"'?&]/g, c => {
let hex = c.charCodeAt(0).toString(16);
if (hex.length < 2) {
hex = '0' + hex;
}
return '&#x' + hex.toUpperCase() + ';';
});
}
export function textToHtml(str) {
return escapeHtml(str).replace(/\n/g, '<br />');
}
export function htmlToText(str) {
str = str
// we can't process tags on multiple lines so remove newlines first
.replace(/\r?\n/g, '\u0001')
.replace(/<!--.*?-->/gi, ' ')
.replace(/<br\b[^>]*>/gi, '\n')
.replace(/<\/?(p|div|table|tr|td|th)\b[^>]*>/gi, '\n\n')
.replace(/<script\b[^>]*>.*?<\/script\b[^>]*>/gi, ' ')
.replace(/^.*<body\b[^>]*>/i, '')
.replace(/^.*<\/head\b[^>]*>/i, '')
.replace(/^.*<!doctype\b[^>]*>/i, '')
.replace(/<\/body\b[^>]*>.*$/i, '')
.replace(/<\/html\b[^>]*>.*$/i, '')
.replace(/<a\b[^>]*href\s*=\s*["']?([^\s"']+)[^>]*>/gi, ' ($1) ')
.replace(/<\/?(span|em|i|strong|b|u|a)\b[^>]*>/gi, '')
.replace(/<li\b[^>]*>[\n\u0001\s]*/gi, '* ')
.replace(/<hr\b[^>]*>/g, '\n-------------\n')
.replace(/<[^>]*>/g, ' ')
// convert linebreak placeholders back to newlines
.replace(/\u0001/g, '\n')
.replace(/[ \t]+/g, ' ')
.replace(/^\s+$/gm, '')
.replace(/\n\n+/g, '\n\n')
.replace(/^\n+/, '\n')
.replace(/\n+$/, '\n');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
return str;
}
function formatTextAddress(address) {
return []
.concat(address.name || [])
.concat(address.name ? `<${address.address}>` : address.address)
.join(' ');
}
function formatTextAddresses(addresses) {
let parts = [];
let processAddress = (address, partCounter) => {
if (partCounter) {
parts.push(', ');
}
if (address.group) {
let groupStart = `${address.name}:`;
let groupEnd = `;`;
parts.push(groupStart);
address.group.forEach(processAddress);
parts.push(groupEnd);
} else {
parts.push(formatTextAddress(address));
}
};
addresses.forEach(processAddress);
return parts.join('');
}
function formatHtmlAddress(address) {
return `<a href="mailto:${escapeHtml(address.address)}" class="postal-email-address">${escapeHtml(address.name || `<${address.address}>`)}</a>`;
}
function formatHtmlAddresses(addresses) {
let parts = [];
let processAddress = (address, partCounter) => {
if (partCounter) {
parts.push('<span class="postal-email-address-separator">, </span>');
}
if (address.group) {
let groupStart = `<span class="postal-email-address-group">${escapeHtml(address.name)}:</span>`;
let groupEnd = `<span class="postal-email-address-group">;</span>`;
parts.push(groupStart);
address.group.forEach(processAddress);
parts.push(groupEnd);
} else {
parts.push(formatHtmlAddress(address));
}
};
addresses.forEach(processAddress);
return parts.join(' ');
}
function foldLines(str, lineLength, afterSpace) {
str = (str || '').toString();
lineLength = lineLength || 76;
let pos = 0,
len = str.length,
result = '',
line,
match;
while (pos < len) {
line = str.substr(pos, lineLength);
if (line.length < lineLength) {
result += line;
break;
}
if ((match = line.match(/^[^\n\r]*(\r?\n|\r)/))) {
line = match[0];
result += line;
pos += line.length;
continue;
} else if ((match = line.match(/(\s+)[^\s]*$/)) && match[0].length - (afterSpace ? (match[1] || '').length : 0) < line.length) {
line = line.substr(0, line.length - (match[0].length - (afterSpace ? (match[1] || '').length : 0)));
} else if ((match = str.substr(pos + line.length).match(/^[^\s]+(\s*)/))) {
line = line + match[0].substr(0, match[0].length - (!afterSpace ? (match[1] || '').length : 0));
}
result += line;
pos += line.length;
if (pos < len) {
result += '\r\n';
}
}
return result;
}
export function formatTextHeader(message) {
let rows = [];
if (message.from) {
rows.push({ key: 'From', val: formatTextAddress(message.from) });
}
if (message.subject) {
rows.push({ key: 'Subject', val: message.subject });
}
if (message.date) {
let dateOptions = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false
};
let dateStr = typeof Intl === 'undefined' ? message.date
: new Intl.DateTimeFormat('default', dateOptions).format(new Date(message.date));
rows.push({ key: 'Date', val: dateStr });
}
if (message.to && message.to.length) {
rows.push({ key: 'To', val: formatTextAddresses(message.to) });
}
if (message.cc && message.cc.length) {
rows.push({ key: 'Cc', val: formatTextAddresses(message.cc) });
}
if (message.bcc && message.bcc.length) {
rows.push({ key: 'Bcc', val: formatTextAddresses(message.bcc) });
}
// Align keys and values by adding space between these two
// Also make sure that the separator line is as long as the longest line
// Should end up with something like this:
/*
-----------------------------
From: xx xx <xxx@xxx.com>
Subject: Example Subject
Date: 16/02/2021, 02:57:06
To: not@found.com
-----------------------------
*/
let maxKeyLength = rows
.map(r => r.key.length)
.reduce((acc, cur) => {
return cur > acc ? cur : acc;
}, 0);
rows = rows.flatMap(row => {
let sepLen = maxKeyLength - row.key.length;
let prefix = `${row.key}: ${' '.repeat(sepLen)}`;
let emptyPrefix = `${' '.repeat(row.key.length + 1)} ${' '.repeat(sepLen)}`;
let foldedLines = foldLines(row.val, 80, true)
.split(/\r?\n/)
.map(line => line.trim());
return foldedLines.map((line, i) => `${i ? emptyPrefix : prefix}${line}`);
});
console.log(rows);
console.log(rows.map(r => r.length));
let maxLineLength = rows
.map(r => r.length)
.reduce((acc, cur) => {
return cur > acc ? cur : acc;
}, 0);
console.log(maxLineLength);
let lineMarker = '-'.repeat(maxLineLength);
let template = `
${lineMarker}
${rows.join('\n')}
${lineMarker}
`;
return template;
}
export function formatHtmlHeader(message) {
let rows = [];
if (message.from) {
rows.push(`<div class="postal-email-header-key">From</div><div class="postal-email-header-value">${formatHtmlAddress(message.from)}</div>`);
}
if (message.subject) {
rows.push(
`<div class="postal-email-header-key">Subject</div><div class="postal-email-header-value postal-email-header-subject">${escapeHtml(
message.subject
)}</div>`
);
}
if (message.date) {
let dateOptions = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false
};
let dateStr = typeof Intl === 'undefined' ? message.date
: new Intl.DateTimeFormat('default', dateOptions).format(new Date(message.date));
rows.push(
`<div class="postal-email-header-key">Date</div><div class="postal-email-header-value postal-email-header-date" data-date="${escapeHtml(
message.date
)}">${escapeHtml(dateStr)}</div>`
);
}
if (message.to && message.to.length) {
rows.push(`<div class="postal-email-header-key">To</div><div class="postal-email-header-value">${formatHtmlAddresses(message.to)}</div>`);
}
if (message.cc && message.cc.length) {
rows.push(`<div class="postal-email-header-key">Cc</div><div class="postal-email-header-value">${formatHtmlAddresses(message.cc)}</div>`);
}
if (message.bcc && message.bcc.length) {
rows.push(`<div class="postal-email-header-key">Bcc</div><div class="postal-email-header-value">${formatHtmlAddresses(message.bcc)}</div>`);
}
let template = `<div class="postal-email-header">${rows.length ? '<div class="postal-email-header-row">' : ''}${rows.join(
'</div>\n<div class="postal-email-header-row">'
)}${rows.length ? '</div>' : ''}</div>`;
return template;
}