emailrelay-check-address-domains.jsΒΆ

//
// SPDX-FileCopyrightText: 2026 Graeme Walker <graeme_walker@users.sourceforge.net>
// SPDX-License-Identifier: FSFAP
//
// Copyright (c) 2026 Graeme Walker <graeme_walker@users.sourceforge.net>
//
// Copying and distribution of this file, with or without modification,
// are permitted in any medium without royalty provided the copyright
// notice and this notice are preserved.  This file is offered as-is,
// without any warranty.
// ===
//
// emailrelay-check-address-domains.js
//
// An example E-MailRelay filter script for Windows that
// checks the domain parts of the envelope-from address
// and all envelope-to recipient addresses against a
// hard-coded allow-list.
//
try
{
    // list of allowed domains...
    var domains = [
            "books.example.com" ,
            "xn--bcher-kva.example.de" ,
    ] ;

    function allow_domain( domain )
    {
            for( var i = 0 ; i < domains.length ; i++ )
            {
                    if( domains[i] === domain.toLowerCase() )
                            return true ;
            }
            return false ;
    }

    function match( re , s )
    {
            var m = s.match( re ) ;
            if( !m ) return "" ;
            return m[1] ;
    }

    function allow_address( address )
    {
            return allow_domain( match( /@(\S*)/ , address ) ) ;
    }

    // read the envelope
    var envelope = WScript.Arguments(1) ;
    var fs = WScript.CreateObject( "Scripting.FileSystemObject" ) ;
    var ts = fs.OpenTextFile( envelope , 1 , false ) ;
    var txt = ts.ReadAll() ;
    ts.Close() ;

    var denied = [] ;

    // check envelope 'from' address
    var re_from = /^X-MailRelay-From:\s*(\S*)/m ;
    var address_from = match( re_from , txt ) ;
    if( !allow_address(address_from) )
            denied.push( address_from ) ;

    // check envelope 'to' addresses
    var re_to = /^X-MailRelay-To-[^:]*:\s*(\S*)/gm ;
    var match_to ;
    while( (match_to = re_to.exec(txt)) !== null )
    {
            var address_to = match_to[1] ;
            if( !allow_address( address_to ) )
                    denied.push( address_to ) ;
    }

    // return the result
    if( denied.length == 0 )
    {
            WScript.Quit( 0 ) ;
    }
    else
    {
            WScript.StdOut.WriteLine( "<<invalid domain>>" ) ;
            WScript.StdOut.WriteLine( "<<" + denied.toString() + ">>" ) ;
            WScript.Quit( 1 ) ;
    }
}
catch( e )
{
    // report errors using the special <<...>> markers
    WScript.StdOut.WriteLine( "<<error>>" ) ;
    WScript.StdOut.WriteLine( "<<" + e.name + ": " + e.message + ">>" ) ;
    WScript.Quit( 1 ) ;
}