Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
305 lines (255 loc) · 8.71 KB
/
Copy pathbackground.js
File metadata and controls
305 lines (255 loc) · 8.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/**
* SimpleLogin Forward - Background Script
*
* Listens for compose send events and replaces recipients with
* SimpleLogin reverse aliases.
*/
// Persistent listener for onBeforeSend
// This will wake up the extension when a message is about to be sent
browser.compose.onBeforeSend.addListener(async (tab, details) => {
console.log("[SimpleLogin Forward] onBeforeSend triggered");
try {
// 1. Get configuration
const config = await browser.storage.local.get({
apiKey: "",
apiBaseUrl: "https://app.simplelogin.io",
mailboxId: null,
enabled: true,
hostname: null
});
// Check if enabled and API key is configured
if (!config.enabled) {
console.log("[SimpleLogin Forward] Extension is disabled");
return;
}
if (!config.apiKey) {
console.log("[SimpleLogin Forward] API key not configured");
return;
}
// 2. Get the SimpleLogin alias from Reply-To (or From as fallback)
let aliasEmail = null;
// First check Reply-To (set by our alias selector)
if (details.replyTo && details.replyTo.length > 0) {
// replyTo can be a string or an array
const replyTo = Array.isArray(details.replyTo) ? details.replyTo[0] : details.replyTo;
aliasEmail = extractEmailFromIdentity(replyTo);
console.log("[SimpleLogin Forward] Reply-To alias:", aliasEmail);
}
// Fallback to From if no Reply-To (for backward compatibility)
if (!aliasEmail) {
aliasEmail = extractEmailFromIdentity(details.from);
console.log("[SimpleLogin Forward] From alias:", aliasEmail);
}
if (!aliasEmail) {
console.log("[SimpleLogin Forward] No alias found, skipping");
return;
}
// 3. Check if this is a SimpleLogin alias
const aliasId = await SimpleLoginAPI.getAliasId(aliasEmail);
if (!aliasId) {
console.log("[SimpleLogin Forward] Not a SimpleLogin alias, skipping");
return;
}
console.log("[SimpleLogin Forward] Alias ID:", aliasId);
// 4. Collect all recipients (to/cc/bcc)
const recipients = [
...(details.to || []),
...(details.cc || []),
...(details.bcc || [])
];
console.log("[SimpleLogin Forward] Recipients:", recipients);
// 5. For each recipient, get or create reverse alias
const reverseAliasMap = new Map();
for (const recipient of recipients) {
// Recipient can be a string "email@domain.com"
// or an object { email: "email@domain.com", name: "Name" }
const email = typeof recipient === "string"
? recipient
: (recipient.email || "");
if (!email) continue;
const normalizedEmail = email.toLowerCase().trim();
// Skip if this looks like a reverse alias already
if (isReverseAlias(normalizedEmail, config.hostname || config.apiBaseUrl)) {
console.log("[SimpleLogin Forward] Skipping reverse alias:", normalizedEmail);
reverseAliasMap.set(normalizedEmail, normalizedEmail);
continue;
}
try {
const reverseAlias = await SimpleLoginAPI.getOrCreateContact(aliasId, normalizedEmail);
if (reverseAlias) {
reverseAliasMap.set(normalizedEmail, reverseAlias);
console.log("[SimpleLogin Forward] Mapped", normalizedEmail, "->", reverseAlias);
} else {
// Keep original if we couldn't get a reverse alias
reverseAliasMap.set(normalizedEmail, normalizedEmail);
}
} catch (error) {
console.error("[SimpleLogin Forward] Error getting reverse alias for", normalizedEmail, ":", error);
// Keep original on error
reverseAliasMap.set(normalizedEmail, normalizedEmail);
}
}
// 6. Replace recipients with reverse aliases
const replaceWithReverseAlias = (recipientList) => {
if (!recipientList || recipientList.length === 0) return null;
return recipientList.map(r => {
const email = typeof r === "string" ? r : (r.email || "");
const reverseAlias = reverseAliasMap.get(email.toLowerCase().trim());
if (!reverseAlias || reverseAlias === email) {
return r; // No change
}
// Return in the same format as input
if (typeof r === "string") {
return reverseAlias;
} else {
// Preserve name if present
return {
email: reverseAlias,
name: r.name || ""
};
}
});
};
const newDetails = {
to: replaceWithReverseAlias(details.to),
cc: replaceWithReverseAlias(details.cc),
bcc: replaceWithReverseAlias(details.bcc)
};
console.log("[SimpleLogin Forward] New recipients:", newDetails);
// 7. Apply changes
await browser.compose.setComposeDetails(tab.id, newDetails);
console.log("[SimpleLogin Forward] Successfully replaced recipients with reverse aliases");
} catch (error) {
console.error("[SimpleLogin Forward] Error in onBeforeSend:", error);
}
});
/**
* Extract email address from identity object or string
*/
function extractEmailFromIdentity(from) {
if (!from) return null;
if (typeof from === "string") {
return from;
}
// from can be { id: string, name: string, email: string } or { identityId: string }
if (from.email) {
return from.email;
}
if (from.id) {
return from.id;
}
return null;
}
/**
* Check if an email looks like a SimpleLogin reverse alias
*/
function isReverseAlias(email, apiBaseUrl) {
if (!email) return false;
// Default to app.simplelogin.io if not specified
const defaultDomains = [
"simplelogin.com",
"slmail.me",
"simplelogin.co"
];
// Extract domain from email
const emailDomain = email.split("@")[1];
if (!emailDomain) return false;
// Check against default domains
for (const domain of defaultDomains) {
if (emailDomain === domain || emailDomain.endsWith("." + domain)) {
// Check for reverse-alias pattern (starts with "reply-" or "reverse-alias")
const localPart = email.split("@")[0];
if (localPart.startsWith("reply-") || localPart.startsWith("ra-")) {
return true;
}
}
}
// Check for custom domain based on apiBaseUrl
if (apiBaseUrl) {
try {
const url = new URL(apiBaseUrl);
const hostname = url.hostname;
// Remove "app." prefix if present
const baseDomain = hostname.replace(/^app\./, "");
if (emailDomain === baseDomain || emailDomain.endsWith("." + baseDomain)) {
const localPart = email.split("@")[0];
if (localPart.startsWith("reply-") || localPart.startsWith("ra-")) {
return true;
}
}
} catch (e) {
// Invalid URL, ignore
}
}
return false;
}
/**
* Handle compose action button click
* Open options page
*/
browser.composeAction.onClicked.addListener(async (tab) => {
await browser.runtime.openOptionsPage();
});
/**
* Handle installation
*/
browser.runtime.onInstalled.addListener(async (details) => {
if (details.reason === "install") {
console.log("[SimpleLogin Forward] Extension installed");
// Open options page on first install
await browser.runtime.openOptionsPage();
} else if (details.reason === "update") {
console.log("[SimpleLogin Forward] Extension updated to version:", browser.runtime.getManifest().version);
}
});
/**
* Handle messages from options page
*/
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "clearCache") {
SimpleLoginAPI.clearCache();
sendResponse({ success: true });
} else if (message.action === "testConnection") {
testConnection(message.config)
.then(result => sendResponse({ success: true, result }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true; // Async response
}
return false;
});
/**
* Test connection to SimpleLogin API
*/
async function testConnection(config) {
try {
// Clear cache to force fresh data
SimpleLoginAPI.clearCache();
// Update storage with test config temporarily
const oldConfig = await browser.storage.local.get({
apiKey: "",
apiBaseUrl: "https://app.simplelogin.io",
mailboxId: null
});
await browser.storage.local.set({
apiKey: config.apiKey,
apiBaseUrl: config.apiBaseUrl || oldConfig.apiBaseUrl,
mailboxId: config.mailboxId || oldConfig.mailboxId
});
// Try to fetch aliases
const aliases = await SimpleLoginAPI.getAliases();
// Restore old config
await browser.storage.local.set(oldConfig);
return {
success: true,
aliasCount: aliases.length
};
} catch (error) {
// Restore old config on error
await browser.storage.local.set({
apiKey: oldConfig.apiKey,
apiBaseUrl: oldConfig.apiBaseUrl,
mailboxId: oldConfig.mailboxId
});
throw error;
}
}