dsh-mishu 0.5.4 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Where reminders go.
3
+ *
4
+ * desktop this computer's own notifications: macOS through osascript,
5
+ * Windows through a PowerShell toast, Linux through notify-send.
6
+ * A server without a desktop has none and says so.
7
+ * feishu a custom bot in a Feishu / Lark group (just you is fine). Its
8
+ * webhook address and optional signing secret are secrets: they
9
+ * live in the keychain (or the secrets file), never the notebook.
10
+ *
11
+ * Text reaches the helper programs as arguments to a fixed script or on
12
+ * stdin, never inside the script itself, so nothing in a title can run.
13
+ */
14
+ import { createHmac } from 'node:crypto';
15
+ import { findProgram, runProgram } from "./exec.js";
16
+ import { bi, MishuError } from "./i18n.js";
17
+ const one = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
18
+ export class DesktopChannel {
19
+ id = 'desktop';
20
+ platform;
21
+ env;
22
+ constructor(platform = process.platform, env = process.env) {
23
+ this.platform = platform;
24
+ this.env = env;
25
+ }
26
+ async status() {
27
+ if (this.platform === 'darwin')
28
+ return findProgram('osascript') === undefined ? { available: false, why: bi('没找到 osascript', 'osascript was not found') } : { available: true };
29
+ if (this.platform === 'win32')
30
+ return findProgram('powershell') === undefined ? { available: false, why: bi('没找到 Windows PowerShell', 'Windows PowerShell was not found') } : { available: true };
31
+ if (this.env.DISPLAY === undefined && this.env.WAYLAND_DISPLAY === undefined) {
32
+ return { available: false, why: bi('这台电脑没有桌面(比如服务器),弹不出电脑通知。用飞书就行。', 'This computer has no desktop (a server, say), so it cannot show notifications. Use Feishu instead.') };
33
+ }
34
+ return findProgram('notify-send') === undefined
35
+ ? { available: false, why: bi('没找到 notify-send(Debian/Ubuntu:sudo apt install libnotify-bin)', 'notify-send was not found (Debian/Ubuntu: sudo apt install libnotify-bin)') }
36
+ : { available: true };
37
+ }
38
+ async send(message) {
39
+ const title = one(message.title, 80);
40
+ const body = one(message.body, 200);
41
+ let result;
42
+ if (this.platform === 'darwin') {
43
+ result = await runProgram(findProgram('osascript'), ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv) sound name "default"', '-e', 'end run', title, body]);
44
+ }
45
+ else if (this.platform === 'win32') {
46
+ result = await runProgram(findProgram('powershell'), ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_TOAST], `${title}\n${body}`);
47
+ }
48
+ else {
49
+ result = await runProgram(findProgram('notify-send'), ['-a', 'DSH', title, body]);
50
+ }
51
+ if (result.code !== 0)
52
+ throw new Error(`notification failed (${(result.stderr.trim() || result.failure || `exit ${result.code}`).slice(0, 200)})`);
53
+ }
54
+ }
55
+ // Title on the first line of stdin, body after it; shown as Windows PowerShell's toast.
56
+ const WINDOWS_TOAST = [
57
+ '$t=[Console]::In.ReadLine();$b=[Console]::In.ReadToEnd();',
58
+ '[void][Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime];',
59
+ '$x=[Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02);',
60
+ "$n=$x.GetElementsByTagName('text');[void]$n.Item(0).AppendChild($x.CreateTextNode($t));[void]$n.Item(1).AppendChild($x.CreateTextNode($b));",
61
+ "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe').Show([Windows.UI.Notifications.ToastNotification]::new($x))",
62
+ ].join('');
63
+ export const FEISHU_WEBHOOK = 'feishu:webhook';
64
+ export const FEISHU_SECRET = 'feishu:secret';
65
+ const WEBHOOK = /^https:\/\/open\.(feishu\.cn|larksuite\.com)\/open-apis\/bot\/v2\/hook\/[\w-]{8,}$/;
66
+ /** Feishu's errors for a custom bot, said so you know what to change in the group's bot settings. */
67
+ function feishuError(code, msg) {
68
+ if (code === 19024)
69
+ return bi('飞书拒收:消息里没有机器人设置的关键词。把关键词设成"小秘书",或者改用签名校验。', 'Feishu refused it: the message lacks the bot\'s keyword. Set the keyword to "小秘书" or use signature verification instead.');
70
+ if (code === 19021)
71
+ return bi('飞书拒收:签名不对。把机器人"签名校验"里的密钥重新复制过来。', 'Feishu refused it: wrong signature. Copy the bot\'s signing secret again.');
72
+ if (code === 19022)
73
+ return bi('飞书拒收:这台电脑的 IP 不在机器人的 IP 白名单里。', 'Feishu refused it: this computer\'s IP is not on the bot\'s allowlist.');
74
+ if (code === 19001 || /not found|invalid/i.test(msg))
75
+ return bi('飞书找不到这个机器人:地址抄错了,或者机器人已经被删掉。', 'Feishu does not know this bot: the address is mistyped or the bot was removed.');
76
+ return bi(`飞书拒收(${code}:${msg})`, `Feishu refused it (${code}: ${msg})`);
77
+ }
78
+ export class FeishuChannel {
79
+ id = 'feishu';
80
+ secrets;
81
+ post;
82
+ constructor(secrets, post) {
83
+ this.secrets = secrets;
84
+ this.post = post ?? globalThis.fetch;
85
+ }
86
+ async status() {
87
+ return await this.secrets.get(FEISHU_WEBHOOK).catch(() => undefined) === undefined
88
+ ? { available: false, why: bi('还没填飞书机器人的地址。', 'No Feishu bot address yet.') }
89
+ : { available: true };
90
+ }
91
+ async send(message) {
92
+ const webhook = await this.secrets.get(FEISHU_WEBHOOK);
93
+ if (webhook === undefined)
94
+ throw new MishuError(bi('还没填飞书机器人的地址。', 'No Feishu bot address yet.'));
95
+ await sendFeishu(this.post, webhook, await this.secrets.get(FEISHU_SECRET), message.text);
96
+ }
97
+ }
98
+ async function sendFeishu(post, webhook, secret, text, now = Date.now()) {
99
+ const timestamp = String(Math.floor(now / 1000));
100
+ // Feishu signs with HMAC-SHA256 keyed by "timestamp\nsecret" over an empty message.
101
+ const signed = secret === undefined ? {} : { timestamp, sign: createHmac('sha256', `${timestamp}\n${secret}`).update('').digest('base64') };
102
+ const response = await post(webhook, {
103
+ method: 'POST',
104
+ headers: { 'content-type': 'application/json; charset=utf-8' },
105
+ body: JSON.stringify({ ...signed, msg_type: 'text', content: { text } }),
106
+ });
107
+ const raw = await response.text();
108
+ let answer;
109
+ try {
110
+ answer = JSON.parse(raw);
111
+ }
112
+ catch {
113
+ throw new MishuError(bi(`飞书没有正常回应(HTTP ${response.status})`, `Feishu did not answer properly (HTTP ${response.status})`));
114
+ }
115
+ const code = answer.code ?? answer.StatusCode ?? 0;
116
+ if (code !== 0)
117
+ throw new MishuError(feishuError(code, answer.msg ?? answer.StatusMessage ?? ''));
118
+ }
119
+ /**
120
+ * Keep a bot address (and its signing secret, if the bot uses one) after
121
+ * sending a first message through it, so a wrong address never gets saved.
122
+ */
123
+ export async function saveFeishu(secrets, input, lang, post) {
124
+ const webhook = input.webhook.trim();
125
+ const secret = input.secret?.trim() || undefined;
126
+ if (!WEBHOOK.test(webhook)) {
127
+ throw new MishuError(bi('这不像飞书机器人的地址:应该以 https://open.feishu.cn/open-apis/bot/v2/hook/ 开头。', 'That is not a Feishu bot address: it starts with https://open.feishu.cn/open-apis/bot/v2/hook/.'));
128
+ }
129
+ const status = await secrets.status();
130
+ if (!status.available)
131
+ throw new MishuError(bi(`没法保存:${status.why.zh}`, `Cannot save it: ${status.why.en}`));
132
+ await sendFeishu(post ?? globalThis.fetch, webhook, secret, lang === 'zh' ? '小秘书已经连上这个群,以后的提醒会发到这里。' : 'The secretary is connected to this group; reminders will come here.');
133
+ await secrets.set(FEISHU_WEBHOOK, webhook);
134
+ if (secret === undefined)
135
+ await secrets.delete(FEISHU_SECRET);
136
+ else
137
+ await secrets.set(FEISHU_SECRET, secret);
138
+ }
139
+ export async function deleteFeishu(secrets) {
140
+ await secrets.delete(FEISHU_WEBHOOK);
141
+ await secrets.delete(FEISHU_SECRET);
142
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * "Sign in with GitHub" without pasting a token: GitHub's device flow.
3
+ *
4
+ * The secretary asks GitHub for a short code, you enter it at
5
+ * github.com/login/device (on any computer) and approve, and the secretary
6
+ * receives a token, checks it like a pasted one and keeps it in the
7
+ * keychain (or the secrets file). It needs the client id of a GitHub OAuth
8
+ * App with device flow enabled; the id is public, there is no secret.
9
+ *
10
+ * https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#device-flow
11
+ */
12
+ import { bi, MishuError } from "../i18n.js";
13
+ import { saveGithubToken } from "./token.js";
14
+ /** Notifications, and repo so CI runs, pull requests and issues of private repositories can be looked up. */
15
+ export const DEVICE_SCOPES = 'notifications repo';
16
+ export class GithubDeviceLogin {
17
+ options;
18
+ current = { state: 'idle' };
19
+ /** Bumped by every start and cancel, so an older poll loop stops quietly. */
20
+ generation = 0;
21
+ constructor(options) {
22
+ this.options = options;
23
+ }
24
+ status() {
25
+ if (this.current.state === 'waiting' && this.now() > this.current.expiresAt) {
26
+ this.current = { state: 'failed', message: EXPIRED };
27
+ }
28
+ return this.current;
29
+ }
30
+ cancel() {
31
+ this.generation++;
32
+ this.current = { state: 'idle' };
33
+ }
34
+ /** Ask GitHub for a code; polling for your approval runs in the background. */
35
+ async start() {
36
+ if (this.options.clientId === '') {
37
+ throw new MishuError(bi('还没有配置 GitHub 应用,没法用 GitHub 登录。可以改用下面的"粘贴 token"。', 'No GitHub app is configured, so signing in with GitHub is not available. Paste a token below instead.'));
38
+ }
39
+ const generation = ++this.generation;
40
+ const answer = await this.form('https://github.com/login/device/code', { client_id: this.options.clientId, scope: DEVICE_SCOPES });
41
+ const deviceCode = String(answer.device_code ?? '');
42
+ const userCode = String(answer.user_code ?? '');
43
+ if (deviceCode === '' || userCode === '')
44
+ throw new MishuError(failure(answer));
45
+ const expiresAt = this.now() + Number(answer.expires_in ?? 900) * 1000;
46
+ this.current = { state: 'waiting', userCode, verificationUri: String(answer.verification_uri ?? 'https://github.com/login/device'), expiresAt };
47
+ void this.poll(generation, deviceCode, Number(answer.interval ?? 5), expiresAt);
48
+ return this.current;
49
+ }
50
+ async poll(generation, deviceCode, interval, expiresAt) {
51
+ const stale = () => generation !== this.generation;
52
+ try {
53
+ while (!stale()) {
54
+ await this.sleep(interval * 1000);
55
+ if (stale())
56
+ return;
57
+ if (this.now() > expiresAt) {
58
+ this.current = { state: 'failed', message: EXPIRED };
59
+ return;
60
+ }
61
+ const answer = await this.form('https://github.com/login/oauth/access_token', {
62
+ client_id: this.options.clientId,
63
+ device_code: deviceCode,
64
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
65
+ });
66
+ if (stale())
67
+ return;
68
+ if (typeof answer.access_token === 'string' && answer.access_token !== '') {
69
+ const { login } = await saveGithubToken(this.options.secrets, answer.access_token, this.options.fetch);
70
+ if (!stale())
71
+ this.current = { state: 'done', login };
72
+ return;
73
+ }
74
+ switch (answer.error) {
75
+ case 'authorization_pending':
76
+ break;
77
+ case 'slow_down':
78
+ interval = Number(answer.interval ?? interval + 5);
79
+ break;
80
+ case 'expired_token':
81
+ this.current = { state: 'failed', message: EXPIRED };
82
+ return;
83
+ case 'access_denied':
84
+ this.current = { state: 'failed', message: bi('你在 GitHub 上取消了授权。', 'You cancelled the authorization on GitHub.') };
85
+ return;
86
+ default:
87
+ this.current = { state: 'failed', message: failure(answer) };
88
+ return;
89
+ }
90
+ }
91
+ }
92
+ catch (error) {
93
+ if (!stale())
94
+ this.current = { state: 'failed', message: error instanceof MishuError ? error.text : bi(`连不上 GitHub:${error.message}`, `Could not reach GitHub: ${error.message}`) };
95
+ }
96
+ }
97
+ async form(url, fields) {
98
+ const post = this.options.post ?? globalThis.fetch;
99
+ const response = await post(url, {
100
+ method: 'POST',
101
+ headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'dsh-mishu' },
102
+ body: new URLSearchParams(fields).toString(),
103
+ });
104
+ const text = await response.text();
105
+ try {
106
+ return JSON.parse(text);
107
+ }
108
+ catch {
109
+ return { error: `http_${response.status}`, error_description: text.slice(0, 200) };
110
+ }
111
+ }
112
+ now() {
113
+ return (this.options.now ?? Date.now)();
114
+ }
115
+ sleep(ms) {
116
+ return (this.options.sleep ?? (wait => new Promise(resolve => setTimeout(resolve, wait))))(ms);
117
+ }
118
+ }
119
+ const EXPIRED = bi('登录码过期了,再点一次"用 GitHub 登录"。', 'The sign-in code expired; click "Sign in with GitHub" again.');
120
+ function failure(answer) {
121
+ const what = String(answer.error_description ?? answer.error ?? 'unknown error');
122
+ if (answer.error === 'http_404' || /^not found$/i.test(String(answer.error ?? answer.message ?? ''))) {
123
+ return bi('GitHub 找不到这个应用:Client ID 不对。', 'GitHub does not know this app: the client id is wrong.');
124
+ }
125
+ if (answer.error === 'device_flow_disabled') {
126
+ return bi('这个 GitHub 应用没有打开"设备登录"(Enable Device Flow)。', 'This GitHub app does not have device flow enabled.');
127
+ }
128
+ return bi(`GitHub 登录没成功:${what}`, `Signing in with GitHub failed: ${what}`);
129
+ }
@@ -12,6 +12,8 @@ import { bi, MishuError } from "../i18n.js";
12
12
  import { GitHubClient, GitHubError } from "./client.js";
