Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 66 additions & 32 deletions src/lib/mail-tm.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import axios from 'axios';
import crypto from 'crypto';
import { isIP } from 'node:net';
import tls from 'node:tls';

import { MessageObjProps } from '@/components/temp-email/types/types';

const MAIL_TM_API = 'https://api.mail.tm';

const mailTm = axios.create({
baseURL: MAIL_TM_API,
headers: { accept: 'application/json' },
timeout: 15000,
});
const MAIL_TM_HOST = 'api.mail.tm';
const REQUEST_TIMEOUT_MS = 15000;

interface MailTmAddress {
address: string;
Expand All @@ -28,9 +23,64 @@ interface MailTmMessage {
html?: string[];
}

const randomHash = (bytes: number) => crypto.randomBytes(bytes).toString('hex');
interface RequestOptions {
body?: unknown;
jwt?: string;
clientIp?: string;
}

const send = (payload: string) =>
new Promise<{ status: number; body: string }>((resolve, reject) => {
const socket = tls.connect({ host: MAIL_TM_HOST, port: 443, servername: MAIL_TM_HOST }, () =>
socket.write(payload),
);
let raw = '';

socket.setEncoding('utf8');
socket.setTimeout(REQUEST_TIMEOUT_MS, () => socket.destroy(new Error('mail.tm request timed out')));
socket.on('data', (chunk: string) => (raw += chunk));
socket.on('error', reject);
socket.on('end', () => {
const headersEnd = raw.indexOf('\r\n\r\n');

const forwardClientIp = (clientIp?: string) => (clientIp && isIP(clientIp) ? { 'x-forwarded-for': clientIp } : {});
if (headersEnd < 0) return reject(new Error('mail.tm sent a malformed response'));

resolve({ status: Number(raw.slice(9, 12)), body: raw.slice(headersEnd + 4) });
});
});

const request = async <T>(method: string, url: string, options: RequestOptions = {}): Promise<T> => {
const payload = options.body === undefined ? '' : JSON.stringify(options.body);
const headers = [
`${method} ${url} HTTP/1.0`,
`Host: ${MAIL_TM_HOST}`,
'Accept: application/json',
'Connection: close',
];

if (options.jwt) headers.push(`Authorization: Bearer ${options.jwt}`);
if (payload) headers.push('Content-Type: application/json', `Content-Length: ${Buffer.byteLength(payload)}`);
if (options.clientIp && isIP(options.clientIp)) headers.push(`X-Forwarded-For: ${options.clientIp}`);

const { status, body } = await send(`${headers.join('\r\n')}\r\n\r\n${payload}`);

if (status < 200 || status >= 300) {
throw Object.assign(new Error(`mail.tm responded ${status} for ${url}`), {
config: { url },
response: { status, data: body },
});
}

return body ? JSON.parse(body) : (undefined as T);
};

const getJwt = async (address: string, password: string, clientIp?: string): Promise<string> => {
const { token } = await request<{ token: string }>('POST', '/token', { body: { address, password }, clientIp });

return token;
};

const randomHash = (bytes: number) => crypto.randomBytes(bytes).toString('hex');

const toAddress = (to: MailTmAddress | MailTmAddress[]) => (Array.isArray(to) ? to[0]?.address : to?.address);

Expand All @@ -46,9 +96,7 @@ const toMessageObj = (message: MailTmMessage): MessageObjProps => ({
});

export const createAccount = async (clientIp?: string): Promise<{ address: string; token: string }> => {
const headers = forwardClientIp(clientIp);

const { data: domains } = await mailTm.get<{ domain: string; isActive: boolean }[]>('/domains?page=1', { headers });
const domains = await request<{ domain: string; isActive: boolean }[]>('GET', '/domains?page=1', { clientIp });

const domain = domains.find((item) => item.isActive)?.domain;

Expand All @@ -57,29 +105,17 @@ export const createAccount = async (clientIp?: string): Promise<{ address: strin
const address = `${randomHash(6)}@${domain}`;
const password = randomHash(12);

await mailTm.post('/accounts', { address, password }, { headers });
await request('POST', '/accounts', { body: { address, password }, clientIp });

return { address, token: password };
};

const getJwt = async (address: string, password: string, clientIp?: string): Promise<string> => {
const { data } = await mailTm.post<{ token: string }>(
'/token',
{ address, password },
{ headers: forwardClientIp(clientIp) },
);

return data.token;
};

export const getInbox = async (address: string, password: string, clientIp?: string): Promise<MessageObjProps[]> => {
const jwt = await getJwt(address, password, clientIp);

const { data } = await mailTm.get<MailTmMessage[]>('/messages?page=1', {
headers: { ...forwardClientIp(clientIp), authorization: `Bearer ${jwt}` },
});
const messages = await request<MailTmMessage[]>('GET', '/messages?page=1', { jwt, clientIp });

return data.map(toMessageObj);
return messages.map(toMessageObj);
};

export const getMessage = async (
Expand All @@ -90,9 +126,7 @@ export const getMessage = async (
): Promise<MessageObjProps> => {
const jwt = await getJwt(address, password, clientIp);

const { data } = await mailTm.get<MailTmMessage>(`/messages/${encodeURIComponent(messageId)}`, {
headers: { ...forwardClientIp(clientIp), authorization: `Bearer ${jwt}` },
});
const message = await request<MailTmMessage>('GET', `/messages/${encodeURIComponent(messageId)}`, { jwt, clientIp });

return toMessageObj(data);
return toMessageObj(message);
};
Loading