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

server.js 7.6KB

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