SMAM (short for Send Me A Mail) is a free (as in freedom) contact form embedding software.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. var pug = require('pug');
  2. var nodemailer = require('nodemailer');
  3. var crypto = require('crypto');
  4. var settings = require('./settings');
  5. // Web server
  6. var bodyParser = require('body-parser');
  7. var express = require('express');
  8. var app = express();
  9. // Logging
  10. var printit = require('printit');
  11. var log = printit({
  12. prefix: 'SMAM',
  13. date: true
  14. });
  15. // nodemailer initial configuration
  16. var transporter = nodemailer.createTransport(settings.mailserver);
  17. // Verification tokens
  18. var tokens = {};
  19. // Serve static (JS + HTML) files
  20. app.use(express.static('front'));
  21. // Body parsing
  22. app.use(bodyParser.urlencoded({ extended: true }));
  23. app.use(bodyParser.json());
  24. // Allow cross-origin requests.
  25. app.all('/*', function(req, res, next) {
  26. res.header('Access-Control-Allow-Origin', settings.formUrl);
  27. res.header('Access-Control-Allow-Headers', 'Content-Type')
  28. next();
  29. });
  30. // A request on /register generates a token and store it, along the user's
  31. // address, on the tokens object
  32. app.get('/register', function(req, res, next) {
  33. // Get IP from express
  34. let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  35. if(tokens[ip] === undefined) {
  36. tokens[ip] = [];
  37. }
  38. // Generate token
  39. crypto.randomBytes(10, (err, buf) => {
  40. let token = buf.toString('hex');
  41. // Store and send the token
  42. tokens[ip].push({
  43. token: token,
  44. // A token expires after 12h
  45. expire: new Date().getTime() + 12 * 3600 * 1000
  46. });
  47. res.status(200).send(token);
  48. });
  49. });
  50. // A request on /send with user input = mail to be sent
  51. app.post('/send', function(req, res, next) {
  52. if(!checkBody(req.body)) {
  53. return res.status(400).send();
  54. }
  55. let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  56. if(!checkToken(ip, req.body.token)) {
  57. return res.status(403).send();
  58. }
  59. // Count the failures
  60. let status = {
  61. failed: 0,
  62. total: settings.recipients.length
  63. };
  64. // params will be used as:
  65. // - values for html generation from the pug template
  66. // - parameters for sending the mail(s)
  67. let params = {
  68. subject: req.body.subj,
  69. from: req.body.name + '<' + settings.mailserver.auth.user + '>',
  70. replyTo: req.body.name + ' <' + req.body.addr + '>',
  71. html: req.body.text
  72. };
  73. // Replacing the mail's content with HTML from the pug template
  74. // Commenting the line below will bypass the generation and only user the
  75. // text entered by the user
  76. params.html = pug.renderFile('template.pug', params);
  77. log.info('Sending message from ' + params.replyTo);
  78. // Send the email to all users
  79. sendMails(params, function(err, infos) {
  80. if(err) {
  81. log.error(err);
  82. }
  83. logStatus(infos);
  84. }, function() {
  85. if(status.failed === status.total) {
  86. res.status(500).send();
  87. } else {
  88. res.status(200).send();
  89. }
  90. })
  91. });
  92. // Use either the default port or the one chosen by the user (PORT env variable)
  93. var port = process.env.PORT || 1970;
  94. // Same for the host (using the HOST env variable)
  95. var host = process.env.HOST || '0.0.0.0';
  96. // Start the server
  97. app.listen(port, host, function() {
  98. log.info('Server started on ' + host + ':' + port);
  99. });
  100. // Run the clean every hour
  101. var tokensChecks = setTimeout(cleanTokens, 3600 * 1000);
  102. // Send mails to the recipients specified in the JSON settings file
  103. // content: object containing mail params
  104. // {
  105. // subject: String
  106. // from: String (following RFC 1036 (https://tools.ietf.org/html/rfc1036#section-2.1.1))
  107. // html: String
  108. // }
  109. // update(next, infos): Called each time a mail is sent with the infos provided
  110. // by nodemailer
  111. // done(): Called once each mail has been sent
  112. function sendMails(params, update, done) {
  113. let mails = settings.recipients.map((recipient) => {
  114. // Promise for each recipient to send each mail asynchronously
  115. return new Promise((sent) => {
  116. params.to = recipient;
  117. // Send the email
  118. transporter.sendMail(params, (err, infos) => {
  119. if(err) {
  120. return update(err, recipient);
  121. }
  122. update(null, infos);
  123. // Promise callback
  124. sent();
  125. });
  126. });
  127. });
  128. // Run all the promises (= send all the mails)
  129. Promise.all(mails).then(done);
  130. }
  131. // Produces log from the infos provided by nodemailer
  132. // infos: infos provided by nodemailer
  133. // return: nothing
  134. function logStatus(infos) {
  135. if(infos.accepted.length !== 0) {
  136. log.info('Message sent to ' + infos.accepted[0]);
  137. }
  138. if(infos.rejected.length !== 0) {
  139. status.failed++;
  140. log.info('Message failed to send to ' + infos.rejected[0]);
  141. }
  142. }
  143. // Checks if the request's sender has been registered (and unregister it if not)
  144. // ip: sender's IP address
  145. // token: token used by the sender
  146. // return: true if the user was registered, false else
  147. function checkToken(ip, token) {
  148. let verified = false;
  149. // Check if there's at least one token for this IP
  150. if(tokens[ip] !== undefined) {
  151. if(tokens[ip].length !== 0) {
  152. // There's at least one element for this IP, let's check the tokens
  153. for(var i = 0; i < tokens[ip].length; i++) {
  154. if(!tokens[ip][i].token.localeCompare(token)) {
  155. // We found the right token
  156. verified = true;
  157. // Removing the token
  158. tokens[ip].pop(tokens[ip][i]);
  159. break;
  160. }
  161. }
  162. }
  163. }
  164. if(!verified) {
  165. log.warn(ip + ' just tried to send a message with an invalid token');
  166. }
  167. return verified;
  168. }
  169. // Checks if all the required fields are in the request body
  170. // body: body taken from express's request object
  171. // return: true if the body is valid, false else
  172. function checkBody(body) {
  173. let valid = false;
  174. if(body.token !== undefined && body.subj !== undefined
  175. && body.name !== undefined && body.addr !== undefined
  176. && body.text !== undefined) {
  177. valid = true;
  178. }
  179. return valid;
  180. }
  181. // Checks the tokens object to see if no token has expired
  182. // return: nothing
  183. function cleanTokens() {
  184. // Get current time for comparison
  185. let now = new Date().getTime();
  186. for(let ip in tokens) { // Check for each IP in the object
  187. for(let token of tokens[ip]) { // Check for each token of an IP
  188. if(token.expire < now) { // Token has expired
  189. tokens[ip].pop(token);
  190. }
  191. }
  192. if(tokens[ip].length === 0) { // No more element for this IP
  193. delete tokens[ip];
  194. }
  195. }
  196. log.info('Cleared expired tokens');
  197. }