Repository navigation
Expand file tree
/
Copy pathtempmail.mjs
More file actions
52 lines (44 loc) · 1.97 KB
/
Copy pathtempmail.mjs
File metadata and controls
52 lines (44 loc) · 1.97 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
const BASE = "https://api.mail.tm";
export async function createTempEmail() {
const res = await fetch(BASE + "/domains", { headers: { accept: "application/ld+json" } });
if (!res.ok) throw new Error("Failed to fetch mail.tm domains");
const data = await res.json();
const member = Array.isArray(data["hydra:member"]) ? data["hydra:member"] : [];
const domain = member[0]?.domain;
if (!domain) throw new Error("No mail.tm domain available");
const address = `user${Date.now() % 1000000}@${domain}`;
const password = "Temp_" + Math.random().toString(36).slice(2, 10);
const createRes = await fetch(BASE + "/accounts", {
method: "POST",
headers: { "content-type": "application/json", accept: "application/ld+json" },
body: JSON.stringify({ address, password }),
});
if (!createRes.ok) throw new Error("Failed to create temp account");
const tokenRes = await fetch(BASE + "/token", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ address, password }),
});
if (!tokenRes.ok) throw new Error("Failed to authorize temp account");
const { token } = await tokenRes.json();
return { address, password, token, provider: { name: "mail.tm", domain } };
}
export async function waitForOTP(token, provider, timeoutMs = 90000, intervalMs = 3000) {
const deadline = Date.now() + timeoutMs;
const headers = { authorization: `Bearer ${token}`, accept: "application/ld+json" };
while (Date.now() < deadline) {
const res = await fetch(BASE + "/messages", { headers });
if (res.ok) {
const data = await res.json();
const member = Array.isArray(data["hydra:member"]) ? data["hydra:member"] : [];
const msg = member[0];
if (msg) {
const body = msg.text || msg.html || "";
const match = body.match(/\b(\d{6})\b/);
if (match) return match[1];
}
}
await new Promise((r) => setTimeout(r, intervalMs));
}
throw new Error("OTP timeout waiting for email");
}