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

server.js 7.0KB

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