13
13
  /** The keychain entry for a token pasted on the settings page. */
14
14
  export const GITHUB_SECRET = 'github';
15
+ /** The OAuth App behind "Sign in with GitHub" (device flow, "DSH 小秘书"); public, not a secret. */
16
+ export const GITHUB_CLIENT_ID = 'Ov23liejlNOyARQKgy5x';
15
17
  /** Opens GitHub's "new classic token" page with the two scopes ticked. */
16
18
  export const NEW_TOKEN_URL = 'https://github.com/settings/tokens/new?scopes=notifications,repo&description=DSH%20mishu';
17
19
  /** `ghPath` is for tests: a fixed path, or `null` for "not installed". */
package/lib/core/index.js CHANGED
@@ -11,20 +11,23 @@ export { GitHubClient, GitHubError } from "./github/client.js";
11
11
  export { gatherFacts, Lookups, parseCheckSuiteTitle } from "./github/facts.js";
12
12
  export { CLOSING_REASONS, judge } from "./github/rules.js";
13
13
  export { syncGithub } from "./github/sync.js";
14
- export { deleteGithubToken, GITHUB_SECRET, NEW_TOKEN_URL, resolveGithubToken, saveGithubToken } from "./github/token.js";
14
+ export { DEVICE_SCOPES, GithubDeviceLogin } from "./github/device.js";
15
+ export { deleteGithubToken, GITHUB_CLIENT_ID, GITHUB_SECRET, NEW_TOKEN_URL, resolveGithubToken, saveGithubToken } from "./github/token.js";
15
16
  export { bi, decode, detectLang, errorText, LANGS, MishuError, pick } from "./i18n.js";
