@xpoudy/free-tools 0.1.1 → 1.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.
package/assets/mail.js ADDED
@@ -0,0 +1,302 @@
1
+ import {InputError,asciiDomain,emailFormat,requiredText,textList,showInteger as whole,
2
+ csvDownload,modelResult as result} from './common.js';
3
+
4
+ export function parseHeaders(content) {
5
+ const raw=requiredText(content,'message headers',300_000).replace(/^\uFEFF/,'').trimStart();
6
+ const headerBlock=raw.split(/\r?\n\r?\n/,1)[0].trimEnd();
7
+ const headers=new Map();
8
+ let current=null, values=null;
9
+ for(const line of headerBlock.split(/\r?\n/)){
10
+ if(/^[ \t]/.test(line) && current){
11
+ values[values.length-1]+=' '+line.trim();
12
+ continue;
13
+ }
14
+ const match=line.match(/^([!-9;-~]+):[ \t]*(.*)$/);
15
+ if(!match) throw new InputError('Paste raw email headers. A header line is missing its field name or colon.');
16
+ current=match[1].toLowerCase();
17
+ if(!headers.has(current)) headers.set(current,[]);
18
+ values=headers.get(current);
19
+ values.push(match[2].trim());
20
+ }
21
+ return headers;
22
+ }
23
+ function removeComments(text) {
24
+ let depth=0, quoted=false, output='';
25
+ for(let p=0;p<text.length;p++){
26
+ const ch=text[p];
27
+ if(ch==='\\' && (quoted || depth)){
28
+ if(!depth) output+=ch+(text[p+1]??'');
29
+ p++;
30
+ }else if(!depth && ch==='"'){
31
+ quoted=!quoted; output+=ch;
32
+ }else if(!quoted && ch==='('){if(!depth) output+=' ';depth++;}
33
+ else if(!quoted && ch===')' && depth) depth--;
34
+ else if(!depth) output+=ch;
35
+ }
36
+ return output;
37
+ }
38
+
39
+ export function authentication(input) {
40
+ const headers=parseHeaders(input.headers);
41
+ const found=headers.get('authentication-results')??[];
42
+ const identity=['from','return-path','reply-to'].flatMap(name=>{
43
+ const values=headers.get(name);
44
+ return values?.length ? [[{'from':'Visible From','return-path':'Return-Path','reply-to':'Reply-To'}[name],values.join(' / ')]]:[];
45
+ });
46
+ const rows=[];
47
+ const methods=['spf','dkim','dmarc'];
48
+ for(const raw of found){
49
+ const clean=removeComments(raw);
50
+ const chunks=clean.split(';');
51
+ const server=chunks.shift().trim();
52
+ for(const part of chunks){
53
+ const match=part.match(/^\s*(spf|dkim|dmarc)(?:\/\d+)?\s*=\s*([a-z-]+)/i);
54
+ if(!match) continue;
55
+ const fields=[...part.matchAll(/\b(smtp\.(?:mailfrom|helo)|header\.(?:d|i|from))\s*=\s*("[^"]*"|[^;\s]+)/gi)];
56
+ rows.push([match[1].toUpperCase(),match[2].toUpperCase(),
57
+ fields.map(field=>field[1]+'='+field[2]).join(' ')||'No domain reported',server||'Unspecified']);
58
+ }
59
+ }
60
+ const metrics=methods.map(method=>{
61
+ const statuses=[...new Set(rows.filter(x=>x[0]===method.toUpperCase()).map(x=>x[1]))];
62
+ return [method.toUpperCase(),statuses.join(' / ')||'Not reported'];
63
+ });
64
+ return result(metrics,{
65
+ table:{columns:['Check','Reported result','Identity','Reporting server'],rows:rows.slice(0,100),total:rows.length},
66
+ blocks:identity,
67
+ notes:[found.length?'Use the results added by a receiving system you trust. Messages can contain several authentication reports; these values are not independently verified.' :
68
+ 'No Authentication-Results field was found. Open the original received message, then copy the full headers.',
69
+ 'A pass in these headers does not establish inbox placement.']});
70
+ }
71
+
72
+ function ipv4(value) {
73
+ const parts=value.split('.');
74
+ return parts.length===4 && parts.every(part=>/^(?:0|[1-9]\d{0,2})$/.test(part) && Number(part)<=255);
75
+ }
76
+ function ipv6(value) {
77
+ if(!value.includes(':') || !/^[a-f0-9:.]+$/i.test(value)) return false;
78
+ try { return new URL('http://['+value+']/').hostname.startsWith('['); }catch {return false;}
79
+ }
80
+ function spfName(value) {
81
+ const name=String(value).trim().toLowerCase();
82
+ const normalized=name.endsWith('.')?name.slice(0,-1):name;
83
+ if(asciiDomain(normalized)) return asciiDomain(normalized);
84
+ const labels=normalized.split('.');
85
+ if(normalized.length>253 || labels.length<2 || !/^[a-z0-9-]+$/.test(labels.at(-1))) return null;
86
+ return labels.every(label=>/^(?!-)[a-z0-9_-]{1,63}(?<!-)$/.test(label)) ? normalized : null;
87
+ }
88
+ function domainSpec(value) {
89
+ if(spfName(value)) return true;
90
+ if(!value.includes('%')) return false;
91
+ const expanded=value.replace(/%(?:\{[slodipvhcrt][0-9]*r?[.\-+,/_=]*\}|[%_\-])/gi,'placeholder');
92
+ return Boolean(spfName(expanded));
93
+ }
94
+
95
+ function stripTXT(line) {
96
+ const clean=line.trim();
97
+ if(!clean.startsWith('"')) return clean;
98
+ const tokens=[...clean.matchAll(/"([^"\\]*)"/g)];
99
+ if(!tokens.length || clean.replace(/"[^"\\]*"/g,'').trim()) throw new InputError('Paste the SPF value or its quoted TXT chunks.');
100
+ return tokens.map(x=>x[1]).join('');
101
+ }
102
+ function spfMethod(token) {
103
+ const bare=token.replace(/^[+?~-]/,'');
104
+ if(/^all$/i.test(bare)) return 'all';
105
+ const mx=bare.match(/^(a|mx)(?::([^/]+))?(?:\/(\d+))?(?:\/\/(\d+))?$/i);
106
+ if(mx){
107
+ if((mx[2]&&!domainSpec(mx[2])) || (mx[3]&&Number(mx[3])>32) || (mx[4]&&Number(mx[4])>128)) {
108
+ throw new InputError('Check the domain or address mask in '+token+'.');
109
+ }
110
+ return mx[1].toLowerCase();
111
+ }
112
+ const domain=bare.match(/^(include|exists|ptr)(?::(.+))?$/i);
113
+ if(domain){
114
+ const method=domain[1].toLowerCase();
115
+ if((method!=='ptr'&&!domain[2]) || (domain[2]&&!domainSpec(domain[2]))) throw new InputError('Check the domain in '+token+'.');
116
+ return method;
117
+ }
118
+ const ip=bare.match(/^(ip4|ip6):([^/]+)(?:\/(\d+))?$/i);
119
+ if(ip){
120
+ const version=ip[1].toLowerCase();
121
+ if((version==='ip4'?!ipv4(ip[2]):!ipv6(ip[2])) || (ip[3]&&Number(ip[3])>(version==='ip4'?32:128))) {
122
+ throw new InputError('Check the address or prefix in '+token+'.');
123
+ }
124
+ return version;
125
+ }
126
+ const mod=token.match(/^([a-z][\w.-]*)=(\S+)$/i);
127
+ if(mod){
128
+ const term=mod[1].toLowerCase();
129
+ if(['redirect','exp'].includes(term) && !domainSpec(mod[2])) throw new InputError('Check the domain in '+token+'.');
130
+ return term==='redirect' ? term : 'modifier';
131
+ }
132
+ throw new InputError('Unsupported or malformed SPF term: '+token.slice(0,120)+'.');
133
+ }
134
+
135
+ export function spf(input) {
136
+ const raw=String(input.existing??'').trim();
137
+ const lines=raw.split(/\r?\n/).filter(line=>line.trim());
138
+ if(lines.length>1) throw new InputError('Enter one SPF record per DNS name. Merge duplicate SPF records only after reviewing their authorization rules.');
139
+ const existing=lines.length?stripTXT(lines[0]):'';
140
+ if(existing && !/^v=spf1(?:\s|$)/i.test(existing)) throw new InputError('Paste the SPF TXT value beginning with v=spf1.');
141
+ const outside=String(input.final_policy??'keep');
142
+ if(!['keep','~all','-all','?all','+all'].includes(outside)) throw new InputError('Choose a valid SPF final policy.');
143
+ const terms=existing?existing.split(/\s+/).slice(1):[];
144
+ if(terms.length>100) throw new InputError('Keep the draft within 100 SPF terms.');
145
+ const current=terms.map(token=>({token,kind:spfMethod(token)}));
146
+ const terminals=current.filter(row=>row.kind==='all');
147
+ if(terminals.length>1 || (terminals.length && current.slice(current.indexOf(terminals[0])+1).some(row=>!['modifier','redirect'].includes(row.kind)))) {
148
+ throw new InputError('Review the existing all rule. SPF mechanisms after all are never evaluated.');
149
+ }
150
+ for(const name of ['redirect','exp']){
151
+ if(terms.filter(t=>t.toLowerCase().startsWith(name+'=')).length>1) throw new InputError('The SPF value includes more than one '+name+' modifier.');
152
+ }
153
+ const relevant=new Map();
154
+ for(const token of terms){
155
+ const m=token.match(/^([+?~-]?)include:(.+)$/i);
156
+ if(m) relevant.set(spfName(m[2])||m[2].toLowerCase(),m[1]||'+');
157
+ }
158
+ const additions=[];
159
+ for(const item of [...new Set(textList(input.includes).map(v=>v.toLowerCase()))]){
160
+ const domain=spfName(item);
161
+ if(!domain) throw new InputError('Enter a valid provider domain for each include. Do not paste include: or a URL.');
162
+ if(relevant.has(domain)&&relevant.get(domain)!=='+') throw new InputError('The existing include for '+domain+' has a non-pass qualifier. Review it before adding that provider.');
163
+ if(!relevant.has(domain)) additions.push('include:'+domain);
164
+ relevant.set(domain,'+');
165
+ }
166
+ if(additions.length>100) throw new InputError('Keep the draft within 100 include additions.');
167
+ const final=outside==='keep'?(terminals[0]?.token||''):outside;
168
+ const mechanisms=current.filter(row=>!['all','modifier','redirect'].includes(row.kind)).map(row=>row.token);
169
+ const modifiers=terms.filter(t=>/^[a-z][\w.-]*=/i.test(t));
170
+ if(!existing && !additions.length && !final) throw new InputError('Enter an SPF record, an authorized provider domain, or a final policy.');
171
+ const all=['v=spf1',...mechanisms,...additions,...(final?[final]:[]),...modifiers];
172
+ const record=all.join(' ');
173
+ if(record.length>4096) throw new InputError('The draft exceeds 4,096 characters. Review the sending sources.');
174
+ const lookups=all.slice(1).filter(t=>['include','a','mx','ptr','exists','redirect'].includes(spfMethod(t))).length;
175
+ const notes=[
176
+ 'This counts DNS-using terms visible in the pasted value. Includes and redirects can contain further DNS lookups. Verify the complete record with your DNS provider.',
177
+ 'Publish one SPF policy at a given DNS name. Confirm that every listed source is authorized before publishing.',
178
+ ];
179
+ if(final==='all'||final==='+all') notes.unshift('This final policy authorizes any sender. Review it before publishing.');
180
+ if(final && current.some(row=>row.kind==='redirect')) notes.unshift('A redirect modifier has no effect when the policy contains all.');
181
+ if(lookups>10) notes.unshift('The pasted policy already shows more than 10 DNS-using terms before considering nested records.');
182
+ if(record.length>255) notes.push('This value exceeds one DNS TXT character-string. Use your provider’s instructions to publish it as a single TXT record with joined chunks.');
183
+ return result([['Draft length',whole(record.length)+' characters'],['Visible DNS-using terms',whole(lookups)],['New includes',whole(additions.length)]],
184
+ {text:record,notes});
185
+ }
186
+
187
+ export function dmarc(input) {
188
+ const domain=asciiDomain(input.domain_name);
189
+ if(!domain) throw new InputError('Enter a public domain, such as example.com.');
190
+ const policy=String(input.policy??''), subdomain=String(input.subdomain_policy??'inherit');
191
+ const policies=['none','quarantine','reject'];
192
+ if(!policies.includes(policy)||!['inherit',...policies].includes(subdomain)) throw new InputError('Choose a valid DMARC policy.');
193
+ const spfAlignment=String(input.spf_alignment??'r'), dkimAlignment=String(input.dkim_alignment??'r');
194
+ if(!['r','s'].includes(spfAlignment)||!['r','s'].includes(dkimAlignment)) throw new InputError('Choose relaxed or strict alignment.');
195
+ const recipients=[];
196
+ const seenRecipients=new Set();
197
+ for(const value of textList(input.report_addresses)){
198
+ const email=value.replace(/^mailto:/i,'').trim();
199
+ const verdict=emailFormat(email);
200
+ if(!verdict.key||/[;!,]/.test(email)) throw new InputError('Enter one standard aggregate report email address per line.');
201
+ if(!seenRecipients.has(verdict.key)){
202
+ seenRecipients.add(verdict.key);
203
+ recipients.push(email.slice(0,email.lastIndexOf('@'))+'@'+verdict.domain);
204
+ }
205
+ }
206
+ if(recipients.length>10) throw new InputError('Use up to 10 aggregate report recipients.');
207
+ const tags=['v=DMARC1','p='+policy];
208
+ if(subdomain!=='inherit') tags.push('sp='+subdomain);
209
+ tags.push('aspf='+spfAlignment,'adkim='+dkimAlignment);
210
+ if(recipients.length) tags.push('rua='+recipients.map(email=>{
211
+ const at=email.lastIndexOf('@');
212
+ return 'mailto:'+encodeURIComponent(email.slice(0,at))+email.slice(at);
213
+ }).join(','));
214
+ const record=tags.join('; ')+';';
215
+ const name='_dmarc.'+domain;
216
+ const notes=[
217
+ 'Publish as one TXT record at the indicated name. Test SPF, DKIM and DMARC alignment from every legitimate sending service before changing enforcement.',
218
+ 'Reporting domains outside your organization may need DNS authorization. Check that the reporting mailbox can accept reports and that sharing is appropriate.',
219
+ ];
220
+ if(record.length>255) notes.push('The value exceeds one DNS TXT character-string. Follow your provider’s instructions for joined chunks in one record.');
221
+ return result([['DNS name',name],['Record type','TXT'],['Policy',policy],['Report recipients',whole(recipients.length)]],
222
+ {text:record,notes});
223
+ }
224
+
225
+ function HTTPSurl(text) {
226
+ try{
227
+ if(/\s/.test(text)) return false;
228
+ const parsed=new URL(text);
229
+ return parsed.protocol==='https:' && !parsed.username && !parsed.password && !parsed.hash && !!parsed.hostname
230
+ && /^https:\/\//i.test(text);
231
+ }catch{return false;}
232
+ }
233
+
234
+ export function unsubscribe(input) {
235
+ const headers=parseHeaders(input.headers);
236
+ const unsubscribeHeaders=headers.get('list-unsubscribe')??[];
237
+ const postHeaders=headers.get('list-unsubscribe-post')??[];
238
+ const all=unsubscribeHeaders.flatMap(value=>[...value.matchAll(/<([^<>]+)>/g)].map(match=>match[1].trim()));
239
+ const https=all.filter(HTTPSurl);
240
+ const mailto=all.filter(value=>/^mailto:/i.test(value));
241
+ const validPost=postHeaders.length===1 && /^List-Unsubscribe=One-Click$/.test(postHeaders[0]);
242
+ const cover=(headers.get('dkim-signature')??[]).some(sig=>{
243
+ const h=sig.match(/(?:^|;)\s*h\s*=\s*([^;]+)/i);
244
+ const fields=new Set((h?.[1]??'').split(':').map(x=>x.trim().toLowerCase()));
245
+ return fields.has('list-unsubscribe') && fields.has('list-unsubscribe-post');
246
+ });
247
+ const plainHttp=all.some(value=>/^http:/i.test(value));
248
+ const complete=unsubscribeHeaders.length===1 && https.length===1 && !plainHttp && validPost && cover;
249
+ return result([['Header review',complete?'Required fields present':'Needs review'],
250
+ ['HTTPS endpoints',whole(https.length)],['Valid one-click POST field',validPost?'Present':'Missing or invalid'],
251
+ ['Both fields listed on a DKIM signature',cover?'Listed':'Not listed']],{
252
+ table:{columns:['Header check','What the paste contains'],rows:[
253
+ ['List-Unsubscribe',unsubscribeHeaders.length===1?(https.length===1&&!plainHttp?'One HTTPS URL is present.':'Use one HTTPS URL and remove any plain HTTP URL.'):
254
+ unsubscribeHeaders.length?'More than one field.':'Missing.'],
255
+ ['List-Unsubscribe-Post',validPost?'List-Unsubscribe=One-Click':(postHeaders.join(' / ')||'Missing.')],
256
+ ['DKIM coverage',cover?'A signature lists both headers. Cryptographic verification is separate.':'No signature lists both headers.'],
257
+ ['Mailto entries',whole(mailto.length)]
258
+ ]},notes:['This tool reads headers without requesting URLs or changing subscriptions. It cannot verify endpoint behavior or DKIM signatures.',
259
+ 'Test the receiving inbox action and confirm it prevents later marketing to the test contact.']});
260
+ }
261
+
262
+ function bounceMeaning(smtp,enhanced,line){
263
+ if(enhanced==='5.1.1') return ['Invalid recipient','Confirm the address. Keep confirmed invalid addresses out of later sends.'];
264
+ if(enhanced==='5.7.26'||enhanced==='5.7.515') return ['Authentication or sender policy','Inspect SPF, DKIM and DMARC for the actual message. Read the receiving provider’s explanation.'];
265
+ if(enhanced && /^(?:[45])\.2\.2$/.test(enhanced)) return ['Mailbox capacity','Read the recipient server’s retry guidance and check whether the mailbox can receive mail.'];
266
+ if(enhanced && /^[45]\.7\./.test(enhanced)) return ['Security or provider policy','Read the full provider response. Check sender authentication, permission and any stated restrictions.'];
267
+ if(enhanced && /^[45]\.1\./.test(enhanced)) return ['Address or routing','Check which address or route the full response names before changing the list.'];
268
+ if(smtp===421||enhanced?.startsWith('4.')) return ['Temporary delivery failure','Check queue and provider status. Use bounded retries according to your service’s policy.'];
269
+ if(/\b(?:user unknown|no such (?:user|mailbox)|recipient not found)\b/i.test(line)) return ['Likely invalid recipient','Confirm the recipient address against the provider’s full response.'];
270
+ if(smtp && smtp>=500) return ['Rejected attempt','Read the provider’s reason and correct it before retrying.'];
271
+ if(smtp && smtp>=400) return ['Temporary delivery failure','Check the queue and the provider’s stated retry behavior.'];
272
+ return ['Provider-specific failure','Check the full delivery notice or provider help for the stated reason.'];
273
+ }
274
+
275
+ export function bounce(input) {
276
+ const raw=requiredText(input.response,'an SMTP response',120_000);
277
+ const logs=raw.split(/\r?\n/).filter(line=>line.trim());
278
+ const rows=[];
279
+ let temporary=0, permanent=0;
280
+ const seen=new Set();
281
+ for(const line of logs){
282
+ const enhanced=line.match(/(?<![\d.])([45]\.[0-9]{1,3}\.[0-9]{1,3})(?![\d.])/);
283
+ const regular=line.match(/(?:^|\s|[:=(])([45][0-5]\d)(?=(?:[\s-]|$))/);
284
+ if(!regular&&!enhanced) continue;
285
+ const smtp=regular?Number(regular[1]):null, code=enhanced?.[1];
286
+ const id=String(smtp??'')+' '+String(code??'')+' '+line.trim();
287
+ if(seen.has(id)) continue;
288
+ seen.add(id);
289
+ const mismatch=smtp&&code&&String(smtp)[0]!==code[0];
290
+ const replyClass=smtp?String(smtp)[0]:code[0];
291
+ const permanence=replyClass==='4'?'Temporary':'Permanent';
292
+ if(permanence==='Temporary') temporary++; else permanent++;
293
+ const [meaning,action]=bounceMeaning(smtp,code,line);
294
+ rows.push([smtp??'—',code??'—',mismatch?permanence+' · conflicting codes':permanence,meaning,action]);
295
+ }
296
+ if(!rows.length) throw new InputError('No SMTP 4xx or 5xx code was found. Paste the actual failure line, such as 550 5.1.1.');
297
+ const columns=['SMTP','Enhanced status','Failure class','Likely area','First check'];
298
+ return result([['Failure lines',whole(rows.length)],['Temporary',whole(temporary)],['Permanent',whole(permanent)]],{
299
+ table:{columns,rows:rows.slice(0,60),total:rows.length},
300
+ downloads:[csvDownload('smtp-bounce-explanations.csv',columns,rows)],
301
+ notes:['Codes describe delivery attempts. Provider wording is important, and a permanent policy rejection is different from an invalid recipient.']});
302
+ }
@@ -0,0 +1,47 @@
1
+ import {InputError,modelResult,requiredText} from './common.js';
2
+
3
+ const CODES=new Map([
4
+ ['127.0.0.2','SBL listing'],['127.0.0.3','CSS listing'],['127.0.0.4','XBL listing'],['127.0.0.9','DROP listing'],
5
+ ['127.0.0.10','PBL policy listing maintained by the network'],['127.0.0.11','PBL policy listing maintained by Spamhaus'],['127.0.0.30','BCL listing'],
6
+ ['127.0.1.2','Low-reputation domain'],['127.0.1.4','Phishing-related domain'],['127.0.1.5','Malware-related domain'],['127.0.1.6','Botnet control domain'],
7
+ ['127.0.1.102','Abused legitimate domain'],['127.0.1.103','Abused redirector'],['127.0.1.104','Abused domain used in phishing'],['127.0.1.105','Abused domain used by malware'],['127.0.1.106','Abused domain hosting botnet control'],
8
+ ['127.0.1.255','Domain list cannot be queried with an IP address'],['127.255.255.250','Query key disabled'],['127.255.255.251','Invalid use of query key'],['127.255.255.252','Incorrect blocklist query name'],['127.255.255.254','Public resolver rejected'],['127.255.255.255','Query limit exceeded']
9
+ ]);
10
+ const httpMap=new Map([1002,1003,1004,1009,1010,1011,1030,2002,2004,2005,2006,2102,2103,2104,2105,2106,256250,256251].map(n=>[String(n),n<2000?'127.0.0.'+(n-1000):n<3000?'127.0.1.'+(n-2000):'127.255.255.'+(n-256000)]));
11
+ const errorCodes=new Set(['127.0.1.255',...Array.from({length:6},(_,i)=>'127.255.255.'+(250+i))]);
12
+ export function blocklistDecode(values){
13
+ const input=requiredText(values.codes,'a Spamhaus result or DNS status',3500);
14
+ const codes=[...new Set(input.match(/\b(?:NXDOMAIN|NOERROR|SERVFAIL|REFUSED|TIMEOUT|\d{1,3}(?:\.\d{1,3}){3}|\d{4,6})\b/gi)??[])];
15
+ if(!codes.length)throw new InputError('Paste a DNS code, HTTP result code, or status such as NXDOMAIN.');
16
+ const rows=codes.slice(0,30).map(original=>{
17
+ const code=httpMap.get(original)??original.toUpperCase();
18
+ if(CODES.has(code))return [original,errorCodes.has(code)?'Lookup failed':'Listing reported',CODES.get(code)];
19
+ if(code==='NXDOMAIN')return [original,'No listing returned','Check that the lookup used the correct list and a supported resolver.'];
20
+ if(code==='NOERROR')return [original,'DNS query completed','Read the returned A records before drawing a conclusion.'];
21
+ if(['SERVFAIL','REFUSED','TIMEOUT'].includes(code))return [original,'Lookup failed','The response cannot establish listing status.'];
22
+ return [original,'Unrecognized','Confirm the list and code with the provider.'];
23
+ });
24
+ const count=status=>String(rows.filter(r=>r[1]===status).length);
25
+ return modelResult([['Listing signals',count('Listing reported')],['Lookup errors',count('Lookup failed')],['Inputs interpreted',String(rows.length)]],{table:{columns:['Supplied value','Interpretation','Details'],rows},notes:['This decodes the responses you supply. Open the provider checker for a fresh result. A PBL entry is a sending policy signal and does not by itself show an incident.']});
26
+ }
27
+
28
+ export function emailSpamCheck(values){
29
+ const subject=String(values.subject??'').trim();
30
+ const draft=requiredText(values.message,'message text or HTML',120000);
31
+ const html=/<(?:body|html|div|table|p|a|img)\b/i.test(draft);
32
+ const visible=html?draft.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi,' ').replace(/<!--[^]*?-->/g,' ').replace(/<[^>]*>/g,' ').replace(/&(?:nbsp|amp|lt|gt|quot);/gi,' '):draft;
33
+ const words=visible.match(/[\p{L}\p{N}]+/gu)??[];
34
+ const distinct=new Set((draft.match(/https?:\/\/[^\s"'<>]+/gi)??[]).map(x=>x.replace(/[.,;!?]+$/,'')));
35
+ const images=[...draft.matchAll(/<img\b[^>]*>/gi)];
36
+ const missingAlt=images.filter(i=>!/\balt\s*=/i.test(i[0])).length;
37
+ const issues=[];
38
+ if(!subject)issues.push(['Subject','Add a subject that describes the message.']);
39
+ if(/!{3,}|\?{3,}/.test(subject+' '+visible))issues.push(['Repeated punctuation','Check punctuation where the message looks hard to read.']);
40
+ const allCaps=words.filter(w=>w.length>3&&/^[A-Z]+$/.test(w));
41
+ if(allCaps.length>=3&&allCaps.length/words.length>.2)issues.push(['Capitalization','Many words are uppercase. Review emphasis and readability.']);
42
+ if(distinct.size>=5)issues.push(['Many links','Check that every link is relevant and recognizable.']);
43
+ if(missingAlt)issues.push(['Image alternative text',`${missingAlt} image tag${missingAlt===1?' has':'s have'} no alt attribute.`]);
44
+ if(html&&images.length&&words.length<10)issues.push(['Image-heavy message','Provide readable text for recipients who block images.']);
45
+ if(html&&/(?:<script\b|<iframe\b|\s(?:href|src)\s*=\s*["']?javascript:)/i.test(draft))issues.push(['Unsupported active content','Use standard links and email-compatible HTML.']);
46
+ return modelResult([['Review items',String(issues.length)],['Readable words',String(words.length)],['Links found',String(distinct.size)],['Input',html?'HTML':'Plain text']],{table:{columns:['Finding','What to review'],rows:issues},notes:[issues.length?'Review each item in the context of your message.':'No issues were found by these specific rules.','A message-content check cannot determine sender reputation or predict inbox placement.']});
47
+ }
@@ -0,0 +1,6 @@
1
+ body{background:#050912;color:#e2e8f0;font-family:system-ui,sans-serif}
2
+ .mirror-directory{padding:3rem 0;max-width:70rem;margin:auto;width:calc(100% - 2rem)}
3
+ .mirror-directory ul{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,19rem),1fr));gap:1rem;list-style:none;padding:0}
4
+ .mirror-directory li{padding:1rem;border:1px solid #253244;background:#0a0f1d;border-radius:14px}
5
+ .mirror-directory a,.mirror-origin a{color:#00f5d4;text-decoration:underline}
6
+ .mirror-directory li p{margin:.55rem 0;color:#cbd5e1}
@@ -0,0 +1,179 @@
1
+ import {InputError,requiredText,MAX_FILE_SIZE,MAX_ROWS,showInteger as whole,
2
+ showPercent as percent,ratio,csvDownload,modelResult as result} from './common.js';
3
+
4
+ const MAX_EXPANDED=8*1024*1024;
5
+ const MAX_REPORTS=20;
6
+ const decoder=new TextDecoder('utf-8',{fatal:true});
7
+
8
+ function decode(bytes) {
9
+ try { return decoder.decode(bytes); }
10
+ catch {throw new InputError('Use UTF-8 encoded DMARC reports.');}
11
+ }
12
+
13
+ async function expand(bytes,format,expected=MAX_EXPANDED) {
14
+ if(typeof DecompressionStream!=='function') throw new InputError('This browser cannot decompress that format. Open the XML file directly.');
15
+ let reader;
16
+ try {
17
+ const stream=new Blob([bytes]).stream().pipeThrough(new DecompressionStream(format));
18
+ reader=stream.getReader();
19
+ }catch{throw new InputError('This browser cannot decompress that format. Open the XML file directly.');}
20
+ let total=0;
21
+ const chunks=[];
22
+ try{
23
+ while(true){
24
+ const next=await reader.read();
25
+ if(next.done) break;
26
+ total+=next.value.byteLength;
27
+ if(total>MAX_EXPANDED||total>expected){
28
+ await reader.cancel();
29
+ throw new InputError('The archive expands beyond the report size limit.');
30
+ }
31
+ chunks.push(next.value);
32
+ }
33
+ }catch(error){
34
+ if(error instanceof InputError) throw error;
35
+ throw new InputError('The compressed report is incomplete or invalid.');
36
+ }finally{reader.releaseLock();}
37
+ const out=new Uint8Array(total);
38
+ let offset=0;
39
+ for(const chunk of chunks){out.set(chunk,offset);offset+=chunk.byteLength;}
40
+ return out;
41
+ }
42
+
43
+ const crcTable=Uint32Array.from({length:256},(_,i)=>{
44
+ let x=i;
45
+ for(let p=0;p<8;p++) x=(x&1)?(0xedb88320^(x>>>1)):(x>>>1);
46
+ return x>>>0;
47
+ });
48
+ function crc32(bytes) {
49
+ let crc=0xffffffff;
50
+ for(const b of bytes) crc=crcTable[(crc^b)&255]^(crc>>>8);
51
+ return (crc^0xffffffff)>>>0;
52
+ }
53
+
54
+ async function xmlFromZip(bytes) {
55
+ const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);
56
+ const u16=p=>view.getUint16(p,true), u32=p=>view.getUint32(p,true);
57
+ const fail=()=>{throw new InputError('Use a regular ZIP archive with unencrypted XML files, or extract the XML and open it directly.');};
58
+ let end=-1;
59
+ for(let p=bytes.byteLength-22;p>=Math.max(0,bytes.byteLength-65557);p--){
60
+ if(u32(p)===0x06054b50 && p+22+u16(p+20)===bytes.byteLength){end=p;break;}
61
+ }
62
+ if(end<0 || u16(end+4) || u16(end+6) || u16(end+8)!==u16(end+10)) fail();
63
+ const count=u16(end+10), size=u32(end+12), start=u32(end+16);
64
+ if(count>200 || start+size>end) fail();
65
+ let cursor=start, sum=0;
66
+ const reports=[];
67
+ for(let i=0;i<count;i++){
68
+ if(cursor+46>start+size || u32(cursor)!==0x02014b50) fail();
69
+ const flag=u16(cursor+8), method=u16(cursor+10), checksum=u32(cursor+16);
70
+ const compressed=u32(cursor+20), expanded=u32(cursor+24);
71
+ const length=u16(cursor+28), extra=u16(cursor+30), comment=u16(cursor+32);
72
+ const local=u32(cursor+42), next=cursor+46+length+extra+comment;
73
+ if(next>start+size) fail();
74
+ const name=new TextDecoder().decode(bytes.subarray(cursor+46,cursor+46+length));
75
+ cursor=next;
76
+ if(!/\.xml$/i.test(name) || name.startsWith('__MACOSX/')) continue;
77
+ if((flag&1) || ![0,8].includes(method) || local+30>start || u32(local)!==0x04034b50
78
+ || u16(local+8)!==method || (u16(local+6)&1)) fail();
79
+ const body=local+30+u16(local+26)+u16(local+28);
80
+ if(body+compressed>start || expanded>MAX_EXPANDED || sum+expanded>MAX_EXPANDED
81
+ || reports.length>=MAX_REPORTS) fail();
82
+ const raw=bytes.subarray(body,body+compressed);
83
+ const data=method===0 ? raw : await expand(raw,'deflate-raw',expanded);
84
+ if(data.byteLength!==expanded || crc32(data)!==checksum) fail();
85
+ sum+=expanded;
86
+ reports.push(decode(data));
87
+ }
88
+ if(!reports.length) throw new InputError('No XML reports were found inside the ZIP.');
89
+ return reports;
90
+ }
91
+
92
+ async function readReportFile(file) {
93
+ if(file.size>MAX_FILE_SIZE) throw new InputError('Use files up to 4 MB each.');
94
+ const bytes=new Uint8Array(await file.arrayBuffer());
95
+ if(bytes[0]===0x1f&&bytes[1]===0x8b) return [decode(await expand(bytes,'gzip'))];
96
+ if(bytes[0]===0x50&&bytes[1]===0x4b) return xmlFromZip(bytes);
97
+ if(/\.(?:zip|gz)$/i.test(file.name)) throw new InputError('The file contents do not match its ZIP or GZIP extension.');
98
+ return [decode(bytes)];
99
+ }
100
+
101
+ const direct=(element,name)=>Array.from(element?.children??[]).find(child=>child.localName===name);
102
+ const val=(element,name)=>direct(element,name)?.textContent.trim()??'';
103
+
104
+ function parseReport(input,DOM=globalThis.DOMParser) {
105
+ const xml=requiredText(input,'DMARC report XML',MAX_EXPANDED);
106
+ if(/<!DOCTYPE|<!ENTITY/i.test(xml)) throw new InputError('XML declarations that define a document type or entities are not accepted.');
107
+ const doc=new DOM().parseFromString(xml,'application/xml');
108
+ if(doc.getElementsByTagName('parsererror').length||doc.documentElement.localName!=='feedback'){
109
+ throw new InputError('That is not a readable DMARC aggregate report. Use an XML report with a feedback root.');
110
+ }
111
+ const root=doc.documentElement;
112
+ const meta=direct(root,'report_metadata'), identity=direct(root,'policy_published');
113
+ const reportId=val(meta,'report_id'), org=val(meta,'org_name')||'Unspecified';
114
+ const domain=val(identity,'domain')||'Unspecified';
115
+ const range=direct(meta,'date_range');
116
+ const key=reportId ? JSON.stringify([org,reportId,domain,val(range,'begin'),val(range,'end')]) : null;
117
+ const records=Array.from(root.children).filter(child=>child.localName==='record');
118
+ if(!records.length) throw new InputError('The report contains no DMARC records.');
119
+ if(records.length>MAX_ROWS) throw new InputError('Keep reports to 25,000 result rows or fewer.');
120
+ const entries=records.map(record=>{
121
+ const row=direct(record,'row'), ids=direct(record,'identifiers'), evaluated=direct(row,'policy_evaluated');
122
+ const source=val(row,'source_ip');
123
+ const count=val(row,'count');
124
+ if(!source || !/^\d{1,9}$/.test(count) || Number(count)<1) throw new InputError('A report record is missing its source IP or a valid message count.');
125
+ const readCheck=key=>['pass','fail'].includes(val(evaluated,key).toLowerCase()) ? val(evaluated,key).toLowerCase():'unknown';
126
+ return [org,domain,source,val(ids,'header_from')||'Unspecified',Number(count),readCheck('spf'),readCheck('dkim'),
127
+ val(evaluated,'disposition')||'Unspecified'];
128
+ });
129
+ return {key,entries};
130
+ }
131
+
132
+ export async function dmarcReports(input,{files={},DOM}={}) {
133
+ const incoming=files.reports??[];
134
+ if(incoming.length>MAX_REPORTS) throw new InputError('Open up to 20 report files.');
135
+ const xml=[];
136
+ if(String(input.xml??'').trim()) xml.push(input.xml);
137
+ for(const file of incoming){
138
+ xml.push(...await readReportFile(file));
139
+ if(xml.length>MAX_REPORTS || xml.reduce((n,s)=>n+s.length,0)>MAX_EXPANDED){
140
+ throw new InputError('Open up to 20 reports and 8 MB of unpacked XML per run.');
141
+ }
142
+ }
143
+ if(!xml.length) throw new InputError('Open a DMARC XML, GZIP, or ZIP file, or paste report XML.');
144
+ const seen=new Set(), rows=[];
145
+ let duplicates=0, pass=0, fail=0, unknown=0;
146
+ for(const text of xml){
147
+ const parsed=parseReport(text,DOM);
148
+ if(parsed.key&&seen.has(parsed.key)){duplicates++;continue;}
149
+ if(parsed.key) seen.add(parsed.key);
150
+ if(rows.length+parsed.entries.length>MAX_ROWS) throw new InputError('Keep the selected reports to 25,000 total result rows.');
151
+ for(const entry of parsed.entries){
152
+ rows.push(entry);
153
+ if(entry[5]==='pass'||entry[6]==='pass') pass+=entry[4];
154
+ else if(entry[5]==='fail'&&entry[6]==='fail') fail+=entry[4];
155
+ else unknown+=entry[4];
156
+ }
157
+ }
158
+ const bySource=new Map();
159
+ for(const row of rows){
160
+ const [,,ip,,count,spf,dkim]=row;
161
+ if(!bySource.has(ip)) bySource.set(ip,[ip,0,0,0,0]);
162
+ const source=bySource.get(ip);
163
+ source[1]+=count;
164
+ if(spf==='pass'||dkim==='pass') source[2]+=count;
165
+ else if(spf==='fail'&&dkim==='fail') source[3]+=count;
166
+ else source[4]+=count;
167
+ }
168
+ const sources=[...bySource.values()].sort((a,b)=>b[1]-a[1]);
169
+ const columns=['Source IP','Messages','Aligned pass','Aligned fail','Unknown'];
170
+ const columnsRaw=['Reporter','Published domain','Source IP','Header From','Messages','SPF alignment','DKIM alignment','Disposition'];
171
+ return result([['Reports analyzed',whole(xml.length-duplicates)],['Messages',whole(pass+fail+unknown)],
172
+ ['Aligned pass',whole(pass)],['Aligned fail',whole(fail)],['Aligned pass, known results',percent(ratio(pass,pass+fail))],
173
+ ['Unknown alignment',whole(unknown)]],{
174
+ table:{columns,rows:sources.slice(0,40),total:sources.length},
175
+ downloads:[csvDownload('dmarc-sending-sources.csv',columns,sources),csvDownload('dmarc-report-records.csv',columnsRaw,rows)],
176
+ notes:[duplicates?whole(duplicates)+' repeated report(s) skipped by reporter, report ID, published domain, and date range.':
177
+ 'These results summarize what reporting providers recorded.',
178
+ 'An aligned SPF or DKIM pass counts as a DMARC pass. Missing results are kept separate. Policy disposition is included in the raw record export.']});
179
+ }