mirror of
https://github.com/dreamhunter2333/cloudflare_temp_email.git
synced 2026-09-08 17:08:59 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f40b99d877 |
@@ -21,6 +21,7 @@
|
|||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|
||||||
|
- fix: |邮箱鉴权| 修复旧邮箱凭证仍可访问 API、Telegram 越权解绑、重新绑定失效及外部发信保存凭证的问题
|
||||||
- fix: |Frontend| 修复 AdSense 脚本包含不受支持的 `data-onload` 和 `data-onerror` 属性
|
- fix: |Frontend| 修复 AdSense 脚本包含不受支持的 `data-onload` 和 `data-onerror` 属性
|
||||||
- fix: |Admin| 修复权限设置加载完成前短暂显示管理员密码输入框的问题
|
- fix: |Admin| 修复权限设置加载完成前短暂显示管理员密码输入框的问题
|
||||||
- fix: |Admin| 修复切换一级标签页时二级标签页偶发无选中项、内容不显示及指示条偏移的问题
|
- fix: |Admin| 修复切换一级标签页时二级标签页偶发无选中项、内容不显示及指示条偏移的问题
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|
||||||
|
- fix: |Mailbox Auth| Fix stale mailbox credentials retaining API access, unauthorized Telegram unbinding, ineffective rebinding and credential storage in external sent mail
|
||||||
- fix: |Frontend| Remove unsupported `data-onload` and `data-onerror` attributes from the AdSense script
|
- fix: |Frontend| Remove unsupported `data-onload` and `data-onerror` attributes from the AdSense script
|
||||||
- fix: |Admin| Avoid briefly showing the Admin password dialog before access settings finish loading
|
- fix: |Admin| Avoid briefly showing the Admin password dialog before access settings finish loading
|
||||||
- fix: |Admin| Fix secondary tabs occasionally losing their active item, hiding content, and leaving the indicator offset after switching primary tabs
|
- fix: |Admin| Fix secondary tabs occasionally losing their active item, hiding content, and leaving the indicator offset after switching primary tabs
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ USER_ROLES = [
|
|||||||
{ domains = [], role = "empty-role", prefix = "EMPTY" },
|
{ domains = [], role = "empty-role", prefix = "EMPTY" },
|
||||||
]
|
]
|
||||||
JWT_SECRET = "e2e-test-secret-key"
|
JWT_SECRET = "e2e-test-secret-key"
|
||||||
|
TELEGRAM_BOT_TOKEN = "e2e-telegram-test-token"
|
||||||
BLACK_LIST = ""
|
BLACK_LIST = ""
|
||||||
ENABLE_USER_CREATE_EMAIL = true
|
ENABLE_USER_CREATE_EMAIL = true
|
||||||
ENABLE_USER_DELETE_EMAIL = true
|
ENABLE_USER_DELETE_EMAIL = true
|
||||||
|
|||||||
@@ -170,7 +170,17 @@ for (const { base, disabled } of [
|
|||||||
const inbox = await list(request, '/admin/mails', { address: mailbox.address });
|
const inbox = await list(request, '/admin/mails', { address: mailbox.address });
|
||||||
const sent = await list(request, '/admin/sendbox', { address: mailbox.address });
|
const sent = await list(request, '/admin/sendbox', { address: mailbox.address });
|
||||||
const sender = await list(request, '/admin/address_sender', { address: mailbox.address });
|
const sender = await list(request, '/admin/address_sender', { address: mailbox.address });
|
||||||
const reply = await (await call(request, '/api/auto_reply', { headers: addressAuth(mailbox) })).json();
|
let replyMailbox = mailbox;
|
||||||
|
if (!address) {
|
||||||
|
await call(request, '/api/auto_reply', { headers: addressAuth(mailbox) }, 401);
|
||||||
|
// A new credential lets us check that no old auto-reply data survived cleanup.
|
||||||
|
const [name, domain] = mailbox.address.split('@');
|
||||||
|
replyMailbox = await (await call(request, '/admin/new_address', {
|
||||||
|
method: 'POST', data: { name, domain, enablePrefix: false },
|
||||||
|
})).json();
|
||||||
|
}
|
||||||
|
const reply = await (await call(request, '/api/auto_reply', { headers: addressAuth(replyMailbox) })).json();
|
||||||
|
if (!address) await call(request, `/admin/delete_address/${replyMailbox.address_id}`, { method: 'DELETE' });
|
||||||
const bound = await (await call(request, '/user_api/bind_address', { headers: userAuth(user) })).json();
|
const bound = await (await call(request, '/user_api/bind_address', { headers: userAuth(user) })).json();
|
||||||
return [Number(!!address), inbox.count, sent.count, sender.count, Number(!!reply.subject),
|
return [Number(!!address), inbox.count, sent.count, sender.count, Number(!!reply.subject),
|
||||||
bound.results.filter((row: { name: string }) => row.name === mailbox.address).length];
|
bound.results.filter((row: { name: string }) => row.name === mailbox.address).length];
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import { expect, test, type APIRequestContext } from '@playwright/test';
|
||||||
|
import { createHmac } from 'node:crypto';
|
||||||
|
|
||||||
|
import { WORKER_URL, TEST_DOMAIN, createTestAddress, deleteAddress, seedTestMail } from '../../fixtures/test-helpers';
|
||||||
|
|
||||||
|
function signToken(payload: Record<string, unknown>) {
|
||||||
|
const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
|
||||||
|
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
||||||
|
const signature = createHmac('sha256', 'e2e-test-secret-key')
|
||||||
|
.update(`${header}.${body}`).digest('base64url');
|
||||||
|
return `${header}.${body}.${signature}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectRejected(request: APIRequestContext, jwt: string) {
|
||||||
|
for (const [method, path] of [
|
||||||
|
['GET', '/api/settings'],
|
||||||
|
['GET', '/api/mails?limit=20&offset=0'],
|
||||||
|
['GET', '/api/mail/1'],
|
||||||
|
['GET', '/api/parsed_mails?limit=20&offset=0'],
|
||||||
|
['GET', '/api/parsed_mail/1'],
|
||||||
|
['GET', '/api/sendbox?limit=20&offset=0'],
|
||||||
|
['GET', '/api/auto_reply'],
|
||||||
|
['POST', '/api/webhook/settings'],
|
||||||
|
['POST', '/api/attachment/get_url'],
|
||||||
|
['POST', '/api/address_change_password'],
|
||||||
|
['POST', '/api/request_send_mail_access'],
|
||||||
|
['POST', '/api/send_mail'],
|
||||||
|
['PATCH', '/api/mails/1/read'],
|
||||||
|
['DELETE', '/api/mails/1'],
|
||||||
|
['DELETE', '/api/sendbox/1'],
|
||||||
|
['DELETE', '/api/clear_inbox'],
|
||||||
|
['DELETE', '/api/clear_sent_items'],
|
||||||
|
['DELETE', '/api/delete_address'],
|
||||||
|
]) {
|
||||||
|
const response = await request.fetch(`${WORKER_URL}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Authorization: `Bearer ${jwt}` },
|
||||||
|
...(method === 'POST' || method === 'PATCH' ? { data: {} } : {}),
|
||||||
|
});
|
||||||
|
expect(response.status(), `${method} ${path}`).toBe(401);
|
||||||
|
}
|
||||||
|
const login = await request.post(`${WORKER_URL}/open_api/credential_login`, {
|
||||||
|
data: { credential: jwt },
|
||||||
|
});
|
||||||
|
expect(login.status()).toBe(401);
|
||||||
|
const send = await request.post(`${WORKER_URL}/external/api/send_mail`, {
|
||||||
|
data: { token: jwt },
|
||||||
|
});
|
||||||
|
expect(send.status()).toBe(401);
|
||||||
|
const bind = await request.post(`${WORKER_URL}/user_api/bind_address`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${jwt}`,
|
||||||
|
'x-user-token': signToken({ user_id: 1, exp: Math.floor(Date.now() / 1000) + 60 }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(bind.status()).toBe(401);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('deleted credentials cannot access or delete a recreated mailbox', async ({ request }) => {
|
||||||
|
const name = `credential${Date.now()}`;
|
||||||
|
const create = async () => {
|
||||||
|
const response = await request.post(`${WORKER_URL}/api/new_address`, {
|
||||||
|
data: { name, domain: TEST_DOMAIN },
|
||||||
|
});
|
||||||
|
expect(response.ok()).toBe(true);
|
||||||
|
return await response.json();
|
||||||
|
};
|
||||||
|
const original = await create();
|
||||||
|
await deleteAddress(request, original.jwt);
|
||||||
|
await expectRejected(request, original.jwt);
|
||||||
|
|
||||||
|
const recreated = await create();
|
||||||
|
try {
|
||||||
|
expect(recreated.address).toBe(original.address);
|
||||||
|
expect(recreated.address_id).not.toBe(original.address_id);
|
||||||
|
await seedTestMail(request, recreated.address, { subject: 'New owner mail' });
|
||||||
|
await expectRejected(request, original.jwt);
|
||||||
|
const mails = await request.get(`${WORKER_URL}/api/mails?limit=20&offset=0`, {
|
||||||
|
headers: { Authorization: `Bearer ${recreated.jwt}` },
|
||||||
|
});
|
||||||
|
expect(mails.ok()).toBe(true);
|
||||||
|
expect((await mails.json()).count).toBe(1);
|
||||||
|
} finally {
|
||||||
|
await deleteAddress(request, recreated.jwt);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid numeric/string IDs work; missing, invalid and mismatched IDs are rejected', async ({ request }) => {
|
||||||
|
const mailbox = await createTestAddress(request, 'credential-id');
|
||||||
|
try {
|
||||||
|
for (const address_id of [mailbox.address_id, String(mailbox.address_id)]) {
|
||||||
|
const token = signToken({ address: mailbox.address, address_id });
|
||||||
|
const settings = await request.get(`${WORKER_URL}/api/settings`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
expect(settings.ok()).toBe(true);
|
||||||
|
const login = await request.post(`${WORKER_URL}/open_api/credential_login`, {
|
||||||
|
data: { credential: token },
|
||||||
|
});
|
||||||
|
expect(login.ok()).toBe(true);
|
||||||
|
}
|
||||||
|
for (const payload of [
|
||||||
|
{ address: mailbox.address },
|
||||||
|
...[0, -1, 1.5, true, null, '', '1e3', {}, Number.MAX_SAFE_INTEGER + 1]
|
||||||
|
.map(address_id => ({ address: mailbox.address, address_id })),
|
||||||
|
{ address: `other@${TEST_DOMAIN}`, address_id: mailbox.address_id },
|
||||||
|
{ address_id: mailbox.address_id },
|
||||||
|
]) {
|
||||||
|
const jwt = signToken(payload);
|
||||||
|
const response = await request.get(`${WORKER_URL}/api/mails?limit=20&offset=0`, {
|
||||||
|
headers: { Authorization: `Bearer ${jwt}` },
|
||||||
|
});
|
||||||
|
expect(response.status(), JSON.stringify(payload)).toBe(401);
|
||||||
|
const login = await request.post(`${WORKER_URL}/open_api/credential_login`, {
|
||||||
|
data: { credential: jwt },
|
||||||
|
});
|
||||||
|
expect(login.status(), JSON.stringify(payload)).toBe(401);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await deleteAddress(request, mailbox.jwt);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -51,4 +51,33 @@ test.describe('Send Mail via SMTP', () => {
|
|||||||
// Cleanup
|
// Cleanup
|
||||||
await deleteAddress(request, jwt);
|
await deleteAddress(request, jwt);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('external sending stores mail fields without bearer credentials', async ({ request }) => {
|
||||||
|
const { jwt, address } = await createTestAddress(request, 'external-sender');
|
||||||
|
const mail = {
|
||||||
|
from_name: 'External sender', to_name: 'Recipient', to_mail: 'recipient@test.example.com',
|
||||||
|
subject: `External ${Date.now()}`, content: 'External message', is_html: false,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const listener = onMailpitMessage(message => message.Subject === mail.subject);
|
||||||
|
await listener.ready;
|
||||||
|
const response = await request.post(`${WORKER_URL}/external/api/send_mail`, {
|
||||||
|
data: { ...mail, token: jwt, extra_credential: 'must-not-be-stored' },
|
||||||
|
});
|
||||||
|
expect(response.ok(), await response.text()).toBe(true);
|
||||||
|
expect((await listener.message).From.Address).toBe(address);
|
||||||
|
const sendbox = await request.get(`${WORKER_URL}/api/sendbox?limit=20&offset=0`, {
|
||||||
|
headers: { Authorization: `Bearer ${jwt}` },
|
||||||
|
});
|
||||||
|
expect(sendbox.ok()).toBe(true);
|
||||||
|
const { results } = await sendbox.json();
|
||||||
|
expect(results).toHaveLength(1);
|
||||||
|
const stored = JSON.parse(results[0].raw);
|
||||||
|
expect(stored).toMatchObject(mail);
|
||||||
|
expect(stored).not.toHaveProperty('token');
|
||||||
|
expect(stored).not.toHaveProperty('extra_credential');
|
||||||
|
} finally {
|
||||||
|
await deleteAddress(request, jwt);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { expect, test, type APIRequestContext } from '@playwright/test';
|
||||||
|
import { createHmac } from 'node:crypto';
|
||||||
|
|
||||||
|
import { WORKER_URL, createTestAddress } from '../../fixtures/test-helpers';
|
||||||
|
|
||||||
|
function initData(userId: number) {
|
||||||
|
const fields = {
|
||||||
|
auth_date: String(Math.floor(Date.now() / 1000)),
|
||||||
|
user: JSON.stringify({ id: userId }),
|
||||||
|
};
|
||||||
|
const key = createHmac('sha256', 'WebAppData').update('e2e-telegram-test-token').digest();
|
||||||
|
const hash = createHmac('sha256', key)
|
||||||
|
.update(Object.entries(fields).map(([name, value]) => `${name}=${value}`).join('\n'))
|
||||||
|
.digest('hex');
|
||||||
|
return new URLSearchParams({ ...fields, hash }).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bind(request: APIRequestContext, userId: number, jwt: string) {
|
||||||
|
const response = await request.post(`${WORKER_URL}/telegram/bind_address`, {
|
||||||
|
data: { initData: initData(userId), jwt },
|
||||||
|
});
|
||||||
|
expect(response.ok(), await response.text()).toBe(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function unbind(request: APIRequestContext, userId: number, address: string, status = 200) {
|
||||||
|
const response = await request.post(`${WORKER_URL}/telegram/unbind_address`, {
|
||||||
|
data: { initData: initData(userId), address },
|
||||||
|
});
|
||||||
|
expect(response.status(), await response.text()).toBe(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addressList(request: APIRequestContext, userId: number) {
|
||||||
|
const response = await request.post(`${WORKER_URL}/telegram/get_bind_address`, {
|
||||||
|
data: { initData: initData(userId) },
|
||||||
|
});
|
||||||
|
expect(response.ok(), await response.text()).toBe(true);
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Telegram users can remove their own bindings after another user binds the mailbox', async ({ request }) => {
|
||||||
|
const mailbox = await createTestAddress(request, 'tg-owner');
|
||||||
|
const owner = Date.now();
|
||||||
|
const other = owner + 1;
|
||||||
|
try {
|
||||||
|
await bind(request, owner, mailbox.jwt);
|
||||||
|
await unbind(request, other, mailbox.address, 400);
|
||||||
|
await unbind(request, owner, mailbox.address);
|
||||||
|
|
||||||
|
await bind(request, owner, mailbox.jwt);
|
||||||
|
await bind(request, other, mailbox.jwt);
|
||||||
|
await unbind(request, owner, mailbox.address);
|
||||||
|
expect(await addressList(request, owner)).toEqual([]);
|
||||||
|
expect(await addressList(request, other)).toEqual([{ address: mailbox.address, jwt: mailbox.jwt }]);
|
||||||
|
await unbind(request, other, mailbox.address);
|
||||||
|
expect(await addressList(request, other)).toEqual([]);
|
||||||
|
|
||||||
|
await bind(request, owner, mailbox.jwt);
|
||||||
|
await bind(request, other, mailbox.jwt);
|
||||||
|
await bind(request, owner, mailbox.jwt);
|
||||||
|
expect(await addressList(request, owner)).toEqual([{ address: mailbox.address, jwt: mailbox.jwt }]);
|
||||||
|
await unbind(request, other, mailbox.address);
|
||||||
|
await unbind(request, owner, mailbox.address);
|
||||||
|
expect(await addressList(request, owner)).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await request.delete(`${WORKER_URL}/api/delete_address`, {
|
||||||
|
headers: { Authorization: `Bearer ${mailbox.jwt}` },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stale Telegram credentials cannot unbind; internal mailbox cleanup still works', async ({ request }) => {
|
||||||
|
const original = await createTestAddress(request, 'tg-stale');
|
||||||
|
const owner = Date.now();
|
||||||
|
await bind(request, owner, original.jwt);
|
||||||
|
const deletion = await request.delete(`${WORKER_URL}/admin/delete_address/${original.address_id}`);
|
||||||
|
expect(deletion.ok()).toBe(true);
|
||||||
|
const [name, domain] = original.address.split('@');
|
||||||
|
const creation = await request.post(`${WORKER_URL}/admin/new_address`, {
|
||||||
|
data: { name, domain, enablePrefix: false },
|
||||||
|
});
|
||||||
|
expect(creation.ok()).toBe(true);
|
||||||
|
const recreated = await creation.json();
|
||||||
|
try {
|
||||||
|
expect(recreated.address_id).not.toBe(original.address_id);
|
||||||
|
await unbind(request, owner, recreated.address, 400);
|
||||||
|
const response = await request.delete(`${WORKER_URL}/api/delete_address`, {
|
||||||
|
headers: { Authorization: `Bearer ${recreated.jwt}` },
|
||||||
|
});
|
||||||
|
expect(response.ok(), await response.text()).toBe(true);
|
||||||
|
|
||||||
|
const listing = await request.post(`${WORKER_URL}/telegram/get_bind_address`, {
|
||||||
|
data: { initData: initData(owner) },
|
||||||
|
});
|
||||||
|
expect(listing.ok()).toBe(true);
|
||||||
|
expect(await listing.json()).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await request.delete(`${WORKER_URL}/admin/delete_address/${recreated.address_id}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { Context, Next } from 'hono';
|
||||||
|
import { jwt } from 'hono/jwt';
|
||||||
|
import { Jwt } from 'hono/utils/jwt';
|
||||||
|
|
||||||
|
import i18n from './i18n';
|
||||||
|
|
||||||
|
const validateAddressPayload = async (
|
||||||
|
c: Context<HonoCustomType>,
|
||||||
|
payload: Record<string, unknown>,
|
||||||
|
): Promise<JwtPayload | null> => {
|
||||||
|
const { address, address_id } = payload;
|
||||||
|
if (typeof address !== 'string' || !address) return null;
|
||||||
|
if (typeof address_id !== 'number'
|
||||||
|
&& (typeof address_id !== 'string' || !/^\d+$/.test(address_id))
|
||||||
|
) return null;
|
||||||
|
const addressId = Number(address_id);
|
||||||
|
if (!Number.isSafeInteger(addressId) || addressId <= 0) return null;
|
||||||
|
const exists = await c.env.DB.prepare(
|
||||||
|
`SELECT id FROM address WHERE id = ? AND name = ?`
|
||||||
|
).bind(addressId, address).first<number>('id');
|
||||||
|
return exists ? { address, address_id: addressId } : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const verifyAddressToken = async (
|
||||||
|
c: Context<HonoCustomType>,
|
||||||
|
token: string,
|
||||||
|
): Promise<JwtPayload> => {
|
||||||
|
const payload = await Jwt.verify(token, c.env.JWT_SECRET, 'HS256');
|
||||||
|
const addressPayload = await validateAddressPayload(c, payload);
|
||||||
|
if (!addressPayload) {
|
||||||
|
throw new Error(i18n.getMessagesbyContext(c).InvalidAddressCredentialMsg);
|
||||||
|
}
|
||||||
|
return addressPayload;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const addressJwtAuth = async (c: Context<HonoCustomType>, next: Next) => (
|
||||||
|
jwt({ secret: c.env.JWT_SECRET, alg: 'HS256' })(c, async () => {
|
||||||
|
const payload = await validateAddressPayload(c, c.get('jwtPayload'));
|
||||||
|
if (!payload) {
|
||||||
|
c.res = c.text(i18n.getMessagesbyContext(c).InvalidAddressCredentialMsg, 401);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
c.set('jwtPayload', payload);
|
||||||
|
await next();
|
||||||
|
})
|
||||||
|
);
|
||||||
@@ -62,32 +62,7 @@ const deleteMail = async (c: Context<HonoCustomType>) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getSettings = async (c: Context<HonoCustomType>) => {
|
const getSettings = async (c: Context<HonoCustomType>) => {
|
||||||
const { address, address_id } = c.get("jwtPayload")
|
const { address } = c.get("jwtPayload")
|
||||||
const msgs = i18n.getMessagesbyContext(c);
|
|
||||||
if (address_id && address_id > 0) {
|
|
||||||
try {
|
|
||||||
const db_address_id = await c.env.DB.prepare(
|
|
||||||
`SELECT id FROM address where id = ? `
|
|
||||||
).bind(address_id).first("id");
|
|
||||||
if (!db_address_id) {
|
|
||||||
return c.text(msgs.InvalidAddressMsg, 400)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
return c.text(msgs.InvalidAddressMsg, 400)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (!address_id) {
|
|
||||||
const db_address_id = await c.env.DB.prepare(
|
|
||||||
`SELECT id FROM address where name = ? `
|
|
||||||
).bind(address).first("id");
|
|
||||||
if (!db_address_id) {
|
|
||||||
return c.text(msgs.InvalidAddressMsg, 400)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
return c.text(msgs.InvalidAddressMsg, 400)
|
|
||||||
}
|
|
||||||
|
|
||||||
updateAddressUpdatedAt(c, address);
|
updateAddressUpdatedAt(c, address);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Context, Hono } from 'hono'
|
import { Context, Hono } from 'hono'
|
||||||
import { Jwt } from 'hono/utils/jwt'
|
import { verifyAddressToken } from '../address_auth';
|
||||||
import { createMimeMessage } from 'mimetext';
|
import { createMimeMessage } from 'mimetext';
|
||||||
import { Resend } from 'resend';
|
import { Resend } from 'resend';
|
||||||
import { WorkerMailer, WorkerMailerOptions } from 'worker-mailer';
|
import { WorkerMailer, WorkerMailerOptions } from 'worker-mailer';
|
||||||
@@ -261,15 +261,14 @@ api.post('/api/send_mail', async (c) => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
api.post('/external/api/send_mail', async (c) => {
|
api.post('/external/api/send_mail', async (c) => {
|
||||||
const msgs = i18n.getMessagesbyContext(c);
|
const reqJson = await c.req.json();
|
||||||
const { token } = await c.req.json();
|
const payload = await verifyAddressToken(c, reqJson?.token).catch(() => null);
|
||||||
|
if (!payload) {
|
||||||
|
return c.text(i18n.getMessagesbyContext(c).InvalidAddressCredentialMsg, 401);
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const { address } = await Jwt.verify(token, c.env.JWT_SECRET, "HS256");
|
const { from_name, to_mail, to_name, subject, content, is_html } = reqJson;
|
||||||
if (!address) {
|
await sendMail(c, payload.address, { from_name, to_mail, to_name, subject, content, is_html });
|
||||||
return c.text(msgs.AddressNotFoundMsg, 400)
|
|
||||||
}
|
|
||||||
const reqJson = await c.req.json();
|
|
||||||
await sendMail(c, address as string, reqJson);
|
|
||||||
return c.json({ status: "ok" })
|
return c.json({ status: "ok" })
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Failed to send mail", e);
|
console.error("Failed to send mail", e);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Hono } from 'hono'
|
import { Hono } from 'hono'
|
||||||
import { Jwt } from 'hono/utils/jwt'
|
import { verifyAddressToken } from '../address_auth';
|
||||||
|
|
||||||
import utils, { checkCfTurnstile, getPasswords, getAdminPasswords, hashPassword } from '../utils';
|
import utils, { checkCfTurnstile, getPasswords, getAdminPasswords, hashPassword } from '../utils';
|
||||||
import i18n from '../i18n';
|
import i18n from '../i18n';
|
||||||
@@ -56,10 +56,7 @@ api.post('/open_api/credential_login', async (c) => {
|
|||||||
return c.text(msgs.InvalidAddressCredentialMsg, 401)
|
return c.text(msgs.InvalidAddressCredentialMsg, 401)
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const payload = await Jwt.verify(credential, c.env.JWT_SECRET, "HS256");
|
await verifyAddressToken(c, credential);
|
||||||
if (!payload.address) {
|
|
||||||
return c.text(msgs.InvalidAddressCredentialMsg, 401)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return c.text(msgs.InvalidAddressCredentialMsg, 401)
|
return c.text(msgs.InvalidAddressCredentialMsg, 401)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { Context } from "hono";
|
import { Context } from "hono";
|
||||||
import { Jwt } from "hono/utils/jwt";
|
import { Jwt } from "hono/utils/jwt";
|
||||||
|
import { verifyAddressToken } from '../address_auth';
|
||||||
import { CONSTANTS } from "../constants";
|
import { CONSTANTS } from "../constants";
|
||||||
import { getBooleanValue, getIntValue, getJsonSetting } from "../utils";
|
import { getBooleanValue, getIntValue, getJsonSetting } from "../utils";
|
||||||
import { deleteAddressWithData, newAddress, generateRandomName } from "../common";
|
import { deleteAddressWithData, newAddress, generateRandomName } from "../common";
|
||||||
import { LocaleMessages } from "../i18n/type";
|
import { LocaleMessages } from "../i18n/type";
|
||||||
|
import i18n from '../i18n';
|
||||||
|
|
||||||
export const tgUserNewAddress = async (
|
export const tgUserNewAddress = async (
|
||||||
c: Context<HonoCustomType>, userId: string, address: string,
|
c: Context<HonoCustomType>, userId: string, address: string,
|
||||||
@@ -63,17 +65,9 @@ export const jwtListToAddressData = async (
|
|||||||
const invalidJwtList = [] as string[];
|
const invalidJwtList = [] as string[];
|
||||||
for (const jwt of jwtList) {
|
for (const jwt of jwtList) {
|
||||||
try {
|
try {
|
||||||
const { address, address_id } = await Jwt.verify(jwt, c.env.JWT_SECRET, "HS256");
|
const { address, address_id } = await verifyAddressToken(c, jwt);
|
||||||
const name = await c.env.DB.prepare(
|
addressList.push(address);
|
||||||
`SELECT name FROM address WHERE id = ? `
|
addressIdMap[address] = address_id;
|
||||||
).bind(address_id).first("name");
|
|
||||||
if (!name) {
|
|
||||||
addressList.push(msgs.TgInvalidAddressMsg);
|
|
||||||
invalidJwtList.push(jwt);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
addressList.push(address as string);
|
|
||||||
addressIdMap[address as string] = address_id as number;
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
addressList.push(msgs.TgInvalidCredentialMsg);
|
addressList.push(msgs.TgInvalidCredentialMsg);
|
||||||
invalidJwtList.push(jwt);
|
invalidJwtList.push(jwt);
|
||||||
@@ -87,13 +81,11 @@ export const bindTelegramAddress = async (
|
|||||||
c: Context<HonoCustomType>, userId: string, jwt: string,
|
c: Context<HonoCustomType>, userId: string, jwt: string,
|
||||||
msgs: LocaleMessages
|
msgs: LocaleMessages
|
||||||
): Promise<string> => {
|
): Promise<string> => {
|
||||||
const { address } = await Jwt.verify(jwt, c.env.JWT_SECRET, "HS256");
|
const { address } = await verifyAddressToken(c, jwt);
|
||||||
if (!address) {
|
|
||||||
throw Error(msgs.TgInvalidCredentialMsg);
|
|
||||||
}
|
|
||||||
const jwtList = await c.env.KV.get<string[]>(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, 'json') || [];
|
const jwtList = await c.env.KV.get<string[]>(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, 'json') || [];
|
||||||
const { addressIdMap } = await jwtListToAddressData(c, jwtList, msgs);
|
const { addressIdMap } = await jwtListToAddressData(c, jwtList, msgs);
|
||||||
if (address as string in addressIdMap) {
|
if (address as string in addressIdMap) {
|
||||||
|
await c.env.KV.put(`${CONSTANTS.TG_KV_PREFIX}:${address}`, userId.toString());
|
||||||
return address as string;
|
return address as string;
|
||||||
}
|
}
|
||||||
if (jwtList.length >= getIntValue(c.env.TG_MAX_ADDRESS, 5)) {
|
if (jwtList.length >= getIntValue(c.env.TG_MAX_ADDRESS, 5)) {
|
||||||
@@ -105,10 +97,9 @@ export const bindTelegramAddress = async (
|
|||||||
return address as string;
|
return address as string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const unbindTelegramAddress = async (
|
const removeTelegramBinding = async (
|
||||||
c: Context<HonoCustomType>, userId: string, address: string
|
c: Context<HonoCustomType>, userId: string, address: string, jwtList: string[]
|
||||||
): Promise<boolean> => {
|
): Promise<boolean> => {
|
||||||
const jwtList = await c.env.KV.get<string[]>(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, 'json') || [];
|
|
||||||
const newJwtList = [];
|
const newJwtList = [];
|
||||||
for (const jwt of jwtList) {
|
for (const jwt of jwtList) {
|
||||||
try {
|
try {
|
||||||
@@ -122,17 +113,29 @@ export const unbindTelegramAddress = async (
|
|||||||
newJwtList.push(jwt);
|
newJwtList.push(jwt);
|
||||||
}
|
}
|
||||||
await c.env.KV.put(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, JSON.stringify(newJwtList));
|
await c.env.KV.put(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, JSON.stringify(newJwtList));
|
||||||
await c.env.KV.delete(`${CONSTANTS.TG_KV_PREFIX}:${address}`);
|
const owner = await c.env.KV.get<string>(`${CONSTANTS.TG_KV_PREFIX}:${address}`);
|
||||||
|
if (owner === userId) await c.env.KV.delete(`${CONSTANTS.TG_KV_PREFIX}:${address}`);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const unbindTelegramAddress = async (
|
||||||
|
c: Context<HonoCustomType>, userId: string, address: string
|
||||||
|
): Promise<boolean> => {
|
||||||
|
const msgs = i18n.getMessagesbyContext(c);
|
||||||
|
const jwtList = await c.env.KV.get<string[]>(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, 'json') || [];
|
||||||
|
const { addressIdMap } = await jwtListToAddressData(c, jwtList, msgs);
|
||||||
|
if (!Object.hasOwn(addressIdMap, address)) throw Error(msgs.TgAddressNotYoursMsg);
|
||||||
|
return await removeTelegramBinding(c, userId, address, jwtList);
|
||||||
|
}
|
||||||
|
|
||||||
export const unbindTelegramByAddress = async (
|
export const unbindTelegramByAddress = async (
|
||||||
c: Context<HonoCustomType>, address: string
|
c: Context<HonoCustomType>, address: string
|
||||||
): Promise<boolean> => {
|
): Promise<boolean> => {
|
||||||
if (!c.env.KV) return true;
|
if (!c.env.KV) return true;
|
||||||
const userId = await c.env.KV.get<string>(`${CONSTANTS.TG_KV_PREFIX}:${address}`)
|
const userId = await c.env.KV.get<string>(`${CONSTANTS.TG_KV_PREFIX}:${address}`)
|
||||||
if (userId) {
|
if (userId) {
|
||||||
return await unbindTelegramAddress(c, userId, address);
|
const jwtList = await c.env.KV.get<string[]>(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, 'json') || [];
|
||||||
|
return await removeTelegramBinding(c, userId, address, jwtList);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Context } from "hono";
|
import { Context } from "hono";
|
||||||
import { Jwt } from 'hono/utils/jwt'
|
import { verifyAddressToken } from '../address_auth';
|
||||||
import { CONSTANTS } from "../constants";
|
import { CONSTANTS } from "../constants";
|
||||||
import { bindTelegramAddress, jwtListToAddressData, tgUserNewAddress, unbindTelegramAddress } from "./common";
|
import { bindTelegramAddress, jwtListToAddressData, tgUserNewAddress, unbindTelegramAddress } from "./common";
|
||||||
import { checkCfTurnstile, checkIsAdmin, getBooleanValue } from "../utils";
|
import { checkCfTurnstile, checkIsAdmin, getBooleanValue } from "../utils";
|
||||||
@@ -69,7 +69,7 @@ async function getTelegramBindAddress(c: Context<HonoCustomType>): Promise<Respo
|
|||||||
const res = [];
|
const res = [];
|
||||||
for (const jwt of jwtList) {
|
for (const jwt of jwtList) {
|
||||||
try {
|
try {
|
||||||
const { address } = await Jwt.verify(jwt, c.env.JWT_SECRET, "HS256");
|
const { address } = await verifyAddressToken(c, jwt);
|
||||||
res.push({ address, jwt });
|
res.push({ address, jwt });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(`failed to verify jwt with error: ${e}`)
|
console.error(`failed to verify jwt with error: ${e}`)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Context, Hono } from 'hono'
|
import { Context, Hono } from 'hono'
|
||||||
import { cors } from 'hono/cors';
|
import { cors } from 'hono/cors';
|
||||||
import { jwt } from 'hono/jwt'
|
|
||||||
import { Jwt } from 'hono/utils/jwt'
|
import { Jwt } from 'hono/utils/jwt'
|
||||||
|
import { addressJwtAuth } from './address_auth';
|
||||||
|
|
||||||
import { api as commonApi } from './commom_api';
|
import { api as commonApi } from './commom_api';
|
||||||
import { api as openAuthApi } from './open_api/auth';
|
import { api as openAuthApi } from './open_api/auth';
|
||||||
@@ -171,7 +171,7 @@ app.use('/api/*', async (c, next) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await jwt({ secret: c.env.JWT_SECRET, alg: "HS256" })(c, next);
|
return await addressJwtAuth(c, next);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn(e);
|
console.warn(e);
|
||||||
const lang = c.get("lang") || c.env.DEFAULT_LANG;
|
const lang = c.get("lang") || c.env.DEFAULT_LANG;
|
||||||
@@ -221,7 +221,7 @@ app.use('/user_api/*', async (c, next) => {
|
|||||||
if (c.req.path.startsWith('/user_api/bind_address')
|
if (c.req.path.startsWith('/user_api/bind_address')
|
||||||
&& c.req.method === 'POST'
|
&& c.req.method === 'POST'
|
||||||
) {
|
) {
|
||||||
return jwt({ secret: c.env.JWT_SECRET, alg: "HS256" })(c, next);
|
return addressJwtAuth(c, next);
|
||||||
}
|
}
|
||||||
await next();
|
await next();
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user