16
17
  export { addSeries, describeActiveSeries, describeSeries, resolveSeries, stopSeries, tickManual, upcoming, } from "./manual.js";
17
18
  export { DEFAULT_DEMOTION, isActive, isDemoted, setStatusByUser, snoozeByUser } from "./matters.js";
18
19
  export { CATEGORIES, CATEGORY_LABELS, DEFAULT_LEAD_DAYS, REPEATS } from "./recur.js";
19
20
  export { MishuStore } from "./store.js";
20
21
  export { addDays, dayOf, formatMoment } from "./time.js";
21
- export { MAIL_PRESETS, presetById, secretAccount } from "./mail/account.js";
22
+ export { MAIL_PRESETS, normalizePassword, presetById, presetForAddress, providerMismatch, secretAccount } from "./mail/account.js";
22
23
  export { ImapFetcher } from "./mail/imap.js";
23
24
  export { judgeMail } from "./mail/rules.js";
24
25
  export { describeMailError, MAIL_SOURCE, mailReportKey, syncMail } from "./mail/sync.js";
25
26
  export { findProgram } from "./exec.js";
27
+ export { deleteFeishu, DesktopChannel, FeishuChannel, saveFeishu, FEISHU_WEBHOOK } from "./channels.js";
28
+ export { DEFAULT_NOTIFY, deliver, inQuiet, localClock, notifySettings, notifyTick, NOTIFY_REPORT_KEY, saveNotifySettings, testMessage, URGENT_REASONS, } from "./notify.js";
26
29
  export { restartPlan, scheduleRestart } from "./restart.js";
