aiplang 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/bin/aiplang.js +7 -7
  2. package/package.json +7 -5
  3. package/server/node_modules/.package-lock.json +9 -0
  4. package/server/node_modules/nodemailer/.gitattributes +6 -0
  5. package/server/node_modules/nodemailer/.ncurc.js +9 -0
  6. package/server/node_modules/nodemailer/.prettierignore +8 -0
  7. package/server/node_modules/nodemailer/.prettierrc +12 -0
  8. package/server/node_modules/nodemailer/.prettierrc.js +10 -0
  9. package/server/node_modules/nodemailer/.release-please-config.json +9 -0
  10. package/server/node_modules/nodemailer/CHANGELOG.md +976 -0
  11. package/server/node_modules/nodemailer/CODE_OF_CONDUCT.md +76 -0
  12. package/server/node_modules/nodemailer/LICENSE +16 -0
  13. package/server/node_modules/nodemailer/README.md +86 -0
  14. package/server/node_modules/nodemailer/SECURITY.txt +22 -0
  15. package/server/node_modules/nodemailer/eslint.config.js +88 -0
  16. package/server/node_modules/nodemailer/lib/addressparser/index.js +382 -0
  17. package/server/node_modules/nodemailer/lib/base64/index.js +140 -0
  18. package/server/node_modules/nodemailer/lib/dkim/index.js +245 -0
  19. package/server/node_modules/nodemailer/lib/dkim/message-parser.js +154 -0
  20. package/server/node_modules/nodemailer/lib/dkim/relaxed-body.js +154 -0
  21. package/server/node_modules/nodemailer/lib/dkim/sign.js +116 -0
  22. package/server/node_modules/nodemailer/lib/errors.js +58 -0
  23. package/server/node_modules/nodemailer/lib/fetch/cookies.js +276 -0
  24. package/server/node_modules/nodemailer/lib/fetch/index.js +278 -0
  25. package/server/node_modules/nodemailer/lib/json-transport/index.js +82 -0
  26. package/server/node_modules/nodemailer/lib/mail-composer/index.js +599 -0
  27. package/server/node_modules/nodemailer/lib/mailer/index.js +446 -0
  28. package/server/node_modules/nodemailer/lib/mailer/mail-message.js +312 -0
  29. package/server/node_modules/nodemailer/lib/mime-funcs/index.js +610 -0
  30. package/server/node_modules/nodemailer/lib/mime-funcs/mime-types.js +2109 -0
  31. package/server/node_modules/nodemailer/lib/mime-node/index.js +1334 -0
  32. package/server/node_modules/nodemailer/lib/mime-node/last-newline.js +33 -0
  33. package/server/node_modules/nodemailer/lib/mime-node/le-unix.js +40 -0
  34. package/server/node_modules/nodemailer/lib/mime-node/le-windows.js +49 -0
  35. package/server/node_modules/nodemailer/lib/nodemailer.js +151 -0
  36. package/server/node_modules/nodemailer/lib/punycode/index.js +460 -0
  37. package/server/node_modules/nodemailer/lib/qp/index.js +230 -0
  38. package/server/node_modules/nodemailer/lib/sendmail-transport/index.js +205 -0
  39. package/server/node_modules/nodemailer/lib/ses-transport/index.js +223 -0
  40. package/server/node_modules/nodemailer/lib/shared/index.js +698 -0
  41. package/server/node_modules/nodemailer/lib/smtp-connection/data-stream.js +105 -0
  42. package/server/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js +144 -0
  43. package/server/node_modules/nodemailer/lib/smtp-connection/index.js +1903 -0
  44. package/server/node_modules/nodemailer/lib/smtp-pool/index.js +641 -0
  45. package/server/node_modules/nodemailer/lib/smtp-pool/pool-resource.js +256 -0
  46. package/server/node_modules/nodemailer/lib/smtp-transport/index.js +402 -0
  47. package/server/node_modules/nodemailer/lib/stream-transport/index.js +135 -0
  48. package/server/node_modules/nodemailer/lib/well-known/index.js +47 -0
  49. package/server/node_modules/nodemailer/lib/well-known/services.json +619 -0
  50. package/server/node_modules/nodemailer/lib/xoauth2/index.js +436 -0
  51. package/server/node_modules/nodemailer/package.json +48 -0
  52. package/server/server.js +686 -865
  53. /package/{FLUX-PROJECT-KNOWLEDGE.md → aiplang-knowledge.md} +0 -0
