Skip to content

Commit

Permalink
fix(link-tracking): Fixed unsubscribe links when click tracking is en…
Browse files Browse the repository at this point in the history
…abled
  • Loading branch information
andris9 committed Aug 28, 2024
1 parent 93a7010 commit 34cdc38
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion lib/add-trackers.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const he = require('he');

const { rewriteTextNodes } = require('./rewrite-text-nodes');

const { getSignedFormDataSync, getServiceSecret } = require('./tools');
Expand Down Expand Up @@ -48,6 +50,27 @@ async function addClickTrackers(html, account, messageId, baseUrl) {
html = html.replace(/(<a[^>]* href\s*=[\s"']*)(http[^"'>\s]+)/gi, (match, prefix, url) => {
const redirectUrl = new URL('redirect', baseUrl);

try {
url = he.decode(url);
} catch (err) {
// ???
}

// check if we need to rewrite the URL
try {
let parsedUrl = new URL(url);
if (parsedUrl.origin === redirectUrl.origin) {
switch (parsedUrl.pathname) {
case '/unsubscribe':
case '/redirect':
// do not rewrite the URL
return match;
}
}
} catch (err) {
// ???
}

let { data, signature } = getSignedFormDataSync(
serviceSecret,
{
Expand All @@ -64,7 +87,12 @@ async function addClickTrackers(html, account, messageId, baseUrl) {
redirectUrl.searchParams.append('sig', signature);
}

return prefix + redirectUrl.href;
return (
prefix +
he.encode(redirectUrl.href, {
useNamedReferences: true
})
);
});

return html;
Expand Down

0 comments on commit 34cdc38

Please sign in to comment.