27
- export { MemorySecrets, secretEnvName, secretFromEnv, systemSecrets } from "./secrets.js";
30
+ export { FileSecrets, KeychainOrFile, MemorySecrets, secretEnvName, secretFromEnv, systemSecrets } from "./secrets.js";
28
31
  export { deleteMailAccount, effectiveSettings, mailAccounts, saveMailAccount, saveSettings } from "./settings.js";
29
32
  export const DEFAULT_HOME = '~/.mishu';
30
33
  /** `~` and `~/…` expand to the home directory on every platform. */
@@ -37,5 +40,5 @@ export function expandHome(path) {
37
40
  }
38
41
  export function mishuPaths(home) {
39
42
  const root = expandHome(home);
40
- return { root, db: join(root, 'mishu.db') };
43
+ return { root, db: join(root, 'mishu.db'), secrets: join(root, 'secrets.json') };
41
44
  }
@@ -6,37 +6,93 @@
6
6
  * system keychain under `mail:<id>`, never in the notebook.
7
7
  */
8
8
  import { bi, MishuError } from "../i18n.js";
9
+ /** Steps, and the same steps as one numbered paragraph. */
10
+ function guide(steps) {
11
+ return {
12
+ steps,
13
+ howTo: bi(steps.map((step, i) => `${i + 1}. ${step.text.zh}`).join(' '), steps.map((step, i) => `${i + 1}. ${step.text.en}`).join(' ')),
14
+ };
15
+ }
16
+ const NETEASE = (name, url) => guide([
17
+ { text: bi(`打开 ${name} 邮箱网页版并登录。`, `Open ${name} Mail on the web and sign in.`), link: { url, label: bi(`打开 ${name} 邮箱`, `Open ${name} Mail`) } },
18
+ { text: bi('点上方的「设置」→「POP3/SMTP/IMAP」,开启「IMAP/SMTP 服务」。', 'Click Settings → POP3/SMTP/IMAP at the top and turn on "IMAP/SMTP".') },
19
+ { text: bi('按提示用手机验证,页面会给你一个「客户端授权码」,复制后粘贴到下面的密码框(不是邮箱登录密码)。', 'Verify with your phone as asked; the page shows a client authorization code. Copy it into the password box below (not your mail password).') },
20
+ ]);
9
21
  export const MAIL_PRESETS = [
10
22
  {
11
23
  id: 'qq', label: bi('QQ 邮箱', 'QQ Mail'), host: 'imap.qq.com', port: 993, secure: true, supported: true,
12
- howTo: bi('在 QQ 邮箱网页版:设置 → 账号与安全 → 安全设置(旧版界面是 设置 → 账户),开启「IMAP/SMTP 服务」,按提示验证后生成 16 位授权码。这里填授权码,不是 QQ 密码;改过 QQ 密码后,旧授权码会失效。', 'In QQ Mail on the web: Settings → Account and Security → Security (Settings → Account in the older layout), turn on "IMAP/SMTP", verify, and generate a 16-character authorization code. Enter that code here, not your QQ password; changing your QQ password expires old codes.'),
24
+ domains: ['qq.com', 'vip.qq.com', 'foxmail.com'], passwordLength: 16,
25
+ ...guide([
26
+ { text: bi('打开 QQ 邮箱网页版并登录。', 'Open QQ Mail on the web and sign in.'), link: { url: 'https://mail.qq.com/', label: bi('打开 QQ 邮箱', 'Open QQ Mail') } },
27
+ { text: bi('点「设置」→「账号与安全」→「安全设置」(旧版界面是「设置」→「账户」),找到「IMAP/SMTP 服务」,点「开启」。', 'Click Settings → Account and Security → Security (Settings → Account in the older layout), find "IMAP/SMTP" and turn it on.') },
28
+ { text: bi('按提示用手机验证,页面会显示一个 16 位授权码,复制后粘贴到下面的密码框(不是 QQ 密码)。改过 QQ 密码后,旧授权码会失效。', 'Verify with your phone as asked; the page shows a 16-character authorization code. Copy it into the password box below (not your QQ password). Changing your QQ password expires old codes.') },
29
+ ]),
13
30
  },
14
31
  {
15
32
  id: '163', label: bi('网易 163 邮箱', 'NetEase 163'), host: 'imap.163.com', port: 993, secure: true, supported: true,
16
- howTo: bi('在 163 邮箱网页版:设置 → POP3/SMTP/IMAP → 开启 IMAP 服务,设置客户端授权码。这里填授权码。', 'In 163 Mail on the web: Settings → POP3/SMTP/IMAP → turn on IMAP and set a client authorization code. Enter that code here.'),
33
+ domains: ['163.com'], ...NETEASE('163', 'https://mail.163.com/'),
17
34
  },
18
35
  {
19
36
  id: '126', label: bi('网易 126 邮箱', 'NetEase 126'), host: 'imap.126.com', port: 993, secure: true, supported: true,
20
- howTo: bi('在 126 邮箱网页版:设置 → POP3/SMTP/IMAP → 开启 IMAP 服务,设置客户端授权码。这里填授权码。', 'In 126 Mail on the web: Settings → POP3/SMTP/IMAP → turn on IMAP and set a client authorization code. Enter that code here.'),
37
+ domains: ['126.com'], ...NETEASE('126', 'https://mail.126.com/'),
21
38
  },
22
39
  {
23
40
  id: 'gmail', label: bi('Gmail', 'Gmail'), host: 'imap.gmail.com', port: 993, secure: true, supported: true,
24
- howTo: bi('Google 账号先开启两步验证,再到「安全性 → 应用专用密码」生成一个 16 位密码,填在这里。', 'Turn on 2-Step Verification for your Google account, then create an app password under Security → App passwords and enter it here.'),
41
+ domains: ['gmail.com', 'googlemail.com'], passwordLength: 16,
42
+ ...guide([
43
+ {
44
+ text: bi('开启 Google 账号的两步验证(已经开了就跳过这步)。', 'Turn on 2-Step Verification for your Google account (skip this if it is on).'),
45
+ link: { url: 'https://myaccount.google.com/signinoptions/twosv', label: bi('打开两步验证', 'Open 2-Step Verification') },
46
+ },
47
+ {
48
+ text: bi('打开「应用专用密码」页面,名字随便填(比如"小秘书"),点「创建」。如果页面说"设置不可用",说明第 1 步还没做。', 'Open the App passwords page, type any name ("secretary") and click Create. If the page says the setting is not available, step 1 is not done yet.'),
49
+ link: { url: 'https://myaccount.google.com/apppasswords', label: bi('打开应用专用密码', 'Open App passwords') },
50
+ },
51
+ { text: bi('把弹出来的 16 位密码复制,粘贴到下面的密码框(带不带空格都行)。它只显示这一次。', 'Copy the 16-character password it shows into the password box below (spaces or not). It is shown only once.') },
52
+ ]),
25
53
  findMessage: id => `https://mail.google.com/mail/u/0/#search/rfc822msgid:${encodeURIComponent(id)}`,
26
54
  },
27
55
  {
28
56
  id: 'icloud', label: bi('iCloud 邮件', 'iCloud Mail'), host: 'imap.mail.me.com', port: 993, secure: true, supported: true,
29
- howTo: bi('在 appleid.apple.com:登录与安全 → App 专用密码,生成一个填在这里。用户名一般是 @icloud.com 前面的部分。', 'At appleid.apple.com: Sign-In and Security → App-Specific Passwords; create one and enter it here. The user name is usually the part before @icloud.com.'),
57
+ domains: ['icloud.com', 'me.com', 'mac.com'],
58
+ ...guide([
59
+ { text: bi('打开 Apple 账户页面并登录。', 'Open your Apple Account page and sign in.'), link: { url: 'https://account.apple.com/account/manage', label: bi('打开 Apple 账户', 'Open Apple Account') } },
60
+ { text: bi('点「登录与安全」→「App 专用密码」,点「+」,名字随便填。', 'Click Sign-In and Security → App-Specific Passwords, click +, and type any name.') },
61
+ { text: bi('把显示的密码(xxxx-xxxx-xxxx-xxxx)复制,粘贴到下面的密码框。', 'Copy the password it shows (xxxx-xxxx-xxxx-xxxx) into the password box below.') },
62
+ ]),
30
63
  },
31
64
  {
32
65
  id: 'outlook', label: bi('Outlook / Hotmail', 'Outlook / Hotmail'), host: 'outlook.office365.com', port: 993, secure: true, supported: false,
66
+ domains: ['outlook.com', 'hotmail.com', 'live.com', 'msn.com'], steps: [],
33
67
  howTo: bi('微软已经不允许用密码登录 IMAP,需要 OAuth 授权,小秘书暂时还不支持。', 'Microsoft no longer allows password logins over IMAP; it needs OAuth, which the secretary does not support yet.'),
34
68
  },
35
69
  {
36
70
  id: 'custom', label: bi('其他(自己填服务器)', 'Other (enter the server)'), host: '', port: 993, secure: true, supported: true,
71
+ domains: [], steps: [],
37
72
  howTo: bi('填你的邮件服务商给的 IMAP 服务器、端口和密码(很多服务商要求用专门的客户端授权码)。', 'Enter the IMAP server, port and password your provider gives you (many require a separate app password).'),
38
73
  },
39
74
  ];
