You can try this. Just set a snapshop first incase it does something funky that I didn't catch. I should note that this will only apply the mask to layers that are not in a group.
#target photoshop
if(app.documents.length>0){
var docRef = activeDocument;
var layerNum = docRef.layers.length;
for(var i=0;i<layerNum;i++){
docRef.activeLayer = docRef.layers[i];
if(!docRef.activeLayer.isBackgroundLayer){
try{addMask ()}
catch(e){}
}
}
}
else{alert('There are no open files')};
function addMask(){
var idMk = charIDToTypeID( "Mk " );
var desc2 = new ActionDescriptor();
var idNw = charIDToTypeID( "Nw " );
var idChnl = charIDToTypeID( "Chnl" );
desc2.putClass( idNw, idChnl );
var idAt = charIDToTypeID( "At " );
var ref1 = new ActionReference();
var idChnl = charIDToTypeID( "Chnl" );
var idChnl = charIDToTypeID( "Chnl" );
var idMsk = charIDToTypeID( "Msk " );
ref1.putEnumerated( idChnl, idChnl, idMsk );
desc2.putReference( idAt, ref1 );
var idUsng = charIDToTypeID( "Usng" );
var idUsrM = charIDToTypeID( "UsrM" );
var idHdAl = charIDToTypeID( "HdAl" );
desc2.putEnumerated( idUsng, idUsrM, idHdAl );
executeAction( idMk, desc2, DialogModes.NO );
}