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

server.js 6.8KB

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