75
+ /** The provider an address belongs to, from its domain; `undefined` when we do not know it. */
76
+ export function presetForAddress(address) {
77
+ const domain = address.trim().toLowerCase().split('@')[1] ?? '';
78
+ return MAIL_PRESETS.find(p => p.domains.includes(domain));
79
+ }
80
+ /**
81
+ * The password as the server wants it. App passwords and codes are shown in
82
+ * groups ("abcd efgh ijkl mnop") and copied with the spaces; they never
83
+ * contain one, so spaces go when the provider fixes the length.
84
+ */
85
+ export function normalizePassword(presetId, password) {
86
+ return presetById(presetId).passwordLength === undefined ? password : password.replace(/\s+/g, '');
87
+ }
88
+ /** An account whose address belongs to another provider than its server ("…@gmail.com" on imap.qq.com). */
89
+ export function providerMismatch(account) {
90
+ const expected = presetForAddress(account.address);
91
+ if (expected === undefined || expected.id === account.preset || account.preset === 'custom')
92
+ return undefined;
93
+ const domain = account.address.split('@')[1];
94
+ return bi(`地址是 ${domain},服务器却是 ${presetById(account.preset).label.zh}的 ${account.host}。点「编辑」把服务商改成「${expected.label.zh}」。`, `The address is ${domain} but the server is ${account.host} (${presetById(account.preset).label.en}). Click Edit and choose "${expected.label.en}".`);
95
+ }
40
96
  export function presetById(id) {
41
97
  return MAIL_PRESETS.find(p => p.id === id) ?? MAIL_PRESETS[MAIL_PRESETS.length - 1];
42
98
  }
