@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/LICENSE +21 -0
- package/README.md +26 -7
- package/assets/calculators.js +175 -0
- package/assets/common.js +176 -0
- package/assets/copy.js +140 -0
- package/assets/dns.js +280 -0
- package/assets/lists.js +187 -0
- package/assets/mail.js +302 -0
- package/assets/message.js +47 -0
- package/assets/mirror-index.css +6 -0
- package/assets/reports.js +179 -0
- package/assets/toolbox-auth.js +229 -0
- package/assets/toolbox-campaign.js +154 -0
- package/assets/toolbox-compose.js +212 -0
- package/assets/toolbox-data.js +53 -0
- package/assets/toolbox-disposable-license.txt +24 -0
- package/assets/toolbox-disposable.js +1 -0
- package/assets/toolbox-domain.js +199 -0
- package/assets/toolbox-files.js +250 -0
- package/assets/toolbox-leads.js +133 -0
- package/assets/toolbox-measure.js +153 -0
- package/assets/toolbox-pdf-license.txt +177 -0
- package/assets/toolbox-pdf-worker.js +21 -0
- package/assets/toolbox-pdf.js +21 -0
- package/assets/toolbox-ui.js +285 -0
- package/assets/toolbox-vendor-data.js +6 -0
- package/assets/toolbox-vendor-licenses.txt +75 -0
- package/assets/toolbox-vendor-qr.js +8 -0
- package/assets/toolbox.css +14 -0
- package/assets/tools.css +112 -0
- package/assets/ui.js +257 -0
- package/catalog.json +3 -1
- package/favicon-32x32.png +0 -0
- package/index.html +1 -0
- package/index.js +3 -1
- package/package.json +17 -3
- package/tools/cold-email-volume-calculator/index.html +33 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import {InputError,modelResult,requiredText} from './common.js';
|
|
2
|
+
import {hostname,createDns,tags,unquoteTxt,reverseName,spfCheck,dkimCheck,dmarcCheck,ptrLookup} from './dns.js';
|
|
3
|
+
import {brief,check,count,integer,lines,tabular,file,jsonInput} from './toolbox-data.js';
|
|
4
|
+
const encoder=new TextEncoder();
|
|
5
|
+
const b64=bytes=>btoa(Array.from(new Uint8Array(bytes),x=>String.fromCharCode(x)).join(''));
|
|
6
|
+
function bytes64(raw){
|
|
7
|
+
try{return Uint8Array.from(atob(String(raw).replace(/\s/g,'')),x=>x.charCodeAt(0));}
|
|
8
|
+
catch{throw new InputError('The supplied Base64 key or signature is malformed.');}
|
|
9
|
+
}
|
|
10
|
+
function lookupReply(r){
|
|
11
|
+
check(!r.truncated&&[0,3].includes(r.status),'The resolver did not return a complete result. Try again.');
|
|
12
|
+
return r.records.map(x=>unquoteTxt(x.data));
|
|
13
|
+
}
|
|
14
|
+
function tagDetails(records,tag,version){return records.filter(x=>new RegExp(`^${tag}\\s*=\\s*${version}(?:\\s*;|$)`,'i').test(x));}
|
|
15
|
+
function hostList(value){
|
|
16
|
+
return lines(requiredText(value,'one or more MX hostnames',12000)).map(x=>x.startsWith('*.')?'*.'+hostname(x.slice(2)):hostname(x));
|
|
17
|
+
}
|
|
18
|
+
export function mtaPolicy(v){
|
|
19
|
+
const mode=v.mode;
|
|
20
|
+
check(['testing','enforce','none'].includes(mode),'Choose a policy mode.');
|
|
21
|
+
const max=integer(v,'max_age',0,31557600);
|
|
22
|
+
const pattern=mode==='none'&&!v.mx?[]:hostList(v.mx);
|
|
23
|
+
const checks=[];
|
|
24
|
+
if(v.policy){
|
|
25
|
+
const rows=lines(v.policy).map(line=>line.match(/^([^:]+):\s*(.+)$/));
|
|
26
|
+
const groups=new Map();
|
|
27
|
+
for(const row of rows){if(!row){checks.push(['Policy line','Missing key or value']);continue;}
|
|
28
|
+
const id=row[1].toLowerCase();groups.set(id,[...(groups.get(id)??[]),row[2]]);
|
|
29
|
+
}
|
|
30
|
+
if(rows[0]?.[1]!=='version'||groups.get('version')?.join('')!=='STSv1')checks.push(['Version','The first line must be version: STSv1']);
|
|
31
|
+
const modeFromPolicy=groups.get('mode')??[];
|
|
32
|
+
if(modeFromPolicy.length!==1||!['testing','enforce','none'].includes(modeFromPolicy[0]))checks.push(['Mode','Include one supported mode']);
|
|
33
|
+
const age=groups.get('max_age')??[];
|
|
34
|
+
if(age.length!==1||!/^\d+$/.test(age[0])||Number(age[0])>31557600)checks.push(['Maximum age','Provide one integer from 0 to 31,557,600']);
|
|
35
|
+
const mx=groups.get('mx')??[];
|
|
36
|
+
if(modeFromPolicy[0]!=='none'&&!mx.length)checks.push(['MX patterns','This mode needs at least one MX pattern']);
|
|
37
|
+
const valid=[];
|
|
38
|
+
for(const name of mx){try{valid.push(hostList(name)[0]);}catch{checks.push(['MX pattern','Invalid host '+name]);}}
|
|
39
|
+
for(const host of pattern.filter(x=>!x.startsWith('*.'))){
|
|
40
|
+
if(modeFromPolicy[0]!=='none'&&!valid.some(p=>p.startsWith('*.')?host.endsWith(p.slice(1))&&host.split('.').length===p.split('.').length:host===p))checks.push(['MX coverage',host+' does not match a supplied policy pattern']);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const policy=['version: STSv1','mode: '+mode,...[...new Set(pattern)].map(x=>'mx: '+x),'max_age: '+max].join('\n')+'\n';
|
|
44
|
+
return modelResult([['Mode',mode],['MX patterns',count(new Set(pattern).size)],['Pasted policy findings',v.policy?count(checks.length):'No policy supplied']],{text:policy,table:{columns:['Area','Finding'],rows:checks},downloads:[file('mta-sts.txt',policy)],notes:['A published policy also requires a corresponding DNS assertion and an HTTPS endpoint. This tool builds the file and reads the text you supply.']});
|
|
45
|
+
}
|
|
46
|
+
export async function tlsRecord(v,{query=createDns()}={}){
|
|
47
|
+
const domain=hostname(v.domain), name='_smtp._tls.'+domain;
|
|
48
|
+
const records=tagDetails(lookupReply(await query(name,'TXT')),'v','TLSRPTv1');
|
|
49
|
+
const status=records.length===0?'Record missing':records.length>1?'Multiple records':'Record found';
|
|
50
|
+
const parsed=tags(records[0]??'');
|
|
51
|
+
const rows=(parsed.output.get('rua')??'').split(',').map(x=>x.trim()).filter(Boolean).map(url=>[url,/^mailto:[^@\s]+@[^@\s]+$|^https:\/\/[^\s]+$/i.test(url)?'Supported scheme':'Review URI']);
|
|
52
|
+
return modelResult([['DNS name',name],['Status',status],['Report destinations',count(rows.length)]],{text:records.join('\n')||undefined,table:{columns:['URI','Review'],rows},notes:[...(!rows.length&&records.length?['Add at least one destination in rua.']:[]),...(parsed.duplicates.length||parsed.malformed.length?['The record contains duplicate or malformed tags.']:[]),'Destinations are read from public DNS. This tool does not send a test report.']});
|
|
53
|
+
}
|
|
54
|
+
export async function tlsReport(v,{files={}}={}){
|
|
55
|
+
let raw=v.report;
|
|
56
|
+
const upload=files.upload?.[0];
|
|
57
|
+
if(upload){
|
|
58
|
+
check(upload.size<=4e6,'Use a report smaller than 4 MB.');
|
|
59
|
+
if(/\.gz$/i.test(upload.name)){
|
|
60
|
+
check(globalThis.DecompressionStream,'Your browser cannot open gzip. Unpack the report and select the JSON.');
|
|
61
|
+
const reader=upload.stream().pipeThrough(new DecompressionStream('gzip')).getReader();
|
|
62
|
+
const decoder=new TextDecoder('utf-8',{fatal:true});
|
|
63
|
+
let total=0;
|
|
64
|
+
raw='';
|
|
65
|
+
try{
|
|
66
|
+
for(;;){const {value,done}=await reader.read();if(done)break;total+=value.length;if(total>8e6){await reader.cancel();throw new Error('too large');}raw+=decoder.decode(value,{stream:true});}
|
|
67
|
+
raw+=decoder.decode();
|
|
68
|
+
}catch{throw new InputError('The gzip file is invalid or expands beyond 8 MB.');}
|
|
69
|
+
}else raw=await upload.text();
|
|
70
|
+
}
|
|
71
|
+
const data=jsonInput(raw,'a TLS reporting JSON file');
|
|
72
|
+
check(Array.isArray(data?.policies)&&data.policies.length<=300,'Expected up to 300 entries under policies in a TLS reporting JSON file.');
|
|
73
|
+
let success=0,failed=0;
|
|
74
|
+
const rows=[];
|
|
75
|
+
const amount=x=>Number.isSafeInteger(x)&&x>=0?x:0;
|
|
76
|
+
for(const p of data.policies){
|
|
77
|
+
if(!p||typeof p!=='object')continue;
|
|
78
|
+
success+=amount(p.summary?.['total-successful-session-count']);
|
|
79
|
+
failed+=amount(p.summary?.['total-failure-session-count']);
|
|
80
|
+
for(const entry of (Array.isArray(p['failure-details'])?p['failure-details']:[]).slice(0,300)){
|
|
81
|
+
if(!entry||typeof entry!=='object')continue;
|
|
82
|
+
rows.push([p.policy?.['policy-domain']??'',entry['receiving-mx-hostname']??'',entry['result-type']??'Unspecified',amount(entry['failed-session-count'])]);
|
|
83
|
+
if(rows.length>=12000)throw new InputError('The report contains too many detail entries. Try a smaller file.');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return tabular([['Reporting organization',String(data['organization-name']??'Unknown')],['Successful sessions',count(success)],['Failed sessions',count(failed)]],['Policy domain','Receiving MX','Failure type','Count'],rows,'smtp-tls-report.csv',['Totals come from the report summary. Detail rows can cover only a subset of failures.']);
|
|
87
|
+
}
|
|
88
|
+
export async function bimiRecord(v,{query=createDns()}={}){
|
|
89
|
+
const domain=hostname(v.domain);
|
|
90
|
+
const selector=String(v.selector||'default').trim();
|
|
91
|
+
check(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(selector),'Enter a single DNS label as the BIMI selector.');
|
|
92
|
+
const name=hostname(selector+'._bimi.'+domain,true);
|
|
93
|
+
const records=tagDetails(lookupReply(await query(name,'TXT')),'v','BIMI1');
|
|
94
|
+
const {output,duplicates,malformed}=tags(records[0]??'');
|
|
95
|
+
const logo=output.get('l')??'';
|
|
96
|
+
const certainty=records.length!==1?(records.length?'Multiple BIMI records':'No BIMI record'):duplicates.length||malformed.length?'Malformed BIMI record':!logo?'Logo URL empty':!/^https:\/\/\S+$/i.test(logo)?'Review the logo URL':'Logo URL found';
|
|
97
|
+
return modelResult([['DNS name',name],['Status',certainty],['Certificate URL',output.get('a')||'Not supplied']],{text:records.join('\n')||undefined,notes:['This checks the TXT record. The SVG, certificate, and recipient provider requirements can affect whether a logo appears.']});
|
|
98
|
+
}
|
|
99
|
+
export function bimiSvg(v){
|
|
100
|
+
const svg=requiredText(v.svg,'SVG text',150000);
|
|
101
|
+
check(!/<!DOCTYPE|<!ENTITY/i.test(svg),'Remove the document type and entity declarations before checking the file.');
|
|
102
|
+
const doc=new DOMParser().parseFromString(svg,'image/svg+xml');
|
|
103
|
+
const root=doc.documentElement;
|
|
104
|
+
check(root.localName==='svg'&&!doc.querySelector('parsererror')&&root.namespaceURI==='http://www.w3.org/2000/svg','Enter a valid SVG document.');
|
|
105
|
+
const issues=[];
|
|
106
|
+
if(root.getAttribute('baseProfile')!=='tiny-ps')issues.push(['Profile','Use baseProfile="tiny-ps".']);
|
|
107
|
+
if(root.getAttribute('version')!=='1.2')issues.push(['Version','Use SVG version 1.2.']);
|
|
108
|
+
const view=(root.getAttribute('viewBox')??'').trim().split(/[\s,]+/).map(Number);
|
|
109
|
+
if(view.length!==4||view.some(x=>!Number.isFinite(x))||view[2]<=0||view[3]!==view[2])issues.push(['Canvas','Use a positive square viewBox.']);
|
|
110
|
+
if(!root.querySelector('title')?.textContent.trim())issues.push(['Title','Add a short logo title.']);
|
|
111
|
+
for(const item of root.querySelectorAll('*')){
|
|
112
|
+
if(['script','foreignObject','image','text','animate','animateTransform','set','video','audio'].includes(item.localName))issues.push([item.localName,'Review BIMI support for this element.']);
|
|
113
|
+
for(const attr of item.attributes){if(/^on/i.test(attr.name)||(/^(?:href|xlink:href)$/i.test(attr.name)&&!attr.value.startsWith('#'))||/url\s*\(\s*["']?(?!#)[^)]/i.test(attr.value))issues.push([attr.name,'Remove external resources or active attributes.']);}
|
|
114
|
+
if(issues.length>=100)break;
|
|
115
|
+
}
|
|
116
|
+
return tabular([['Findings',count(issues.length)],['Analyzed bytes',count(encoder.encode(svg).length)]],['Check','Finding'],issues,null,['This checks common BIMI SVG requirements. A provider can also validate certification and branding independently.']);
|
|
117
|
+
}
|
|
118
|
+
const rsa={name:'RSASSA-PKCS1-v1_5',hash:'SHA-256'};
|
|
119
|
+
export async function dkimGenerate(v){
|
|
120
|
+
const domain=hostname(v.domain);
|
|
121
|
+
const selector=String(v.selector??'').trim();
|
|
122
|
+
check(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(selector),'Enter a single DKIM selector label.');
|
|
123
|
+
check(globalThis.crypto?.subtle,'Open this tool over HTTPS in a current browser to generate a key.');
|
|
124
|
+
const pair=await crypto.subtle.generateKey({...rsa,modulusLength:2048,publicExponent:new Uint8Array([1,0,1])},true,['sign','verify']);
|
|
125
|
+
const publicKey=b64(await crypto.subtle.exportKey('spki',pair.publicKey));
|
|
126
|
+
const privateKey=b64(await crypto.subtle.exportKey('pkcs8',pair.privateKey)).match(/.{1,64}/g).join('\n');
|
|
127
|
+
const record='v=DKIM1; k=rsa; p='+publicKey;
|
|
128
|
+
return modelResult([['DNS hostname',selector+'._domainkey.'+domain],['RSA key','2,048 bits']],{text:record,downloads:[file('dkim-private.pem','-----BEGIN PRIVATE KEY-----\n'+privateKey+'\n-----END PRIVATE KEY-----\n'),file('dkim-public-record.txt',record+'\n')],notes:['Keep the private PEM on the signing system. Publish only the public record. If your email provider manages signing, use the selector and record it assigns instead.']});
|
|
129
|
+
}
|
|
130
|
+
function messageParts(raw){
|
|
131
|
+
const message=raw.replace(/\r?\n/g,'\r\n');
|
|
132
|
+
const separator=message.indexOf('\r\n\r\n');
|
|
133
|
+
check(separator>0,'Separate the message headers and body with a blank line.');
|
|
134
|
+
const headers=message.slice(0,separator).split(/\r\n(?![ \t])/).map(line=>{
|
|
135
|
+
const index=line.indexOf(':');
|
|
136
|
+
return {name:line.slice(0,index).toLowerCase(),line,index};
|
|
137
|
+
});
|
|
138
|
+
check(headers.every(x=>x.index>0&&/^[!-9;-~]+$/.test(x.name)),'The message contains a malformed header.');
|
|
139
|
+
return {headers,body:message.slice(separator+4)};
|
|
140
|
+
}
|
|
141
|
+
const canonHeader=(line,mode)=>{
|
|
142
|
+
if(mode==='simple')return line;
|
|
143
|
+
const index=line.indexOf(':');
|
|
144
|
+
return line.slice(0,index).trim().toLowerCase()+':'+line.slice(index+1).replace(/\r\n/g,'').replace(/[ \t]+/g,' ').trim();
|
|
145
|
+
};
|
|
146
|
+
function canonBody(raw,mode){
|
|
147
|
+
let body=raw;
|
|
148
|
+
if(mode==='relaxed')body=body.split('\r\n').map(s=>s.replace(/[ \t]+$/,'').replace(/[ \t]+/g,' ')).join('\r\n');
|
|
149
|
+
body=body.replace(/(?:\r\n)+$/,'');
|
|
150
|
+
return body?body+'\r\n':mode==='simple'?'\r\n':'';
|
|
151
|
+
}
|
|
152
|
+
export async function dkimVerify(v){
|
|
153
|
+
const raw=requiredText(v.message,'a complete RFC 5322 email',1000000);
|
|
154
|
+
const {headers,body}=messageParts(raw);
|
|
155
|
+
const signature=headers.find(x=>x.name==='dkim-signature');
|
|
156
|
+
check(signature,'The message does not contain a DKIM-Signature header.');
|
|
157
|
+
const {output,duplicates,malformed}=tags(signature.line.slice(signature.index+1).replace(/\r\n[ \t]+/g,' '));
|
|
158
|
+
check(!duplicates.length&&!malformed.length&&output.get('a')==='rsa-sha256','This version verifies RSA-SHA256 signatures with valid tag syntax.');
|
|
159
|
+
for(const name of ['d','s','h','b','bh'])check(output.get(name),'The signature is missing the '+name+' tag.');
|
|
160
|
+
const [modeHeader,modeBody='simple']=(output.get('c')??'simple/simple').split('/');
|
|
161
|
+
check(['simple','relaxed'].includes(modeHeader)&&['simple','relaxed'].includes(modeBody),'Use a message signed with simple or relaxed canonicalization.');
|
|
162
|
+
const decoded=encoder.encode(canonBody(body,modeBody));
|
|
163
|
+
const size=output.get('l');
|
|
164
|
+
check(size===undefined||(/^\d+$/.test(size)&&Number(size)<=decoded.length),'The signature specifies an invalid body length.');
|
|
165
|
+
const bodyHash=b64(await crypto.subtle.digest('SHA-256',size===undefined?decoded:decoded.slice(0,Number(size))));
|
|
166
|
+
if(bodyHash!==output.get('bh').replace(/\s/g,''))return modelResult([['Signature result','Body hash mismatch'],['Signing domain',output.get('d')],['Selector',output.get('s')]],{notes:['Use the original message file without forwarding it or editing line breaks.']});
|
|
167
|
+
const source=requiredText(v.key,'the corresponding public key',12000).trim();
|
|
168
|
+
const record=source.startsWith('-----')?source.replace(/-----[^-]+-----/g,''):source.includes('p=')?tags(source).output.get('p'):source;
|
|
169
|
+
check(record?.trim(),'The supplied public key is empty.');
|
|
170
|
+
let key;
|
|
171
|
+
try{key=await crypto.subtle.importKey('spki',bytes64(record),rsa,false,['verify']);}
|
|
172
|
+
catch{throw new InputError('Supply the matching RSA public key as a DNS p= value or a public PEM.');}
|
|
173
|
+
const list=output.get('h').split(':').map(x=>x.trim().toLowerCase());
|
|
174
|
+
check(list.includes('from')&&headers.some(x=>x.name==='from'),'The signature must include the message’s From header.');
|
|
175
|
+
const used=new Set([signature]);
|
|
176
|
+
const signed=[];
|
|
177
|
+
for(const name of list){
|
|
178
|
+
const item=headers.findLast(h=>h.name===name&&!used.has(h));
|
|
179
|
+
if(item){used.add(item);signed.push(canonHeader(item.line,modeHeader)+'\r\n');}
|
|
180
|
+
}
|
|
181
|
+
const without=signature.line.replace(/(^|;)\s*b\s*=([^;]*)/i,match=>match.slice(0,match.indexOf('=')+1));
|
|
182
|
+
signed.push(canonHeader(without,modeHeader));
|
|
183
|
+
const okay=await crypto.subtle.verify(rsa,key,bytes64(output.get('b')),encoder.encode(signed.join('')));
|
|
184
|
+
const expired=output.has('x')&&/^\d+$/.test(output.get('x'))&&Number(output.get('x'))*1000<Date.now();
|
|
185
|
+
return modelResult([['Signature result',okay?(expired?'Signature matches, but expired':'Signature matches'):'Signature mismatch'],['Signing domain',output.get('d')],['Selector',output.get('s')]],{notes:[size===undefined?'The full canonicalized body was tested.':'The signature explicitly covers only part of the body.','The supplied key determines the result. Consult DNS to verify that the key is published for this selector.']});
|
|
186
|
+
}
|
|
187
|
+
export function alignment(v){
|
|
188
|
+
const from=hostname(v.from_domain);
|
|
189
|
+
const parent=hostname(v.from_org);
|
|
190
|
+
const mode=v.mode;
|
|
191
|
+
check(['strict','relaxed'].includes(mode),'Choose an alignment mode.');
|
|
192
|
+
const contains=(domain,org)=>domain===org||domain.endsWith('.'+org);
|
|
193
|
+
check(contains(from,parent),'The From domain must match or be under its supplied organization domain.');
|
|
194
|
+
const rows=[];
|
|
195
|
+
const outcomes=[];
|
|
196
|
+
for(const [label,d,o] of [['SPF',v.spf_domain,v.spf_org],['DKIM',v.dkim_domain,v.dkim_org]]){
|
|
197
|
+
if(!d){rows.push([label,'Not supplied','—']);continue;}
|
|
198
|
+
const domain=hostname(d),org=mode==='strict'?domain:hostname(o);
|
|
199
|
+
check(contains(domain,org),label+' domain does not belong to its supplied organization domain.');
|
|
200
|
+
const match=mode==='strict'?domain===from:org===parent;
|
|
201
|
+
outcomes.push(match);
|
|
202
|
+
rows.push([label,match?'Aligned':'Not aligned',domain]);
|
|
203
|
+
}
|
|
204
|
+
check(outcomes.length>0,'Supply an SPF or DKIM identity that already passed authentication.');
|
|
205
|
+
return tabular([['Simulated DMARC result',outcomes.some(Boolean)?'Passes alignment':'Fails alignment'],['Alignment mode',mode]],['Authenticated identity','Alignment','Domain'],rows,null,['Use the SPF or DKIM identity only if it passed authentication. Organizational domains are supplied by you for the relaxed simulation.']);
|
|
206
|
+
}
|
|
207
|
+
export async function dane(v,{query=createDns()}={}){
|
|
208
|
+
const host=hostname(v.host);
|
|
209
|
+
const name='_25._tcp.'+host;
|
|
210
|
+
const reply=await query(name,'TLSA','Google',true);
|
|
211
|
+
const records=lookupReply(reply);
|
|
212
|
+
const rows=records.map(x=>{const [usage,selector,matching,...association]=x.trim().split(/\s+/);return [usage??'',selector??'',matching??'',association.join('')];});
|
|
213
|
+
return tabular([['TLSA records',count(rows.length)],['Resolver validated',reply.ad?'Yes':'No']],['Usage','Selector','Matching type','Association data'],rows,null,['This looks up published TLSA records for SMTP on port 25. Checking a mail server’s certificate requires a separate TLS connection.']);
|
|
214
|
+
}
|
|
215
|
+
export async function providerReadiness(v,{query=createDns()}={}){
|
|
216
|
+
const domain=hostname(v.domain);
|
|
217
|
+
const selector=String(v.selector??'').trim();
|
|
218
|
+
const jobs=[['SPF',()=>spfCheck({domain},{query})],['DKIM',()=>dkimCheck({domain,selector},{query})],['DMARC',()=>dmarcCheck({domain},{query})]];
|
|
219
|
+
if(v.ip){reverseName(v.ip);jobs.push(['PTR',()=>ptrLookup({ip:v.ip},{query})]);}
|
|
220
|
+
const settled=await Promise.allSettled(jobs.map(([,run])=>run()));
|
|
221
|
+
const rows=settled.map((run,i)=>{
|
|
222
|
+
if(run.status==='rejected')return [jobs[i][0],'Could not verify'];
|
|
223
|
+
const m=new Map(run.value.metrics);
|
|
224
|
+
return [jobs[i][0],m.get('Finding')??`${m.get('Forward matches')} forward-confirmed PTR matches`];
|
|
225
|
+
});
|
|
226
|
+
const sample=String(v.header??'');
|
|
227
|
+
rows.push(['One-click unsubscribe',sample?(/(?:^|\n)List-Unsubscribe:\s*<https:\/\//im.test(sample)&&/(?:^|\n)List-Unsubscribe-Post:\s*List-Unsubscribe=One-Click\b/im.test(sample)?'Appears in supplied header':'Review supplied header'):'Supply a header to check']);
|
|
228
|
+
return tabular([['Sending domain',domain],['Checks shown',count(rows.length)]],['Requirement','Observation'],rows,null,['Gmail, Yahoo, and Outlook use their own thresholds and additional rules. These configuration observations do not represent a provider’s compliance verdict.']);
|
|
229
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import {InputError,modelResult,requiredText,csvDownload,showNumber} from './common.js';
|
|
2
|
+
import {brief,check,count,integer,numeric,spreadsheet,column,tabular,key,list,toRatio,dateOnly,iso,day,file} from './toolbox-data.js';
|
|
3
|
+
const round=x=>Math.round(x*100)/100;
|
|
4
|
+
export function warmup(v){
|
|
5
|
+
const start=integer(v,'start_per_day',0,5000), ceiling=integer(v,'ceiling_per_day',1,5000), increment=integer(v,'increase_per_step',0,5000), step=integer(v,'days_per_step',1,60), days=integer(v,'days',1,180);
|
|
6
|
+
check(start<=ceiling,'The starting volume must be at or below the ceiling.');
|
|
7
|
+
const from=dateOnly(v.start_date,'a start date'), weekdays=v.weekdays==='business';
|
|
8
|
+
const rows=[];let active=0;let total=0;
|
|
9
|
+
for(let i=0;i<days;i++){
|
|
10
|
+
const date=new Date(+from+i*day);
|
|
11
|
+
const on=!weekdays||![0,6].includes(date.getUTCDay());
|
|
12
|
+
const planned=on?Math.min(ceiling,start+Math.floor(active++/step)*increment):0;
|
|
13
|
+
total+=planned;rows.push([iso(date),planned,on?'Active day':'Weekend',total]);
|
|
14
|
+
}
|
|
15
|
+
return tabular([['Total planned',count(total)],['Sending days',count(active)],['Peak planned per day',count(Math.max(...rows.map(r=>r[1])))]],['Date','Planned limit','Schedule','Running total'],rows,'mailbox-ramp-plan.csv',['The plan uses your limits. Provider policies and actual mailbox feedback determine whether to continue or pause.']);
|
|
16
|
+
}
|
|
17
|
+
function countNumber(raw,note){
|
|
18
|
+
if(!/^\d+$/.test(String(raw??'').trim())||!Number.isSafeInteger(Number(raw))||Number(raw)>1e9)throw new InputError('Use a whole count from 0 to 1 billion in '+note+'.');
|
|
19
|
+
return Number(raw);
|
|
20
|
+
}
|
|
21
|
+
const col=(sheet,name)=>column(sheet.columns,name);
|
|
22
|
+
export function warmupReport(v){
|
|
23
|
+
const a=spreadsheet(v.csv);
|
|
24
|
+
const date=col(a,v.date_column),mail=col(a,v.mailbox_column),sent=col(a,v.sent_column),bounced=col(a,v.bounce_column);
|
|
25
|
+
const groups=new Map();
|
|
26
|
+
for(const r of a.rows){
|
|
27
|
+
const stamp=dateOnly(r[date],'an export date');const box=key(r[mail]);
|
|
28
|
+
if(!box)continue;
|
|
29
|
+
const sentCount=countNumber(r[sent],v.sent_column),bounceCount=countNumber(r[bounced],v.bounce_column);
|
|
30
|
+
check(bounceCount<=sentCount,'Each bounce count must be no larger than its sent count.');
|
|
31
|
+
const old=groups.get(box)??{sent:0,bounce:0,dates:new Set()};
|
|
32
|
+
old.sent+=sentCount;old.bounce+=bounceCount;old.dates.add(+stamp);groups.set(box,old);
|
|
33
|
+
}
|
|
34
|
+
const rows=[...groups].map(([box,x])=>{const sorted=[...x.dates].sort((a,b)=>a-b);const span=1+(sorted.at(-1)-sorted[0])/day;return [box,x.sent,x.bounce,toRatio(x.bounce,x.sent),sorted.length,span-sorted.length];}).sort((a,b)=>b[2]-a[2]);
|
|
35
|
+
return tabular([['Mailboxes',count(rows.length)],['Bounces',count(rows.reduce((sum,x)=>sum+x[2],0))]],['Mailbox','Sent','Bounced','Bounce rate','Observed days','Dates missing inside range'],rows,'warmup-summary.csv',['Missing dates can include days you planned to pause. Check the schedule before interpreting missing data as a problem.']);
|
|
36
|
+
}
|
|
37
|
+
function tzFormatter(zone){
|
|
38
|
+
try{return new Intl.DateTimeFormat('en-CA',{timeZone:zone,year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hourCycle:'h23'});}
|
|
39
|
+
catch{throw new InputError('Use an IANA time zone, such as America/New_York or Europe/London.');}
|
|
40
|
+
}
|
|
41
|
+
const components=(format,date)=>Object.fromEntries(format.formatToParts(date).filter(x=>x.type!=='literal').map(x=>[x.type,x.value]));
|
|
42
|
+
const showTime=(fmt,date)=>{const x=components(fmt,date);return `${x.year}-${x.month}-${x.day} ${x.hour}:${x.minute}`;};
|
|
43
|
+
function utcOf(parts){return Date.parse(`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:00Z`);}
|
|
44
|
+
export function timeZone(v){
|
|
45
|
+
const value=String(v.local_time??'').trim();
|
|
46
|
+
check(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value),'Enter a local time such as 2026-12-01T09:30.');
|
|
47
|
+
dateOnly(value.slice(0,10));
|
|
48
|
+
const candidate=Date.parse(value+'Z');check(Number.isFinite(candidate),'Enter a valid hour and minute.');
|
|
49
|
+
const source=tzFormatter(v.source_zone),dest=tzFormatter(v.destination_zone);
|
|
50
|
+
const options=new Set();
|
|
51
|
+
for(const distance of [-36,-18,0,18,36]){
|
|
52
|
+
const start=candidate+distance*3600000;
|
|
53
|
+
const offset=utcOf(components(source,new Date(start)))-start;
|
|
54
|
+
const actual=candidate-offset;
|
|
55
|
+
if(showTime(source,new Date(actual))===value.replace('T',' '))options.add(actual);
|
|
56
|
+
}
|
|
57
|
+
const rows=[...options].sort((a,b)=>a-b).map(x=>[showTime(source,new Date(x)),showTime(dest,new Date(x)),new Date(x).toISOString().slice(0,16)+'Z']);
|
|
58
|
+
const status=rows.length===0?'This local time was skipped':rows.length===2?'This local time occurs twice':'Conversion found';
|
|
59
|
+
return tabular([['Result',status],['Destination',v.destination_zone]],['Source time','Destination time','UTC'],rows,null,['Daylight-saving transitions can skip or repeat local times. When a time repeats, both options are shown.']);
|
|
60
|
+
}
|
|
61
|
+
export function followUp(v){
|
|
62
|
+
const start=dateOnly(v.start_date,'a start date');
|
|
63
|
+
const delays=list(requiredText(v.delays,'one or more delays')).map(x=>countNumber(x,'follow-up delays'));
|
|
64
|
+
check(delays.length>0&&delays.length<=20&&delays.every(x=>x<=90),'Use up to 20 delays from 0 to 90 days.');
|
|
65
|
+
const closed=new Set(list(v.blackouts).map(x=>iso(dateOnly(x,'a blackout date'))));
|
|
66
|
+
let current=+start;
|
|
67
|
+
const skip=v.calendar==='business';
|
|
68
|
+
const shift=()=>{let attempts=0;while(closed.has(iso(new Date(current)))||(skip&&[0,6].includes(new Date(current).getUTCDay()))){current+=day;if(++attempts>500)throw new InputError('Too many consecutive blocked days.');}};
|
|
69
|
+
shift();
|
|
70
|
+
const rows=[['Initial message',iso(new Date(current)),0]];
|
|
71
|
+
for(const [i,delay] of delays.entries()){current+=delay*day;shift();rows.push(['Follow-up '+(i+1),iso(new Date(current)),delay]);}
|
|
72
|
+
const calendar=['BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//Xpoudy//Follow-up Calendar//EN'];
|
|
73
|
+
const generated=new Date().toISOString().replace(/[-:]/g,'').slice(0,15)+'Z';
|
|
74
|
+
const uid=`${generated}-${Math.random().toString(36).slice(2,10)}`;
|
|
75
|
+
for(const [i,[name,date]] of rows.entries())calendar.push('BEGIN:VEVENT',`UID:${uid}-${i}@xpoudy.com`,`DTSTAMP:${generated}`,`DTSTART;VALUE=DATE:${date.replaceAll('-','')}`,`SUMMARY:${name}`,'END:VEVENT');
|
|
76
|
+
calendar.push('END:VCALENDAR','');
|
|
77
|
+
return modelResult([['Steps',count(rows.length)],['Last step',rows.at(-1)[1]]],{table:{columns:['Step','Planned date','Delay after previous step'],rows},downloads:[csvDownload('follow-up-calendar.csv',['Step','Date','Delay'],rows),file('follow-up-calendar.ics',calendar.join('\r\n'),'text/calendar;charset=utf-8')],notes:['Each delay uses calendar days from the previous scheduled step, then moves forward past blocked days if needed.']});
|
|
78
|
+
}
|
|
79
|
+
export function allocation(v){
|
|
80
|
+
const leads=spreadsheet(v.leads), boxes=spreadsheet(v.mailboxes);
|
|
81
|
+
const name=col(boxes,v.mailbox_column), cap=col(boxes,v.limit_column);
|
|
82
|
+
const states=boxes.rows.map(row=>({name:row[name].trim(),capacity:countNumber(row[cap],v.limit_column),used:0}));
|
|
83
|
+
check(states.length>0&&states.length<=500&&states.every(x=>x.name)&&new Set(states.map(x=>key(x.name))).size===states.length,'Supply 1 to 500 unique mailbox labels.');
|
|
84
|
+
let cursor=0,assigned=0;
|
|
85
|
+
const available=states.filter(x=>x.capacity>0);
|
|
86
|
+
const rows=leads.rows.map(row=>{
|
|
87
|
+
if(!available.length)return [...row,'','Unassigned'];
|
|
88
|
+
if(cursor>=available.length)cursor=0;
|
|
89
|
+
const mailbox=available[cursor];assigned++;mailbox.used++;
|
|
90
|
+
if(mailbox.used>=mailbox.capacity)available.splice(cursor,1);else cursor++;
|
|
91
|
+
return [...row,mailbox.name,'Assigned'];
|
|
92
|
+
});
|
|
93
|
+
return modelResult([['Leads assigned',count(assigned)],['Unassigned',count(rows.length-assigned)]],{table:{columns:['Mailbox','Assigned','Capacity'],rows:states.map(x=>[x.name,x.used,x.capacity]).slice(0,100),total:states.length},downloads:[csvDownload('mailbox-allocation.csv',[...leads.columns,'Assigned mailbox','Allocation status'],rows)],notes:['This spreads contacts in input order using supplied limits. It does not connect to mailboxes or schedule sends.']});
|
|
94
|
+
}
|
|
95
|
+
export function frequency(v){
|
|
96
|
+
const input=spreadsheet(v.csv),person=col(input,v.contact_column),when=col(input,v.date_column);
|
|
97
|
+
const limit=integer(v,'maximum_messages',1,10000),window=integer(v,'window_days',1,365);
|
|
98
|
+
const entries=input.rows.map((row,i)=>({i,person:key(row[person]),date:+dateOnly(row[when],'a scheduled date'),row})).sort((a,b)=>a.date-b.date||a.i-b.i);
|
|
99
|
+
const groups=new Map();const output=[];let exceeded=0;
|
|
100
|
+
for(const item of entries){
|
|
101
|
+
if(!item.person){output[item.i]=[...item.row,'','Missing key'];continue;}
|
|
102
|
+
const state=groups.get(item.person)??{left:0,dates:[]};
|
|
103
|
+
while(state.left<state.dates.length&&state.dates[state.left]<=item.date-window*day)state.left++;
|
|
104
|
+
state.dates.push(item.date);groups.set(item.person,state);
|
|
105
|
+
const count=state.dates.length-state.left;if(count>limit)exceeded++;
|
|
106
|
+
output[item.i]=[...item.row,count,count>limit?'Above cap':'Within cap'];
|
|
107
|
+
}
|
|
108
|
+
return tabular([['Scheduled rows',count(output.length)],['Above cap',count(exceeded)]],[...input.columns,'Window count','Pacing check'],output,'contact-frequency-review.csv',['Rows on the same day count in the source order. The rolling window includes the scheduled day.']);
|
|
109
|
+
}
|
|
110
|
+
function eventCounts(v){
|
|
111
|
+
const s=spreadsheet(v.csv);
|
|
112
|
+
const grouping=col(s,v.group_column),status=col(s,v.status_column);
|
|
113
|
+
const groups=new Map();
|
|
114
|
+
for(const row of s.rows){
|
|
115
|
+
const name=row[grouping].trim()||'Unspecified', code=row[status].trim()||'No status';
|
|
116
|
+
const className=/^5(?:\d\d|\.)/.test(code)?'Hard or permanent':/^4(?:\d\d|\.)/.test(code)?'Temporary':'Other or unspecified';
|
|
117
|
+
const id=JSON.stringify([name,className,code]);const old=groups.get(id)??[name,className,code,0];old[3]++;groups.set(id,old);
|
|
118
|
+
}
|
|
119
|
+
return {total:s.rows.length,rows:[...groups.values()].sort((a,b)=>b[3]-a[3])};
|
|
120
|
+
}
|
|
121
|
+
export function bounceReport(v){
|
|
122
|
+
const {rows,total}=eventCounts(v);
|
|
123
|
+
return tabular([['Events',count(total)],['Unique group and status pairs',count(rows.length)]],['Group','SMTP class','Status text','Events'],rows,'grouped-bounce-report.csv',['Supply one bounce event per row. Group by mailbox, campaign, or recipient domain and rerun to compare.']);
|
|
124
|
+
}
|
|
125
|
+
export function incident(v){
|
|
126
|
+
const changes=spreadsheet(v.changes),metrics=spreadsheet(v.metrics);
|
|
127
|
+
const cd=col(changes,'date'),ce=col(changes,'change'),md=col(metrics,'date'),ms=col(metrics,'sent'),mb=col(metrics,'bounced');
|
|
128
|
+
const list=[];let total=0;
|
|
129
|
+
for(const row of changes.rows)list.push([iso(dateOnly(row[cd])), 'Configuration',row[ce],'','']);
|
|
130
|
+
for(const row of metrics.rows){const sent=countNumber(row[ms],'sent'),bounce=countNumber(row[mb],'bounced');check(bounce<=sent,'Bounces cannot exceed sends for a measurement.');total+=bounce;list.push([iso(dateOnly(row[md])),'Measurement','Recorded bounce rate',sent,toRatio(bounce,sent)]);}
|
|
131
|
+
list.sort((a,b)=>a[0].localeCompare(b[0])||a[1].localeCompare(b[1]));
|
|
132
|
+
return tabular([['Changes recorded',count(changes.rows.length)],['Bounces recorded',count(total)]],['Date','Type','Event','Sent','Bounce rate'],list,'deliverability-timeline.csv',['Timing can point to what to inspect. It cannot establish that a DNS or sending change caused a particular failure.']);
|
|
133
|
+
}
|
|
134
|
+
export function sequence(v){
|
|
135
|
+
const audience=requiredText(v.audience,'who the message is for',160).trim();
|
|
136
|
+
const observation=requiredText(v.context,'a specific reason for reaching out',450).trim();
|
|
137
|
+
const offer=requiredText(v.offer,'what you can offer',450).trim();
|
|
138
|
+
const ask=requiredText(v.next_step,'a next step',250).trim();
|
|
139
|
+
const evidence=String(v.evidence??'').slice(0,450).trim();
|
|
140
|
+
const countSteps=integer(v,'steps',1,3);
|
|
141
|
+
const blocks=[['First email',`Hi ${audience},\n\n${observation}\n\n${offer}${evidence?'\n\n'+evidence:''}\n\n${ask}`],['First follow-up',`Hi ${audience},\n\nI wanted to follow up on this. ${offer}${evidence?'\n\n'+evidence:''}\n\n${ask}`],['Final follow-up',`Hi ${audience},\n\nI’ll close the loop for now. If this becomes relevant, feel free to reply.\n\nThanks`]].slice(0,countSteps);
|
|
142
|
+
return modelResult([['Editable drafts',count(blocks.length)]],{blocks,downloads:[file('cold-email-sequence.txt',blocks.map(x=>x.join('\n\n')).join('\n\n---\n\n'))],notes:['The tool assembles editable text. Review every draft for relevance and add your signature and any required opt-out details.']});
|
|
143
|
+
}
|
|
144
|
+
export function sendTime(v){
|
|
145
|
+
const data=spreadsheet(v.csv), time=col(data,v.sent_at), timezone=col(data,v.time_zone), result=col(data,v.replied);
|
|
146
|
+
const hours=Array.from({length:24},()=>({sent:0,replies:0}));const formats=new Map();let skipped=0;
|
|
147
|
+
for(const row of data.rows){
|
|
148
|
+
const when=row[time], outcome=key(row[result]), zone=row[timezone].trim();
|
|
149
|
+
if(!/(?:Z|[+-]\d{2}:\d{2})$/i.test(when)||!Number.isFinite(Date.parse(when))||!['yes','no','1','0','true','false'].includes(outcome)){skipped++;continue;}
|
|
150
|
+
try{if(!formats.has(zone))formats.set(zone,tzFormatter(zone));const hour=Number(components(formats.get(zone),new Date(when)).hour);hours[hour].sent++;hours[hour].replies+=['yes','1','true'].includes(outcome)?1:0;}catch{skipped++;}
|
|
151
|
+
}
|
|
152
|
+
const rows=hours.flatMap((x,i)=>x.sent?[[String(i).padStart(2,'0')+':00',x.sent,x.replies,toRatio(x.replies,x.sent)]]:[]);
|
|
153
|
+
return tabular([['Rows analyzed',count(data.rows.length-skipped)],['Rows skipped',count(skipped)]],['Local hour','Sends','Replies','Reply rate'],rows,'send-time-performance.csv',['Use one recorded message per row with a reliable reply outcome. Small samples should be interpreted cautiously.']);
|
|
154
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import {InputError,modelResult,requiredText,showNumber} from './common.js';
|
|
2
|
+
import {brief,check,count,integer,file,htmlEscape,tabular} from './toolbox-data.js';
|
|
3
|
+
|
|
4
|
+
function template(value){
|
|
5
|
+
const node=document.createElement('template');
|
|
6
|
+
node.innerHTML=requiredText(value,'email HTML',400000);
|
|
7
|
+
return node;
|
|
8
|
+
}
|
|
9
|
+
const safeEmail=value=>/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(value);
|
|
10
|
+
export function safeHttp(raw){
|
|
11
|
+
let url;
|
|
12
|
+
try{url=new URL(String(raw));}catch{throw new InputError('Enter a complete HTTPS or HTTP URL.');}
|
|
13
|
+
check(['https:','http:'].includes(url.protocol)&&!url.username&&!url.password,'Enter a web URL without embedded credentials.');
|
|
14
|
+
return url;
|
|
15
|
+
}
|
|
16
|
+
function plain(root){
|
|
17
|
+
const result=[];
|
|
18
|
+
function read(node){
|
|
19
|
+
if(node.nodeType===3){result.push(node.textContent.replace(/\s+/g,' '));return;}
|
|
20
|
+
const name=node.localName;
|
|
21
|
+
if(['script','style','head','object','iframe','template'].includes(name))return;
|
|
22
|
+
if(name==='li')result.push('\n• ');
|
|
23
|
+
if(name==='img'&&node.getAttribute('alt'))result.push('['+node.getAttribute('alt')+']');
|
|
24
|
+
for(const child of node.childNodes)read(child);
|
|
25
|
+
if(name==='a'){
|
|
26
|
+
const href=node.getAttribute('href')??'';
|
|
27
|
+
if(/^(https?:|mailto:)/i.test(href)&&node.textContent.trim()!==href)result.push(' ('+href+')');
|
|
28
|
+
}
|
|
29
|
+
if(['pre','p','tr','br','li','div','section','h1','h2','h3','ul','ol'].includes(name))result.push('\n');
|
|
30
|
+
if(['td','th'].includes(name))result.push(' ');
|
|
31
|
+
}
|
|
32
|
+
read(root);
|
|
33
|
+
return result.join('').split('\n').map(x=>x.trim()).join('\n').replace(/\n{3,}/g,'\n\n').trim();
|
|
34
|
+
}
|
|
35
|
+
export function htmlToText(v){
|
|
36
|
+
const text=plain(template(v.html).content);
|
|
37
|
+
check(text,'The HTML does not contain readable text.');
|
|
38
|
+
return modelResult([['Characters',count(text.length)],['Lines',count(text.split('\n').length)]],{text,downloads:[file('email.txt',text+'\n')]});
|
|
39
|
+
}
|
|
40
|
+
function cleanPreview(raw){
|
|
41
|
+
const node=template(raw);
|
|
42
|
+
for(const el of node.content.querySelectorAll('script,iframe,frame,object,embed,link,meta,base,style,form,input,button,select,textarea,svg,math,video,audio,picture,source'))el.remove();
|
|
43
|
+
for(const el of node.content.querySelectorAll('*')){
|
|
44
|
+
if(el.localName==='img'){
|
|
45
|
+
const alt=el.getAttribute('alt');
|
|
46
|
+
const replacement=document.createElement('span');
|
|
47
|
+
replacement.textContent=alt?'['+alt+']':'[Image]';
|
|
48
|
+
el.replaceWith(replacement);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
for(const attr of [...el.attributes]){
|
|
52
|
+
const safe=/^(?:align|bgcolor|border|cellpadding|cellspacing|class|colspan|dir|height|lang|role|rowspan|style|title|valign|width)$/i.test(attr.name);
|
|
53
|
+
if(!safe||(attr.name==='style'&&/url\s*\(|@import|expression|behavior|\\/i.test(attr.value)))el.removeAttribute(attr.name);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return node.innerHTML;
|
|
57
|
+
}
|
|
58
|
+
export function htmlPreview(v){
|
|
59
|
+
const width=integer(v,'width',240,1000);
|
|
60
|
+
const html=cleanPreview(v.html);
|
|
61
|
+
const theme=v.theme==='dark'?'dark':'light';
|
|
62
|
+
return modelResult([['Preview width',width+' px'],['Theme',theme]],{preview:{html,width,theme},notes:['This is a sandboxed browser preview. Remote images are replaced with their labels and links are inert. It is not a screenshot from Gmail or Outlook.']});
|
|
63
|
+
}
|
|
64
|
+
export function subjectPreview(v){
|
|
65
|
+
const subject=requiredText(v.subject,'a subject line',250),sender=String(v.sender??'').trim()||'Sender',pre=String(v.preheader??'').trim().slice(0,250);
|
|
66
|
+
const chars=Array.from(subject);
|
|
67
|
+
return modelResult([['Subject characters',count(chars.length)],['Preheader characters',count(Array.from(pre).length)]],{inboxes:[{sender,subject,pre,kind:'Narrow inbox'},{sender,subject,pre,kind:'Wide inbox'}],notes:['Actual truncation depends on the client, font, and display. Use both previews to check that the start of the subject makes sense.']});
|
|
68
|
+
}
|
|
69
|
+
export function signature(v){
|
|
70
|
+
const name=requiredText(v.name,'your name',140).trim();
|
|
71
|
+
const email=requiredText(v.email,'your email',254).trim();
|
|
72
|
+
check(safeEmail(email),'Enter a complete email address.');
|
|
73
|
+
const line=[v.role,v.company].filter(Boolean).map(x=>String(x).trim()).join(' · ');
|
|
74
|
+
const url=v.website?safeHttp(v.website).href:'';
|
|
75
|
+
const text=[name,line,email,v.phone,url].filter(Boolean).join('\n');
|
|
76
|
+
const html=['<table role="presentation" style="font-family:Arial,sans-serif;color:#232b39">','<tr><td style="padding:4px 0"><strong>'+htmlEscape(name)+'</strong></td></tr>',line?'<tr><td>'+htmlEscape(line)+'</td></tr>':'','<tr><td><a href="mailto:'+htmlEscape(email)+'">'+htmlEscape(email)+'</a></td></tr>',v.phone?'<tr><td>'+htmlEscape(v.phone)+'</td></tr>':'',url?'<tr><td><a href="'+htmlEscape(url)+'">Website or booking page</a></td></tr>':'','</table>'].join('\n');
|
|
77
|
+
return modelResult([['Name',name],['Formats','HTML and text']],{preview:{html:cleanPreview(html),width:540,theme:'light'},text:html,downloads:[file('email-signature.html',html,'text/html;charset=utf-8'),file('email-signature.txt',text+'\n')],notes:['Import the HTML using your mail client’s supported signature workflow. You can use the text version for plain-text replies.']});
|
|
78
|
+
}
|
|
79
|
+
export function attachments(v){
|
|
80
|
+
const mb=Number(v.attachment_mb),limit=Number(v.limit_mb);
|
|
81
|
+
check(v.attachment_mb!==''&&v.limit_mb!==''&&Number.isFinite(mb)&&mb>=0&&mb<=10000&&Number.isFinite(limit)&&limit>0&&limit<=10000,'Use valid attachment and message size values in MB.');
|
|
82
|
+
const source=Math.round(mb*1000000);
|
|
83
|
+
const base64=Math.ceil(source/3)*4;
|
|
84
|
+
const total=base64+Math.ceil(base64/76)*2+4096;
|
|
85
|
+
return modelResult([['Estimated message',showNumber(total/1e6)+' MB'],['Remaining room',showNumber(limit-total/1e6)+' MB'],['Assessment',total<=limit*1e6?'Within this limit':'Over this limit']],{notes:['The estimate uses decimal MB, Base64 wrapping, and 4 KB for ordinary body and MIME overhead. Large bodies or many attachment parts can add more.']});
|
|
86
|
+
}
|
|
87
|
+
function mimeLeaf(raw,depth=0){
|
|
88
|
+
check(depth<10,'The message contains too many nested MIME levels.');
|
|
89
|
+
const source=raw.replace(/\r\n/g,'\n');
|
|
90
|
+
const offset=source.indexOf('\n\n');
|
|
91
|
+
check(offset>=0,'Open a complete .eml file with a blank line after the headers.');
|
|
92
|
+
const body=source.slice(offset+2);
|
|
93
|
+
const head=new Map();
|
|
94
|
+
for(const line of source.slice(0,offset).replace(/\n[ \t]+/g,' ').split('\n')){
|
|
95
|
+
const i=line.indexOf(':');if(i>0)head.set(line.slice(0,i).toLowerCase(),line.slice(i+1).trim());
|
|
96
|
+
}
|
|
97
|
+
const type=head.get('content-type')??'text/plain; charset=utf-8';
|
|
98
|
+
const boundary=/;\s*boundary\s*=\s*(?:"([^"]+)"|([^;\s]+))/i.exec(type);
|
|
99
|
+
if(/^multipart\//i.test(type)&&boundary){
|
|
100
|
+
const mark='--'+(boundary[1]??boundary[2]);
|
|
101
|
+
const parts=[];
|
|
102
|
+
let part;
|
|
103
|
+
for(const line of body.split('\n')){
|
|
104
|
+
if(line.trimEnd()===mark||line.trimEnd()===mark+'--'){
|
|
105
|
+
if(part)parts.push(part.join('\n'));
|
|
106
|
+
if(line.trimEnd().endsWith('--'))break;
|
|
107
|
+
part=[];
|
|
108
|
+
}else if(part)part.push(line);
|
|
109
|
+
if(parts.length>80)throw new InputError('The message has too many MIME parts.');
|
|
110
|
+
}
|
|
111
|
+
return {head,parts:parts.flatMap(child=>mimeLeaf(child,depth+1).parts)};
|
|
112
|
+
}
|
|
113
|
+
const charset=/charset\s*=\s*"?([^";\s]+)/i.exec(type)?.[1]??'utf-8';
|
|
114
|
+
const enc=(head.get('content-transfer-encoding')??'').toLowerCase();
|
|
115
|
+
const name=/(?:filename|name)\s*=\s*(?:"([^"]+)"|([^;\s]+))/i.exec((head.get('content-disposition')??'')+'; '+type);
|
|
116
|
+
let decoded=body;
|
|
117
|
+
let byteCount=new TextEncoder().encode(body).length;
|
|
118
|
+
try{
|
|
119
|
+
if(enc==='base64'||enc==='quoted-printable'){
|
|
120
|
+
const bytes=enc==='base64'?Uint8Array.from(atob(body.replace(/\s/g,'')),x=>x.charCodeAt(0)):Uint8Array.from(body.replace(/=\n/g,'').replace(/=([0-9a-f]{2})/gi,(_,x)=>String.fromCharCode(parseInt(x,16))),x=>x.charCodeAt(0));
|
|
121
|
+
byteCount=bytes.length;
|
|
122
|
+
decoded=/^text\//i.test(type)?new TextDecoder(charset).decode(bytes):'';
|
|
123
|
+
}
|
|
124
|
+
}catch{decoded='[Could not decode this MIME part]';}
|
|
125
|
+
const kind=type.split(';')[0].toLowerCase();
|
|
126
|
+
return {head,parts:[{kind,name:name?.[1]??name?.[2]??'',bytes:byteCount,decoded}]};
|
|
127
|
+
}
|
|
128
|
+
export function emlViewer(v){
|
|
129
|
+
const {head,parts}=mimeLeaf(requiredText(v.message,'an email message',3e6));
|
|
130
|
+
const readable=parts.filter(x=>x.kind==='text/plain'||x.kind==='text/html').map(x=>[x.name||x.kind,x.kind==='text/html'&&x.decoded?plain(template(x.decoded).content):x.decoded]);
|
|
131
|
+
return modelResult([['From',head.get('from')??'—'],['Subject',head.get('subject')??'—'],['MIME parts',count(parts.length)]],{table:{columns:['Part','Filename','Bytes'],rows:parts.map(x=>[x.kind,x.name||'—',x.bytes])},blocks:readable,notes:['Binary attachments are listed without being executed or opened. HTML is shown as readable text.']});
|
|
132
|
+
}
|
|
133
|
+
export function compatibility(v){
|
|
134
|
+
const markup=requiredText(v.html,'email HTML',300000);
|
|
135
|
+
const rules=[[/display\s*:\s*grid\b/i,'CSS grid','Review a table or simple block fallback.'],[/display\s*:\s*flex\b/i,'Flexbox','Some clients use older renderers. Verify the layout with a fallback.'],[/position\s*:\s*(fixed|sticky)/i,'Fixed or sticky position','Use normal document flow for essential content.'],[/@font-face/i,'Web fonts','Include a readable system font fallback.'],[/background-image\s*:/i,'Background images','Set a solid background color and ensure text is readable without the image.'],[/<video\b/i,'Embedded video','Include an image or link fallback.'],[/<form\b/i,'Embedded form','Provide a normal link to the form.']];
|
|
136
|
+
return tabular([['Features to review',count(rules.filter(x=>x[0].test(markup)).length)]],['Feature','Fallback to consider'],rules.filter(x=>x[0].test(markup)).map(x=>x.slice(1)),null,['These static rules point out features to test. They do not reproduce a particular version of an email client.']);
|
|
137
|
+
}
|
|
138
|
+
function rgb(value){
|
|
139
|
+
if(!/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(value))return null;
|
|
140
|
+
let digits=value.slice(1);
|
|
141
|
+
if(digits.length===3)digits=digits.split('').map(c=>c+c).join('');
|
|
142
|
+
return digits.match(/../g).map(n=>{const x=parseInt(n,16)/255;return x<=.04045?x/12.92:((x+.055)/1.055)**2.4;});
|
|
143
|
+
}
|
|
144
|
+
export function accessibility(v){
|
|
145
|
+
const contents=template(v.html).content;
|
|
146
|
+
const issues=[];
|
|
147
|
+
const images=[...contents.querySelectorAll('img')];
|
|
148
|
+
const missing=images.filter(el=>!el.hasAttribute('alt')).length;
|
|
149
|
+
if(missing)issues.push(['Image alternatives',missing+' images have no alt attribute']);
|
|
150
|
+
const links=[...contents.querySelectorAll('a[href]')];
|
|
151
|
+
const unclear=links.filter(el=>/^(?:click here|here|more|read more|learn more)?$/i.test(el.textContent.trim()||el.querySelector('img[alt]')?.getAttribute('alt')||'')).length;
|
|
152
|
+
if(unclear)issues.push(['Link text',unclear+' links have empty or ambiguous labels']);
|
|
153
|
+
const headings=[...contents.querySelectorAll('h1,h2,h3,h4,h5,h6')].map(el=>+el.localName.slice(1));
|
|
154
|
+
if(headings.some((x,i)=>i>0&&x>headings[i-1]+1))issues.push(['Headings','A heading level was skipped']);
|
|
155
|
+
const fg=rgb(v.foreground??''), bg=rgb(v.background??'');
|
|
156
|
+
check((!v.foreground&&!v.background)||(fg&&bg),'Enter both contrast colors as hex values such as #1a1a1a and #ffffff.');
|
|
157
|
+
let ratio='Not supplied';
|
|
158
|
+
if(fg&&bg){const lum=xs=>xs[0]*.2126+xs[1]*.7152+xs[2]*.0722;const a=lum(fg),b=lum(bg);const r=(Math.max(a,b)+.05)/(Math.min(a,b)+.05);ratio=showNumber(r)+':1';if(r<4.5)issues.push(['Text contrast','Below 4.5:1 for normal text']);}
|
|
159
|
+
return tabular([['Checks to review',count(issues.length)],['Supplied color contrast',ratio]],['Area','Finding'],issues,null,['The contrast value applies only to the two colors you entered. Review the rendered message and reading order separately.']);
|
|
160
|
+
}
|
|
161
|
+
export function cssInline(v){
|
|
162
|
+
const node=template(v.html);
|
|
163
|
+
const styleNodes=[...node.content.querySelectorAll('style')];
|
|
164
|
+
const css=styleNodes.map(el=>el.textContent).join('\n')+'\n'+String(v.css??'');
|
|
165
|
+
check(css.length<=140000,'Use less than 140 KB of CSS.');
|
|
166
|
+
check(globalThis.CSSStyleSheet,'This browser cannot parse CSS stylesheets. Try a current browser.');
|
|
167
|
+
const sheet=new CSSStyleSheet();
|
|
168
|
+
sheet.replaceSync(css);
|
|
169
|
+
const preserved=[];
|
|
170
|
+
let rules=0;
|
|
171
|
+
const set=new Map();
|
|
172
|
+
for(const rule of sheet.cssRules){
|
|
173
|
+
if(rule.type!==1){preserved.push(rule.cssText);continue;}
|
|
174
|
+
if(!/^[A-Za-z0-9_.#*\-\s>,+~]+$/.test(rule.selectorText)){preserved.push(rule.cssText);continue;}
|
|
175
|
+
const spec=rule.selectorText.match(/#/g)?.length*10000||0;
|
|
176
|
+
const score=spec+(rule.selectorText.match(/\./g)?.length??0)*100+rule.selectorText.split(/\s+/).length;
|
|
177
|
+
try{
|
|
178
|
+
for(const el of node.content.querySelectorAll(rule.selectorText)){
|
|
179
|
+
for(const name of rule.style){
|
|
180
|
+
const item=set.get(el)??new Map();set.set(el,item);
|
|
181
|
+
const prior=item.get(name);
|
|
182
|
+
const priority=rule.style.getPropertyPriority(name);
|
|
183
|
+
const rank=score+(priority?1000000:0);
|
|
184
|
+
if(!prior||rank>=prior.rank)item.set(name,{value:rule.style.getPropertyValue(name),priority,rank});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
rules++;
|
|
188
|
+
}catch{preserved.push(rule.cssText);}
|
|
189
|
+
}
|
|
190
|
+
for(const [el,properties] of set){
|
|
191
|
+
for(const [prop,x] of properties){if(!el.style.getPropertyValue(prop)||(x.priority&&!el.style.getPropertyPriority(prop)))el.style.setProperty(prop,x.value,x.priority);}
|
|
192
|
+
}
|
|
193
|
+
for(const node of styleNodes)node.remove();
|
|
194
|
+
const html=(preserved.length?'<style>\n'+preserved.join('\n').replace(/<\/style/gi,'<\\/style')+'\n</style>\n':'')+node.innerHTML;
|
|
195
|
+
return modelResult([['Inline rules applied',count(rules)],['Rules left in a stylesheet',count(preserved.length)]],{text:html,downloads:[file('email-inline.html',html,'text/html;charset=utf-8')],notes:['Simple selectors are supported. Conditional rules remain in the stylesheet. Inspect the output when several selectors or inline declarations affect the same property.']});
|
|
196
|
+
}
|
|
197
|
+
export function textCompare(v){
|
|
198
|
+
const split=x=>requiredText(x,'both draft versions',60000).replace(/\r\n/g,'\n').split('\n');
|
|
199
|
+
const a=split(v.before), b=split(v.after);
|
|
200
|
+
check(a.length<=800&&b.length<=800,'Compare up to 800 lines per draft.');
|
|
201
|
+
const width=b.length+1;
|
|
202
|
+
const dp=new Uint16Array((a.length+1)*width);
|
|
203
|
+
for(let i=a.length-1;i>=0;i--)for(let j=b.length-1;j>=0;j--)dp[i*width+j]=a[i]===b[j]?dp[(i+1)*width+j+1]+1:Math.max(dp[(i+1)*width+j],dp[i*width+j+1]);
|
|
204
|
+
let i=0,j=0;
|
|
205
|
+
const rows=[];
|
|
206
|
+
while(i<a.length||j<b.length){
|
|
207
|
+
if(i<a.length&&j<b.length&&a[i]===b[j]){i++;j++;}
|
|
208
|
+
else if(j<b.length&&(i===a.length||dp[i*width+j+1]>dp[(i+1)*width+j]))rows.push(['Added',j+1,b[j++]]);
|
|
209
|
+
else rows.push(['Removed',i+1,a[i++]]);
|
|
210
|
+
}
|
|
211
|
+
return tabular([['Removed lines',count(rows.filter(x=>x[0]==='Removed').length)],['Added lines',count(rows.filter(x=>x[0]==='Added').length)]],['Change','Line number','Text'],rows,'email-draft-diff.csv');
|
|
212
|
+
}
|