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

server.js 6.5KB

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