@@ -11,15 +11,44 @@ import { bi } from "../i18n.js";
11
11
  import { presetById } from "./account.js";
12
12
  import { judgeMail } from "./rules.js";
13
13
  export const MAIL_SOURCE = 'mail';
14
- /** A connection or login failure, said so a person knows what to fix. */
15
- export function describeMailError(error, account) {
14
+ /** What some providers' refusals mean, in words you can act on. */
15
+ const KNOWN_REFUSALS = [
16
+ {
17
+ presets: ['gmail'], match: /application-specific password required/i,
18
+ text: bi('Google 不接受账号的登录密码:这里要填「应用专用密码」(16 位)。按步骤第 1、2 步生成一个,大约一分钟。', 'Google does not take your account password here: it needs an app password (16 characters). Steps 1 and 2 make one in about a minute.'),
19
+ },
20
+ {
21
+ presets: ['gmail'], match: /invalid credentials/i,
22
+ text: bi('Google 不认这个应用专用密码:可能抄错了,或者已经在 Google 账号里删掉了。按步骤第 2 步重新生成一个再试。', 'Google does not accept this app password: it may be mistyped or deleted from your Google account. Make a new one with step 2 and try again.'),
23
+ },
24
+ {
25
+ presets: ['gmail'], match: /web login required|log in via your web browser/i,
26
+ text: bi('Google 拦下了这次登录:先在浏览器里登录一次 Gmail,再回来试。', 'Google blocked this sign-in: sign in to Gmail in a browser once, then try again.'),
27
+ },
28
+ {
29
+ presets: ['qq'], match: /login fail/i,
30
+ text: bi('QQ 邮箱不让登录:最常见是还没开启 IMAP 服务,或者填的是 QQ 密码而不是授权码;改过 QQ 密码后,旧授权码也会失效。', 'QQ Mail refused the sign-in: usually IMAP is not turned on, or this is your QQ password instead of the authorization code; changing your QQ password also expires old codes.'),
31
+ },
32
+ {
33
+ presets: ['163', '126'], match: /unsafe login/i,
34
+ text: bi('网易邮箱拦下了这次登录:确认设置里已开启 IMAP 服务,并且填的是客户端授权码。', 'NetEase Mail blocked this sign-in: check that IMAP is turned on in its settings and that this is the client authorization code.'),
35
+ },
36
+ ];
37
+ /**
38
+ * A connection or login failure, said so a person knows what to fix. With
39
+ * `steps` (the default) a login failure also repeats where the provider's
40
+ * app password comes from; the add-account dialog shows those steps already.
41
+ */
42
+ export function describeMailError(error, account, options = {}) {
16
43
  const raw = error.responseText ?? error.message ?? String(error);
17
- const auth = /auth|login|password|credential|AUTHENTICATIONFAILED|LOGIN failed/i.test(raw);
44
+ const known = KNOWN_REFUSALS.find(k => k.presets.includes(account.preset) && k.match.test(raw));
45
+ const auth = known !== undefined || /auth|login|password|credential|AUTHENTICATIONFAILED|LOGIN failed/i.test(raw);
18
46
  if (!auth)
19
47
  return bi(`连接 ${account.host}:${account.port} 失败:${raw}`, `Could not reach ${account.host}:${account.port}: ${raw}`);
20
48
  const preset = presetById(account.preset);
21
- const howTo = preset.id === 'custom' ? undefined : preset.howTo;
22
- return bi(`登录失败:服务器不接受这个用户名或密码(${raw})。多数邮箱要先开启 IMAP,再填客户端授权码或应用专用密码,不是网页登录密码。${howTo === undefined ? '' : `\n${preset.label.zh}:${howTo.zh}`}`, `Login failed: the server rejected the user name or password (${raw}). Most providers need IMAP turned on and an app password, not your web password.${howTo === undefined ? '' : `\n${preset.label.en}: ${howTo.en}`}`);
49
+ const steps = options.steps !== false && preset.id !== 'custom' ? preset.howTo : undefined;
50
+ const what = known?.text ?? bi('登录失败:服务器不接受这个用户名或密码。多数邮箱要先开启 IMAP,再填客户端授权码或应用专用密码,不是网页登录密码。', 'Login failed: the server rejected the user name or password. Most providers need IMAP turned on and an app password, not your web password.');
51
+ return bi(`${what.zh}(服务器原话:${raw})${steps === undefined ? '' : `\n${preset.label.zh}:${steps.zh}`}`, `${what.en} (The server said: ${raw})${steps === undefined ? '' : `\n${preset.label.en}: ${steps.en}`}`);
23
52
  }
24
53
  export function mailReportKey(accountId) {
25
54
  return `mail.lastSync.${accountId}`;