@@ -0,0 +1,76 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ - Using welcoming and inclusive language
18
+ - Being respectful of differing viewpoints and experiences
19
+ - Gracefully accepting constructive criticism
20
+ - Focusing on what is best for the community
21
+ - Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ - The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ - Trolling, insulting/derogatory comments, and personal or political attacks
28
+ - Public or private harassment
29
+ - Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ - Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at info@nodemailer.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
+
73
+ [homepage]: https://www.contributor-covenant.org
74
+
75
+ For answers to common questions about this code of conduct, see
76
+ https://www.contributor-covenant.org/faq
@@ -0,0 +1,16 @@
1
+ Copyright (c) 2011-2023 Andris Reinman
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16
+ SOFTWARE.
@@ -0,0 +1,86 @@
1
+ # Nodemailer
2
+
3
+ [![Nodemailer](https://raw.githubusercontent.com/nodemailer/nodemailer/master/assets/nm_logo_200x136.png)](https://nodemailer.com/about/)
4
+
5
+ Send emails from Node.js – easy as cake! 🍰✉️
6
+
7
+ [![NPM](https://nodei.co/npm/nodemailer.png?downloads=true&downloadRank=true&stars=true)](https://nodemailer.com/about/)
8
+
9
+ See [nodemailer.com](https://nodemailer.com/) for documentation and terms.
10
+
11
+ > [!TIP]
12
+ > Check out **[EmailEngine](https://emailengine.app/?utm_source=github-nodemailer&utm_campaign=nodemailer&utm_medium=readme-link)** – a self-hosted email gateway that allows making **REST requests against IMAP and SMTP servers**. EmailEngine also sends webhooks whenever something changes on the registered accounts.\
13
+ > \
14
+ > Using the email accounts registered with EmailEngine, you can receive and [send emails](https://emailengine.app/sending-emails?utm_source=github-nodemailer&utm_campaign=nodemailer&utm_medium=readme-link). EmailEngine supports OAuth2, delayed sends, opens and clicks tracking, bounce detection, etc. All on top of regular email accounts without an external MTA service.
15
+
16
+ ## Having an issue?
17
+
18
+ #### First review the docs
19
+
20
+ Documentation for Nodemailer can be found at [nodemailer.com](https://nodemailer.com/about/).
21
+
22
+ #### Nodemailer throws a SyntaxError for "..."
23
+
24
+ You are using an older Node.js version than v6.0. Upgrade Node.js to get support for the spread operator. Nodemailer supports all Node.js versions starting from Node.js@v6.0.0.
25
+
26
+ #### I'm having issues with Gmail
27
+
28
+ Gmail either works well, or it does not work at all. It is probably easier to switch to an alternative service instead of fixing issues with Gmail. If Gmail does not work for you, then don't use it. Read more about it [here](https://nodemailer.com/usage/using-gmail/).
29
+
30
+ #### I get ETIMEDOUT errors
31
+
32
+ Check your firewall settings. Timeout usually occurs when you try to open a connection to a firewalled port either on the server or on your machine. Some ISPs also block email ports to prevent spamming.
33
+
34
+ #### Nodemailer works on one machine but not in another
35
+
36
+ It's either a firewall issue, or your SMTP server blocks authentication attempts from some servers.
37
+
38
+ #### I get TLS errors
39
+
40
+ - If you are running the code on your machine, check your antivirus settings. Antiviruses often mess around with email ports usage. Node.js might not recognize the MITM cert your antivirus is using.
41
+ - Latest Node versions allow only TLS versions 1.2 and higher. Some servers might still use TLS 1.1 or lower. Check Node.js docs on how to get correct TLS support for your app. You can change this with [tls.minVersion](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tls_tls_createsecurecontext_options) option
42
+ - You might have the wrong value for the `secure` option. This should be set to `true` only for port 465. For every other port, it should be `false`. Setting it to `false` does not mean that Nodemailer would not use TLS. Nodemailer would still try to upgrade the connection to use TLS if the server supports it.
43
+ - Older Node versions do not fully support the certificate chain of the newest Let's Encrypt certificates. Either set [tls.rejectUnauthorized](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tlsconnectoptions-callback) to `false` to skip chain verification or upgrade your Node version
44
+
45
+ ```js
46
+ let configOptions = {
47
+ host: 'smtp.example.com',
48
+ port: 587,
49
+ tls: {
50
+ rejectUnauthorized: true,
51
+ minVersion: 'TLSv1.2'
52
+ }
53
+ };
54
+ ```
55
+
56
+ #### I have issues with DNS / hosts file
57
+
58
+ Node.js uses [c-ares](https://nodejs.org/en/docs/meta/topics/dependencies/#c-ares) to resolve domain names, not the DNS library provided by the system, so if you have some custom DNS routing set up, it might be ignored. Nodemailer runs [dns.resolve4()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnsresolve4hostname-options-callback) and [dns.resolve6()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnsresolve6hostname-options-callback) to resolve hostname into an IP address. If both calls fail, then Nodemailer will fall back to [dns.lookup()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnslookuphostname-options-callback). If this does not work for you, you can hard code the IP address into the configuration like shown below. In that case, Nodemailer would not perform any DNS lookups.
59
+
60
+ ```js
61
+ let configOptions = {
62
+ host: '1.2.3.4',
63
+ port: 465,
64
+ secure: true,
65
+ tls: {
66
+ // must provide server name, otherwise TLS certificate check will fail
67
+ servername: 'example.com'
68
+ }
69
+ };
70
+ ```
71
+
72
+ #### I have an issue with TypeScript types
73
+
74
+ Nodemailer has official support for Node.js only. For anything related to TypeScript, you need to directly contact the authors of the [type definitions](https://www.npmjs.com/package/@types/nodemailer).
75
+
76
+ #### I have a different problem
77
+
78
+ If you are having issues with Nodemailer, then the best way to find help would be [Stack Overflow](https://stackoverflow.com/search?q=nodemailer) or revisit the [docs](https://nodemailer.com/about/).
79
+
80
+ ### License
81
+
82
+ Nodemailer is licensed under the **MIT No Attribution license**
83
+
84
+ ---
85
+
86
+ The Nodemailer logo was designed by [Sven Kristjansen](https://www.behance.net/kristjansen).
@@ -0,0 +1,22 @@
1
+ -----BEGIN PGP SIGNED MESSAGE-----
2
+ Hash: SHA256
3
+
4
+ Contact: mailto:andris@reinman.eu
5
+ Encryption: https://keys.openpgp.org/vks/v1/by-fingerprint/5D952A46E1D8C931F6364E01DC6C83F4D584D364
6
+ Preferred-Languages: en, et
7
+ -----BEGIN PGP SIGNATURE-----
8
+
9
+ iQIzBAEBCAAdFiEEXZUqRuHYyTH2Nk4B3GyD9NWE02QFAmFDnUgACgkQ3GyD9NWE
10
+ 02RqUA/+MM3afmRYq874C7wp+uN6dTMCvUX5g5zqBZ2yKpFr46L+PYvM7o8TMm5h
11
+ hmLT2I1zZmi+xezOL3zHFizaw0tKkZIz9cWl3Jrgs0FLp0zOsSz1xucp9Q2tYM/Q
12
+ vbiP6ys0gbim4tkDGRmZOEiO23s0BuRnmHt7vZg210O+D105Yd8/Ohzbj6PSLBO5
13
+ W1tA7Xw5t0FQ14NNH5+MKyDIKoCX12n0FmrC6qLTXeojf291UgKhCUPda3LIGTmx
14
+ mTXz0y68149Mw+JikRCYP8HfGRY9eA4XZrYXF7Bl2T9OJpKD3JAH+69P3xBw19Gn
15
+ Csaw3twu8P1bxoVGjY4KRrBOp68W8TwZYjWVWbqY6oV8hb/JfrMxa+kaSxRuloFs
16
+ oL6+phrDSPTWdOj2LlEDBJbPOMeDFzIlsBBcJ/JHCEHTvlHl7LoWr3YuWce9PUwl
17
+ 4r3JUovvaeuJxLgC0vu3WCB3Jeocsl3SreqNkrVc1IjvkSomn3YGm5nCNAd/2F0V
18
+ exCGRk/8wbkSjAY38GwQ8K/VuFsefWN3L9sVwIMAMu88KFCAN+GzVFiwvyIXehF5
19
+ eogP9mIXzdQ5YReQjUjApOzGz54XnDyv9RJ3sdvMHosLP+IOg+0q5t9agWv6aqSR
20
+ 2HzCpiQnH/gmM5NS0AU4Koq/L7IBeLu1B8+61/+BiHgZJJmPdgU=
21
+ =BUZr
22
+ -----END PGP SIGNATURE-----
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+
3
+ const globals = require('globals');
4
+
5
+ module.exports = [
6
+ {
7
+ ignores: ['node_modules/**', 'coverage/**', 'dist/**', 'build/**', '.nyc_output/**']
8
+ },
9
+ {
10
+ files: ['**/*.js'],
11
+ languageOptions: {
12
+ ecmaVersion: 2017,
13
+ sourceType: 'script',
14
+ globals: Object.assign({}, globals.node, globals.es2017, {
15
+ it: true,
16
+ describe: true,
17
+ beforeEach: true,
18
+ afterEach: true
19
+ })
20
+ },
21
+ rules: {
22
+ // Error detection
23
+ 'for-direction': 'error',
24
+ 'no-await-in-loop': 'error',
25
+ 'no-div-regex': 'error',
26
+ eqeqeq: 'error',
27
+ 'dot-notation': 'error',
28
+ curly: 'error',
29
+ 'no-fallthrough': 'error',
30
+ 'no-unused-expressions': [
31
+ 'error',
32
+ {
33
+ allowShortCircuit: true
34
+ }
35
+ ],
36
+ 'no-unused-vars': [
37
+ 'error',
38
+ {
39
+ varsIgnorePattern: '^_',
40
+ argsIgnorePattern: '^_',
41
+ caughtErrorsIgnorePattern: '^_'
42
+ }
43
+ ],
44
+ 'handle-callback-err': 'error',
45
+ 'no-new': 'error',
46
+ 'new-cap': 'error',
47
+ 'no-eval': 'error',
48
+ 'no-invalid-this': 'error',
49
+ radix: ['error', 'always'],
50
+ 'no-use-before-define': ['error', 'nofunc'],
51
+ 'callback-return': ['error', ['callback', 'cb', 'done']],
52
+ 'no-regex-spaces': 'error',
53
+ 'no-empty': 'error',
54
+ 'no-duplicate-case': 'error',
55
+ 'no-empty-character-class': 'error',
56
+ 'no-redeclare': 'off', // Disabled per project preference
57
+ 'block-scoped-var': 'error',
58
+ 'no-sequences': 'error',
59
+ 'no-throw-literal': 'error',
60
+ 'no-useless-call': 'error',
61
+ 'no-useless-concat': 'error',
62
+ 'no-void': 'error',
63
+ yoda: 'error',
64
+ 'no-undef': 'error',
65
+ 'global-require': 'error',
66
+ 'no-var': 'error',
67
+ 'no-bitwise': 'error',
68
+ 'no-lonely-if': 'error',
69
+ 'no-mixed-spaces-and-tabs': 'error',
70
+ 'arrow-body-style': ['error', 'as-needed'],
71
+ 'arrow-parens': ['error', 'as-needed'],
72
+ 'prefer-arrow-callback': 'error',
73
+ 'object-shorthand': 'error',
74
+ 'prefer-spread': 'error',
75
+ 'no-prototype-builtins': 'off', // Disabled per project preference
76
+ strict: ['error', 'global'],
77
+
78
+ // Disable all formatting rules (handled by Prettier)
79
+ indent: 'off',
80
+ quotes: 'off',
81
+ 'linebreak-style': 'off',
82
+ semi: 'off',
83
+ 'quote-props': 'off',
84
+ 'comma-dangle': 'off',
85
+ 'comma-style': 'off'
86
+ }
87
+ }
88
+ ];
@@ -0,0 +1,382 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Converts tokens for a single address into an address object
5
+ *
6
+ * @param {Array} tokens Tokens object
7
+ * @param {Number} depth Current recursion depth for nested group protection
8
+ * @return {Object} Address object
9
+ */
10
+ function _handleAddress(tokens, depth) {
11
+ let isGroup = false;
12
+ let state = 'text';
13
+ const addresses = [];
14
+ const data = {
15
+ address: [],
16
+ comment: [],
17
+ group: [],
18
+ text: [],
19
+ textWasQuoted: []
20
+ };
21
+ let insideQuotes = false;
22
+
23
+ // Filter out <addresses>, (comments) and regular text
24
+ for (let i = 0, len = tokens.length; i < len; i++) {
25
+ const token = tokens[i];
26
+ const prevToken = i ? tokens[i - 1] : null;
27
+ if (token.type === 'operator') {
28
+ switch (token.value) {
29
+ case '<':
30
+ state = 'address';
31
+ insideQuotes = false;
32
+ break;
33
+ case '(':
34
+ state = 'comment';
35
+ insideQuotes = false;
36
+ break;
37
+ case ':':
38
+ state = 'group';
39
+ isGroup = true;
40
+ insideQuotes = false;
41
+ break;
42
+ case '"':
43
+ insideQuotes = !insideQuotes;
44
+ state = 'text';
45
+ break;
46
+ default:
47
+ state = 'text';
48
+ insideQuotes = false;
49
+ break;
50
+ }
51
+ } else if (token.value) {
52
+ if (state === 'address') {
53
+ // Handle unquoted name that includes a "<".
54
+ // Apple Mail truncates everything between an unexpected < and an address.
55
+ token.value = token.value.replace(/^[^<]*<\s*/, '');
56
+ }
57
+
58
+ if (prevToken && prevToken.noBreak && data[state].length) {
59
+ data[state][data[state].length - 1] += token.value;
60
+ if (state === 'text' && insideQuotes) {
61
+ data.textWasQuoted[data.textWasQuoted.length - 1] = true;
62
+ }
63
+ } else {
64
+ data[state].push(token.value);
65
+ if (state === 'text') {
66
+ data.textWasQuoted.push(insideQuotes);
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ // If there is no text but a comment, replace the two
73
+ if (!data.text.length && data.comment.length) {
74
+ data.text = data.comment;
75
+ data.comment = [];
76
+ }
77
+
78
+ if (isGroup) {
79
+ // http://tools.ietf.org/html/rfc2822#appendix-A.1.3
80
+ data.text = data.text.join(' ');
81
+
82
+ // Parse group members, but flatten any nested groups (RFC 5322 doesn't allow nesting)
83
+ let groupMembers = [];
84
+ if (data.group.length) {
85
+ const parsedGroup = addressparser(data.group.join(','), { _depth: depth + 1 });
86
+ parsedGroup.forEach(member => {
87
+ if (member.group) {
88
+ groupMembers = groupMembers.concat(member.group);
89
+ } else {
90
+ groupMembers.push(member);
91
+ }
92
+ });
93
+ }
94
+
95
+ addresses.push({
96
+ name: data.text || '',
97
+ group: groupMembers
98
+ });
99
+ } else {
100
+ // If no address was found, try to detect one from regular text
101
+ if (!data.address.length && data.text.length) {
102
+ for (let i = data.text.length - 1; i >= 0; i--) {
103
+ // Security: Do not extract email addresses from quoted strings.
104
+ // RFC 5321 allows @ inside quoted local-parts like "user@domain"@example.com.
105
+ // Extracting emails from quoted text leads to misrouting vulnerabilities.
106
+ if (!data.textWasQuoted[i] && /^[^@\s]+@[^@\s]+$/.test(data.text[i])) {
107
+ data.address = data.text.splice(i, 1);
108
+ data.textWasQuoted.splice(i, 1);
109
+ break;
110
+ }
111
+ }
112
+
113
+ // Try a looser regex match if strict match found nothing
114
+ if (!data.address.length) {
115
+ let extracted = false;
116
+ for (let i = data.text.length - 1; i >= 0; i--) {
117
+ // Security: Do not extract email addresses from quoted strings
118
+ if (!data.textWasQuoted[i]) {
119
+ data.text[i] = data.text[i]
120
+ .replace(/\s*\b[^@\s]+@[^\s]+\b\s*/, match => {
121
+ if (!extracted) {
122
+ data.address = [match.trim()];
123
+ extracted = true;
124
+ return ' ';
125
+ }
126
+ return match;
127
+ })
128
+ .trim();
129
+ if (extracted) {
130
+ break;
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+
137
+ // If there's still no text but a comment exists, replace the two
138
+ if (!data.text.length && data.comment.length) {
139
+ data.text = data.comment;
140
+ data.comment = [];
141
+ }
142
+
143
+ // Keep only the first address occurrence, push others to regular text
144
+ if (data.address.length > 1) {
145
+ data.text = data.text.concat(data.address.splice(1));
146
+ }
147
+
148
+ // Join values with spaces
149
+ data.text = data.text.join(' ');
150
+ data.address = data.address.join(' ');
151
+
152
+ const address = {
153
+ address: data.address || data.text || '',
154
+ name: data.text || data.address || ''
155
+ };
156
+
157
+ if (address.address === address.name) {
158
+ if (/@/.test(address.address || '')) {
159
+ address.name = '';
160
+ } else {
161
+ address.address = '';
162
+ }
163
+ }
164
+
165
+ addresses.push(address);
166
+ }
167
+
168
+ return addresses;
169
+ }
170
+
171
+ /**
172
+ * Creates a Tokenizer object for tokenizing address field strings
173
+ *
174
+ * @constructor
175
+ * @param {String} str Address field string
176
+ */
177
+ class Tokenizer {
178
+ constructor(str) {
179
+ this.str = (str || '').toString();
180
+ this.operatorCurrent = '';
181
+ this.operatorExpecting = '';
182
+ this.node = null;
183
+ this.escaped = false;
184
+
185
+ this.list = [];
186
+ /**
187
+ * Operator tokens and which tokens are expected to end the sequence
188
+ */
189
+ this.operators = {
190
+ '"': '"',
191
+ '(': ')',
192
+ '<': '>',
193
+ ',': '',
194
+ ':': ';',
195
+ // Semicolons are not a legal delimiter per the RFC2822 grammar other
196
+ // than for terminating a group, but they are also not valid for any
197
+ // other use in this context. Given that some mail clients have
198
+ // historically allowed the semicolon as a delimiter equivalent to the
199
+ // comma in their UI, it makes sense to treat them the same as a comma
200
+ // when used outside of a group.
201
+ ';': ''
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Tokenizes the original input string
207
+ *
208
+ * @return {Array} An array of operator|text tokens
209
+ */
210
+ tokenize() {
211
+ const list = [];
212
+
213
+ for (let i = 0, len = this.str.length; i < len; i++) {
214
+ const chr = this.str.charAt(i);
215
+ const nextChr = i < len - 1 ? this.str.charAt(i + 1) : null;
216
+ this.checkChar(chr, nextChr);
217
+ }
218
+
219
+ this.list.forEach(node => {
220
+ node.value = (node.value || '').toString().trim();
221
+ if (node.value) {
222
+ list.push(node);
223
+ }
224
+ });
225
+
226
+ return list;
227
+ }
228
+
229
+ /**
230
+ * Checks if a character is an operator or text and acts accordingly
231
+ *
232
+ * @param {String} chr Character from the address field
233
+ */
234
+ checkChar(chr, nextChr) {
235
+ if (this.escaped) {
236
+ // ignore next condition blocks
237
+ } else if (chr === this.operatorExpecting) {
238
+ this.node = {
239
+ type: 'operator',
240
+ value: chr
241
+ };
242
+
243
+ if (nextChr && ![' ', '\t', '\r', '\n', ',', ';'].includes(nextChr)) {
244
+ this.node.noBreak = true;
245
+ }
246
+
247
+ this.list.push(this.node);
248
+ this.node = null;
249
+ this.operatorExpecting = '';
250
+ this.escaped = false;
251
+
252
+ return;
253
+ } else if (!this.operatorExpecting && chr in this.operators) {
254
+ this.node = {
255
+ type: 'operator',
256
+ value: chr
257
+ };
258
+ this.list.push(this.node);
259
+ this.node = null;
260
+ this.operatorExpecting = this.operators[chr];
261
+ this.escaped = false;
262
+ return;
263
+ } else if (['"', "'"].includes(this.operatorExpecting) && chr === '\\') {
264
+ this.escaped = true;
265
+ return;
266
+ }
267
+
268
+ if (!this.node) {
269
+ this.node = {
270
+ type: 'text',
271
+ value: ''
272
+ };
273
+ this.list.push(this.node);
274
+ }
275
+
276
+ if (chr === '\n') {
277
+ // Convert newlines to spaces. Carriage return is ignored as \r and \n usually
278
+ // go together anyway and there already is a WS for \n. Lone \r means something is fishy.
279
+ chr = ' ';
280
+ }
281
+
282
+ if (chr.charCodeAt(0) >= 0x21 || [' ', '\t'].includes(chr)) {
283
+ // skip command bytes
284
+ this.node.value += chr;
285
+ }
286
+
287
+ this.escaped = false;
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Maximum recursion depth for parsing nested groups.
293
+ * RFC 5322 doesn't allow nested groups, so this is a safeguard against
294
+ * malicious input that could cause stack overflow.
295
+ */
296
+ const MAX_NESTED_GROUP_DEPTH = 50;
297
+
298
+ /**
299
+ * Parses structured e-mail addresses from an address field
300
+ *
301
+ * Example:
302
+ *
303
+ * 'Name <address@domain>'
304
+ *
305
+ * will be converted to
306
+ *
307
+ * [{name: 'Name', address: 'address@domain'}]
308
+ *
309
+ * @param {String} str Address field
310
+ * @param {Object} options Optional options object
311
+ * @param {Number} options._depth Internal recursion depth counter (do not set manually)
312
+ * @return {Array} An array of address objects
313
+ */
314
+ function addressparser(str, options) {
315
+ options = options || {};
316
+ const depth = options._depth || 0;
317
+
318
+ // Prevent stack overflow from deeply nested groups (DoS protection)
319
+ if (depth > MAX_NESTED_GROUP_DEPTH) {
320
+ return [];
321
+ }
322
+
323
+ const tokenizer = new Tokenizer(str);
324
+ const tokens = tokenizer.tokenize();
325
+
326
+ const addresses = [];
327
+ let address = [];
328
+ let parsedAddresses = [];
329
+
330
+ tokens.forEach(token => {
331
+ if (token.type === 'operator' && (token.value === ',' || token.value === ';')) {
332
+ if (address.length) {
333
+ addresses.push(address);
334
+ }
335
+ address = [];
336
+ } else {
337
+ address.push(token);
338
+ }
339
+ });
340
+
341
+ if (address.length) {
342
+ addresses.push(address);
343
+ }
344
+
345
+ addresses.forEach(addr => {
346
+ const handled = _handleAddress(addr, depth);
347
+ if (handled.length) {
348
+ parsedAddresses = parsedAddresses.concat(handled);
349
+ }
350
+ });
351
+
352
+ // Merge fragments produced when unquoted display names contain commas.
353
+ // "Joe Foo, PhD <joe@example.com>" is split on the comma into
354
+ // [{name:"Joe Foo", address:""}, {name:"PhD", address:"joe@example.com"}].
355
+ // Recombine: a name-only entry followed by an entry with both name and address.
356
+ for (let i = parsedAddresses.length - 2; i >= 0; i--) {
357
+ const current = parsedAddresses[i];
358
+ const next = parsedAddresses[i + 1];
359
+ if (current.address === '' && current.name && !current.group && next.address && next.name) {
360
+ next.name = current.name + ', ' + next.name;
361
+ parsedAddresses.splice(i, 1);
362
+ }
363
+ }
364
+
365
+ if (options.flatten) {
366
+ const flatAddresses = [];
367
+ const walkAddressList = list => {
368
+ list.forEach(entry => {
369
+ if (entry.group) {
370
+ return walkAddressList(entry.group);
371
+ }
372
+ flatAddresses.push(entry);
373
+ });
374
+ };
375
+ walkAddressList(parsedAddresses);
376
+ return flatAddresses;
377
+ }
378
+
379
+ return parsedAddresses;
380
+ }
381
+
382
+ module.exports = addressparser;