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

server.js 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. params.custom = processCustom(req.body.custom);
  82. // Replacing the mail's content with HTML from the pug template
  83. // Commenting the line below will bypass the generation and only user the
  84. // text entered by the user
  85. params.html = pug.renderFile('template.pug', params);
  86. log.info(lang.log_sending, params.replyTo);
  87. // Send the email to all users
  88. sendMails(params, function(err, infos) {
  89. if(err) {
  90. log.error(err);
  91. }
  92. logStatus(infos);
  93. }, function() {
  94. if(status.failed === status.total) {
  95. res.status(500).send();
  96. } else {
  97. res.status(200).send();
  98. }
  99. })
  100. });
  101. // A request on /lang sends translated strings (according to the locale set in
  102. // the app settings), alongside the boolean for the display of labels in the
  103. // form block.
  104. app.get('/lang', function(req, res, next) {
  105. // Response will be JSON
  106. res.header('Access-Control-Allow-Headers', 'Content-Type');
  107. // Preventing un-updated settings files
  108. let labels = true;
  109. if(settings.labels !== undefined) {
  110. labels = settings.labels;
  111. }
  112. // Send the infos
  113. res.status(200).send({
  114. 'labels': labels,
  115. 'translations': locale.client
  116. });
  117. });
  118. // A request on /fields sends data on custom fields.
  119. app.get('/fields', function(req, res, next) {
  120. // Response will be JSON
  121. res.header('Access-Control-Allow-Headers', 'Content-Type');
  122. // Send an array anyway, its length will determine if we need to display any
  123. let customFields = settings.customFields || [];
  124. // Send custom fields data
  125. res.status(200).send(customFields);
  126. });
  127. // Use either the default port or the one chosen by the user (PORT env variable)
  128. var port = process.env.PORT || 1970;
  129. // Same for the host (using the HOST env variable)
  130. var host = process.env.HOST || '0.0.0.0';
  131. // Start the server
  132. app.listen(port, host, function() {
  133. log.info(lang.log_server_start, host + ':' + port);
  134. });
  135. // Run the clean every hour
  136. var tokensChecks = setTimeout(cleanTokens, 3600 * 1000);
  137. // Send mails to the recipients specified in the JSON settings file
  138. // content: object containing mail params
  139. // {
  140. // subject: String
  141. // from: String (following RFC 1036 (https://tools.ietf.org/html/rfc1036#section-2.1.1))
  142. // html: String
  143. // }
  144. // update(next, infos): Called each time a mail is sent with the infos provided
  145. // by nodemailer
  146. // done(): Called once each mail has been sent
  147. function sendMails(params, update, done) {
  148. let mails = settings.recipients.map((recipient) => {
  149. // Promise for each recipient to send each mail asynchronously
  150. return new Promise((sent) => {
  151. params.to = recipient;
  152. // Send the email
  153. transporter.sendMail(params, (err, infos) => {
  154. sent();
  155. if(err) {
  156. return update(err, recipient);
  157. }
  158. update(null, infos);
  159. // Promise callback
  160. });
  161. });
  162. });
  163. // Run all the promises (= send all the mails)
  164. Promise.all(mails).then(done);
  165. }
  166. // Produces log from the infos provided by nodemailer
  167. // infos: infos provided by nodemailer
  168. // return: nothing
  169. function logStatus(infos) {
  170. if(infos.accepted.length !== 0) {
  171. log.info(lang.log_send_success, infos.accepted[0]);
  172. }
  173. if(infos.rejected.length !== 0) {
  174. status.failed++;
  175. log.info(lang.log_send_failure, infos.rejected[0]);
  176. }
  177. }
  178. // Checks if the request's sender has been registered (and unregister it if not)
  179. // ip: sender's IP address
  180. // token: token used by the sender
  181. // return: true if the user was registered, false else
  182. function checkToken(ip, token) {
  183. let verified = false;
  184. // Check if there's at least one token for this IP
  185. if(tokens[ip] !== undefined) {
  186. if(tokens[ip].length !== 0) {
  187. // There's at least one element for this IP, let's check the tokens
  188. for(var i = 0; i < tokens[ip].length; i++) {
  189. if(!tokens[ip][i].token.localeCompare(token)) {
  190. // We found the right token
  191. verified = true;
  192. // Removing the token
  193. tokens[ip].pop(tokens[ip][i]);
  194. break;
  195. }
  196. }
  197. }
  198. }
  199. if(!verified) {
  200. log.warn(ip, lang.log_invalid_token);
  201. }
  202. return verified;
  203. }
  204. // Checks if all the required fields are in the request body
  205. // body: body taken from express's request object
  206. // return: true if the body is valid, false else
  207. function checkBody(body) {
  208. let valid = false;
  209. if(body.token !== undefined && body.subj !== undefined
  210. && body.name !== undefined && body.addr !== undefined
  211. && body.text !== undefined) {
  212. valid = true;
  213. }
  214. return valid;
  215. }
  216. // Checks the tokens object to see if no token has expired
  217. // return: nothing
  218. function cleanTokens() {
  219. // Get current time for comparison
  220. let now = new Date().getTime();
  221. for(let ip in tokens) { // Check for each IP in the object
  222. for(let token of tokens[ip]) { // Check for each token of an IP
  223. if(token.expire < now) { // Token has expired
  224. tokens[ip].pop(token);
  225. }
  226. }
  227. if(tokens[ip].length === 0) { // No more element for this IP
  228. delete tokens[ip];
  229. }
  230. }
  231. log.info(lang.log_cleared_token);
  232. }
  233. function processCustom(custom) {
  234. let fields = {};
  235. for(let field in custom) {
  236. let type = settings.customFields[field].type;
  237. switch(type) {
  238. case 'select': custom[field] = settings.customFields[field]
  239. .options[custom[field]];
  240. break;
  241. }
  242. fields[field] = {
  243. value: custom[field],
  244. label: settings.customFields[field].label
  245. }
  246. }
  247. return fields;
  248. }