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

server.js 9.1KB

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