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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. var pug = require('pug');
  2. var nodemailer = require('nodemailer');
  3. var crypto = require('crypto');
  4. var fs = require('fs');
  5. var settings = require('./settings');
  6. // Translation
  7. var locale = require('./locales/' + settings.language);
  8. var lang = locale.server;
  9. // Web server
  10. var bodyParser = require('body-parser');
  11. var cors = require('cors');
  12. var express = require('express');
  13. var app = express();
  14. // Logging
  15. var printit = require('printit');
  16. var log = printit({
  17. prefix: 'SMAM',
  18. date: true
  19. });
  20. // nodemailer initial configuration
  21. var transporter = nodemailer.createTransport(settings.mailserver);
  22. // Verification tokens
  23. var tokens = {};
  24. // Default template
  25. // JavaScript has no native way to handle multi-line strings, so we put our template
  26. // in a comment inside a function fro which we generate a string.
  27. // cf: https://tomasz.janczuk.org/2013/05/multi-line-strings-in-javascript-and.html
  28. var defaultTemplate = (function() {/*
  29. html
  30. body
  31. p.subj
  32. span(style="font-weight:bold") Subject: 
  33. span= subject
  34. p.from
  35. span(style="font-weight:bold") Sent from: 
  36. span= replyTo
  37. each field in custom
  38. p.custom
  39. span(style="font-weight:bold")= field.label + ': '
  40. span= field.value
  41. p.message
  42. span(style="font-weight:bold") Message: 
  43. p= html
  44. */}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];
  45. // Serve static (JS + HTML) files
  46. app.use(express.static('front'));
  47. // Body parsing
  48. app.use(bodyParser.urlencoded({ extended: true }));
  49. app.use(bodyParser.json());
  50. // Allow cross-origin requests.
  51. var corsOptions = {
  52. origin: settings.formOrigin,
  53. optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  54. };
  55. app.use(cors(corsOptions));
  56. // Taking care of preflight requests
  57. app.options('*', cors(corsOptions));
  58. // A request on /register generates a token and store it, along the user's
  59. // address, on the tokens object
  60. app.get('/register', function(req, res, next) {
  61. // Get IP from express
  62. let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  63. if(tokens[ip] === undefined) {
  64. tokens[ip] = [];
  65. }
  66. // Generate token
  67. crypto.randomBytes(10, (err, buf) => {
  68. let token = buf.toString('hex');
  69. // Store and send the token
  70. tokens[ip].push({
  71. token: token,
  72. // A token expires after 12h
  73. expire: new Date().getTime() + 12 * 3600 * 1000
  74. });
  75. res.status(200).send(token);
  76. });
  77. });
  78. // A request on /send with user input = mail to be sent
  79. app.post('/send', function(req, res, next) {
  80. // Response will be JSON
  81. res.header('Access-Control-Allow-Headers', 'Content-Type');
  82. if(!checkBody(req.body)) {
  83. return res.status(400).send();
  84. }
  85. let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  86. // Token verification
  87. if(!checkToken(ip, req.body.token)) {
  88. return res.status(403).send();
  89. }
  90. // Count the failures
  91. let status = {
  92. failed: 0,
  93. total: settings.recipients.length
  94. };
  95. // params will be used as:
  96. // - values for html generation from the pug template
  97. // - parameters for sending the mail(s)
  98. let params = {
  99. subject: req.body.subj,
  100. from: req.body.name + '<' + settings.mailserver.auth.user + '>',
  101. replyTo: req.body.name + ' <' + req.body.addr + '>',
  102. html: req.body.text
  103. };
  104. // Process custom fields to get data we can use in the HTML generation
  105. params.custom = processCustom(req.body.custom);
  106. // Replacing the mail's content with HTML from the pug template
  107. // Commenting the line below will bypass the generation and only user the
  108. // text entered by the user
  109. fs.access('template.pug', function(err) {
  110. // Checking if the template exists.
  111. // If not, fallback to the default template.
  112. // TODO: Parameterise the template file name.
  113. if(err) {
  114. params.html = pug.render(defaultTemplate, params);
  115. } else {
  116. params.html = pug.renderFile('template.pug', params);
  117. }
  118. log.info(lang.log_sending, params.replyTo);
  119. // Send the email to all users
  120. sendMails(params, function(err, infos) {
  121. if(err) {
  122. log.error(err);
  123. }
  124. logStatus(infos);
  125. }, function() {
  126. if(status.failed === status.total) {
  127. res.status(500).send();
  128. } else {
  129. res.status(200).send();
  130. }
  131. });
  132. });
  133. });
  134. // A request on /lang sends translated strings (according to the locale set in
  135. // the app settings), alongside the boolean for the display of labels in the
  136. // form block.
  137. app.get('/lang', function(req, res, next) {
  138. // Response will be JSON
  139. res.header('Access-Control-Allow-Headers', 'Content-Type');
  140. // Preventing un-updated settings files
  141. let labels = true;
  142. if(settings.labels !== undefined) {
  143. labels = settings.labels;
  144. }
  145. // Send the infos
  146. res.status(200).send({
  147. 'labels': labels,
  148. 'translations': locale.client
  149. });
  150. });
  151. // A request on /fields sends data on custom fields.
  152. app.get('/fields', function(req, res, next) {
  153. // Response will be JSON
  154. res.header('Access-Control-Allow-Headers', 'Content-Type');
  155. // Send an object anyway, its size will determine if we need to display any
  156. let customFields = settings.customFields || {};
  157. // Send custom fields data
  158. res.status(200).send(customFields);
  159. });
  160. // Use either the default port or the one chosen by the user (PORT env variable)
  161. var port = process.env.PORT || 1970;
  162. // Same for the host (using the HOST env variable)
  163. var host = process.env.HOST || '0.0.0.0';
  164. // Start the server
  165. app.listen(port, host, function() {
  166. log.info(lang.log_server_start, host + ':' + port);
  167. });
  168. // Run the clean every hour
  169. var tokensChecks = setTimeout(cleanTokens, 3600 * 1000);
  170. // Send mails to the recipients specified in the JSON settings file
  171. // content: object containing mail params
  172. // {
  173. // subject: String
  174. // from: String (following RFC 1036 (https://tools.ietf.org/html/rfc1036#section-2.1.1))
  175. // html: String
  176. // }
  177. // update(next, infos): Called each time a mail is sent with the infos provided
  178. // by nodemailer
  179. // done(): Called once each mail has been sent
  180. function sendMails(params, update, done) {
  181. let mails = settings.recipients.map((recipient) => {
  182. // Promise for each recipient to send each mail asynchronously
  183. return new Promise((sent) => {
  184. params.to = recipient;
  185. // Send the email
  186. transporter.sendMail(params, (err, infos) => {
  187. sent();
  188. if(err) {
  189. return update(err, recipient);
  190. }
  191. update(null, infos);
  192. // Promise callback
  193. });
  194. });
  195. });
  196. // Run all the promises (= send all the mails)
  197. Promise.all(mails).then(done);
  198. }
  199. // Produces log from the infos provided by nodemailer
  200. // infos: infos provided by nodemailer
  201. // return: nothing
  202. function logStatus(infos) {
  203. if(infos.accepted.length !== 0) {
  204. log.info(lang.log_send_success, infos.accepted[0]);
  205. }
  206. if(infos.rejected.length !== 0) {
  207. status.failed++;
  208. log.info(lang.log_send_failure, infos.rejected[0]);
  209. }
  210. }
  211. // Checks if the request's sender has been registered (and unregister it if not)
  212. // ip: sender's IP address
  213. // token: token used by the sender
  214. // return: true if the user was registered, false else
  215. function checkToken(ip, token) {
  216. let verified = false;
  217. // Check if there's at least one token for this IP
  218. if(tokens[ip] !== undefined) {
  219. if(tokens[ip].length !== 0) {
  220. // There's at least one element for this IP, let's check the tokens
  221. for(var i = 0; i < tokens[ip].length; i++) {
  222. if(!tokens[ip][i].token.localeCompare(token)) {
  223. // We found the right token
  224. verified = true;
  225. // Removing the token
  226. tokens[ip].pop(tokens[ip][i]);
  227. break;
  228. }
  229. }
  230. }
  231. }
  232. if(!verified) {
  233. log.warn(ip, lang.log_invalid_token);
  234. }
  235. return verified;
  236. }
  237. // Checks if all the required fields are in the request body
  238. // body: body taken from express's request object
  239. // return: true if the body is valid, false else
  240. function checkBody(body) {
  241. // Check default fields
  242. if(isInvalid(body.token) || isInvalid(body.subj) || isInvalid(body.name)
  243. || isInvalid(body.addr) || isInvalid(body.text)) {
  244. return false;
  245. }
  246. // Checking required custom fields
  247. for(let field in settings.customFields) {
  248. // No need to check the field if its not required in the settings
  249. if(settings.customFields[field].required) {
  250. if(isInvalid(body.custom[field])) {
  251. return false;
  252. }
  253. }
  254. }
  255. return true;
  256. }
  257. // Checks if the field is invalid. A field is considered as invalid if undefined
  258. // or is an empty string
  259. // field: user-input value of the field
  260. // return: true if the field is valid, false if not
  261. function isInvalid(field) {
  262. return (field === undefined || field.length == 0);
  263. }
  264. // Checks the tokens object to see if no token has expired
  265. // return: nothing
  266. function cleanTokens() {
  267. // Get current time for comparison
  268. let now = new Date().getTime();
  269. for(let ip in tokens) { // Check for each IP in the object
  270. for(let token of tokens[ip]) { // Check for each token of an IP
  271. if(token.expire < now) { // Token has expired
  272. tokens[ip].pop(token);
  273. }
  274. }
  275. if(tokens[ip].length === 0) { // No more element for this IP
  276. delete tokens[ip];
  277. }
  278. }
  279. log.info(lang.log_cleared_token);
  280. }
  281. // Process custom fields to something usable in the HTML generation
  282. // For example, this function replaces indexes with answers in select fields
  283. // custom: object describing data from custom fields
  284. // return: an object with user-input data from each field:
  285. // {
  286. // field name: {
  287. // value: String,
  288. // label: String
  289. // }
  290. // }
  291. function processCustom(custom) {
  292. let fields = {};
  293. // Process each field
  294. for(let field in custom) {
  295. let type = settings.customFields[field].type;
  296. // Match indexes with data when needed
  297. switch(type) {
  298. case 'select': custom[field] = settings.customFields[field]
  299. .options[custom[field]];
  300. break;
  301. }
  302. // Insert data into the final object if the value is set
  303. if(!isInvalid(custom[field])) {
  304. fields[field] = {
  305. value: custom[field],
  306. label: settings.customFields[field].label
  307. }
  308. }
  309. }
  310. return fields;
  311. }