[fix] lib
This commit is contained in:
35 files changed
+21879
-1
No files matched your search
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
import type { MailGatewayApi } from './api.js';
|
||||
export interface MailGatewaySectionProps {
|
||||
api: MailGatewayApi;
|
||||
}
|
||||
export declare function MailGatewaySection({ api }: MailGatewaySectionProps): import("react").JSX.Element;
|
||||
@@ -0,0 +1,150 @@
|
||||
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
||||
import { useEffect, useState } from 'react';
|
||||
import { StatusCard } from './StatusCard.js';
|
||||
const table = {
|
||||
width: '100%',
|
||||
borderCollapse: 'collapse',
|
||||
fontSize: 13,
|
||||
};
|
||||
const cell = {
|
||||
borderBottom: '1px solid var(--dsh-border, #e5e7eb)',
|
||||
padding: '8px 10px',
|
||||
verticalAlign: 'middle',
|
||||
textAlign: 'left',
|
||||
};
|
||||
const input = {
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
padding: '6px 8px',
|
||||
border: '1px solid var(--dsh-border, #d1d5db)',
|
||||
borderRadius: 6,
|
||||
background: 'transparent',
|
||||
color: 'inherit',
|
||||
fontSize: 13,
|
||||
};
|
||||
const button = {
|
||||
padding: '6px 12px',
|
||||
border: '1px solid var(--dsh-border, #d1d5db)',
|
||||
borderRadius: 6,
|
||||
background: 'transparent',
|
||||
color: 'inherit',
|
||||
cursor: 'pointer',
|
||||
fontSize: 13,
|
||||
};
|
||||
const primary = {
|
||||
...button,
|
||||
borderColor: '#2563eb',
|
||||
background: '#2563eb',
|
||||
color: '#fff',
|
||||
};
|
||||
const muted = { color: '#6b7280', fontSize: 12 };
|
||||
const section = { display: 'grid', gap: 16, maxWidth: 760 };
|
||||
const row = { display: 'flex', gap: 8, alignItems: 'center' };
|
||||
export function MailGatewaySection({ api }) {
|
||||
const [snapshot, setSnapshot] = useState();
|
||||
const [mailbox, setMailbox] = useState();
|
||||
const [password, setPassword] = useState('');
|
||||
const [allowed, setAllowed] = useState([]);
|
||||
const [entry, setEntry] = useState('');
|
||||
const [test, setTest] = useState();
|
||||
const [busy, setBusy] = useState(null);
|
||||
const [notice, setNotice] = useState();
|
||||
const applySnapshot = (next, resetMailbox) => {
|
||||
setSnapshot(next);
|
||||
setAllowed([...next.allowedAddresses]);
|
||||
if (resetMailbox) {
|
||||
setMailbox({ ...next.mailbox });
|
||||
setPassword('');
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
void api.get().then(result => {
|
||||
if (!alive)
|
||||
return;
|
||||
if (result.ok)
|
||||
applySnapshot(result.value, true);
|
||||
else
|
||||
setNotice({ kind: 'error', text: result.error.message });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [api]);
|
||||
const setField = (key, value) => {
|
||||
setMailbox(current => (current ? { ...current, [key]: value } : current));
|
||||
};
|
||||
const patch = (source) => ({
|
||||
...source,
|
||||
password: password ? password : undefined,
|
||||
});
|
||||
const saveMailbox = async () => {
|
||||
if (!mailbox)
|
||||
return;
|
||||
setBusy('mailbox');
|
||||
setNotice(undefined);
|
||||
const result = await api.saveMailbox(patch(mailbox));
|
||||
setBusy(null);
|
||||
if (result.ok) {
|
||||
applySnapshot(result.value, true);
|
||||
setTest(undefined);
|
||||
setNotice({ kind: 'ok', text: '邮箱绑定已保存,连接已按新配置重建。' });
|
||||
}
|
||||
else {
|
||||
setNotice({ kind: 'error', text: result.error.message });
|
||||
}
|
||||
};
|
||||
const testConnection = async () => {
|
||||
if (!mailbox)
|
||||
return;
|
||||
setBusy('test');
|
||||
setNotice(undefined);
|
||||
const result = await api.testConnection(patch(mailbox));
|
||||
setBusy(null);
|
||||
if (result.ok) {
|
||||
setTest(result.value);
|
||||
}
|
||||
else {
|
||||
setNotice({ kind: 'error', text: result.error.message });
|
||||
}
|
||||
};
|
||||
const addAddress = () => {
|
||||
const address = entry.trim().toLowerCase();
|
||||
if (!address)
|
||||
return;
|
||||
setAllowed(current => (current.includes(address) ? current : [...current, address]));
|
||||
setEntry('');
|
||||
};
|
||||
const onEntryKey = (event) => {
|
||||
if (event.key !== 'Enter')
|
||||
return;
|
||||
event.preventDefault();
|
||||
addAddress();
|
||||
};
|
||||
const removeAddress = (address) => {
|
||||
setAllowed(current => current.filter(item => item !== address));
|
||||
};
|
||||
const saveWhitelist = async () => {
|
||||
setBusy('whitelist');
|
||||
setNotice(undefined);
|
||||
const result = await api.saveWhitelist(allowed);
|
||||
setBusy(null);
|
||||
if (result.ok) {
|
||||
applySnapshot(result.value, false);
|
||||
setNotice({ kind: 'ok', text: '白名单已保存,收信策略立即生效,连接保持不变。' });
|
||||
}
|
||||
else {
|
||||
setNotice({ kind: 'error', text: result.error.message });
|
||||
}
|
||||
};
|
||||
const numberField = (key) => (event) => {
|
||||
setField(key, Number(event.target.value) || 0);
|
||||
};
|
||||
const textField = (key) => (event) => {
|
||||
setField(key, event.target.value);
|
||||
};
|
||||
const boolField = (key) => (event) => {
|
||||
setField(key, event.target.checked);
|
||||
};
|
||||
return (_jsxs("div", { style: section, children: [_jsx(StatusCard, { status: snapshot?.status, allowedCount: allowed.length, test: test }), _jsxs("div", { children: [_jsx("h3", { style: { margin: '0 0 8px', fontSize: 15 }, children: "\u90AE\u7BB1\u7ED1\u5B9A" }), _jsxs("table", { style: table, children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { style: { ...cell, ...muted, width: 140 }, children: "\u5B57\u6BB5" }), _jsx("th", { style: { ...cell, ...muted }, children: "\u503C" }), _jsx("th", { style: { ...cell, ...muted, width: 240 }, children: "\u8BF4\u660E" })] }) }), _jsxs("tbody", { children: [_jsxs("tr", { children: [_jsx("td", { style: cell, children: "\u90AE\u7BB1\u5730\u5740" }), _jsx("td", { style: cell, children: _jsx("input", { style: input, value: mailbox?.email ?? '', onChange: textField('email') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "\u63A5\u6536\u90AE\u4EF6\u4E0E\u56DE\u4FE1\u4F7F\u7528\u7684\u5730\u5740\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "\u663E\u793A\u540D" }), _jsx("td", { style: cell, children: _jsx("input", { style: input, value: mailbox?.displayName ?? '', onChange: textField('displayName') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "\u56DE\u4FE1\u65F6\u7684\u53D1\u4EF6\u4EBA\u540D\u79F0\uFF0C\u53EF\u7559\u7A7A\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "IMAP \u4E3B\u673A" }), _jsx("td", { style: cell, children: _jsx("input", { style: input, value: mailbox?.imapHost ?? '', onChange: textField('imapHost') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "\u6807\u51C6 IMAP \u670D\u52A1\u5668\u5730\u5740\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "IMAP \u7AEF\u53E3" }), _jsx("td", { style: cell, children: _jsx("input", { style: input, value: mailbox?.imapPort ?? 993, onChange: numberField('imapPort') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "SSL \u4E00\u822C\u4E3A 993\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "IMAP TLS" }), _jsx("td", { style: cell, children: _jsx("input", { type: "checkbox", checked: mailbox?.imapSecure ?? true, onChange: boolField('imapSecure') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "\u52FE\u9009\u8868\u793A\u4F7F\u7528 SSL/TLS\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "SMTP \u4E3B\u673A" }), _jsx("td", { style: cell, children: _jsx("input", { style: input, value: mailbox?.smtpHost ?? '', onChange: textField('smtpHost') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "\u6807\u51C6 SMTP \u670D\u52A1\u5668\u5730\u5740\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "SMTP \u7AEF\u53E3" }), _jsx("td", { style: cell, children: _jsx("input", { style: input, value: mailbox?.smtpPort ?? 465, onChange: numberField('smtpPort') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "SSL \u4E00\u822C\u4E3A 465\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "SMTP TLS" }), _jsx("td", { style: cell, children: _jsx("input", { type: "checkbox", checked: mailbox?.smtpSecure ?? true, onChange: boolField('smtpSecure') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "\u52FE\u9009\u8868\u793A\u4F7F\u7528 SSL/TLS\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "\u767B\u5F55\u7528\u6237\u540D" }), _jsx("td", { style: cell, children: _jsx("input", { style: input, value: mailbox?.username ?? '', onChange: textField('username') }) }), _jsx("td", { style: { ...cell, ...muted }, children: "\u7559\u7A7A\u65F6\u4F7F\u7528\u90AE\u7BB1\u5730\u5740\u3002" })] }), _jsxs("tr", { children: [_jsx("td", { style: cell, children: "\u5BC6\u7801" }), _jsx("td", { style: cell, children: _jsx("input", { style: input, type: "password", value: password, placeholder: snapshot?.passwordSet ? '已设置,留空表示不修改' : '未设置', onChange: event => setPassword(event.target.value) }) }), _jsx("td", { style: { ...cell, ...muted }, children: "\u4FDD\u5B58\u540E\u53EA\u663E\u793A\u201C\u5DF2\u8BBE\u7F6E\u201D\uFF0C\u4E0D\u4F1A\u56DE\u663E\u660E\u6587\u3002" })] })] })] }), _jsxs("div", { style: { ...row, marginTop: 10 }, children: [_jsx("button", { style: primary, disabled: busy !== null, onClick: () => void saveMailbox(), children: busy === 'mailbox' ? '保存中…' : '保存邮箱绑定' }), _jsx("button", { style: button, disabled: busy !== null, onClick: () => void testConnection(), children: busy === 'test' ? '测试中…' : '测试连接' }), _jsx("span", { style: muted, children: "\u4FDD\u5B58\u90AE\u7BB1\u7ED1\u5B9A\u65F6\u4F1A\u6309\u65B0\u914D\u7F6E\u91CD\u5EFA\u8FDE\u63A5\u3002" })] })] }), _jsxs("div", { children: [_jsx("h3", { style: { margin: '0 0 8px', fontSize: 15 }, children: "\u767D\u540D\u5355" }), _jsxs("div", { style: { ...row, marginBottom: 8 }, children: [_jsx("input", { style: { ...input,Line truncated
|
||||
}
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import type { ConnectionTestResult, MailStatus } from '../types.js';
|
||||
export interface StatusCardProps {
|
||||
status?: MailStatus;
|
||||
allowedCount: number;
|
||||
test?: ConnectionTestResult;
|
||||
}
|
||||
/** 纯展示:状态由 MailGatewaySection 统一拉取,这里不发起任何请求。 */
|
||||
export declare function StatusCard({ status, allowedCount, test }: StatusCardProps): import("react").JSX.Element;
|
||||
@@ -0,0 +1,36 @@
|
||||
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
||||
const card = {
|
||||
border: '1px solid var(--dsh-border, #e5e7eb)',
|
||||
borderRadius: 8,
|
||||
padding: '12px 14px',
|
||||
display: 'grid',
|
||||
gap: 6,
|
||||
fontSize: 13,
|
||||
lineHeight: 1.6,
|
||||
};
|
||||
function summary(status) {
|
||||
switch (status?.phase) {
|
||||
case 'connecting':
|
||||
return { text: '正在连接…', color: '#6b7280' };
|
||||
case 'idle':
|
||||
return { text: '已连接,服务器支持 IDLE,新邮件会即时唤醒。', color: '#047857' };
|
||||
case 'polling':
|
||||
return {
|
||||
text: '已连接,服务器不支持 IDLE,自动改为轮询 60s,延迟最长约 1 分钟。',
|
||||
color: '#b45309',
|
||||
};
|
||||
case 'error':
|
||||
return { text: `连接失败:${status.lastError ?? '未知原因'}`, color: '#b91c1c' };
|
||||
default:
|
||||
return { text: '未启用:请先填写完整的邮箱绑定信息。', color: '#6b7280' };
|
||||
}
|
||||
}
|
||||
/** 纯展示:状态由 MailGatewaySection 统一拉取,这里不发起任何请求。 */
|
||||
export function StatusCard({ status, allowedCount, test }) {
|
||||
const state = summary(status);
|
||||
return (_jsxs("div", { style: card, children: [_jsx("div", { style: { color: state.color, fontWeight: 600 }, children: state.text }), status?.phase === 'idle' || status?.phase === 'polling' ? (_jsxs("div", { style: { color: '#6b7280' }, children: ["\u6536\u4FE1\u7B56\u7565\uFF1A", allowedCount > 0 ? `仅接收白名单内 ${allowedCount} 个地址的邮件。` : '白名单为空,不会接收任何邮件。', status.since ? ` 连接建立于 ${new Date(status.since).toLocaleString()}。` : ''] })) : null, allowedCount === 0 && status?.phase !== 'idle' && status?.phase !== 'polling' ? (_jsx("div", { style: { color: '#b45309' }, children: "\u767D\u540D\u5355\u4E3A\u7A7A\uFF1A\u4E0D\u4F1A\u63A5\u6536\u4EFB\u4F55\u90AE\u4EF6\u3002" })) : null, test ? (_jsx("div", { style: { color: test.ok ? '#047857' : '#b91c1c' }, children: test.ok
|
||||
? test.supportsIdle
|
||||
? '测试连接成功:服务器支持 IDLE。'
|
||||
: '测试连接成功:服务器不支持 IDLE,将使用轮询。'
|
||||
: `测试连接失败:${test.error ?? '未知原因'}` })) : null] }));
|
||||
}
|
||||
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol';
|
||||
import type { ConnectionTestResult, MailSnapshot, MailStatus, MailboxPatch } from '../types.js';
|
||||
/** 设置页使用的全部宿主能力;组件只依赖这个接口。 */
|
||||
export interface MailGatewayApi {
|
||||
get(): Promise<RemoteResult<MailSnapshot>>;
|
||||
saveMailbox(patch: MailboxPatch): Promise<RemoteResult<MailSnapshot>>;
|
||||
saveWhitelist(addresses: string[]): Promise<RemoteResult<MailSnapshot>>;
|
||||
testConnection(patch: MailboxPatch): Promise<RemoteResult<ConnectionTestResult>>;
|
||||
status(): Promise<RemoteResult<MailStatus>>;
|
||||
}
|
||||
export declare function createApi(ctx: Context): MailGatewayApi;
|
||||
@@ -0,0 +1,10 @@
|
||||
export function createApi(ctx) {
|
||||
const remote = ctx.remote['mail-gateway'];
|
||||
return {
|
||||
get: () => remote.get(),
|
||||
saveMailbox: patch => remote.saveMailbox(patch),
|
||||
saveWhitelist: addresses => remote.saveWhitelist(addresses),
|
||||
testConnection: patch => remote.testConnection(patch),
|
||||
status: () => remote.status(),
|
||||
};
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
export declare const name = "dsh-mail-sender";
|
||||
export declare const inject: string[];
|
||||
/** 挂载本插件的 Remote 命名空间,并在设置页注册“邮件网关”分区。 */
|
||||
export declare function apply(ctx: Context): Promise<() => Promise<void>>;
|
||||
+20287
File diff suppressed because it is too large.
Load diff
Vendored
+64
@@ -0,0 +1,64 @@
|
||||
import Schema from '@deepseek-ai/schemastery';
|
||||
import type { MailboxSettings } from './types.js';
|
||||
/** schemastery `.volatile()` 字段解析后的稳定引用。 */
|
||||
interface Ref<T> {
|
||||
get(): T;
|
||||
}
|
||||
export interface Config {
|
||||
mailbox: Ref<MailboxSettings>;
|
||||
allowedAddresses: Ref<string[]>;
|
||||
}
|
||||
export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
|
||||
mailbox: Schema<NoInfer<Schemastery.ObjectS<NoInfer<{
|
||||
email: Schema<string, string, "defined">;
|
||||
displayName: Schema<string, string, "defined">;
|
||||
imapHost: Schema<string, string, "defined">;
|
||||
imapPort: Schema<number, number, "defined">;
|
||||
imapSecure: Schema<boolean, boolean, "defined">;
|
||||
smtpHost: Schema<string, string, "defined">;
|
||||
smtpPort: Schema<number, number, "defined">;
|
||||
smtpSecure: Schema<boolean, boolean, "defined">;
|
||||
username: Schema<string, string, "defined">;
|
||||
password: Schema<string, string, "defined">;
|
||||
}>>>, NoInfer<Schemastery.ObjectT<NoInfer<{
|
||||
email: Schema<string, string, "defined">;
|
||||
displayName: Schema<string, string, "defined">;
|
||||
imapHost: Schema<string, string, "defined">;
|
||||
imapPort: Schema<number, number, "defined">;
|
||||
imapSecure: Schema<boolean, boolean, "defined">;
|
||||
smtpHost: Schema<string, string, "defined">;
|
||||
smtpPort: Schema<number, number, "defined">;
|
||||
smtpSecure: Schema<boolean, boolean, "defined">;
|
||||
username: Schema<string, string, "defined">;
|
||||
password: Schema<string, string, "defined">;
|
||||
}>>>, "volatile-defined">;
|
||||
allowedAddresses: Schema<NoInfer<string[]>, NoInfer<string[]>, "volatile-defined">;
|
||||
}>>, Schemastery.ObjectT<NoInfer<{
|
||||
mailbox: Schema<NoInfer<Schemastery.ObjectS<NoInfer<{
|
||||
email: Schema<string, string, "defined">;
|
||||
displayName: Schema<string, string, "defined">;
|
||||
imapHost: Schema<string, string, "defined">;
|
||||
imapPort: Schema<number, number, "defined">;
|
||||
imapSecure: Schema<boolean, boolean, "defined">;
|
||||
smtpHost: Schema<string, string, "defined">;
|
||||
smtpPort: Schema<number, number, "defined">;
|
||||
smtpSecure: Schema<boolean, boolean, "defined">;
|
||||
username: Schema<string, string, "defined">;
|
||||
password: Schema<string, string, "defined">;
|
||||
}>>>, NoInfer<Schemastery.ObjectT<NoInfer<{
|
||||
email: Schema<string, string, "defined">;
|
||||
displayName: Schema<string, string, "defined">;
|
||||
imapHost: Schema<string, string, "defined">;
|
||||
imapPort: Schema<number, number, "defined">;
|
||||
imapSecure: Schema<boolean, boolean, "defined">;
|
||||
smtpHost: Schema<string, string, "defined">;
|
||||
smtpPort: Schema<number, number, "defined">;
|
||||
smtpSecure: Schema<boolean, boolean, "defined">;
|
||||
username: Schema<string, string, "defined">;
|
||||
password: Schema<string, string, "defined">;
|
||||
}>>>, "volatile-defined">;
|
||||
allowedAddresses: Schema<NoInfer<string[]>, NoInfer<string[]>, "volatile-defined">;
|
||||
}>>, "plain">;
|
||||
export declare function mailboxOf(config: Config): MailboxSettings;
|
||||
export declare function addressesOf(config: Config): string[];
|
||||
export {};
|
||||
@@ -0,0 +1,41 @@
|
||||
import Schema from '@deepseek-ai/schemastery';
|
||||
import { createMailbox } from './mailbox.js';
|
||||
const DEFAULT_MAILBOX = {
|
||||
email: '',
|
||||
displayName: '',
|
||||
imapHost: '',
|
||||
imapPort: 993,
|
||||
imapSecure: true,
|
||||
smtpHost: '',
|
||||
smtpPort: 465,
|
||||
smtpSecure: true,
|
||||
username: '',
|
||||
password: '',
|
||||
};
|
||||
export const Config = Schema.object({
|
||||
mailbox: Schema.object({
|
||||
email: Schema.string().default('').description('接收邮件与回信使用的地址'),
|
||||
displayName: Schema.string().default('').description('回信时显示的发件人名称,可留空'),
|
||||
imapHost: Schema.string().default('').description('IMAP 服务器地址'),
|
||||
imapPort: Schema.natural().default(993).description('IMAP 端口,SSL 一般为 993'),
|
||||
imapSecure: Schema.boolean().default(true).description('IMAP 是否使用 TLS'),
|
||||
smtpHost: Schema.string().default('').description('SMTP 服务器地址'),
|
||||
smtpPort: Schema.natural().default(465).description('SMTP 端口,SSL 一般为 465'),
|
||||
smtpSecure: Schema.boolean().default(true).description('SMTP 是否使用 TLS'),
|
||||
username: Schema.string().default('').description('登录用户名,留空时使用邮箱地址'),
|
||||
password: Schema.string().role('secret').default('').description('邮箱密码或应用专用密码'),
|
||||
})
|
||||
.default(DEFAULT_MAILBOX)
|
||||
.volatile()
|
||||
.description('dsh-mail-sender 邮箱绑定'),
|
||||
allowedAddresses: Schema.array(Schema.string())
|
||||
.default([])
|
||||
.volatile()
|
||||
.description('双向白名单:同时校验入站发件地址与出站回复地址'),
|
||||
});
|
||||
export function mailboxOf(config) {
|
||||
return createMailbox(config.mailbox.get());
|
||||
}
|
||||
export function addressesOf(config) {
|
||||
return [...(config.allowedAddresses.get() ?? [])];
|
||||
}
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
export interface CursorRecord {
|
||||
/** IMAP UIDVALIDITY,变化表示邮箱被重建,需要重新建基线。 */
|
||||
uidValidity: string;
|
||||
/** 已处理到的最大 UID。 */
|
||||
uid: number;
|
||||
}
|
||||
/** UID 游标持久化;读写失败时退化为内存游标,不阻塞收信。 */
|
||||
export declare class CursorStore {
|
||||
private readonly file;
|
||||
private cache?;
|
||||
constructor(account: string);
|
||||
read(): Promise<CursorRecord | undefined>;
|
||||
write(record: CursorRecord): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
function cursorPath(account) {
|
||||
const digest = createHash('sha1').update(account).digest('hex').slice(0, 16);
|
||||
return join(homedir(), '.dsh', 'mail-gateway', `${digest}.json`);
|
||||
}
|
||||
/** UID 游标持久化;读写失败时退化为内存游标,不阻塞收信。 */
|
||||
export class CursorStore {
|
||||
file;
|
||||
cache;
|
||||
constructor(account) {
|
||||
this.file = cursorPath(account);
|
||||
}
|
||||
async read() {
|
||||
if (this.cache)
|
||||
return this.cache;
|
||||
try {
|
||||
const raw = await readFile(this.file, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed.uidValidity === 'string' && typeof parsed.uid === 'number') {
|
||||
this.cache = { uidValidity: parsed.uidValidity, uid: parsed.uid };
|
||||
return this.cache;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return undefined;
|
||||
}
|
||||
async write(record) {
|
||||
this.cache = record;
|
||||
try {
|
||||
await mkdir(dirname(this.file), { recursive: true });
|
||||
await writeFile(this.file, JSON.stringify(record), 'utf8');
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import type { MailJob } from './types.js';
|
||||
/**
|
||||
* 邮件会话适配层:ctx.agents / session/event 的全部调用都收在这里,
|
||||
* Agent API 变化时只需改这一个文件。
|
||||
*/
|
||||
export declare class MailDeliverer {
|
||||
private readonly ctx;
|
||||
private readonly onReply;
|
||||
private readonly onLog?;
|
||||
private readonly handles;
|
||||
private readonly turnBuffers;
|
||||
/** 每个会话按投递顺序排队,一轮回复对应队首的一封来信。 */
|
||||
private readonly pending;
|
||||
private readonly off;
|
||||
constructor(ctx: Context, onReply: (job: MailJob, text: string) => Promise<void>, onLog?: ((message: string) => void) | undefined);
|
||||
deliver(job: MailJob): Promise<void>;
|
||||
dispose(): void;
|
||||
private ensure;
|
||||
private handleEvent;
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
||||
/**
|
||||
* 邮件会话适配层:ctx.agents / session/event 的全部调用都收在这里,
|
||||
* Agent API 变化时只需改这一个文件。
|
||||
*/
|
||||
export class MailDeliverer {
|
||||
ctx;
|
||||
onReply;
|
||||
onLog;
|
||||
handles = new Map();
|
||||
turnBuffers = new Map();
|
||||
/** 每个会话按投递顺序排队,一轮回复对应队首的一封来信。 */
|
||||
pending = new Map();
|
||||
off;
|
||||
constructor(ctx, onReply, onLog) {
|
||||
this.ctx = ctx;
|
||||
this.onReply = onReply;
|
||||
this.onLog = onLog;
|
||||
this.off = ctx.on('session/event', (session, event) => {
|
||||
this.handleEvent(session, event);
|
||||
});
|
||||
}
|
||||
async deliver(job) {
|
||||
const handle = await this.ensure(job.sessionId);
|
||||
const queue = this.pending.get(job.sessionId) ?? [];
|
||||
queue.push(job);
|
||||
this.pending.set(job.sessionId, queue);
|
||||
handle.agent.followup(createUserMessage({
|
||||
content: [{ type: 'text', text: job.text }],
|
||||
source: { kind: 'user' },
|
||||
}));
|
||||
}
|
||||
dispose() {
|
||||
this.off();
|
||||
for (const handle of this.handles.values()) {
|
||||
if (handle.owned)
|
||||
void handle.dispose().catch(() => { });
|
||||
}
|
||||
this.handles.clear();
|
||||
this.turnBuffers.clear();
|
||||
this.pending.clear();
|
||||
}
|
||||
async ensure(sessionId) {
|
||||
const cached = this.handles.get(sessionId);
|
||||
if (cached)
|
||||
return cached;
|
||||
const id = sessionId;
|
||||
const live = this.ctx.agents.get(id);
|
||||
if (live) {
|
||||
const borrowed = {
|
||||
agent: live,
|
||||
owned: false,
|
||||
dispose: async () => { },
|
||||
};
|
||||
this.handles.set(sessionId, borrowed);
|
||||
return borrowed;
|
||||
}
|
||||
let handle;
|
||||
try {
|
||||
handle = await this.ctx.agents.resume({ resumeSessionId: id });
|
||||
}
|
||||
catch {
|
||||
handle = await this.ctx.agents.create({ sessionId: id });
|
||||
}
|
||||
const owned = {
|
||||
agent: handle.agent,
|
||||
owned: true,
|
||||
dispose: () => handle.dispose(),
|
||||
};
|
||||
this.handles.set(sessionId, owned);
|
||||
return owned;
|
||||
}
|
||||
handleEvent(session, event) {
|
||||
const sessionId = session.header.id;
|
||||
if (!sessionId.startsWith('mail:') || !this.handles.has(sessionId))
|
||||
return;
|
||||
if (event.type === 'assistant/message') {
|
||||
const text = event.data.message.content
|
||||
.filter(block => block.type === 'text')
|
||||
.map(block => (block.type === 'text' ? block.text : ''))
|
||||
.join('');
|
||||
if (!text)
|
||||
return;
|
||||
const key = `${sessionId}:${event.data.turn}`;
|
||||
this.turnBuffers.set(key, [...(this.turnBuffers.get(key) ?? []), text]);
|
||||
return;
|
||||
}
|
||||
if (event.type === 'turn/end') {
|
||||
const key = `${sessionId}:${event.data.turn}`;
|
||||
const text = (this.turnBuffers.get(key) ?? []).join('\n\n').trim();
|
||||
this.turnBuffers.delete(key);
|
||||
// 无论本轮成败都出队一封,保持“一封信对应一轮”的 FIFO 对齐。
|
||||
const queue = this.pending.get(sessionId);
|
||||
const job = queue?.shift();
|
||||
if (queue && queue.length === 0)
|
||||
this.pending.delete(sessionId);
|
||||
if (!job)
|
||||
return;
|
||||
if (event.data.reason.kind !== 'completed' || !text)
|
||||
return;
|
||||
void this.onReply(job, text).catch(error => {
|
||||
this.onLog?.(`[mail] 回信失败: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import type { MailSnapshot, MailboxSettings } from './types.js';
|
||||
/**
|
||||
* 常驻邮件的编排层:收信 → 串行队列 → 会话 → 回信。
|
||||
* 白名单保存只更新内存策略,邮箱绑定变化才重连。
|
||||
*/
|
||||
export declare class MailGateway {
|
||||
private readonly onLog;
|
||||
private receiver?;
|
||||
private sender?;
|
||||
private readonly deliverer;
|
||||
private readonly queue;
|
||||
private draining;
|
||||
private mailbox;
|
||||
private policy;
|
||||
private allowed;
|
||||
private accountKey;
|
||||
private generation;
|
||||
private status;
|
||||
constructor(ctx: Context, mailbox: MailboxSettings, allowed: readonly string[], onLog?: (message: string) => void);
|
||||
start(): () => Promise<void>;
|
||||
/** 只接受新的绑定与白名单;ctx 不参与重载。 */
|
||||
reload(mailbox: MailboxSettings, allowed: readonly string[]): void;
|
||||
updatePolicy(allowed: readonly string[]): void;
|
||||
snapshot(): MailSnapshot;
|
||||
private restart;
|
||||
private enqueue;
|
||||
/** 串行消费;单封失败只记录,不拖垮常驻循环。 */
|
||||
private drain;
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import { createPolicy } from './policy.js';
|
||||
import { ImapReceiver, POLL_INTERVAL_MS } from './receiver.js';
|
||||
import { CursorStore } from './cursor.js';
|
||||
import { MailDeliverer } from './deliver.js';
|
||||
import { SmtpSender } from './sender.js';
|
||||
import { isMailboxConfigured, mailboxKey, publicMailbox } from './mailbox.js';
|
||||
function errorMessage(error) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
/**
|
||||
* 常驻邮件的编排层:收信 → 串行队列 → 会话 → 回信。
|
||||
* 白名单保存只更新内存策略,邮箱绑定变化才重连。
|
||||
*/
|
||||
export class MailGateway {
|
||||
onLog;
|
||||
receiver;
|
||||
sender;
|
||||
deliverer;
|
||||
queue = [];
|
||||
draining = false;
|
||||
mailbox;
|
||||
policy;
|
||||
allowed;
|
||||
accountKey = '';
|
||||
generation = 0;
|
||||
status = {
|
||||
phase: 'disabled',
|
||||
supportsIdle: false,
|
||||
pollIntervalMs: POLL_INTERVAL_MS,
|
||||
};
|
||||
constructor(ctx, mailbox, allowed, onLog = message => console.warn(message)) {
|
||||
this.onLog = onLog;
|
||||
this.mailbox = mailbox;
|
||||
this.allowed = [...allowed];
|
||||
this.policy = createPolicy(allowed);
|
||||
this.deliverer = new MailDeliverer(ctx, async (job, text) => {
|
||||
if (!this.sender)
|
||||
throw new Error('SMTP 尚未配置');
|
||||
await this.sender.send(job, text);
|
||||
}, onLog);
|
||||
}
|
||||
start() {
|
||||
this.restart();
|
||||
return async () => {
|
||||
this.deliverer.dispose();
|
||||
await this.receiver?.stop();
|
||||
this.receiver = undefined;
|
||||
this.sender?.close();
|
||||
this.sender = undefined;
|
||||
};
|
||||
}
|
||||
/** 只接受新的绑定与白名单;ctx 不参与重载。 */
|
||||
reload(mailbox, allowed) {
|
||||
const nextKey = mailboxKey(mailbox);
|
||||
this.allowed = [...allowed];
|
||||
this.policy = createPolicy(allowed);
|
||||
if (nextKey !== this.accountKey) {
|
||||
this.mailbox = mailbox;
|
||||
this.restart();
|
||||
return;
|
||||
}
|
||||
this.mailbox = mailbox;
|
||||
this.sender?.update(mailbox);
|
||||
}
|
||||
updatePolicy(allowed) {
|
||||
this.allowed = [...allowed];
|
||||
this.policy = createPolicy(allowed);
|
||||
}
|
||||
snapshot() {
|
||||
return {
|
||||
mailbox: publicMailbox(this.mailbox),
|
||||
passwordSet: Boolean(this.mailbox.password),
|
||||
allowedAddresses: [...this.allowed],
|
||||
status: this.status,
|
||||
};
|
||||
}
|
||||
restart() {
|
||||
const generation = ++this.generation;
|
||||
void this.receiver?.stop();
|
||||
this.receiver = undefined;
|
||||
this.sender?.close();
|
||||
this.sender = undefined;
|
||||
if (!isMailboxConfigured(this.mailbox)) {
|
||||
this.accountKey = '';
|
||||
this.status = { phase: 'disabled', supportsIdle: false, pollIntervalMs: POLL_INTERVAL_MS };
|
||||
this.onLog('[mail] 未配置完整邮箱,收信入口保持关闭');
|
||||
return;
|
||||
}
|
||||
this.accountKey = mailboxKey(this.mailbox);
|
||||
this.sender = new SmtpSender(this.mailbox);
|
||||
this.receiver = new ImapReceiver(this.mailbox, () => this.policy, new CursorStore(`${this.mailbox.email}@${this.mailbox.imapHost}`), {
|
||||
onJob: job => this.enqueue(job),
|
||||
onStatus: status => {
|
||||
if (generation === this.generation)
|
||||
this.status = status;
|
||||
},
|
||||
onLog: this.onLog,
|
||||
});
|
||||
this.receiver.start();
|
||||
}
|
||||
enqueue(job) {
|
||||
this.queue.push(job);
|
||||
void this.drain();
|
||||
}
|
||||
/** 串行消费;单封失败只记录,不拖垮常驻循环。 */
|
||||
async drain() {
|
||||
if (this.draining)
|
||||
return;
|
||||
this.draining = true;
|
||||
try {
|
||||
while (this.queue.length) {
|
||||
const job = this.queue.shift();
|
||||
try {
|
||||
await this.deliverer.deliver(job);
|
||||
}
|
||||
catch (error) {
|
||||
this.onLog(`[mail] 投递 ${job.from} 失败: ${errorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
this.draining = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import { Config } from './config.js';
|
||||
export { Config } from './config.js';
|
||||
export declare const name = "dsh-mail-sender";
|
||||
export declare const inject: string[];
|
||||
/**
|
||||
* 常驻入口:邮件驱动会话,而不是等待模型调用的 Tool。
|
||||
* 所有 IMAP/SMTP 资源与监听都收在 ctx.effect 里按序回收。
|
||||
*/
|
||||
export declare function apply(ctx: Context, config: Config): void;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { addressesOf, mailboxOf } from './config.js';
|
||||
import { MailGateway } from './gateway.js';
|
||||
import { MailGatewayService } from './service.js';
|
||||
export { Config } from './config.js';
|
||||
export const name = 'dsh-mail-sender';
|
||||
export const inject = ['agents', 'settings'];
|
||||
/**
|
||||
* 常驻入口:邮件驱动会话,而不是等待模型调用的 Tool。
|
||||
* 所有 IMAP/SMTP 资源与监听都收在 ctx.effect 里按序回收。
|
||||
*/
|
||||
export function apply(ctx, config) {
|
||||
const gateway = new MailGateway(ctx, mailboxOf(config), addressesOf(config));
|
||||
new MailGatewayService(ctx, gateway, config, name);
|
||||
ctx.effect(() => {
|
||||
const disposeGateway = gateway.start();
|
||||
const on = ctx.on;
|
||||
const off = on('loader/volatile-update', () => {
|
||||
gateway.reload(mailboxOf(config), addressesOf(config));
|
||||
});
|
||||
return async () => {
|
||||
off();
|
||||
await disposeGateway();
|
||||
};
|
||||
});
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
import type { MailboxPatch, MailboxSettings } from './types.js';
|
||||
export declare function createMailbox(settings?: Partial<MailboxSettings>): MailboxSettings;
|
||||
/** 合并补丁;password 留空时沿用原密码。 */
|
||||
export declare function mergeMailbox(current: MailboxSettings, patch: MailboxPatch): MailboxSettings;
|
||||
export declare function isMailboxConfigured(mailbox: MailboxSettings): boolean;
|
||||
/** 影响连接的身份键;白名单变化不会出现在这里。 */
|
||||
export declare function mailboxKey(mailbox: MailboxSettings): string;
|
||||
/** 对外展示的邮箱信息,密码始终清空。 */
|
||||
export declare function publicMailbox(mailbox: MailboxSettings): MailboxSettings;
|
||||
export declare function fromHeader(mailbox: MailboxSettings): string;
|
||||
export declare function smtpUser(mailbox: MailboxSettings): string;
|
||||
@@ -0,0 +1,55 @@
|
||||
export function createMailbox(settings = {}) {
|
||||
return {
|
||||
email: settings.email?.trim() ?? '',
|
||||
displayName: settings.displayName?.trim() ?? '',
|
||||
imapHost: settings.imapHost?.trim() ?? '',
|
||||
imapPort: settings.imapPort ?? 993,
|
||||
imapSecure: settings.imapSecure ?? true,
|
||||
smtpHost: settings.smtpHost?.trim() ?? '',
|
||||
smtpPort: settings.smtpPort ?? 465,
|
||||
smtpSecure: settings.smtpSecure ?? true,
|
||||
username: settings.username?.trim() ?? '',
|
||||
password: settings.password ?? '',
|
||||
};
|
||||
}
|
||||
/** 合并补丁;password 留空时沿用原密码。 */
|
||||
export function mergeMailbox(current, patch) {
|
||||
return createMailbox({
|
||||
...current,
|
||||
...patch,
|
||||
password: patch.password ? patch.password : current.password,
|
||||
});
|
||||
}
|
||||
export function isMailboxConfigured(mailbox) {
|
||||
return Boolean(mailbox.email &&
|
||||
mailbox.imapHost &&
|
||||
mailbox.smtpHost &&
|
||||
(mailbox.username || mailbox.email) &&
|
||||
mailbox.password);
|
||||
}
|
||||
/** 影响连接的身份键;白名单变化不会出现在这里。 */
|
||||
export function mailboxKey(mailbox) {
|
||||
return [
|
||||
mailbox.email,
|
||||
mailbox.username,
|
||||
mailbox.password,
|
||||
mailbox.imapHost,
|
||||
mailbox.imapPort,
|
||||
mailbox.imapSecure,
|
||||
mailbox.smtpHost,
|
||||
mailbox.smtpPort,
|
||||
mailbox.smtpSecure,
|
||||
].join('\u0000');
|
||||
}
|
||||
/** 对外展示的邮箱信息,密码始终清空。 */
|
||||
export function publicMailbox(mailbox) {
|
||||
return { ...mailbox, password: '' };
|
||||
}
|
||||
export function fromHeader(mailbox) {
|
||||
if (!mailbox.displayName)
|
||||
return mailbox.email;
|
||||
return `"${mailbox.displayName.replace(/"/g, '')}" <${mailbox.email}>`;
|
||||
}
|
||||
export function smtpUser(mailbox) {
|
||||
return mailbox.username || mailbox.email;
|
||||
}
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import type { ParsedMail } from 'mailparser';
|
||||
import type { MailJob } from './types.js';
|
||||
/** 规范化后的精确地址集合;只由白名单生成。 */
|
||||
export type AccessPolicy = ReadonlySet<string>;
|
||||
export declare function normalizeAddress(address: string): string;
|
||||
/** 生成纯策略快照,不改动入参。 */
|
||||
export declare function createPolicy(addresses: readonly string[]): AccessPolicy;
|
||||
export declare function isAllowed(policy: AccessPolicy, address: string): boolean;
|
||||
/** 拦截自动回复 / 批量邮件,避免邮件环。 */
|
||||
export declare function isAutoReply(mail: ParsedMail): boolean;
|
||||
/** 正文只取 text/plain,缺失时用 HTML 降级;附件一律丢弃。 */
|
||||
export declare function bodyText(mail: ParsedMail): string;
|
||||
/**
|
||||
* 一次解析完成准入判断与字段提取:发件地址只解析一次,
|
||||
* 不在白名单或命中自动流量时返回 null(静默丢弃)。
|
||||
*/
|
||||
export declare function toJob(policy: AccessPolicy, mail: ParsedMail): MailJob | null;
|
||||
@@ -0,0 +1,99 @@
|
||||
export function normalizeAddress(address) {
|
||||
return address.trim().toLowerCase();
|
||||
}
|
||||
/** 生成纯策略快照,不改动入参。 */
|
||||
export function createPolicy(addresses) {
|
||||
const allowed = new Set();
|
||||
for (const address of addresses) {
|
||||
const normalized = normalizeAddress(address);
|
||||
if (normalized)
|
||||
allowed.add(normalized);
|
||||
}
|
||||
return allowed;
|
||||
}
|
||||
export function isAllowed(policy, address) {
|
||||
return policy.has(normalizeAddress(address));
|
||||
}
|
||||
function headerText(mail, name) {
|
||||
const value = mail.headers.get(name);
|
||||
if (typeof value === 'string')
|
||||
return value;
|
||||
if (Array.isArray(value))
|
||||
return value.filter(item => typeof item === 'string').join(', ');
|
||||
return '';
|
||||
}
|
||||
/** 拦截自动回复 / 批量邮件,避免邮件环。 */
|
||||
export function isAutoReply(mail) {
|
||||
const autoSubmitted = headerText(mail, 'auto-submitted').toLowerCase();
|
||||
if (autoSubmitted && autoSubmitted !== 'no')
|
||||
return true;
|
||||
const precedence = headerText(mail, 'precedence').toLowerCase();
|
||||
if (/(^|[\s,;])(bulk|junk|list)([\s,;]|$)/.test(precedence))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
function decodeEntities(text) {
|
||||
return text
|
||||
.replace(/ /gi, ' ')
|
||||
.replace(/</gi, '<')
|
||||
.replace(/>/gi, '>')
|
||||
.replace(/"/gi, '"')
|
||||
.replace(/'|'/gi, "'")
|
||||
.replace(/&/gi, '&');
|
||||
}
|
||||
function htmlToText(html) {
|
||||
return decodeEntities(html
|
||||
.replace(/<(script|style)[\s\S]*?<\/\1>/gi, '')
|
||||
.replace(/<br\s*\/?>/gi, '\n')
|
||||
.replace(/<\/(p|div|li|tr|h[1-6])>/gi, '\n')
|
||||
.replace(/<[^>]+>/g, ''))
|
||||
.replace(/\r\n/g, '\n')
|
||||
.replace(/[ \t]+\n/g, '\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
/** 正文只取 text/plain,缺失时用 HTML 降级;附件一律丢弃。 */
|
||||
export function bodyText(mail) {
|
||||
const plain = mail.text?.trim();
|
||||
if (plain)
|
||||
return plain;
|
||||
if (mail.html)
|
||||
return htmlToText(mail.html);
|
||||
return '';
|
||||
}
|
||||
function referencesOf(mail) {
|
||||
const parts = mail.references
|
||||
? Array.isArray(mail.references)
|
||||
? mail.references
|
||||
: [mail.references]
|
||||
: [];
|
||||
const all = [...parts];
|
||||
if (mail.messageId && !all.includes(mail.messageId))
|
||||
all.push(mail.messageId);
|
||||
return all.length ? all.join(' ') : undefined;
|
||||
}
|
||||
/**
|
||||
* 一次解析完成准入判断与字段提取:发件地址只解析一次,
|
||||
* 不在白名单或命中自动流量时返回 null(静默丢弃)。
|
||||
*/
|
||||
export function toJob(policy, mail) {
|
||||
const sender = mail.from?.value?.[0]?.address;
|
||||
if (!sender)
|
||||
return null;
|
||||
const from = normalizeAddress(sender);
|
||||
if (!isAllowed(policy, from))
|
||||
return null;
|
||||
if (isAutoReply(mail))
|
||||
return null;
|
||||
const text = bodyText(mail);
|
||||
if (!text)
|
||||
return null;
|
||||
return {
|
||||
from,
|
||||
subject: mail.subject?.trim() || '(无主题)',
|
||||
text,
|
||||
messageId: mail.messageId,
|
||||
references: referencesOf(mail),
|
||||
sessionId: `mail:${from}`,
|
||||
};
|
||||
}
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
import type { AccessPolicy } from './policy.js';
|
||||
import type { CursorStore } from './cursor.js';
|
||||
import type { MailJob, MailStatus, MailboxSettings } from './types.js';
|
||||
/** 不支持的服务器按 60s 轮询,延迟上限约 1 分钟。 */
|
||||
export declare const POLL_INTERVAL_MS = 60000;
|
||||
/** 断线重连退避:5s → 10s → 30s → 1min → 5min。 */
|
||||
export declare const BACKOFF_MS: readonly [5000, 10000, 30000, 60000, 300000];
|
||||
export interface ReceiverHooks {
|
||||
onJob(job: MailJob): void;
|
||||
onStatus(status: MailStatus): void;
|
||||
onLog?(message: string): void;
|
||||
}
|
||||
/** 用临时连接探测 IDLE 能力;登录完成后才读取能力表。 */
|
||||
export declare function probeIdle(mailbox: MailboxSettings): Promise<boolean>;
|
||||
export declare class ImapReceiver {
|
||||
private readonly mailbox;
|
||||
private readonly policy;
|
||||
private readonly cursors;
|
||||
private readonly hooks;
|
||||
private running;
|
||||
private client?;
|
||||
private wakeSleep?;
|
||||
private fetching;
|
||||
private cursor;
|
||||
private uidValidity;
|
||||
private status;
|
||||
constructor(mailbox: MailboxSettings, policy: () => AccessPolicy, cursors: CursorStore, hooks: ReceiverHooks);
|
||||
get currentStatus(): MailStatus;
|
||||
start(): void;
|
||||
stop(): Promise<void>;
|
||||
private report;
|
||||
private run;
|
||||
/** 首次配置或 UIDVALIDITY 变化时建立基线,不回放历史邮件。 */
|
||||
private prime;
|
||||
private collect;
|
||||
private sleep;
|
||||
private wake;
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
import { ImapFlow } from 'imapflow';
|
||||
import { simpleParser } from 'mailparser';
|
||||
import { toJob } from './policy.js';
|
||||
/** 不支持的服务器按 60s 轮询,延迟上限约 1 分钟。 */
|
||||
export const POLL_INTERVAL_MS = 60_000;
|
||||
/** 断线重连退避:5s → 10s → 30s → 1min → 5min。 */
|
||||
export const BACKOFF_MS = [5_000, 10_000, 30_000, 60_000, 300_000];
|
||||
function errorMessage(error) {
|
||||
if (error instanceof Error)
|
||||
return error.message;
|
||||
return String(error);
|
||||
}
|
||||
/** 用临时连接探测 IDLE 能力;登录完成后才读取能力表。 */
|
||||
export async function probeIdle(mailbox) {
|
||||
const client = new ImapFlow({
|
||||
host: mailbox.imapHost,
|
||||
port: mailbox.imapPort,
|
||||
secure: mailbox.imapSecure,
|
||||
auth: { user: mailbox.username || mailbox.email, pass: mailbox.password },
|
||||
logger: false,
|
||||
disableAutoIdle: true,
|
||||
greetingTimeout: 10_000,
|
||||
socketTimeout: 15_000,
|
||||
});
|
||||
try {
|
||||
await client.connect();
|
||||
return client.capabilities.get('IDLE') === true;
|
||||
}
|
||||
finally {
|
||||
await client.logout().catch(() => { });
|
||||
}
|
||||
}
|
||||
export class ImapReceiver {
|
||||
mailbox;
|
||||
policy;
|
||||
cursors;
|
||||
hooks;
|
||||
running = false;
|
||||
client;
|
||||
wakeSleep;
|
||||
fetching = false;
|
||||
cursor = 0;
|
||||
uidValidity = '';
|
||||
status = {
|
||||
phase: 'disabled',
|
||||
supportsIdle: false,
|
||||
pollIntervalMs: POLL_INTERVAL_MS,
|
||||
};
|
||||
constructor(mailbox, policy, cursors, hooks) {
|
||||
this.mailbox = mailbox;
|
||||
this.policy = policy;
|
||||
this.cursors = cursors;
|
||||
this.hooks = hooks;
|
||||
}
|
||||
get currentStatus() {
|
||||
return this.status;
|
||||
}
|
||||
start() {
|
||||
if (this.running)
|
||||
return;
|
||||
this.running = true;
|
||||
void this.run();
|
||||
}
|
||||
async stop() {
|
||||
this.running = false;
|
||||
this.wake();
|
||||
const client = this.client;
|
||||
this.client = undefined;
|
||||
if (client)
|
||||
await client.logout().catch(() => { });
|
||||
}
|
||||
report(patch) {
|
||||
this.status = { ...this.status, ...patch };
|
||||
this.hooks.onStatus(this.status);
|
||||
}
|
||||
async run() {
|
||||
let attempt = 0;
|
||||
while (this.running) {
|
||||
this.report({ phase: 'connecting', lastError: undefined, since: undefined });
|
||||
const client = new ImapFlow({
|
||||
host: this.mailbox.imapHost,
|
||||
port: this.mailbox.imapPort,
|
||||
secure: this.mailbox.imapSecure,
|
||||
auth: { user: this.mailbox.username || this.mailbox.email, pass: this.mailbox.password },
|
||||
logger: false,
|
||||
disableAutoIdle: true,
|
||||
maxIdleTime: POLL_INTERVAL_MS,
|
||||
});
|
||||
this.client = client;
|
||||
let lock;
|
||||
try {
|
||||
await client.connect();
|
||||
if (!this.running || this.client !== client)
|
||||
break;
|
||||
// 认证完成后再探测能力,覆盖 iCloud 一类仅在登录后公布 IDLE 的服务器。
|
||||
const supportsIdle = client.capabilities.get('IDLE') === true;
|
||||
lock = await client.getMailboxLock('INBOX');
|
||||
await this.prime(client);
|
||||
attempt = 0;
|
||||
this.report({
|
||||
phase: supportsIdle ? 'idle' : 'polling',
|
||||
supportsIdle,
|
||||
lastError: undefined,
|
||||
since: new Date().toISOString(),
|
||||
});
|
||||
while (this.running && this.client === client) {
|
||||
if (supportsIdle) {
|
||||
const found = await client.idle();
|
||||
if (!found && this.running)
|
||||
await this.sleep(1_000);
|
||||
}
|
||||
else {
|
||||
await this.sleep(POLL_INTERVAL_MS);
|
||||
}
|
||||
if (!this.running || this.client !== client)
|
||||
break;
|
||||
await this.collect(client);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
if (this.running) {
|
||||
attempt = Math.min(attempt + 1, BACKOFF_MS.length);
|
||||
this.report({
|
||||
phase: 'error',
|
||||
lastError: errorMessage(error),
|
||||
since: undefined,
|
||||
});
|
||||
this.hooks.onLog?.(`[mail] IMAP 连接失败: ${errorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
lock?.release();
|
||||
}
|
||||
catch { }
|
||||
if (this.client === client)
|
||||
this.client = undefined;
|
||||
await client.logout().catch(() => { });
|
||||
}
|
||||
if (!this.running)
|
||||
break;
|
||||
const delay = BACKOFF_MS[Math.max(0, attempt - 1)] ?? BACKOFF_MS[BACKOFF_MS.length - 1];
|
||||
await this.sleep(delay);
|
||||
}
|
||||
this.report({ phase: 'disabled', since: undefined });
|
||||
}
|
||||
/** 首次配置或 UIDVALIDITY 变化时建立基线,不回放历史邮件。 */
|
||||
async prime(client) {
|
||||
const mailbox = client.mailbox;
|
||||
if (!mailbox)
|
||||
return;
|
||||
const uidValidity = String(mailbox.uidValidity);
|
||||
const stored = await this.cursors.read();
|
||||
const cursor = stored && stored.uidValidity === uidValidity ? stored.uid : Math.max(0, mailbox.uidNext - 1);
|
||||
this.uidValidity = uidValidity;
|
||||
this.cursor = cursor;
|
||||
await this.cursors.write({ uidValidity, uid: cursor });
|
||||
}
|
||||
async collect(client) {
|
||||
if (this.fetching)
|
||||
return;
|
||||
this.fetching = true;
|
||||
try {
|
||||
const mailbox = client.mailbox;
|
||||
if (!mailbox)
|
||||
return;
|
||||
if (String(mailbox.uidValidity) !== this.uidValidity) {
|
||||
await this.prime(client);
|
||||
return;
|
||||
}
|
||||
const range = `${this.cursor + 1}:*`;
|
||||
for await (const message of client.fetch({ uid: range }, { uid: true, source: true }, { uid: true })) {
|
||||
const uid = message.uid;
|
||||
if (typeof uid !== 'number' || uid <= this.cursor || !message.source)
|
||||
continue;
|
||||
try {
|
||||
const parsed = await simpleParser(message.source);
|
||||
const job = toJob(this.policy(), parsed);
|
||||
if (job)
|
||||
this.hooks.onJob(job);
|
||||
}
|
||||
catch (error) {
|
||||
this.hooks.onLog?.(`[mail] 解析 UID ${uid} 失败: ${errorMessage(error)}`);
|
||||
}
|
||||
if (uid > this.cursor) {
|
||||
this.cursor = uid;
|
||||
void this.cursors.write({ uidValidity: this.uidValidity, uid });
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
if (this.running)
|
||||
this.hooks.onLog?.(`[mail] 收信失败: ${errorMessage(error)}`);
|
||||
}
|
||||
finally {
|
||||
this.fetching = false;
|
||||
}
|
||||
}
|
||||
sleep(ms) {
|
||||
return new Promise(resolve => {
|
||||
const timer = setTimeout(() => {
|
||||
this.wakeSleep = undefined;
|
||||
resolve();
|
||||
}, ms);
|
||||
this.wakeSleep = () => {
|
||||
clearTimeout(timer);
|
||||
this.wakeSleep = undefined;
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
}
|
||||
wake() {
|
||||
this.wakeSleep?.();
|
||||
}
|
||||
}
|
||||
Vendored
+35
@@ -0,0 +1,35 @@
|
||||
import type { RemoteResult, TypertRemoteInfo, TypertRemoteMethod } from '@deepseek-ai/dsh-typert-protocol';
|
||||
import type { ConnectionTestResult, MailSnapshot, MailStatus, MailboxPatch } from './types.js';
|
||||
export declare const TYPERT_REMOTE: TypertRemoteInfo<{
|
||||
readonly "mail-gateway/get": TypertRemoteMethod<{}, MailSnapshot>;
|
||||
readonly "mail-gateway/saveMailbox": TypertRemoteMethod<{
|
||||
patch: MailboxPatch;
|
||||
}, MailSnapshot>;
|
||||
readonly "mail-gateway/saveWhitelist": TypertRemoteMethod<{
|
||||
addresses: readonly string[];
|
||||
}, MailSnapshot>;
|
||||
readonly "mail-gateway/testConnection": TypertRemoteMethod<{
|
||||
patch: MailboxPatch;
|
||||
}, ConnectionTestResult>;
|
||||
readonly "mail-gateway/status": TypertRemoteMethod<{}, MailStatus>;
|
||||
}>;
|
||||
declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
interface TypertRemoteNamespace$6d61696c2d67617465776179 {
|
||||
get: () => Promise<RemoteResult<MailSnapshot>>;
|
||||
saveMailbox: (patch: MailboxPatch) => Promise<RemoteResult<MailSnapshot>>;
|
||||
saveWhitelist: (addresses: string[]) => Promise<RemoteResult<MailSnapshot>>;
|
||||
testConnection: (patch: MailboxPatch) => Promise<RemoteResult<ConnectionTestResult>>;
|
||||
status: () => Promise<RemoteResult<MailStatus>>;
|
||||
}
|
||||
interface TypertRemoteMap {
|
||||
'mail-gateway/get': () => Promise<RemoteResult<MailSnapshot>>;
|
||||
'mail-gateway/saveMailbox': (patch: MailboxPatch) => Promise<RemoteResult<MailSnapshot>>;
|
||||
'mail-gateway/saveWhitelist': (addresses: string[]) => Promise<RemoteResult<MailSnapshot>>;
|
||||
'mail-gateway/testConnection': (patch: MailboxPatch) => Promise<RemoteResult<ConnectionTestResult>>;
|
||||
'mail-gateway/status': () => Promise<RemoteResult<MailStatus>>;
|
||||
}
|
||||
interface TypertRemoteNamespaceMap {
|
||||
'mail-gateway': TypertRemoteNamespace$6d61696c2d67617465776179;
|
||||
}
|
||||
}
|
||||
export default TYPERT_REMOTE;
|
||||
@@ -0,0 +1,91 @@
|
||||
import { z } from 'zod';
|
||||
import { createTypertRemoteInfo } from '@deepseek-ai/dsh-typert-protocol/remote-info';
|
||||
const mailboxSchema = () => z.object({
|
||||
email: z.string(),
|
||||
displayName: z.string(),
|
||||
imapHost: z.string(),
|
||||
imapPort: z.number(),
|
||||
imapSecure: z.boolean(),
|
||||
smtpHost: z.string(),
|
||||
smtpPort: z.number(),
|
||||
smtpSecure: z.boolean(),
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
const statusSchema = () => z.object({
|
||||
phase: z.enum(['disabled', 'connecting', 'idle', 'polling', 'error']),
|
||||
supportsIdle: z.boolean(),
|
||||
pollIntervalMs: z.number(),
|
||||
lastError: z.string().optional(),
|
||||
since: z.string().optional(),
|
||||
});
|
||||
const snapshotSchema = () => z.object({
|
||||
mailbox: mailboxSchema(),
|
||||
passwordSet: z.boolean(),
|
||||
allowedAddresses: z.array(z.string()),
|
||||
status: statusSchema(),
|
||||
});
|
||||
const patchSchema = () => z.object({
|
||||
email: z.string().optional(),
|
||||
displayName: z.string().optional(),
|
||||
imapHost: z.string().optional(),
|
||||
imapPort: z.number().optional(),
|
||||
imapSecure: z.boolean().optional(),
|
||||
smtpHost: z.string().optional(),
|
||||
smtpPort: z.number().optional(),
|
||||
smtpSecure: z.boolean().optional(),
|
||||
username: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
});
|
||||
const testResultSchema = () => z.object({
|
||||
ok: z.boolean(),
|
||||
supportsIdle: z.boolean(),
|
||||
error: z.string().optional(),
|
||||
});
|
||||
function codec(typeSymbol, create) {
|
||||
return { mode: 'strict', typeSymbol, create };
|
||||
}
|
||||
function jsonParameter(name, typeSymbol, create) {
|
||||
return {
|
||||
name,
|
||||
source: 'json',
|
||||
codec: codec(typeSymbol, create),
|
||||
strictCodec: codec(`${typeSymbol}#strict`, create),
|
||||
};
|
||||
}
|
||||
export const TYPERT_REMOTE = createTypertRemoteInfo({
|
||||
package: 'dsh-mail-sender',
|
||||
methods: {
|
||||
'mail-gateway/get': {
|
||||
service: 'mailGateway',
|
||||
invocation: { kind: 'direct' },
|
||||
parameters: [],
|
||||
result: codec('dsh-mail-sender#MailSnapshot', snapshotSchema),
|
||||
},
|
||||
'mail-gateway/saveMailbox': {
|
||||
service: 'mailGateway',
|
||||
invocation: { kind: 'direct' },
|
||||
parameters: [jsonParameter('patch', 'dsh-mail-sender#MailboxPatch', patchSchema)],
|
||||
result: codec('dsh-mail-sender#MailSnapshot', snapshotSchema),
|
||||
},
|
||||
'mail-gateway/saveWhitelist': {
|
||||
service: 'mailGateway',
|
||||
invocation: { kind: 'direct' },
|
||||
parameters: [jsonParameter('addresses', 'dsh-mail-sender#AddressList', () => z.array(z.string()))],
|
||||
result: codec('dsh-mail-sender#MailSnapshot', snapshotSchema),
|
||||
},
|
||||
'mail-gateway/testConnection': {
|
||||
service: 'mailGateway',
|
||||
invocation: { kind: 'direct' },
|
||||
parameters: [jsonParameter('patch', 'dsh-mail-sender#MailboxPatch', patchSchema)],
|
||||
result: codec('dsh-mail-sender#ConnectionTestResult', testResultSchema),
|
||||
},
|
||||
'mail-gateway/status': {
|
||||
service: 'mailGateway',
|
||||
invocation: { kind: 'direct' },
|
||||
parameters: [],
|
||||
result: codec('dsh-mail-sender#MailStatus', statusSchema),
|
||||
},
|
||||
},
|
||||
}, z);
|
||||
export default TYPERT_REMOTE;
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
import type { MailJob, MailboxSettings } from './types.js';
|
||||
/** SMTP 发送器:单例连接池,每封信复用连接。 */
|
||||
export declare class SmtpSender {
|
||||
private mailbox;
|
||||
private transporter?;
|
||||
private key;
|
||||
constructor(mailbox: MailboxSettings);
|
||||
update(mailbox: MailboxSettings): void;
|
||||
private sync;
|
||||
send(job: MailJob, text: string): Promise<void>;
|
||||
/** 关闭连接池;不等待在途邮件的重试。 */
|
||||
close(): void;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import { fromHeader, mailboxKey, smtpUser } from './mailbox.js';
|
||||
function replySubject(subject) {
|
||||
return /^re\s*:/i.test(subject) ? subject : `Re: ${subject}`;
|
||||
}
|
||||
/** SMTP 发送器:单例连接池,每封信复用连接。 */
|
||||
export class SmtpSender {
|
||||
mailbox;
|
||||
transporter;
|
||||
key = '';
|
||||
constructor(mailbox) {
|
||||
this.mailbox = mailbox;
|
||||
this.sync();
|
||||
}
|
||||
update(mailbox) {
|
||||
const next = `${mailboxKey(mailbox)}\u0000${mailbox.displayName}`;
|
||||
if (next === this.key)
|
||||
return;
|
||||
this.close();
|
||||
this.mailbox = mailbox;
|
||||
this.sync();
|
||||
}
|
||||
sync() {
|
||||
this.key = `${mailboxKey(this.mailbox)}\u0000${this.mailbox.displayName}`;
|
||||
this.transporter = nodemailer.createTransport({
|
||||
host: this.mailbox.smtpHost,
|
||||
port: this.mailbox.smtpPort,
|
||||
secure: this.mailbox.smtpSecure,
|
||||
requireTLS: !this.mailbox.smtpSecure,
|
||||
pool: true,
|
||||
maxConnections: 3,
|
||||
auth: { user: smtpUser(this.mailbox), pass: this.mailbox.password },
|
||||
});
|
||||
}
|
||||
async send(job, text) {
|
||||
if (!this.transporter)
|
||||
this.sync();
|
||||
await this.transporter.sendMail({
|
||||
from: fromHeader(this.mailbox),
|
||||
to: job.from,
|
||||
subject: replySubject(job.subject),
|
||||
text,
|
||||
inReplyTo: job.messageId,
|
||||
references: job.references ?? job.messageId,
|
||||
});
|
||||
}
|
||||
/** 关闭连接池;不等待在途邮件的重试。 */
|
||||
close() {
|
||||
this.transporter?.close();
|
||||
this.transporter = undefined;
|
||||
}
|
||||
}
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
|
||||
import type { Config } from './config.js';
|
||||
import type { MailGateway } from './gateway.js';
|
||||
import type { ConnectionTestResult, MailSnapshot, MailStatus, MailboxPatch } from './types.js';
|
||||
/** Remote 面:设置页的读写、测试与状态查询。 */
|
||||
export declare class MailGatewayService extends TypertRemoteService {
|
||||
private readonly context;
|
||||
private readonly gateway;
|
||||
private readonly config;
|
||||
private readonly defaultNamespace;
|
||||
static inject: string[];
|
||||
private namespace?;
|
||||
constructor(context: Context, gateway: MailGateway, config: Config, defaultNamespace: string);
|
||||
get(): Promise<MailSnapshot>;
|
||||
status(): Promise<MailStatus>;
|
||||
saveMailbox(patch: MailboxPatch): Promise<MailSnapshot>;
|
||||
saveWhitelist(addresses: string[]): Promise<MailSnapshot>;
|
||||
testConnection(patch: MailboxPatch): Promise<ConnectionTestResult>;
|
||||
/** profile 里的实例 id 通常就是包名;回退用 schema 里的字段名定位。 */
|
||||
private resolveNamespace;
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
|
||||
var useValue = arguments.length > 2;
|
||||
for (var i = 0; i < initializers.length; i++) {
|
||||
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
||||
}
|
||||
return useValue ? value : void 0;
|
||||
};
|
||||
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
||||
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
|
||||
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
||||
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
||||
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
||||
var _, done = false;
|
||||
for (var i = decorators.length - 1; i >= 0; i--) {
|
||||
var context = {};
|
||||
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
||||
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
||||
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
|
||||
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
|
||||
if (kind === "accessor") {
|
||||
if (result === void 0) continue;
|
||||
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
||||
if (_ = accept(result.get)) descriptor.get = _;
|
||||
if (_ = accept(result.set)) descriptor.set = _;
|
||||
if (_ = accept(result.init)) initializers.unshift(_);
|
||||
}
|
||||
else if (_ = accept(result)) {
|
||||
if (kind === "field") initializers.unshift(_);
|
||||
else descriptor[key] = _;
|
||||
}
|
||||
}
|
||||
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
||||
done = true;
|
||||
};
|
||||
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
|
||||
import { createMailbox, mergeMailbox } from './mailbox.js';
|
||||
import { normalizeAddress } from './policy.js';
|
||||
import { probeIdle } from './receiver.js';
|
||||
function messageOf(error) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
function validate(mailbox) {
|
||||
if (!mailbox.email)
|
||||
return '请填写邮箱地址';
|
||||
if (!mailbox.imapHost)
|
||||
return '请填写 IMAP 主机';
|
||||
if (!mailbox.smtpHost)
|
||||
return '请填写 SMTP 主机';
|
||||
if (!(mailbox.username || mailbox.email))
|
||||
return '请填写登录用户名';
|
||||
if (!mailbox.password)
|
||||
return '请填写密码';
|
||||
if (!Number.isInteger(mailbox.imapPort) || mailbox.imapPort <= 0)
|
||||
return 'IMAP 端口无效';
|
||||
if (!Number.isInteger(mailbox.smtpPort) || mailbox.smtpPort <= 0)
|
||||
return 'SMTP 端口无效';
|
||||
return undefined;
|
||||
}
|
||||
/** Remote 面:设置页的读写、测试与状态查询。 */
|
||||
let MailGatewayService = (() => {
|
||||
let _classSuper = TypertRemoteService;
|
||||
let _instanceExtraInitializers = [];
|
||||
let _get_decorators;
|
||||
let _status_decorators;
|
||||
let _saveMailbox_decorators;
|
||||
let _saveWhitelist_decorators;
|
||||
let _testConnection_decorators;
|
||||
return class MailGatewayService extends _classSuper {
|
||||
static {
|
||||
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
|
||||
_get_decorators = [Remote('get')];
|
||||
_status_decorators = [Remote('status')];
|
||||
_saveMailbox_decorators = [Remote('saveMailbox')];
|
||||
_saveWhitelist_decorators = [Remote('saveWhitelist')];
|
||||
_testConnection_decorators = [Remote('testConnection')];
|
||||
__esDecorate(this, null, _get_decorators, { kind: "method", name: "get", static: false, private: false, access: { has: obj => "get" in obj, get: obj => obj.get }, metadata: _metadata }, null, _instanceExtraInitializers);
|
||||
__esDecorate(this, null, _status_decorators, { kind: "method", name: "status", static: false, private: false, access: { has: obj => "status" in obj, get: obj => obj.status }, metadata: _metadata }, null, _instanceExtraInitializers);
|
||||
__esDecorate(this, null, _saveMailbox_decorators, { kind: "method", name: "saveMailbox", static: false, private: false, access: { has: obj => "saveMailbox" in obj, get: obj => obj.saveMailbox }, metadata: _metadata }, null, _instanceExtraInitializers);
|
||||
__esDecorate(this, null, _saveWhitelist_decorators, { kind: "method", name: "saveWhitelist", static: false, private: false, access: { has: obj => "saveWhitelist" in obj, get: obj => obj.saveWhitelist }, metadata: _metadata }, null, _instanceExtraInitializers);
|
||||
__esDecorate(this, null, _testConnection_decorators, { kind: "method", name: "testConnection", static: false, private: false, access: { has: obj => "testConnection" in obj, get: obj => obj.testConnection }, metadata: _metadata }, null, _instanceExtraInitializers);
|
||||
if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
||||
}
|
||||
context = __runInitializers(this, _instanceExtraInitializers);
|
||||
gateway;
|
||||
config;
|
||||
defaultNamespace;
|
||||
static inject = ['settings'];
|
||||
namespace;
|
||||
constructor(context, gateway, config, defaultNamespace) {
|
||||
super(context, 'mailGateway', { namespace: 'mail-gateway' });
|
||||
this.context = context;
|
||||
this.gateway = gateway;
|
||||
this.config = config;
|
||||
this.defaultNamespace = defaultNamespace;
|
||||
}
|
||||
async get() {
|
||||
return this.gateway.snapshot();
|
||||
}
|
||||
async status() {
|
||||
return this.gateway.snapshot().status;
|
||||
}
|
||||
async saveMailbox(patch) {
|
||||
const current = createMailbox(this.config.mailbox.get());
|
||||
const next = mergeMailbox(current, patch);
|
||||
const invalid = validate(next);
|
||||
if (invalid)
|
||||
throw new RemoteError('gateway/bad-request', invalid, {});
|
||||
const ops = [];
|
||||
for (const field of [
|
||||
'email',
|
||||
'displayName',
|
||||
'imapHost',
|
||||
'imapPort',
|
||||
'imapSecure',
|
||||
'smtpHost',
|
||||
'smtpPort',
|
||||
'smtpSecure',
|
||||
'username',
|
||||
]) {
|
||||
if (next[field] !== current[field])
|
||||
ops.push({ op: 'set', path: ['mailbox', field], value: next[field] });
|
||||
}
|
||||
// 密码留空表示不修改,且绝不把已存密码回写到表单。
|
||||
if (next.password !== current.password) {
|
||||
ops.push({ op: 'set', path: ['mailbox', 'password'], value: next.password });
|
||||
}
|
||||
try {
|
||||
if (ops.length)
|
||||
await this.context.settings.mutate(this.resolveNamespace(), ops);
|
||||
}
|
||||
catch (error) {
|
||||
throw new RemoteError('gateway/internal', messageOf(error), {});
|
||||
}
|
||||
this.gateway.reload(next, this.config.allowedAddresses.get() ?? []);
|
||||
return this.gateway.snapshot();
|
||||
}
|
||||
async saveWhitelist(addresses) {
|
||||
const normalized = [...new Set(addresses.map(normalizeAddress).filter(Boolean))];
|
||||
try {
|
||||
await this.context.settings.mutate(this.resolveNamespace(), [
|
||||
{ op: 'set', path: ['allowedAddresses'], value: normalized },
|
||||
]);
|
||||
}
|
||||
catch (error) {
|
||||
throw new RemoteError('gateway/internal', messageOf(error), {});
|
||||
}
|
||||
// 只更新内存策略,不断开 IMAP 连接。
|
||||
this.gateway.updatePolicy(normalized);
|
||||
return this.gateway.snapshot();
|
||||
}
|
||||
async testConnection(patch) {
|
||||
const mailbox = mergeMailbox(createMailbox(this.config.mailbox.get()), patch);
|
||||
if (!mailbox.imapHost || !(mailbox.username || mailbox.email) || !mailbox.password) {
|
||||
return { ok: false, supportsIdle: false, error: '请先填写 IMAP 主机、用户名和密码' };
|
||||
}
|
||||
try {
|
||||
return { ok: true, supportsIdle: await probeIdle(mailbox) };
|
||||
}
|
||||
catch (error) {
|
||||
return { ok: false, supportsIdle: false, error: messageOf(error) };
|
||||
}
|
||||
}
|
||||
/** profile 里的实例 id 通常就是包名;回退用 schema 里的字段名定位。 */
|
||||
resolveNamespace() {
|
||||
if (this.namespace)
|
||||
return this.namespace;
|
||||
const descriptors = this.context.settings.describe();
|
||||
const own = descriptors.find(item => item.ns === this.defaultNamespace) ??
|
||||
descriptors.find(item => JSON.stringify(item.schema ?? '').includes('imapHost'));
|
||||
if (!own) {
|
||||
throw new RemoteError('gateway/bad-request', '未找到 dsh-mail-sender 的配置项', {});
|
||||
}
|
||||
this.namespace = own.ns;
|
||||
return own.ns;
|
||||
}
|
||||
};
|
||||
})();
|
||||
export { MailGatewayService };
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* Source-mode Typert artifact. Decorated Service methods are discovered from
|
||||
* the live prototype, so no generated compiler facts are required.
|
||||
*/
|
||||
export declare const TYPERT: unknown;
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* Source-mode Typert artifact. Decorated Service methods are discovered from
|
||||
* the live prototype, so no generated compiler facts are required.
|
||||
*/
|
||||
export const TYPERT = undefined;
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
/** 邮箱绑定信息,宿主与客户端共用。 */
|
||||
export interface MailboxSettings {
|
||||
email: string;
|
||||
displayName: string;
|
||||
imapHost: string;
|
||||
imapPort: number;
|
||||
imapSecure: boolean;
|
||||
smtpHost: string;
|
||||
smtpPort: number;
|
||||
smtpSecure: boolean;
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
/** 表单提交的邮箱补丁;空 password 表示不修改已存密码。 */
|
||||
export interface MailboxPatch {
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
imapHost?: string;
|
||||
imapPort?: number;
|
||||
imapSecure?: boolean;
|
||||
smtpHost?: string;
|
||||
smtpPort?: number;
|
||||
smtpSecure?: boolean;
|
||||
username?: string;
|
||||
password?: string;
|
||||
}
|
||||
/** 一次被准入的来信。 */
|
||||
export interface MailJob {
|
||||
readonly from: string;
|
||||
readonly subject: string;
|
||||
readonly text: string;
|
||||
readonly messageId?: string;
|
||||
readonly references?: string;
|
||||
readonly sessionId: string;
|
||||
}
|
||||
export type MailPhase = 'disabled' | 'connecting' | 'idle' | 'polling' | 'error';
|
||||
export interface MailStatus {
|
||||
readonly phase: MailPhase;
|
||||
readonly supportsIdle: boolean;
|
||||
readonly pollIntervalMs: number;
|
||||
readonly lastError?: string;
|
||||
readonly since?: string;
|
||||
}
|
||||
/** 设置页一次读取的完整快照(不含密码明文)。 */
|
||||
export interface MailSnapshot {
|
||||
readonly mailbox: MailboxSettings;
|
||||
readonly passwordSet: boolean;
|
||||
readonly allowedAddresses: readonly string[];
|
||||
readonly status: MailStatus;
|
||||
}
|
||||
export interface ConnectionTestResult {
|
||||
readonly ok: boolean;
|
||||
readonly supportsIdle: boolean;
|
||||
readonly error?: string;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
Reference in new issue
Block a user