From ad12e1ef315c9b4c8eabb20d8cd6a86f3262fc97 Mon Sep 17 00:00:00 2001 From: Adam Rutkowski Date: Wed, 25 Jan 2023 15:15:41 +0100 Subject: [PATCH] Show user feedback form on server errors (#2617) * Move Endpoint errors setup to common config * Implement naive Sentry link resolver * Implement error report e-mail * Delete static sentry script * Implement user feedback form on server errors * Re-arrange pipe * Use Sentry.Config.dsn() where applicable * Fix typo * Use Map.replace/3 --- assets/static/js/sentry-bundle-5.9.1-min.js | 3 - config/config.exs | 8 +- config/dev.exs | 4 - lib/plausible/application.ex | 2 +- .../controllers/error_report_controller.ex | 26 +++ lib/plausible_web/email.ex | 18 ++- lib/plausible_web/router.ex | 1 + .../email/error_report_email.html.eex | 12 ++ .../templates/error/server_error.html.eex | 56 +++++++ .../error/server_error_report_thanks.html.eex | 20 +++ lib/plausible_web/views/email_view.ex | 16 ++ lib/plausible_web/views/error_view.ex | 50 ++---- .../error_report_controller_test.exs | 152 ++++++++++++++++++ 13 files changed, 324 insertions(+), 44 deletions(-) delete mode 100644 assets/static/js/sentry-bundle-5.9.1-min.js create mode 100644 lib/plausible_web/controllers/error_report_controller.ex create mode 100644 lib/plausible_web/templates/email/error_report_email.html.eex create mode 100644 lib/plausible_web/templates/error/server_error.html.eex create mode 100644 lib/plausible_web/templates/error/server_error_report_thanks.html.eex create mode 100644 test/plausible_web/controllers/error_report_controller_test.exs diff --git a/assets/static/js/sentry-bundle-5.9.1-min.js b/assets/static/js/sentry-bundle-5.9.1-min.js deleted file mode 100644 index 3817ba371..000000000 --- a/assets/static/js/sentry-bundle-5.9.1-min.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! @sentry/browser 5.9.1 (4a81f683) | https://github.com/getsentry/sentry-javascript */ -var Sentry=function(n){var t=function(n,r){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r])})(n,r)};function r(n,r){function e(){this.constructor=n}t(n,r),n.prototype=null===r?Object.create(r):(e.prototype=r.prototype,new e)}var e=function(){return(e=Object.assign||function(n){for(var t,r=1,e=arguments.length;r0)&&!(e=o.next()).done;)u.push(e.value)}catch(n){i={error:n}}finally{try{e&&!e.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return u}function o(){for(var n=[],t=0;t=200&&t<300?n.Success:429===t?n.RateLimit:t>=400&&t<500?n.Invalid:t>=500?n.Failed:n.Unknown}}(n.Status||(n.Status={}));var s=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(n,t){return n.__proto__=t,n}:function(n,t){for(var r in t)n.hasOwnProperty(r)||(n[r]=t[r]);return n});var f=function(n){function t(t){var r=this.constructor,e=n.call(this,t)||this;return e.message=t,e.name=r.prototype.constructor.name,s(e,r.prototype),e}return r(t,n),t}(Error);function h(n){switch(Object.prototype.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return n instanceof Error}}function v(n){return"[object ErrorEvent]"===Object.prototype.toString.call(n)}function l(n){return"[object DOMError]"===Object.prototype.toString.call(n)}function d(n){return"[object String]"===Object.prototype.toString.call(n)}function p(n){return null===n||"object"!=typeof n&&"function"!=typeof n}function y(n){return"[object Object]"===Object.prototype.toString.call(n)}function m(n){return"undefined"!=typeof Event&&n instanceof Event}function w(n){return"undefined"!=typeof Element&&n instanceof Element}function b(n){return Boolean(n&&n.then&&"function"==typeof n.then)}function g(){return"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}var E={};function x(){return g()?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:E}function j(){var n=x(),t=n.crypto||n.msCrypto;if(void 0!==t&&t.getRandomValues){var r=new Uint16Array(8);t.getRandomValues(r),r[3]=4095&r[3]|16384,r[4]=16383&r[4]|32768;var e=function(n){for(var t=n.toString(16);t.length<4;)t="0"+t;return t};return e(r[0])+e(r[1])+e(r[2])+e(r[3])+e(r[4])+e(r[5])+e(r[6])+e(r[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(n){var t=16*Math.random()|0;return("x"===n?t:3&t|8).toString(16)})}function _(n){if(!n)return{};var t=n.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!t)return{};var r=t[6]||"",e=t[8]||"";return{host:t[4],path:t[5],protocol:t[2],relative:t[5]+r+e}}function k(n){if(n.message)return n.message;if(n.exception&&n.exception.values&&n.exception.values[0]){var t=n.exception.values[0];return t.type&&t.value?t.type+": "+t.value:t.type||t.value||n.event_id||""}return n.event_id||""}function S(n){var t=x();if(!("console"in t))return n();var r=t.console,e={};["debug","info","warn","error","log","assert"].forEach(function(n){n in t.console&&r[n].__sentry__&&(e[n]=r[n].__sentry_wrapped__,r[n]=r[n].__sentry_original__)});var i=n();return Object.keys(e).forEach(function(n){r[n]=e[n]}),i}function O(n,t,r){n.exception=n.exception||{},n.exception.values=n.exception.values||[],n.exception.values[0]=n.exception.values[0]||{},n.exception.values[0].value=n.exception.values[0].value||t||"",n.exception.values[0].type=n.exception.values[0].type||r||"Error"}function T(n,t){void 0===t&&(t={});try{n.exception.values[0].mechanism=n.exception.values[0].mechanism||{},Object.keys(t).forEach(function(r){n.exception.values[0].mechanism[r]=t[r]})}catch(n){}}function D(n){try{for(var t=n,r=[],e=0,i=0,o=" > ".length,u=void 0;t&&e++<5&&!("html"===(u=R(t))||e>1&&i+r.length*o+u.length>=80);)r.push(u),i+=u.length,t=t.parentNode;return r.reverse().join(" > ")}catch(n){return""}}function R(n){var t,r,e,i,o,u=n,c=[];if(!u||!u.tagName)return"";if(c.push(u.tagName.toLowerCase()),u.id&&c.push("#"+u.id),(t=u.className)&&d(t))for(r=t.split(/\s+/),o=0;o"}try{o.currentTarget=w(i.currentTarget)?D(i.currentTarget):Object.prototype.toString.call(i.currentTarget)}catch(n){o.currentTarget=""}for(var e in"undefined"!=typeof CustomEvent&&n instanceof CustomEvent&&(o.detail=i.detail),i)Object.prototype.hasOwnProperty.call(i,e)&&(o[e]=i);return o}return n}function $(n){return function(n){return~-encodeURI(n).split(/%..|./).length}(JSON.stringify(n))}function X(n,t,r){void 0===t&&(t=3),void 0===r&&(r=102400);var e=z(n,t);return $(e)>r?X(n,t-1,r):e}function G(n,t){return"domain"===t&&n&&"object"==typeof n&&n.u?"[Domain]":"domainEmitter"===t?"[DomainEmitter]":"undefined"!=typeof global&&n===global?"[Global]":"undefined"!=typeof window&&n===window?"[Window]":"undefined"!=typeof document&&n===document?"[Document]":y(r=n)&&"nativeEvent"in r&&"preventDefault"in r&&"stopPropagation"in r?"[SyntheticEvent]":"number"==typeof n&&n!=n?"[NaN]":void 0===n?"[undefined]":"function"==typeof n?"[Function: "+(n.name||"")+"]":n;var r}function J(n,t,r,e){if(void 0===r&&(r=1/0),void 0===e&&(e=new q),0===r)return function(n){var t=Object.prototype.toString.call(n);if("string"==typeof n)return n;if("[object Object]"===t)return"[Object]";if("[object Array]"===t)return"[Array]";var r=G(n);return p(r)?r:t}(t);if(null!=t&&"function"==typeof t.toJSON)return t.toJSON();var i=G(t,n);if(p(i))return i;var o=B(t),u=Array.isArray(t)?[]:{};if(e.memoize(t))return"[Circular ~]";for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&(u[c]=J(c,o[c],r-1,e));return e.unmemoize(t),u}function z(n,t){try{return JSON.parse(JSON.stringify(n,function(n,r){return J(n,r,t)}))}catch(n){return"**non-serializable**"}}function V(n,t){void 0===t&&(t=40);var r=Object.keys(B(n));if(r.sort(),!r.length)return"[object has no keys]";if(r[0].length>=t)return F(r[0],t);for(var e=r.length;e>0;e--){var i=r.slice(0,e).join(", ");if(!(i.length>t))return e===r.length?i:F(i,t)}return""}!function(n){n.PENDING="PENDING",n.RESOLVED="RESOLVED",n.REJECTED="REJECTED"}(U||(U={}));var K=function(){function n(n){var t=this;this.s=U.PENDING,this.h=[],this.v=function(n){t.l(U.RESOLVED,n)},this.p=function(n){t.l(U.REJECTED,n)},this.l=function(n,r){t.s===U.PENDING&&(b(r)?r.then(t.v,t.p):(t.s=n,t.m=r,t.g()))},this.j=function(n){t.h=t.h.concat(n),t.g()},this.g=function(){t.s!==U.PENDING&&(t.s===U.REJECTED?t.h.forEach(function(n){n.onrejected&&n.onrejected(t.m)}):t.h.forEach(function(n){n.onfulfilled&&n.onfulfilled(t.m)}),t.h=[])};try{n(this.v,this.p)}catch(n){this.p(n)}}return n.prototype.toString=function(){return"[object SyncPromise]"},n.resolve=function(t){return new n(function(n){n(t)})},n.reject=function(t){return new n(function(n,r){r(t)})},n.all=function(t){return new n(function(r,e){if(Array.isArray(t))if(0!==t.length){var i=t.length,o=[];t.forEach(function(t,u){n.resolve(t).then(function(n){o[u]=n,0===(i-=1)&&r(o)}).then(null,e)})}else r([]);else e(new TypeError("Promise.all requires an array as input."))})},n.prototype.then=function(t,r){var e=this;return new n(function(n,i){e.j({onfulfilled:function(r){if(t)try{return void n(t(r))}catch(n){return void i(n)}else n(r)},onrejected:function(t){if(r)try{return void n(r(t))}catch(n){return void i(n)}else i(t)}})})},n.prototype.catch=function(n){return this.then(function(n){return n},n)},n.prototype.finally=function(t){var r=this;return new n(function(n,e){var i,o;return r.then(function(n){o=!1,i=n,t&&t()},function(n){o=!0,i=n,t&&t()}).then(function(){o?e(i):n(i)})})},n}(),Q=function(){function n(n){this._=n,this.k=[]}return n.prototype.isReady=function(){return void 0===this._||this.length()0&&r(!1)},n);K.all(t.k).then(function(){clearTimeout(e),r(!0)}).then(null,function(){r(!0)})})},n}();function Y(){if(!("fetch"in x()))return!1;try{return new Headers,new Request(""),new Response,!0}catch(n){return!1}}function Z(){if(!Y())return!1;try{return new Request("_",{referrerPolicy:"origin"}),!0}catch(n){return!1}}var nn=/^[ \t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \t]*$/,tn=function(){function n(n,t,r,e){void 0===n&&(n=j()),void 0===t&&(t=j().substring(16)),this.S=n,this.O=t,this.T=r,this.D=e}return n.prototype.setParent=function(n){return this.D=n,this},n.prototype.setSampled=function(n){return this.T=n,this},n.fromTraceparent=function(t){var r=t.match(nn);if(r){var e=void 0;"1"===r[3]?e=!0:"0"===r[3]&&(e=!1);var i=new n(r[1],r[2],e);return new n(r[1],void 0,e,i)}},n.prototype.toTraceparent=function(){var n="";return!0===this.T?n="-1":!1===this.T&&(n="-0"),this.S+"-"+this.O+n},n.prototype.toJSON=function(){return{parent:this.D&&this.D.toJSON()||void 0,sampled:this.T,span_id:this.O,trace_id:this.S}},n}(),rn=function(){function n(){this.R=!1,this.I=[],this.N=[],this.C=[],this.A={},this.M={},this.U={},this.L={}}return n.prototype.addScopeListener=function(n){this.I.push(n)},n.prototype.addEventProcessor=function(n){return this.N.push(n),this},n.prototype.q=function(){var n=this;this.R||(this.R=!0,setTimeout(function(){n.I.forEach(function(t){t(n)}),n.R=!1}))},n.prototype.F=function(n,t,r,i){var o=this;return void 0===i&&(i=0),new K(function(u,c){var a=n[i];if(null===t||"function"!=typeof a)u(t);else{var s=a(e({},t),r);b(s)?s.then(function(t){return o.F(n,t,r,i+1).then(u)}).then(null,c):o.F(n,s,r,i+1).then(u).then(null,c)}})},n.prototype.setUser=function(n){return this.A=z(n),this.q(),this},n.prototype.setTags=function(n){return this.M=e({},this.M,z(n)),this.q(),this},n.prototype.setTag=function(n,t){var r;return this.M=e({},this.M,((r={})[n]=z(t),r)),this.q(),this},n.prototype.setExtras=function(n){return this.U=e({},this.U,z(n)),this.q(),this},n.prototype.setExtra=function(n,t){var r;return this.U=e({},this.U,((r={})[n]=z(t),r)),this.q(),this},n.prototype.setFingerprint=function(n){return this.H=z(n),this.q(),this},n.prototype.setLevel=function(n){return this.P=z(n),this.q(),this},n.prototype.setTransaction=function(n){return this.W=n,this.q(),this},n.prototype.setContext=function(n,t){return this.L[n]=t?z(t):void 0,this.q(),this},n.prototype.setSpan=function(n){return this.B=n,this.q(),this},n.prototype.startSpan=function(n){var t=new tn;return t.setParent(n),this.setSpan(t),t},n.prototype.getSpan=function(){return this.B},n.clone=function(t){var r=new n;return t&&(r.C=o(t.C),r.M=e({},t.M),r.U=e({},t.U),r.L=e({},t.L),r.A=t.A,r.P=t.P,r.B=t.B,r.W=t.W,r.H=t.H,r.N=o(t.N)),r},n.prototype.clear=function(){return this.C=[],this.M={},this.U={},this.A={},this.L={},this.P=void 0,this.W=void 0,this.H=void 0,this.B=void 0,this.q(),this},n.prototype.addBreadcrumb=function(n,t){var r=(new Date).getTime()/1e3,i=e({timestamp:r},n);return this.C=void 0!==t&&t>=0?o(this.C,[z(i)]).slice(-t):o(this.C,[z(i)]),this.q(),this},n.prototype.clearBreadcrumbs=function(){return this.C=[],this.q(),this},n.prototype.$=function(n){n.fingerprint=n.fingerprint?Array.isArray(n.fingerprint)?n.fingerprint:[n.fingerprint]:[],this.H&&(n.fingerprint=n.fingerprint.concat(this.H)),n.fingerprint&&!n.fingerprint.length&&delete n.fingerprint},n.prototype.applyToEvent=function(n,t){return this.U&&Object.keys(this.U).length&&(n.extra=e({},this.U,n.extra)),this.M&&Object.keys(this.M).length&&(n.tags=e({},this.M,n.tags)),this.A&&Object.keys(this.A).length&&(n.user=e({},this.A,n.user)),this.L&&Object.keys(this.L).length&&(n.contexts=e({},this.L,n.contexts)),this.P&&(n.level=this.P),this.W&&(n.transaction=this.W),this.B&&(n.contexts=n.contexts||{},n.contexts.trace=this.B),this.$(n),n.breadcrumbs=o(n.breadcrumbs||[],this.C),n.breadcrumbs=n.breadcrumbs.length>0?n.breadcrumbs:void 0,this.F(o(en(),this.N),n,t)},n}();function en(){var n=x();return n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.globalEventProcessors=n.__SENTRY__.globalEventProcessors||[],n.__SENTRY__.globalEventProcessors}function on(n){en().push(n)}var un=3,cn=function(){function n(n,t,r){void 0===t&&(t=new rn),void 0===r&&(r=un),this.X=r,this.G=[],this.G.push({client:n,scope:t})}return n.prototype.J=function(n){for(var t,r=[],e=1;e0?n[n.length-1].scope:void 0,r=rn.clone(t);return this.getStack().push({client:this.getClient(),scope:r}),r},n.prototype.popScope=function(){return void 0!==this.getStack().pop()},n.prototype.withScope=function(n){var t=this.pushScope();try{n(t)}finally{this.popScope()}},n.prototype.getClient=function(){return this.getStackTop().client},n.prototype.getScope=function(){return this.getStackTop().scope},n.prototype.getStack=function(){return this.G},n.prototype.getStackTop=function(){return this.G[this.G.length-1]},n.prototype.captureException=function(n,t){var r=this.V=j(),i=t;if(!t){var o=void 0;try{throw new Error("Sentry syntheticException")}catch(n){o=n}i={originalException:n,syntheticException:o}}return this.J("captureException",n,e({},i,{event_id:r})),r},n.prototype.captureMessage=function(n,t,r){var i=this.V=j(),o=r;if(!r){var u=void 0;try{throw new Error(n)}catch(n){u=n}o={originalException:n,syntheticException:u}}return this.J("captureMessage",n,t,e({},o,{event_id:i})),i},n.prototype.captureEvent=function(n,t){var r=this.V=j();return this.J("captureEvent",n,e({},t,{event_id:r})),r},n.prototype.lastEventId=function(){return this.V},n.prototype.addBreadcrumb=function(n,t){var r=this.getStackTop();if(r.scope&&r.client){var i=r.client.getOptions&&r.client.getOptions()||{},o=i.beforeBreadcrumb,u=void 0===o?null:o,c=i.maxBreadcrumbs,a=void 0===c?30:c;if(!(a<=0)){var s=(new Date).getTime()/1e3,f=e({timestamp:s},n),h=u?S(function(){return u(f,t)}):f;null!==h&&r.scope.addBreadcrumb(h,Math.min(a,100))}}},n.prototype.setUser=function(n){var t=this.getStackTop();t.scope&&t.scope.setUser(n)},n.prototype.setTags=function(n){var t=this.getStackTop();t.scope&&t.scope.setTags(n)},n.prototype.setExtras=function(n){var t=this.getStackTop();t.scope&&t.scope.setExtras(n)},n.prototype.setTag=function(n,t){var r=this.getStackTop();r.scope&&r.scope.setTag(n,t)},n.prototype.setExtra=function(n,t){var r=this.getStackTop();r.scope&&r.scope.setExtra(n,t)},n.prototype.setContext=function(n,t){var r=this.getStackTop();r.scope&&r.scope.setContext(n,t)},n.prototype.configureScope=function(n){var t=this.getStackTop();t.scope&&t.client&&n(t.scope)},n.prototype.run=function(n){var t=sn(this);try{n(this)}finally{sn(t)}},n.prototype.getIntegration=function(n){var t=this.getClient();if(!t)return null;try{return t.getIntegration(n)}catch(t){return L.warn("Cannot retrieve integration "+n.id+" from the current Hub"),null}},n.prototype.traceHeaders=function(){var n=this.getStackTop();if(n.scope&&n.client){var t=n.scope.getSpan();if(t)return{"sentry-trace":t.toTraceparent()}}return{}},n}();function an(){var n=x();return n.__SENTRY__=n.__SENTRY__||{hub:void 0},n}function sn(n){var t=an(),r=vn(t);return ln(t,n),r}function fn(){var n=an();return hn(n)&&!vn(n).isOlderThan(un)||ln(n,new cn),g()?function(n){try{var t=(i=module,o="domain",i.require(o)),r=t.active;if(!r)return vn(n);if(!hn(r)||vn(r).isOlderThan(un)){var e=vn(n).getStackTop();ln(r,new cn(e.client,rn.clone(e.scope)))}return vn(r)}catch(t){return vn(n)}var i,o}(n):vn(n)}function hn(n){return!!(n&&n.__SENTRY__&&n.__SENTRY__.hub)}function vn(n){return n&&n.__SENTRY__&&n.__SENTRY__.hub?n.__SENTRY__.hub:(n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.hub=new cn,n.__SENTRY__.hub)}function ln(n,t){return!!n&&(n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.hub=t,!0)}function dn(n){for(var t=[],r=1;r1&&(v=d.slice(0,-1).join("/"),l=d.pop()),this.Y({host:a,pass:c,path:v,projectId:l,port:h,protocol:e,user:o})},n.prototype.Y=function(n){this.protocol=n.protocol,this.user=n.user,this.pass=n.pass||"",this.host=n.host,this.port=n.port||"",this.path=n.path||"",this.projectId=n.projectId},n.prototype.Z=function(){var n=this;if(["protocol","user","host","projectId"].forEach(function(t){if(!n[t])throw new f("Invalid Dsn")}),"http"!==this.protocol&&"https"!==this.protocol)throw new f("Invalid Dsn");if(this.port&&isNaN(parseInt(this.port,10)))throw new f("Invalid Dsn")},n}(),wn=function(){function n(n){this.dsn=n,this.nn=new mn(n)}return n.prototype.getDsn=function(){return this.nn},n.prototype.getStoreEndpoint=function(){return""+this.tn()+this.getStoreEndpointPath()},n.prototype.getStoreEndpointWithUrlEncodedAuth=function(){var n,t={sentry_key:this.nn.user,sentry_version:"7"};return this.getStoreEndpoint()+"?"+(n=t,Object.keys(n).map(function(t){return encodeURIComponent(t)+"="+encodeURIComponent(n[t])}).join("&"))},n.prototype.tn=function(){var n=this.nn,t=n.protocol?n.protocol+":":"",r=n.port?":"+n.port:"";return t+"//"+n.host+r},n.prototype.getStoreEndpointPath=function(){var n=this.nn;return(n.path?"/"+n.path:"")+"/api/"+n.projectId+"/store/"},n.prototype.getRequestHeaders=function(n,t){var r=this.nn,e=["Sentry sentry_version=7"];return e.push("sentry_timestamp="+(new Date).getTime()),e.push("sentry_client="+n+"/"+t),e.push("sentry_key="+r.user),r.pass&&e.push("sentry_secret="+r.pass),{"Content-Type":"application/json","X-Sentry-Auth":e.join(", ")}},n.prototype.getReportDialogEndpoint=function(n){void 0===n&&(n={});var t=this.nn,r=this.tn()+(t.path?"/"+t.path:"")+"/api/embed/error-page/",e=[];for(var i in e.push("dsn="+t.toString()),n)if("user"===i){if(!n.user)continue;n.user.name&&e.push("name="+encodeURIComponent(n.user.name)),n.user.email&&e.push("email="+encodeURIComponent(n.user.email))}else e.push(encodeURIComponent(i)+"="+encodeURIComponent(n[i]));return e.length?r+"?"+e.join("&"):r},n}(),bn=[];function gn(n){var t={};return function(n){var t=n.defaultIntegrations&&o(n.defaultIntegrations)||[],r=n.integrations,e=[];if(Array.isArray(r)){var i=r.map(function(n){return n.name}),u=[];t.forEach(function(n){-1===i.indexOf(n.name)&&-1===u.indexOf(n.name)&&(e.push(n),u.push(n.name))}),r.forEach(function(n){-1===u.indexOf(n.name)&&(e.push(n),u.push(n.name))})}else"function"==typeof r?(e=r(t),e=Array.isArray(e)?e:[e]):e=o(t);var c=e.map(function(n){return n.name});return-1!==c.indexOf("Debug")&&e.push.apply(e,o(e.splice(c.indexOf("Debug"),1))),e}(n).forEach(function(n){t[n.name]=n,function(n){-1===bn.indexOf(n.name)&&(n.setupOnce(on,fn),bn.push(n.name),L.log("Integration installed: "+n.name))}(n)}),t}var En,xn=function(){function n(n,t){this.rn={},this.en=!1,this.in=new n(t),this.on=t,t.dsn&&(this.un=new mn(t.dsn)),this.cn()&&(this.rn=gn(this.on))}return n.prototype.captureException=function(n,t,r){var e=this,i=t&&t.event_id;return this.en=!0,this.an().eventFromException(n,t).then(function(n){return e.sn(n,t,r)}).then(function(n){i=n&&n.event_id,e.en=!1}).then(null,function(n){L.error(n),e.en=!1}),i},n.prototype.captureMessage=function(n,t,r,e){var i=this,o=r&&r.event_id;return this.en=!0,(p(n)?this.an().eventFromMessage(""+n,t,r):this.an().eventFromException(n,r)).then(function(n){return i.sn(n,r,e)}).then(function(n){o=n&&n.event_id,i.en=!1}).then(null,function(n){L.error(n),i.en=!1}),o},n.prototype.captureEvent=function(n,t,r){var e=this,i=t&&t.event_id;return this.en=!0,this.sn(n,t,r).then(function(n){i=n&&n.event_id,e.en=!1}).then(null,function(n){L.error(n),e.en=!1}),i},n.prototype.getDsn=function(){return this.un},n.prototype.getOptions=function(){return this.on},n.prototype.flush=function(n){var t=this;return this.fn(n).then(function(r){return clearInterval(r.interval),t.an().getTransport().close(n).then(function(n){return r.ready&&n})})},n.prototype.close=function(n){var t=this;return this.flush(n).then(function(n){return t.getOptions().enabled=!1,n})},n.prototype.getIntegrations=function(){return this.rn||{}},n.prototype.getIntegration=function(n){try{return this.rn[n.id]||null}catch(t){return L.warn("Cannot retrieve integration "+n.id+" from the current Client"),null}},n.prototype.fn=function(n){var t=this;return new K(function(r){var e=0,i=0;clearInterval(i),i=setInterval(function(){t.en?(e+=1,n&&e>=n&&r({interval:i,ready:!1})):r({interval:i,ready:!0})},1)})},n.prototype.an=function(){return this.in},n.prototype.cn=function(){return!1!==this.getOptions().enabled&&void 0!==this.un},n.prototype.hn=function(n,t,r){var i=this.getOptions(),o=i.environment,u=i.release,c=i.dist,a=i.maxValueLength,s=void 0===a?250:a,f=e({},n);void 0===f.environment&&void 0!==o&&(f.environment=o),void 0===f.release&&void 0!==u&&(f.release=u),void 0===f.dist&&void 0!==c&&(f.dist=c),f.message&&(f.message=F(f.message,s));var h=f.exception&&f.exception.values&&f.exception.values[0];h&&h.value&&(h.value=F(h.value,s));var v=f.request;v&&v.url&&(v.url=F(v.url,s)),void 0===f.event_id&&(f.event_id=j()),this.vn(f.sdk);var l=K.resolve(f);return t&&(l=t.applyToEvent(f,r)),l},n.prototype.vn=function(n){var t=Object.keys(this.rn);n&&t.length>0&&(n.integrations=t)},n.prototype.sn=function(n,t,r){var e=this,i=this.getOptions(),o=i.beforeSend,u=i.sampleRate;return this.cn()?"number"==typeof u&&Math.random()>u?K.reject("This event has been sampled, will not send event."):new K(function(i,u){e.hn(n,r,t).then(function(n){if(null!==n){var r=n;try{if(t&&t.data&&!0===t.data.__sentry__||!o)return e.an().sendEvent(r),void i(r);var c=o(n,t);if(void 0===c)L.error("`beforeSend` method has to return `null` or a valid event.");else if(b(c))e.ln(c,i,u);else{if(null===(r=c))return L.log("`beforeSend` returned `null`, will not send event."),void i(null);e.an().sendEvent(r),i(r)}}catch(n){e.captureException(n,{data:{__sentry__:!0},originalException:n}),u("`beforeSend` threw an error, will not send event.")}}else u("An event processor returned null, will not send event.")}).then(null,function(){u("`beforeSend` threw an error, will not send event.")})}):K.reject("SDK not enabled, will not send event.")},n.prototype.ln=function(n,t,r){var e=this;n.then(function(n){null!==n?(e.an().sendEvent(n),t(n)):r("`beforeSend` returned `null`, will not send event.")}).then(null,function(n){r("beforeSend rejected with "+n)})},n}(),jn=function(){function t(){}return t.prototype.sendEvent=function(t){return K.resolve({reason:"NoopTransport: Event has been skipped because no Dsn is configured.",status:n.Status.Skipped})},t.prototype.close=function(n){return K.resolve(!0)},t}(),_n=function(){function n(n){this.on=n,this.on.dsn||L.warn("No DSN provided, backend will not do anything."),this.dn=this.pn()}return n.prototype.pn=function(){return new jn},n.prototype.eventFromException=function(n,t){throw new f("Backend has to implement `eventFromException` method")},n.prototype.eventFromMessage=function(n,t,r){throw new f("Backend has to implement `eventFromMessage` method")},n.prototype.sendEvent=function(n){this.dn.sendEvent(n).then(null,function(n){L.error("Error while sending event: "+n)})},n.prototype.getTransport=function(){return this.dn},n}();var kn=function(){function n(){this.name=n.id}return n.prototype.setupOnce=function(){En=Function.prototype.toString,Function.prototype.toString=function(){for(var n=[],t=0;t|[-a-z]+:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,In=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js))(?::(\d+))?(?::(\d+))?\s*$/i,Nn=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Cn=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,An=/\((\S*)(?::(\d+))(?::(\d+))\)/;function Mn(n){var t=null,r=n&&n.framesToPop;try{if(t=function(n){if(!n||!n.stacktrace)return null;for(var t,r=n.stacktrace,e=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,i=/ line (\d+), column (\d+)\s*(?:in (?:]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i,o=r.split("\n"),u=[],c=0;c eval")>-1&&(t=Cn.exec(r[3]))?(r[1]=r[1]||"eval",r[3]=t[1],r[4]=t[2],r[5]=""):0!==u||r[5]||void 0===n.columnNumber||(i[0].column=n.columnNumber+1),e={url:r[3],func:r[1]||Dn,args:r[2]?r[2].split(","):[],line:r[4]?+r[4]:null,column:r[5]?+r[5]:null}}!e.func&&e.line&&(e.func=Dn),i.push(e)}if(!i.length)return null;return{message:Ln(n),name:n.name,stack:i}}(n))return Un(t,r)}catch(n){}return{message:Ln(n),name:n&&n.name,stack:[],failed:!0}}function Un(n,t){try{return e({},n,{stack:n.stack.slice(t)})}catch(t){return n}}function Ln(n){var t=n&&n.message;return t?t.error&&"string"==typeof t.error.message?t.error.message:t:"No error message"}var qn=50;function Fn(n){var t=Pn(n.stack),r={type:n.name,value:n.message};return t&&t.length&&(r.stacktrace={frames:t}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Hn(n){return{exception:{values:[Fn(n)]}}}function Pn(n){if(!n||!n.length)return[];var t=n,r=t[0].func||"",e=t[t.length-1].func||"";return-1===r.indexOf("captureMessage")&&-1===r.indexOf("captureException")||(t=t.slice(1)),-1!==e.indexOf("sentryWrapped")&&(t=t.slice(0,-1)),t.map(function(n){return{colno:null===n.column?void 0:n.column,filename:n.url||t[0].url,function:n.func||"?",in_app:!0,lineno:null===n.line?void 0:n.line}}).slice(0,qn).reverse()}function Wn(n,t,r){var e,i;if(void 0===r&&(r={}),v(n)&&n.error)return e=Hn(Mn(n=n.error));if(l(n)||(i=n,"[object DOMException]"===Object.prototype.toString.call(i))){var o=n,u=o.name||(l(o)?"DOMError":"DOMException"),c=o.message?u+": "+o.message:u;return O(e=Bn(c,t,r),c),e}return h(n)?e=Hn(Mn(n)):y(n)||m(n)?(T(e=function(n,t,r){var e={exception:{values:[{type:m(n)?n.constructor.name:r?"UnhandledRejection":"Error",value:"Non-Error "+(r?"promise rejection":"exception")+" captured with keys: "+V(n)}]},extra:{__serialized__:X(n)}};if(t){var i=Pn(Mn(t).stack);e.stacktrace={frames:i}}return e}(n,t,r.rejection),{synthetic:!0}),e):(O(e=Bn(n,t,r),""+n,void 0),T(e,{synthetic:!0}),e)}function Bn(n,t,r){void 0===r&&(r={});var e={message:n};if(r.attachStacktrace&&t){var i=Pn(Mn(t).stack);e.stacktrace={frames:i}}return e}var $n,Xn,Gn=function(){function n(n){this.options=n,this.k=new Q(30),this.url=new wn(this.options.dsn).getStoreEndpointWithUrlEncodedAuth()}return n.prototype.sendEvent=function(n){throw new f("Transport Class has to implement `sendEvent` method")},n.prototype.close=function(n){return this.k.drain(n)},n}(),Jn=x(),zn=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n._n=new Date(Date.now()),n}return r(e,t),e.prototype.sendEvent=function(t){var r=this;if(new Date(Date.now())0}function et(n,t,r){if(void 0===t&&(t={}),"function"!=typeof n)return n;try{if(n.__sentry__)return n;if(n.__sentry_wrapped__)return n.__sentry_wrapped__}catch(t){return n}var sentryWrapped=function(){r&&"function"==typeof r&&r.apply(this,arguments);var i=Array.prototype.slice.call(arguments);try{var o=i.map(function(n){return et(n,t)});return n.handleEvent?n.handleEvent.apply(this,o):n.apply(this,o)}catch(n){throw tt+=1,setTimeout(function(){tt-=1}),pn(function(r){r.addEventProcessor(function(n){var r=e({},n);return t.mechanism&&(O(r,void 0,void 0),T(r,t.mechanism)),r.extra=e({},r.extra,{arguments:z(i,3)}),r}),captureException(n)}),n}};try{for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(sentryWrapped[i]=n[i])}catch(n){}n.prototype=n.prototype||{},sentryWrapped.prototype=n.prototype,Object.defineProperty(n,"__sentry_wrapped__",{enumerable:!1,value:sentryWrapped}),Object.defineProperties(sentryWrapped,{__sentry__:{enumerable:!1,value:!0},__sentry_original__:{enumerable:!1,value:n}});try{Object.getOwnPropertyDescriptor(sentryWrapped,"name").configurable&&Object.defineProperty(sentryWrapped,"name",{get:function(){return n.name}})}catch(n){}return sentryWrapped}var it=0;function ot(n,t){return void 0===t&&(t=!1),function(r){if($n=void 0,r&&Xn!==r){Xn=r;var e=function(){var t;try{t=r.target?D(r.target):D(r)}catch(n){t=""}0!==t.length&&fn().addBreadcrumb({category:"ui."+n,message:t},{event:r,name:n})};it&&clearTimeout(it),t?it=setTimeout(e):e()}}}function ut(){return function(n){var t;try{t=n.target}catch(n){return}var r=t&&t.tagName;r&&("INPUT"===r||"TEXTAREA"===r||t.isContentEditable)&&($n||ot("input")(n),clearTimeout($n),$n=setTimeout(function(){$n=void 0},nt))}}var ct=function(){function t(n){this.name=t.id,this.kn=x(),this.Sn=null,this.On=null,this.Tn=!1,this.Dn=!1,this.on=e({onerror:!0,onunhandledrejection:!0},n)}return t.prototype.setupOnce=function(){Error.stackTraceLimit=50,this.on.onerror&&(L.log("Global Handler attached: onerror"),this.Rn()),this.on.onunhandledrejection&&(L.log("Global Handler attached: onunhandledrejection"),this.In())},t.prototype.Rn=function(){if(!this.Tn){var n=this;this.Sn=this.kn.onerror,this.kn.onerror=function(r,e,i,o,u){var c=fn(),a=c.getIntegration(t),s=u&&!0===u.__sentry_own_request__;if(!a||rt()||s)return!n.Sn||n.Sn.apply(this,arguments);var f=c.getClient(),h=p(u)?n.Nn(r,e,i,o):n.Cn(Wn(u,void 0,{attachStacktrace:f&&f.getOptions().attachStacktrace,rejection:!1}),e,i,o);return T(h,{handled:!1,type:"onerror"}),c.captureEvent(h,{originalException:u}),!n.Sn||n.Sn.apply(this,arguments)},this.Tn=!0}},t.prototype.In=function(){if(!this.Dn){var r=this;this.On=this.kn.onunhandledrejection,this.kn.onunhandledrejection=function(e){var i=e;try{i=e&&"reason"in e?e.reason:e}catch(n){}var o=fn(),u=o.getIntegration(t),c=i&&!0===i.__sentry_own_request__;if(!u||rt()||c)return!r.On||r.On.apply(this,arguments);var a=o.getClient(),s=p(i)?r.An(i):Wn(i,void 0,{attachStacktrace:a&&a.getOptions().attachStacktrace,rejection:!0});return s.level=n.Severity.Error,T(s,{handled:!1,type:"onunhandledrejection"}),o.captureEvent(s,{originalException:i}),!r.On||r.On.apply(this,arguments)},this.Dn=!0}},t.prototype.Nn=function(n,t,r,e){var i,o=v(n)?n.message:n;if(d(o)){var u=o.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);u&&(i=u[1],o=u[2])}var c={exception:{values:[{type:i||"Error",value:o}]}};return this.Cn(c,t,r,e)},t.prototype.An=function(n){return{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+n}]}}},t.prototype.Cn=function(n,t,r,e){n.exception=n.exception||{},n.exception.values=n.exception.values||[],n.exception.values[0]=n.exception.values[0]||{},n.exception.values[0].stacktrace=n.exception.values[0].stacktrace||{},n.exception.values[0].stacktrace.frames=n.exception.values[0].stacktrace.frames||[];var i=isNaN(parseInt(e,10))?void 0:e,o=isNaN(parseInt(r,10))?void 0:r,u=d(t)&&t.length>0?t:function(){try{return document.location.href}catch(n){return""}}();return 0===n.exception.values[0].stacktrace.frames.length&&n.exception.values[0].stacktrace.frames.push({colno:i,filename:u,function:"?",in_app:!0,lineno:o}),n},t.id="GlobalHandlers",t}(),at=function(){function n(){this.Mn=0,this.name=n.id}return n.prototype.Un=function(n){return function(){for(var t=[],r=0;r"}catch(n){return""}}var ft,ht=x(),vt=function(){function t(n){this.name=t.id,this.on=e({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},n)}return t.prototype.Fn=function(){"console"in ht&&["debug","info","warn","error","log","assert"].forEach(function(r){r in ht.console&&W(ht.console,r,function(e){return function(){for(var i=[],o=0;o2?t[2]:void 0;return e&&u(ft,String(e)),n.apply(this,t)}}},t.prototype.Bn=function(){if("XMLHttpRequest"in ht){var n=XMLHttpRequest.prototype;W(n,"open",function(n){return function(){for(var t=[],r=0;r"},handled:!0,type:"instrument"}})})}(n,i)}),"onreadystatechange"in i&&"function"==typeof i.onreadystatechange?W(i,"onreadystatechange",function(n){return et(n,{mechanism:{data:{function:"onreadystatechange",handler:n&&n.name||""},handled:!0,type:"instrument"}},o)}):i.onreadystatechange=o,n.apply(this,r)}})}},t.addBreadcrumb=function(n,r){fn().getIntegration(t)&&fn().addBreadcrumb(n,r)},t.prototype.setupOnce=function(){this.on.console&&this.Fn(),this.on.dom&&this.Hn(),this.on.xhr&&this.Bn(),this.on.fetch&&this.Pn(),this.on.history&&this.Wn()},t.id="Breadcrumbs",t}();function lt(t){try{var r=JSON.parse(t);vt.addBreadcrumb({category:"sentry",event_id:r.event_id,level:r.level||n.Severity.fromString("error"),message:k(r)},{event:r})}catch(n){L.error("Error while adding sentry type breadcrumb")}}var dt="cause",pt=5,yt=function(){function n(t){void 0===t&&(t={}),this.name=n.id,this.$n=t.key||dt,this._=t.limit||pt}return n.prototype.setupOnce=function(){on(function(t,r){var e=fn().getIntegration(n);return e?e.Xn(t,r):t})},n.prototype.Xn=function(n,t){if(!(n.exception&&n.exception.values&&t&&t.originalException instanceof Error))return n;var r=this.Gn(t.originalException,this.$n);return n.exception.values=o(r,n.exception.values),n},n.prototype.Gn=function(n,t,r){if(void 0===r&&(r=[]),!(n[t]instanceof Error)||r.length+1>=this._)return r;var e=Fn(Mn(n[t]));return this.Gn(n[t],t,o([e],r))},n.id="LinkedErrors",n}(),mt=x(),wt=function(){function n(){this.name=n.id}return n.prototype.setupOnce=function(){on(function(t){if(fn().getIntegration(n)){if(!mt.navigator||!mt.location)return t;var r=t.request||{};return r.url=r.url||mt.location.href,r.headers=r.headers||{},r.headers["User-Agent"]=mt.navigator.userAgent,e({},t,{request:r})}return t})},n.id="UserAgent",n}(),bt=Object.freeze({GlobalHandlers:ct,TryCatch:at,Breadcrumbs:vt,LinkedErrors:yt,UserAgent:wt}),gt=[new On,new kn,new at,new vt,new ct,new yt,new wt];var Et={},xt=x();xt.Sentry&&xt.Sentry.Integrations&&(Et=xt.Sentry.Integrations);var jt=e({},Et,Tn,bt);return n.BrowserClient=Zn,n.Hub=cn,n.Integrations=jt,n.SDK_NAME=Yn,n.SDK_VERSION="5.9.1",n.Scope=rn,n.Span=tn,n.Transports=Kn,n.addBreadcrumb=function(n){dn("addBreadcrumb",n)},n.addGlobalEventProcessor=on,n.captureEvent=function(n){return dn("captureEvent",n)},n.captureException=captureException,n.captureMessage=function(n,t){var r;try{throw new Error(n)}catch(n){r=n}return dn("captureMessage",n,t,{originalException:n,syntheticException:r})},n.close=function(n){var t=fn().getClient();return t?t.close(n):K.reject(!1)},n.configureScope=function(n){dn("configureScope",n)},n.defaultIntegrations=gt,n.flush=function(n){var t=fn().getClient();return t?t.flush(n):K.reject(!1)},n.forceLoad=function(){},n.getCurrentHub=fn,n.getHubFromCarrier=vn,n.init=function(n){if(void 0===n&&(n={}),void 0===n.defaultIntegrations&&(n.defaultIntegrations=gt),void 0===n.release){var t=x();t.SENTRY_RELEASE&&t.SENTRY_RELEASE.id&&(n.release=t.SENTRY_RELEASE.id)}!function(n,t){!0===t.debug&&L.enable(),fn().bindClient(new n(t))}(Zn,n)},n.lastEventId=function(){return fn().lastEventId()},n.onLoad=function(n){n()},n.setContext=function(n,t){dn("setContext",n,t)},n.setExtra=function(n,t){dn("setExtra",n,t)},n.setExtras=function(n){dn("setExtras",n)},n.setTag=function(n,t){dn("setTag",n,t)},n.setTags=function(n){dn("setTags",n)},n.setUser=function(n){dn("setUser",n)},n.showReportDialog=function(n){void 0===n&&(n={}),n.eventId||(n.eventId=fn().lastEventId());var t=fn().getClient();t&&t.showReportDialog(n)},n.withScope=pn,n.wrap=function(n){return et(n)()},n}({}); -//# sourceMappingURL=bundle.min.js.map diff --git a/config/config.exs b/config/config.exs index 32456c2a7..a514f79ad 100644 --- a/config/config.exs +++ b/config/config.exs @@ -3,7 +3,13 @@ import Config config :plausible, ecto_repos: [Plausible.Repo, Plausible.ClickhouseRepo] -config :plausible, PlausibleWeb.Endpoint, pubsub_server: Plausible.PubSub +config :plausible, PlausibleWeb.Endpoint, + pubsub_server: Plausible.PubSub, + render_errors: [ + view: PlausibleWeb.ErrorView, + layout: {PlausibleWeb.LayoutView, "focus.html"}, + accepts: ~w(html json) + ] # Configures Elixir's Logger config :logger, :console, diff --git a/config/dev.exs b/config/dev.exs index 7c77914a6..77acf097a 100644 --- a/config/dev.exs +++ b/config/dev.exs @@ -1,10 +1,6 @@ import Config config :plausible, PlausibleWeb.Endpoint, - render_errors: [ - view: PlausibleWeb.ErrorView, - accepts: ~w(html json) - ], server: true, debug_errors: true, code_reloader: true, diff --git a/lib/plausible/application.ex b/lib/plausible/application.ex index 4e2a9aed0..24e85432c 100644 --- a/lib/plausible/application.ex +++ b/lib/plausible/application.ex @@ -60,7 +60,7 @@ defmodule Plausible.Application do end defp maybe_add_sentry_pool(pool_config) do - case Application.get_env(:sentry, :dsn) do + case Sentry.Config.dsn() do dsn when is_binary(dsn) -> Map.put(pool_config, dsn, size: 50) diff --git a/lib/plausible_web/controllers/error_report_controller.ex b/lib/plausible_web/controllers/error_report_controller.ex new file mode 100644 index 000000000..7d48f1a57 --- /dev/null +++ b/lib/plausible_web/controllers/error_report_controller.ex @@ -0,0 +1,26 @@ +defmodule PlausibleWeb.ErrorReportController do + use PlausibleWeb, :controller + + plug PlausibleWeb.RequireAccountPlug + + def submit_error_report(conn, %{ + "error" => %{"trace_id" => trace_id, "user_feedback" => feedback} + }) do + reported_by = "#{conn.assigns.current_user.name} <#{conn.assigns.current_user.email}>" + email_template = PlausibleWeb.Email.error_report(reported_by, trace_id, feedback) + + Plausible.Mailer.deliver_later(email_template) + + thanks(conn) + end + + def submit_error_report(conn, _params) do + thanks(conn) + end + + defp thanks(conn) do + conn + |> put_view(PlausibleWeb.ErrorView) + |> render("server_error_report_thanks.html", layout: {PlausibleWeb.LayoutView, "focus.html"}) + end +end diff --git a/lib/plausible_web/email.ex b/lib/plausible_web/email.ex index 5387f8408..f222500ec 100644 --- a/lib/plausible_web/email.ex +++ b/lib/plausible_web/email.ex @@ -320,6 +320,21 @@ defmodule PlausibleWeb.Email do }) end + def error_report(reported_by, trace_id, feedback) do + Map.new() + |> Map.put(:layout, nil) + |> base_email() + |> to("bugs@plausible.io") + |> put_param("ReplyTo", reported_by) + |> tag("sentry") + |> subject("Feedback to Sentry Trace #{trace_id}") + |> render("error_report_email.html", %{ + reported_by: reported_by, + feedback: feedback, + trace_id: trace_id + }) + end + def base_email(), do: base_email(%{layout: "base_email.html"}) def base_email(%{layout: layout}) do @@ -334,7 +349,6 @@ defmodule PlausibleWeb.Email do defp maybe_put_layout(email, nil), do: email defp maybe_put_layout(email, layout) do - email - |> put_html_layout({PlausibleWeb.LayoutView, layout}) + put_html_layout(email, {PlausibleWeb.LayoutView, layout}) end end diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex index 04b750f07..fa9839e86 100644 --- a/lib/plausible_web/router.ex +++ b/lib/plausible_web/router.ex @@ -139,6 +139,7 @@ defmodule PlausibleWeb.Router do post "/password/request-reset", AuthController, :password_reset_request get "/password/reset", AuthController, :password_reset_form post "/password/reset", AuthController, :password_reset + post "/error_report", ErrorReportController, :submit_error_report end scope "/", PlausibleWeb do diff --git a/lib/plausible_web/templates/email/error_report_email.html.eex b/lib/plausible_web/templates/email/error_report_email.html.eex new file mode 100644 index 000000000..2a32b79dd --- /dev/null +++ b/lib/plausible_web/templates/email/error_report_email.html.eex @@ -0,0 +1,12 @@ +

Error report

+

+Reported by: <%= @reported_by %> +
+Sentry trace: <%= @trace_id %> +
+

+

User feedback:

+
+<%= @feedback %>
+
+
diff --git a/lib/plausible_web/templates/error/server_error.html.eex b/lib/plausible_web/templates/error/server_error.html.eex new file mode 100644 index 000000000..e8670e13a --- /dev/null +++ b/lib/plausible_web/templates/error/server_error.html.eex @@ -0,0 +1,56 @@ +
+
+

Oops, sorry about that...

+ +
+
+
+ +
+
+

+ There has been a server error. + <%= if !assigns[:selfhosted?] do %> + But don't worry, we're on it! + <% end %> +

+ +
+

+ <%= if assigns[:trace_id] && !assigns[:selfhosted?] do %> + If you would like to help, tell us what you were trying to do. Our development team will receive your report. + <% else %> + We have been notified. + <% end %> +

+
+
+
+
+ + <%= if !assigns[:selfhosted?] do %> + <%= if assigns[:trace_id] do %> +
+ <%= form_for :error, Routes.error_report_path(PlausibleWeb.Endpoint, :submit_error_report), fn f -> %> + <%= hidden_input f, :trace_id, value: @trace_id %> + <%= label f, "What happened?", class: "block text-sm font-medium text-gray-700 dark:text-gray-300" %> + <%= textarea f, :user_feedback, rows: 5, class: "block w-full max-w-xl border-gray-300 dark:border-gray-700 resize-none shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:bg-gray-900 dark:text-gray-300", placeholder: "I clicked on 'X' and then hit 'Confirm'..." %> + <%= submit "Send feedback →", class: "button mt-4 w-full" %> + <% end %> +
+ <% end %> + +
+

+ <%= link("Home page", to: "/", class: "text-indigo-500 mr-8") %> + <%= link("Status page", to: "https://status.plausible.io", class: "mr-8 text-indigo-500") %> + <%= link("Contact us", to: "https://plausible.io/contact", class: "text-indigo-500") %> +

+
+ <% end %> + + +
+
diff --git a/lib/plausible_web/templates/error/server_error_report_thanks.html.eex b/lib/plausible_web/templates/error/server_error_report_thanks.html.eex new file mode 100644 index 000000000..f4f3ac371 --- /dev/null +++ b/lib/plausible_web/templates/error/server_error_report_thanks.html.eex @@ -0,0 +1,20 @@ +
+
+

Thank you!

+ +
+
+

+ Your report has been submitted. +

+
+
+
+

+ <%= link("Home page", to: "/", class: "text-indigo-500 mr-8") %> + <%= link("Status page", to: "https://status.plausible.io", class: "mr-8 text-indigo-500") %> + <%= link("Contact us", to: "https://plausible.io/contact", class: "text-indigo-500") %> +

+
+
+
diff --git a/lib/plausible_web/views/email_view.ex b/lib/plausible_web/views/email_view.ex index ccff31964..786efb537 100644 --- a/lib/plausible_web/views/email_view.ex +++ b/lib/plausible_web/views/email_view.ex @@ -18,4 +18,20 @@ defmodule PlausibleWeb.EmailView do def date_format(date) do Timex.format!(date, "{D} {Mshort} {YYYY}") end + + def sentry_link(trace_id, dsn \\ Sentry.Config.dsn()) do + search_query = URI.encode_query(%{query: trace_id}) + path = "/organizations/sentry/issues/" + + if is_binary(dsn) do + dsn + |> URI.parse() + |> Map.replace(:userinfo, nil) + |> Map.replace(:path, path) + |> Map.replace(:query, search_query) + |> URI.to_string() + else + "" + end + end end diff --git a/lib/plausible_web/views/error_view.ex b/lib/plausible_web/views/error_view.ex index a452439ad..c9b422c71 100644 --- a/lib/plausible_web/views/error_view.ex +++ b/lib/plausible_web/views/error_view.ex @@ -22,41 +22,25 @@ defmodule PlausibleWeb.ErrorView do ) end - def render("500.html", assigns) do - case Sentry.get_last_event_id_and_source() do - {event_id, :plug} when is_binary(event_id) -> - current_user = assigns[:current_user] - - opts = - %{ - eventId: event_id, - user: %{ - name: current_user && current_user.name, - email: current_user && current_user.email - } - } - |> Jason.encode!() - - ~E""" - - - """ + def render(<<"5", _error_5xx::binary-size(2), ".html">>, assigns) do + current_user = assigns[:current_user] + selfhosted? = Plausible.Release.selfhost?() + last_event = Sentry.get_last_event_id_and_source() + + case {selfhosted?, current_user, last_event} do + {false, current_user, {event_id, :plug}} + when is_binary(event_id) and not is_nil(current_user) -> + opts = %{ + trace_id: event_id, + user_name: current_user.name, + user_email: current_user.email, + selfhosted?: selfhosted? + } + + render("server_error.html", Map.merge(opts, assigns)) _ -> - render( - "error.html", - Map.merge( - %{ - layout: false, - status: 500, - message: "Oops! Looks like we're having server issues" - }, - assigns - ) - ) + render("server_error.html", Map.put(assigns, :selfhosted?, selfhosted?)) end end diff --git a/test/plausible_web/controllers/error_report_controller_test.exs b/test/plausible_web/controllers/error_report_controller_test.exs new file mode 100644 index 000000000..fe269837f --- /dev/null +++ b/test/plausible_web/controllers/error_report_controller_test.exs @@ -0,0 +1,152 @@ +defmodule PlausibleWeb.ErrorReportControllerTest do + use PlausibleWeb.ConnCase, async: true + use Bamboo.Test + + import Phoenix.View + + alias PlausibleWeb.Endpoint + alias PlausibleWeb.ErrorView + alias PlausibleWeb.EmailView + + describe "building sentry links" do + test "no dsn configured" do + assert EmailView.sentry_link("some-trace") == "" + end + + test "with dsn" do + sample_dsn = "https://foobarbaz@somehost.example.com/1" + + assert EmailView.sentry_link("some-trace", sample_dsn) == + "https://somehost.example.com/organizations/sentry/issues/?query=some-trace" + end + end + + describe "Logged in" do + setup [:create_user, :log_in] + + for error <- ["500", "502", "503", "504"] do + test "renders the form when sentry metadata present: #{error}", %{user: user} do + Sentry.put_last_event_id_and_source("some-event-id", :plug) + action_path = Routes.error_report_path(Endpoint, :submit_error_report) + + assert html = + render_to_string(ErrorView, unquote(error) <> ".html", %{ + current_user: user + }) + + assert form_exists?(html, action_path) + assert submit_button(html, "form[action=\"#{action_path}\"]") + + assert element_exists?( + html, + "input[type=\"hidden\"][name=\"error[trace_id]\"][value=\"some-event-id\"]" + ) + end + end + + test "submitting the feedback form for authenticated user", %{conn: conn, user: user} do + action_path = Routes.error_report_path(Endpoint, :submit_error_report) + + conn = + post(conn, action_path, %{ + "error" => %{"trace_id" => "some-trace-id", "user_feedback" => "Guiz pls fix"} + }) + + assert html = html_response(conn, 200) + assert html =~ "Your report has been submitted" + + reply_to = "#{user.name} <#{user.email}>" + + assert_delivered_email_matches(%{ + to: [nil: "bugs@plausible.io"], + subject: "Feedback to Sentry Trace some-trace-id", + private: %{ + message_params: %{ + "ReplyTo" => ^reply_to + } + } + }) + end + + test "submitting no feedback for authenticated user", %{conn: conn} do + action_path = Routes.error_report_path(Endpoint, :submit_error_report) + + conn = + post(conn, action_path, %{ + "error" => %{"trace_id" => "some-trace-id"} + }) + + assert html = html_response(conn, 200) + assert html =~ "Your report has been submitted" + + refute_email_delivered_with(%{ + subject: "Feedback to Sentry Trace some-trace-id" + }) + end + + test "email renders properly" do + assert email = PlausibleWeb.Email.error_report("Alice Bob", "some-trace", "hello world") + + text = + email + |> Map.fetch!(:html_body) + |> Floki.parse_document!() + |> Floki.text() + + assert text =~ "Reported by: Alice Bob" + assert text =~ "Sentry trace: some-trace" + assert text =~ "User feedback:\nhello world" + end + end + + describe "Not logged in" do + test "submitting the feedback form for unauthenticated user", %{conn: conn} do + action_path = Routes.error_report_path(Endpoint, :submit_error_report) + + conn = + post(conn, action_path, %{ + "error" => %{"trace_id" => "some-trace-id", "user_feedback" => "Guiz pls fix"} + }) + + assert redirected_to(conn) == "/login" + end + + for error <- ["500", "502", "503", "504"] do + test "renders the error page, no form, when sentry metadata absent: #{error}", %{conn: conn} do + conn = + conn + |> bypass_through(PlausibleWeb.Router, [:browser]) + |> get("/") + + assert html = render_to_string(ErrorView, unquote(error) <> ".html", %{conn: conn}) + text = html |> Floki.parse_document!() |> Floki.text() + assert text =~ "There has been a server error" + assert text =~ "But don't worry, we're on it!" + + action_path = Routes.error_report_path(Endpoint, :submit_error_report) + refute form_exists?(html, action_path) + end + end + end + + defp form_exists?(html, action_path) do + element_exists?(html, "form[action=\"" <> action_path <> "\"]") + end + + defp element_exists?(html, selector) do + html + |> find(selector) + |> Enum.empty?() + |> Kernel.not() + end + + defp submit_button(html, form) do + find(html, "#{form} button[type=\"submit\"]") + end + + defp find(html, value) do + html + |> Floki.parse_document!() + |> Floki.find(value) + end +end