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.
- package/README.md +40 -12
- package/lib/client.js +868 -346
- package/lib/core/channels.js +142 -0
- package/lib/core/github/device.js +129 -0
- package/lib/core/github/token.js +2 -0
- package/lib/core/index.js +7 -4
- package/lib/core/mail/account.js +61 -5
- package/lib/core/mail/sync.js +34 -5
- package/lib/core/notify.js +198 -0
- package/lib/core/restart.js +35 -5
- package/lib/core/secrets.js +102 -2
- package/lib/core/settings.js +2 -2
- package/lib/dsh/api.js +80 -7
- package/lib/dsh/config.js +2 -1
- package/lib/dsh/plugin.js +4 -0
- package/lib/dsh/runtime.js +45 -4
- package/lib/types/core/channels.d.ts +61 -0
- package/lib/types/core/github/device.d.ts +64 -0
- package/lib/types/core/github/token.d.ts +2 -0
- package/lib/types/core/index.d.ts +8 -4
- package/lib/types/core/mail/account.d.ts +25 -1
- package/lib/types/core/mail/sync.d.ts +8 -2
- package/lib/types/core/notify.d.ts +97 -0
- package/lib/types/core/restart.d.ts +22 -7
- package/lib/types/core/secrets.d.ts +50 -4
- package/lib/types/dsh/config.d.ts +2 -0
- package/lib/types/dsh/runtime.d.ts +13 -4
- package/package.json +1 -1
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reaching you without you opening the board: a daily brief, urgent items
|
|
3
|
+
* as they come, and quiet hours.
|
|
4
|
+
*
|
|
5
|
+
* Urgent means someone is waiting on you or it is due today:
|
|
6
|
+
* - things you told it: due today or overdue
|
|
7
|
+
* - GitHub: a review requested, a mention, an assignment
|
|
8
|
+
* - mail: a meeting invitation
|
|
9
|
+
* Everything else waits for the daily brief. Each urgent item is sent once
|
|
10
|
+
* (again only when it changes reason or due day); turning reminders on does
|
|
11
|
+
* not send what was already on the board. During quiet hours nothing is
|
|
12
|
+
* sent; what came up is sent when they end.
|
|
13
|
+
*
|
|
14
|
+
* Times are read in the time zone your browser reported, so a server
|
|
15
|
+
* running on UTC still sends the brief at your morning.
|
|
16
|
+
*/
|
|
17
|
+
import { reasonLabel } from "./brief.js";
|
|
18
|
+
import { bi, decode, MishuError } from "./i18n.js";
|
|
19
|
+
import { isActive } from "./matters.js";
|
|
20
|
+
import { dayOf } from "./time.js";
|
|
21
|
+
export const DEFAULT_NOTIFY = {
|
|
22
|
+
brief: { enabled: true, time: '09:00' },
|
|
23
|
+
urgent: true,
|
|
24
|
+
quiet: { enabled: true, from: '22:00', to: '08:00' },
|
|
25
|
+
timeZone: '',
|
|
26
|
+
channels: { desktop: true, feishu: false },
|
|
27
|
+
};
|
|
28
|
+
export const URGENT_REASONS = ['review-requested', 'mentioned', 'assigned', 'mail-invite'];
|
|
29
|
+
const SETTINGS_KEY = 'notify.settings';
|
|
30
|
+
const STATE_KEY = 'notify.state';
|
|
31
|
+
export const NOTIFY_REPORT_KEY = 'notify.last';
|
|
32
|
+
export function notifySettings(store) {
|
|
33
|
+
const saved = store.get(SETTINGS_KEY) ?? {};
|
|
34
|
+
return {
|
|
35
|
+
brief: { ...DEFAULT_NOTIFY.brief, ...saved.brief },
|
|
36
|
+
urgent: saved.urgent ?? DEFAULT_NOTIFY.urgent,
|
|
37
|
+
quiet: { ...DEFAULT_NOTIFY.quiet, ...saved.quiet },
|
|
38
|
+
timeZone: saved.timeZone ?? DEFAULT_NOTIFY.timeZone,
|
|
39
|
+
channels: { ...DEFAULT_NOTIFY.channels, ...saved.channels },
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
43
|
+
/** Check what the page sent and keep it; throws a sentence a person can act on. */
|
|
44
|
+
export function saveNotifySettings(store, input, now) {
|
|
45
|
+
const current = notifySettings(store);
|
|
46
|
+
const next = {
|
|
47
|
+
brief: { ...current.brief, ...input.brief },
|
|
48
|
+
urgent: input.urgent ?? current.urgent,
|
|
49
|
+
quiet: { ...current.quiet, ...input.quiet },
|
|
50
|
+
timeZone: input.timeZone ?? current.timeZone,
|
|
51
|
+
channels: { ...current.channels, ...input.channels },
|
|
52
|
+
};
|
|
53
|
+
for (const time of [next.brief.time, next.quiet.from, next.quiet.to]) {
|
|
54
|
+
if (!TIME.test(time))
|
|
55
|
+
throw new MishuError(bi(`时间要写成 08:30 这样:${time}`, `Write times like 08:30: ${time}`));
|
|
56
|
+
}
|
|
57
|
+
if (next.timeZone !== '') {
|
|
58
|
+
try {
|
|
59
|
+
new Intl.DateTimeFormat('en', { timeZone: next.timeZone });
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw new MishuError(bi(`不认识这个时区:${next.timeZone}`, `Unknown time zone: ${next.timeZone}`));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
store.set(SETTINGS_KEY, next);
|
|
66
|
+
store.log(now, 'notify-settings', next);
|
|
67
|
+
return next;
|
|
68
|
+
}
|
|
69
|
+
/** The day and minute of the day in a time zone ('' = this computer's). */
|
|
70
|
+
export function localClock(now, timeZone) {
|
|
71
|
+
const parts = new Intl.DateTimeFormat('en-CA', {
|
|
72
|
+
...timeZone === '' ? {} : { timeZone },
|
|
73
|
+
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
|
|
74
|
+
}).formatToParts(new Date(now));
|
|
75
|
+
const part = (type) => parts.find(p => p.type === type)?.value ?? '00';
|
|
76
|
+
return { day: `${part('year')}-${part('month')}-${part('day')}`, minutes: Number(part('hour')) * 60 + Number(part('minute')) };
|
|
77
|
+
}
|
|
78
|
+
const minutesOf = (time) => Number(time.slice(0, 2)) * 60 + Number(time.slice(3, 5));
|
|
79
|
+
/** Whether a minute of the day is inside quiet hours, which may run past midnight. */
|
|
80
|
+
export function inQuiet(minutes, quiet) {
|
|
81
|
+
if (!quiet.enabled)
|
|
82
|
+
return false;
|
|
83
|
+
const from = minutesOf(quiet.from);
|
|
84
|
+
const to = minutesOf(quiet.to);
|
|
85
|
+
if (from === to)
|
|
86
|
+
return false;
|
|
87
|
+
return from < to ? minutes >= from && minutes < to : minutes >= from || minutes < to;
|
|
88
|
+
}
|
|
89
|
+
/** Open items someone is waiting on, or due today. */
|
|
90
|
+
export function urgentMatters(store, today) {
|
|
91
|
+
return store.openMatters().filter(m => isActive(m, today) && (m.source === 'manual' ? m.dueDay !== null && m.dueDay <= today : URGENT_REASONS.includes(m.reason ?? '')));
|
|
92
|
+
}
|
|
93
|
+
const urgentKey = (m) => `${m.id}:${m.reason ?? ''}:${m.dueDay ?? ''}`;
|
|
94
|
+
const SIGN = bi('打开小秘书看板处理。', 'Open the secretary board to handle them.');
|
|
95
|
+
function urgentMessage(matters, lang) {
|
|
96
|
+
const zh = lang === 'zh';
|
|
97
|
+
const line = (m) => {
|
|
98
|
+
const why = m.source === 'manual' ? (zh ? `${m.dueDay} 到期` : `due ${m.dueDay}`) : reasonLabel(m.reason, lang);
|
|
99
|
+
return `• ${decode(m.title, lang)}${why === '' ? '' : `(${why})`}`;
|
|
100
|
+
};
|
|
101
|
+
const first = decode(matters[0].title, lang);
|
|
102
|
+
return {
|
|
103
|
+
kind: 'urgent',
|
|
104
|
+
title: zh ? `小秘书:${matters.length} 件急事` : `Secretary: ${matters.length} urgent`,
|
|
105
|
+
body: matters.length === 1 ? first : (zh ? `${first} 等 ${matters.length} 件` : `${first} and ${matters.length - 1} more`),
|
|
106
|
+
text: [zh ? `小秘书:${matters.length} 件急事` : `Secretary: ${matters.length} urgent`, ...matters.slice(0, 10).map(line),
|
|
107
|
+
...matters.length > 10 ? [zh ? `…还有 ${matters.length - 10} 件` : `…and ${matters.length - 10} more`] : [], SIGN[lang]].join('\n'),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** The brief, from what the board shows; `undefined` when there is nothing to tell. */
|
|
111
|
+
export function briefMessage(board, lang) {
|
|
112
|
+
const zh = lang === 'zh';
|
|
113
|
+
const { handle, remember } = board.columns;
|
|
114
|
+
if (handle.length === 0 && board.metrics.dueSoon === 0)
|
|
115
|
+
return undefined;
|
|
116
|
+
const lines = handle.slice(0, 10).map(card => `• ${card.title}(${card.meta})`);
|
|
117
|
+
const soon = remember.filter(card => card.tone !== 'normal').slice(0, 5).map(card => `• ${card.title}(${card.meta})`);
|
|
118
|
+
const title = zh ? '小秘书 · 今日简报' : 'Secretary · daily brief';
|
|
119
|
+
return {
|
|
120
|
+
kind: 'brief',
|
|
121
|
+
title,
|
|
122
|
+
body: board.summary,
|
|
123
|
+
text: [title, board.summary,
|
|
124
|
+
...lines.length > 0 ? ['', zh ? '要你处理:' : 'To handle:', ...lines] : [],
|
|
125
|
+
...handle.length > 10 ? [zh ? `…还有 ${handle.length - 10} 件` : `…and ${handle.length - 10} more`] : [],
|
|
126
|
+
...soon.length > 0 ? ['', zh ? '快到期:' : 'Coming up:', ...soon] : [],
|
|
127
|
+
'', SIGN[lang]].join('\n'),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
export function testMessage(lang) {
|
|
131
|
+
return lang === 'zh'
|
|
132
|
+
? { kind: 'test', title: '小秘书', body: '提醒能送到这里。', text: '小秘书:提醒能送到这里。' }
|
|
133
|
+
: { kind: 'test', title: 'Secretary', body: 'Reminders reach you here.', text: 'Secretary: reminders reach you here.' };
|
|
134
|
+
}
|
|
135
|
+
/** Send to every enabled channel; one failing does not stop the others. */
|
|
136
|
+
export async function deliver(store, channels, message, count, now) {
|
|
137
|
+
const results = [];
|
|
138
|
+
for (const channel of channels) {
|
|
139
|
+
try {
|
|
140
|
+
await channel.send(message);
|
|
141
|
+
results.push({ channel: channel.id, ok: true });
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
results.push({ channel: channel.id, ok: false, error: error instanceof MishuError ? error.text.en : error.message });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const report = { at: now, kind: message.kind, count, results };
|
|
148
|
+
if (message.kind !== 'test')
|
|
149
|
+
store.set(NOTIFY_REPORT_KEY, report);
|
|
150
|
+
// Counts and channels only: titles never go to the log.
|
|
151
|
+
store.log(now, 'notify', { kind: message.kind, count, results: results.map(r => ({ channel: r.channel, ok: r.ok })) });
|
|
152
|
+
return report;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* One look at the clock: send what is due. Called every minute and after
|
|
156
|
+
* each sync. `channels` are the enabled ones; `board` builds the brief.
|
|
157
|
+
*/
|
|
158
|
+
export async function notifyTick(options) {
|
|
159
|
+
const { store, now, lang, channels } = options;
|
|
160
|
+
const settings = notifySettings(store);
|
|
161
|
+
if (channels.length === 0)
|
|
162
|
+
return [];
|
|
163
|
+
const clock = localClock(now, settings.timeZone);
|
|
164
|
+
const today = dayOf(now);
|
|
165
|
+
const urgent = urgentMatters(store, today);
|
|
166
|
+
let state = store.get(STATE_KEY);
|
|
167
|
+
if (state === undefined) {
|
|
168
|
+
// First look: what is already on the board is not news, and a brief whose time has passed waits for tomorrow.
|
|
169
|
+
state = { sent: Object.fromEntries(urgent.map(m => [urgentKey(m), now])) };
|
|
170
|
+
if (clock.minutes >= minutesOf(settings.brief.time))
|
|
171
|
+
state.briefDay = clock.day;
|
|
172
|
+
store.set(STATE_KEY, state);
|
|
173
|
+
return [];
|
|
174
|
+
}
|
|
175
|
+
const reports = [];
|
|
176
|
+
if (!inQuiet(clock.minutes, settings.quiet)) {
|
|
177
|
+
const fresh = settings.urgent ? urgent.filter(m => state.sent[urgentKey(m)] === undefined) : [];
|
|
178
|
+
if (fresh.length > 0) {
|
|
179
|
+
reports.push(await deliver(store, channels, urgentMessage(fresh, lang), fresh.length, now));
|
|
180
|
+
for (const m of fresh)
|
|
181
|
+
state.sent[urgentKey(m)] = now;
|
|
182
|
+
}
|
|
183
|
+
if (settings.brief.enabled && state.briefDay !== clock.day && clock.minutes >= minutesOf(settings.brief.time)) {
|
|
184
|
+
state.briefDay = clock.day;
|
|
185
|
+
const board = options.board();
|
|
186
|
+
const message = briefMessage(board, lang);
|
|
187
|
+
if (message !== undefined)
|
|
188
|
+
reports.push(await deliver(store, channels, message, board.columns.handle.length, now));
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
// Forget what was sent for items closed a week ago.
|
|
192
|
+
const open = new Set(urgent.map(urgentKey));
|
|
193
|
+
for (const [key, at] of Object.entries(state.sent))
|
|
194
|
+
if (!open.has(key) && now - at > 7 * 86_400_000)
|
|
195
|
+
delete state.sent[key];
|
|
196
|
+
store.set(STATE_KEY, state);
|
|
197
|
+
return reports;
|
|
198
|
+
}
|
package/lib/core/restart.js
CHANGED
|
@@ -15,14 +15,19 @@
|
|
|
15
15
|
* Windows `taskkill /PID` without /F (a close request), then the app again
|
|
16
16
|
* Linux SIGTERM to the app, then the app again
|
|
17
17
|
*
|
|
18
|
+
* On a server set up with dsh-vps, DSH is a child of the dsh-gate login
|
|
19
|
+
* gateway (`$GATE_HOME/gate/server.js`, run by systemd), which starts DSH
|
|
20
|
+
* again whenever it exits and picks up the new sign-in token itself. There
|
|
21
|
+
* a restart is simply DSH exiting cleanly; the page reconnects.
|
|
22
|
+
*
|
|
18
23
|
* DSH started with the `dsh` command is not restarted from here: its web
|
|
19
24
|
* address (with a new sign-in token) is printed in that terminal, which a
|
|
20
25
|
* detached replacement could not reach. The page says what to do instead.
|
|
21
26
|
*/
|
|
22
27
|
import { execFileSync, spawn } from 'node:child_process';
|
|
23
|
-
import { readlinkSync } from 'node:fs';
|
|
28
|
+
import { readFileSync, readlinkSync } from 'node:fs';
|
|
24
29
|
import { tmpdir } from 'node:os';
|
|
25
|
-
import { join } from 'node:path';
|
|
30
|
+
import { join, posix } from 'node:path';
|
|
26
31
|
import { findProgram } from "./exec.js";
|
|
27
32
|
import { bi } from "./i18n.js";
|
|
28
33
|
/** `<x>.app` holding a macOS executable, if any. */
|
|
@@ -52,8 +57,21 @@ function bundleIdOf(app) {
|
|
|
52
57
|
return undefined;
|
|
53
58
|
}
|
|
54
59
|
}
|
|
60
|
+
function parentArguments(ppid) {
|
|
61
|
+
try {
|
|
62
|
+
return readFileSync(`/proc/${ppid}/cmdline`, 'utf8').split('\0').filter(Boolean);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
55
68
|
function here() {
|
|
56
|
-
const facts = {
|
|
69
|
+
const facts = {
|
|
70
|
+
env: process.env, platform: process.platform, execPath: process.execPath, ppid: process.ppid, electron: process.versions.electron,
|
|
71
|
+
parentExe: undefined, bundleId: undefined, parentArgs: undefined,
|
|
72
|
+
};
|
|
73
|
+
if (facts.platform === 'linux' && facts.env.GATE_HOME !== undefined)
|
|
74
|
+
facts.parentArgs = parentArguments(facts.ppid);
|
|
57
75
|
if (facts.electron === undefined || facts.env.ELECTRON_RUN_AS_NODE !== '1' || facts.ppid <= 1)
|
|
58
76
|
return facts;
|
|
59
77
|
facts.parentExe = parentExecutable(facts.ppid, facts.platform);
|
|
@@ -68,6 +86,13 @@ function samePath(a, b, platform) {
|
|
|
68
86
|
const FROM_TERMINAL = bi('这个 DSH 是用 dsh 命令启动的,小秘书没法替它重启:回到运行 dsh 的那个终端按 Ctrl+C,再运行同一条命令。', 'This DSH was started with the dsh command, so the secretary cannot restart it: press Ctrl+C in the terminal running dsh, then run the same command again.');
|
|
69
87
|
/** How DSH can be restarted from here, or why it cannot. */
|
|
70
88
|
export function restartPlan(facts = here()) {
|
|
89
|
+
// dsh-vps: the parent must be that very gateway, not just a shell that has GATE_HOME set.
|
|
90
|
+
const gateHome = facts.env.GATE_HOME;
|
|
91
|
+
if (gateHome !== undefined && gateHome !== '') {
|
|
92
|
+
const gate = posix.join(gateHome, 'gate', 'server.js');
|
|
93
|
+
if (facts.parentArgs?.includes(gate) === true)
|
|
94
|
+
return { kind: 'gate', gate };
|
|
95
|
+
}
|
|
71
96
|
const desktop = facts.electron !== undefined && facts.env.ELECTRON_RUN_AS_NODE === '1' && facts.ppid > 1 && samePath(facts.parentExe, facts.execPath, facts.platform);
|
|
72
97
|
if (!desktop)
|
|
73
98
|
return { kind: 'none', why: FROM_TERMINAL };
|
|
@@ -140,8 +165,13 @@ export function restartHelperSource(plan, log, tools = MAC_TOOLS) {
|
|
|
140
165
|
"main().catch(e => note('helper failed: ' + (e && e.stack || e)))",
|
|
141
166
|
].join('\n');
|
|
142
167
|
}
|
|
143
|
-
/** Start the helper and
|
|
144
|
-
export function scheduleRestart(plan) {
|
|
168
|
+
/** Start the restart: under dsh-gate, exit; in the desktop app, start the helper and say where it logs. Runs with this process's Node (Electron as Node in the app). */
|
|
169
|
+
export function scheduleRestart(plan, exit = () => process.kill(process.pid, 'SIGTERM')) {
|
|
170
|
+
if (plan.kind === 'gate') {
|
|
171
|
+
// Let the page receive its answer, then leave the normal way; the gateway starts DSH again.
|
|
172
|
+
setTimeout(exit, 400);
|
|
173
|
+
return { reconnect: true };
|
|
174
|
+
}
|
|
145
175
|
const log = join(tmpdir(), `dsh-mishu-restart-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.log`);
|
|
146
176
|
const helper = spawn(process.execPath, ['-e', restartHelperSource(plan, log)], { detached: true, stdio: 'ignore', env: process.env, windowsHide: true });
|
|
147
177
|
helper.unref();
|
package/lib/core/secrets.js
CHANGED
|
@@ -7,9 +7,17 @@
|
|
|
7
7
|
*
|
|
8
8
|
* Secrets travel to the helper on stdin only, never as command-line
|
|
9
9
|
* arguments, which other processes on the machine could read. Everything is
|
|
10
|
-
* stored under the service name "dsh-mishu".
|
|
11
|
-
*
|
|
10
|
+
* stored under the service name "dsh-mishu".
|
|
11
|
+
*
|
|
12
|
+
* A computer without a usable keychain (a Linux server with no desktop,
|
|
13
|
+
* say) keeps them in `secrets.json` in the notebook directory instead:
|
|
14
|
+
* mode 600, so only your own system account can read it. That is how gh,
|
|
15
|
+
* git and Thunderbird manage on such machines, and it is said plainly on
|
|
16
|
+
* the settings page: protected by file permissions, not encrypted.
|
|
17
|
+
* `secretFromEnv` remains a last resort.
|
|
12
18
|
*/
|
|
19
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
20
|
+
import { dirname } from 'node:path';
|
|
13
21
|
import { findProgram, runProgram } from "./exec.js";
|
|
14
22
|
import { bi } from "./i18n.js";
|
|
15
23
|
export const SERVICE = 'dsh-mishu';
|
|
@@ -168,3 +176,95 @@ export function secretFromEnv(account) {
|
|
|
168
176
|
const value = process.env[secretEnvName(account)];
|
|
169
177
|
return value === undefined || value === '' ? undefined : value;
|
|
170
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* Secrets in one JSON file, readable by your system account only (600).
|
|
181
|
+
* Written to a temporary file first and renamed, so a crash never leaves
|
|
182
|
+
* half a file; a file that cannot be read is never overwritten.
|
|
183
|
+
*/
|
|
184
|
+
export class FileSecrets {
|
|
185
|
+
kind = 'file';
|
|
186
|
+
path;
|
|
187
|
+
constructor(path) { this.path = path; }
|
|
188
|
+
async status() { return { available: true }; }
|
|
189
|
+
read() {
|
|
190
|
+
if (!existsSync(this.path))
|
|
191
|
+
return {};
|
|
192
|
+
// Put the permissions back if something loosened them.
|
|
193
|
+
if (process.platform !== 'win32' && (statSync(this.path).mode & 0o077) !== 0)
|
|
194
|
+
chmodSync(this.path, 0o600);
|
|
195
|
+
let parsed;
|
|
196
|
+
try {
|
|
197
|
+
parsed = JSON.parse(readFileSync(this.path, 'utf8'));
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
throw new Error(`${this.path} cannot be read (${error.message}); fix or remove it`);
|
|
201
|
+
}
|
|
202
|
+
const secrets = parsed.secrets;
|
|
203
|
+
return typeof secrets === 'object' && secrets !== null ? { ...secrets } : {};
|
|
204
|
+
}
|
|
205
|
+
write(secrets) {
|
|
206
|
+
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
207
|
+
const temp = `${this.path}.${process.pid}.tmp`;
|
|
208
|
+
writeFileSync(temp, `${JSON.stringify({ version: 1, secrets }, null, 2)}\n`, { mode: 0o600 });
|
|
209
|
+
renameSync(temp, this.path);
|
|
210
|
+
}
|
|
211
|
+
async get(account) { return this.read()[account]; }
|
|
212
|
+
async set(account, secret) {
|
|
213
|
+
checkAccount(account);
|
|
214
|
+
checkSecret(secret);
|
|
215
|
+
this.write({ ...this.read(), [account]: secret });
|
|
216
|
+
}
|
|
217
|
+
async delete(account) {
|
|
218
|
+
const secrets = this.read();
|
|
219
|
+
if (!(account in secrets))
|
|
220
|
+
return;
|
|
221
|
+
delete secrets[account];
|
|
222
|
+
this.write(secrets);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* The keychain when it works, else the file. Reads look in both, so a
|
|
227
|
+
* secret saved to the file before a keychain was set up is still found;
|
|
228
|
+
* saving to the keychain removes the file's copy.
|
|
229
|
+
*/
|
|
230
|
+
export class KeychainOrFile {
|
|
231
|
+
keychain;
|
|
232
|
+
file;
|
|
233
|
+
usable;
|
|
234
|
+
constructor(keychain, file) {
|
|
235
|
+
this.keychain = keychain;
|
|
236
|
+
this.file = file;
|
|
237
|
+
}
|
|
238
|
+
get kind() { return this.keychain.kind; }
|
|
239
|
+
keychainStatus() {
|
|
240
|
+
// Asked once per run: a missing helper does not appear while DSH runs.
|
|
241
|
+
this.usable ??= this.keychain.status().catch((error) => ({ available: false, why: bi(error.message, error.message) }));
|
|
242
|
+
return this.usable;
|
|
243
|
+
}
|
|
244
|
+
async status() {
|
|
245
|
+
const keychain = await this.keychainStatus();
|
|
246
|
+
return keychain.available ? keychain : { available: true, file: { path: this.file.path, why: keychain.why } };
|
|
247
|
+
}
|
|
248
|
+
async get(account) {
|
|
249
|
+
if ((await this.keychainStatus()).available) {
|
|
250
|
+
const stored = await this.keychain.get(account);
|
|
251
|
+
if (stored !== undefined)
|
|
252
|
+
return stored;
|
|
253
|
+
}
|
|
254
|
+
return this.file.get(account);
|
|
255
|
+
}
|
|
256
|
+
async set(account, secret) {
|
|
257
|
+
if ((await this.keychainStatus()).available) {
|
|
258
|
+
await this.keychain.set(account, secret);
|
|
259
|
+
await this.file.delete(account);
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
await this.file.set(account, secret);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async delete(account) {
|
|
266
|
+
if ((await this.keychainStatus()).available)
|
|
267
|
+
await this.keychain.delete(account);
|
|
268
|
+
await this.file.delete(account);
|
|
269
|
+
}
|
|
270
|
+
}
|
package/lib/core/settings.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* password goes to the system keychain (see secrets.ts), never here.
|
|
7
7
|
*/
|
|
8
8
|
import { MishuError, bi } from "./i18n.js";
|
|
9
|
-
import { resolveAccount, secretAccount } from "./mail/account.js";
|
|
9
|
+
import { normalizePassword, resolveAccount, secretAccount } from "./mail/account.js";
|
|
10
10
|
import { MAIL_SOURCE } from "./mail/sync.js";
|
|
11
11
|
import { CATEGORIES } from "./recur.js";
|
|
12
12
|
import { secretFromEnv } from "./secrets.js";
|
|
@@ -70,7 +70,7 @@ export async function saveMailAccount(store, secrets, input, password, now) {
|
|
|
70
70
|
const account = resolveAccount({ ...existing, ...input }, id);
|
|
71
71
|
const keychain = (await secrets.status()).available;
|
|
72
72
|
if (keychain && password !== undefined && password !== '')
|
|
73
|
-
await secrets.set(secretAccount(id), password);
|
|
73
|
+
await secrets.set(secretAccount(id), normalizePassword(account.preset, password));
|
|
74
74
|
else if (keychain && existing === undefined && await secrets.get(secretAccount(id)) === undefined && secretFromEnv(secretAccount(id)) === undefined) {
|
|
75
75
|
throw new MishuError(bi('新邮箱要填密码(授权码)', 'a new account needs its password (app password)'));
|
|
76
76
|
}
|
package/lib/dsh/api.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* travel inward: they go straight to the keychain, and no endpoint ever
|
|
10
10
|
* returns one.
|
|
11
11
|
*/
|
|
12
|
-
import { addDays, addSeries, bi, buildAsk, buildBoard, buildDetail, dayOf, deleteGithubToken, deleteMailAccount, describeMailError, MishuError, describeSeries, detectLang, errorText, GitHubClient, MAIL_PRESETS, mailReportKey, NEW_TOKEN_URL, resolveSeries, saveGithubToken, saveMailAccount, saveSettings, secretAccount, secretEnvName, setStatusByUser, snoozeByUser, stopSeries, tickManual, } from "../core/index.js";
|
|
12
|
+
import { addDays, addSeries, bi, deleteFeishu, deliver, FEISHU_WEBHOOK, notifySettings, NOTIFY_REPORT_KEY, saveFeishu, saveNotifySettings, testMessage, buildAsk, buildBoard, buildDetail, dayOf, deleteGithubToken, deleteMailAccount, describeMailError, MishuError, describeSeries, detectLang, errorText, GitHubClient, MAIL_PRESETS, mailReportKey, NEW_TOKEN_URL, normalizePassword, providerMismatch, resolveSeries, saveGithubToken, saveMailAccount, saveSettings, secretAccount, secretEnvName, setStatusByUser, snoozeByUser, stopSeries, tickManual, } from "../core/index.js";
|
|
13
13
|
import { resolveAccount } from "../core/mail/account.js";
|
|
14
14
|
export const API_BASE = '/api/dsh-mishu';
|
|
15
15
|
class ApiError extends Error {
|
|
@@ -88,6 +88,7 @@ export function apiHandlers(runtime, clock = Date.now) {
|
|
|
88
88
|
...a,
|
|
89
89
|
hasPassword: (await runtime.mailPassword(a.id)) !== undefined,
|
|
90
90
|
envName: secretEnvName(secretAccount(a.id)),
|
|
91
|
+
mismatch: providerMismatch(a)?.[lang] ?? null,
|
|
91
92
|
report: store.get(mailReportKey(a.id)) ?? null,
|
|
92
93
|
})));
|
|
93
94
|
return {
|
|
@@ -97,11 +98,30 @@ export function apiHandlers(runtime, clock = Date.now) {
|
|
|
97
98
|
tokenEnv: runtime.config.github.tokenEnv,
|
|
98
99
|
token: 'error' in token ? { found: false, text: token.error[lang] } : { found: true, from: token.from },
|
|
99
100
|
newTokenUrl: NEW_TOKEN_URL,
|
|
101
|
+
deviceLogin: runtime.config.github.clientId !== '',
|
|
100
102
|
lastSync: store.get('github.lastSync') ?? null,
|
|
101
103
|
},
|
|
102
|
-
secrets: {
|
|
104
|
+
secrets: {
|
|
105
|
+
kind: runtime.secrets.kind,
|
|
106
|
+
available: secrets.available,
|
|
107
|
+
...secrets.available ? {} : { why: secrets.why[lang] },
|
|
108
|
+
...secrets.available && secrets.file !== undefined ? { file: { path: secrets.file.path, why: secrets.file.why[lang] } } : {},
|
|
109
|
+
},
|
|
103
110
|
accounts,
|
|
104
|
-
|
|
111
|
+
notify: {
|
|
112
|
+
settings: notifySettings(store),
|
|
113
|
+
channels: await Promise.all(['desktop', 'feishu'].map(async (id) => {
|
|
114
|
+
const status = await runtime.channels[id].status();
|
|
115
|
+
return { id, enabled: notifySettings(store).channels[id], available: status.available, ...status.available ? {} : { why: status.why[lang] } };
|
|
116
|
+
})),
|
|
117
|
+
feishu: { configured: (await runtime.secrets.get(FEISHU_WEBHOOK).catch(() => undefined)) !== undefined },
|
|
118
|
+
last: store.get(NOTIFY_REPORT_KEY) ?? null,
|
|
119
|
+
},
|
|
120
|
+
presets: MAIL_PRESETS.map(p => ({
|
|
121
|
+
id: p.id, label: p.label[lang], host: p.host, port: p.port, secure: p.secure, supported: p.supported, howTo: p.howTo[lang],
|
|
122
|
+
domains: p.domains, passwordLength: p.passwordLength ?? null,
|
|
123
|
+
steps: p.steps.map(step => ({ text: step.text[lang], ...step.link === undefined ? {} : { link: { url: step.link.url, label: step.link.label[lang] } } })),
|
|
124
|
+
})),
|
|
105
125
|
};
|
|
106
126
|
};
|
|
107
127
|
return {
|
|
@@ -208,10 +228,58 @@ export function apiHandlers(runtime, clock = Date.now) {
|
|
|
208
228
|
const { login } = await saveGithubToken(runtime.secrets, typeof body.token === 'string' ? body.token : '');
|
|
209
229
|
return { login, view: await settingsView(lang) };
|
|
210
230
|
},
|
|
231
|
+
/** "Sign in with GitHub": a code to enter on github.com; the host waits for your approval. */
|
|
232
|
+
'/github/device/start': async (body) => ({ login: deviceView(await runtime.githubLogin.start(), langOf(body)) }),
|
|
233
|
+
'/github/device/status': async (body) => {
|
|
234
|
+
const lang = langOf(body);
|
|
235
|
+
const state = runtime.githubLogin.status();
|
|
236
|
+
return { login: deviceView(state, lang), ...state.state === 'done' ? { view: await settingsView(lang) } : {} };
|
|
237
|
+
},
|
|
238
|
+
'/github/device/cancel': async (body) => {
|
|
239
|
+
runtime.githubLogin.cancel();
|
|
240
|
+
return { login: deviceView(runtime.githubLogin.status(), langOf(body)) };
|
|
241
|
+
},
|
|
211
242
|
'/github/token/delete': async (body) => {
|
|
212
243
|
await deleteGithubToken(runtime.secrets);
|
|
213
244
|
return { view: await settingsView(langOf(body)) };
|
|
214
245
|
},
|
|
246
|
+
// ── reminders ─────────────────────────────────────────
|
|
247
|
+
'/notify/save': async (body) => {
|
|
248
|
+
const lang = langOf(body);
|
|
249
|
+
saveNotifySettings(need(lang), (body.notify ?? {}), clock());
|
|
250
|
+
return { view: await settingsView(lang) };
|
|
251
|
+
},
|
|
252
|
+
/** One test message through one channel, turned on or not. */
|
|
253
|
+
'/notify/test': async (body) => {
|
|
254
|
+
const lang = langOf(body);
|
|
255
|
+
const id = String(body.channel);
|
|
256
|
+
const channel = runtime.channels[id];
|
|
257
|
+
if (channel === undefined)
|
|
258
|
+
throw new ApiError(lang === 'zh' ? '没有这个渠道' : 'No such channel');
|
|
259
|
+
const status = await channel.status();
|
|
260
|
+
if (!status.available)
|
|
261
|
+
throw new ApiError(status.why[lang]);
|
|
262
|
+
const report = await deliver(need(lang), [channel], testMessage(lang), 0, clock());
|
|
263
|
+
const failed = report.results.find(r => !r.ok);
|
|
264
|
+
if (failed !== undefined)
|
|
265
|
+
throw new ApiError(failed.error ?? '');
|
|
266
|
+
return { sent: true };
|
|
267
|
+
},
|
|
268
|
+
/** A Feishu bot: tried with a first message, then kept as a secret; reminders go there from now on. */
|
|
269
|
+
'/feishu/save': async (body) => {
|
|
270
|
+
const lang = langOf(body);
|
|
271
|
+
const store = need(lang);
|
|
272
|
+
await saveFeishu(runtime.secrets, { webhook: String(body.webhook ?? ''), ...typeof body.secret === 'string' ? { secret: body.secret } : {} }, lang);
|
|
273
|
+
saveNotifySettings(store, { channels: { ...notifySettings(store).channels, feishu: true } }, clock());
|
|
274
|
+
return { view: await settingsView(lang) };
|
|
275
|
+
},
|
|
276
|
+
'/feishu/delete': async (body) => {
|
|
277
|
+
const lang = langOf(body);
|
|
278
|
+
const store = need(lang);
|
|
279
|
+
await deleteFeishu(runtime.secrets);
|
|
280
|
+
saveNotifySettings(store, { channels: { ...notifySettings(store).channels, feishu: false } }, clock());
|
|
281
|
+
return { view: await settingsView(lang) };
|
|
282
|
+
},
|
|
215
283
|
'/mail/save': async (body) => {
|
|
216
284
|
const lang = langOf(body);
|
|
217
285
|
const account = await saveMailAccount(need(lang), runtime.secrets, accountInput(body.account), password(body), clock());
|
|
@@ -222,7 +290,8 @@ export function apiHandlers(runtime, clock = Date.now) {
|
|
|
222
290
|
const lang = langOf(body);
|
|
223
291
|
const input = accountInput(body.account);
|
|
224
292
|
const draft = resolveAccount(input, input.id ?? 0);
|
|
225
|
-
const
|
|
293
|
+
const typed = password(body);
|
|
294
|
+
const secret = typed !== undefined ? normalizePassword(draft.preset, typed) : input.id === undefined ? undefined : await runtime.mailPassword(input.id);
|
|
226
295
|
if (secret === undefined)
|
|
227
296
|
throw new ApiError(lang === 'zh' ? '先填密码(授权码)再测试' : 'Enter the password (app password) first');
|
|
228
297
|
try {
|
|
@@ -230,7 +299,8 @@ export function apiHandlers(runtime, clock = Date.now) {
|
|
|
230
299
|
return { unread: messages.length };
|
|
231
300
|
}
|
|
232
301
|
catch (error) {
|
|
233
|
-
|
|
302
|
+
// The dialog shows the provider's steps already; the error only says what went wrong.
|
|
303
|
+
throw new MishuError(describeMailError(error, draft, { steps: false }));
|
|
234
304
|
}
|
|
235
305
|
},
|
|
236
306
|
'/mail/delete': async (body) => {
|
|
@@ -249,8 +319,7 @@ export function apiHandlers(runtime, clock = Date.now) {
|
|
|
249
319
|
const plan = runtime.restarter.plan();
|
|
250
320
|
if (plan.kind === 'none')
|
|
251
321
|
throw new ApiError(plan.why[langOf(body)]);
|
|
252
|
-
|
|
253
|
-
return { restarting: true, log };
|
|
322
|
+
return { restarting: true, ...runtime.restarter.schedule(plan) };
|
|
254
323
|
},
|
|
255
324
|
'/mail/sync': async (body) => {
|
|
256
325
|
const lang = langOf(body);
|
|
@@ -262,6 +331,10 @@ export function apiHandlers(runtime, clock = Date.now) {
|
|
|
262
331
|
},
|
|
263
332
|
};
|
|
264
333
|
}
|
|
334
|
+
/** The page's view of a sign-in: messages in its language. */
|
|
335
|
+
function deviceView(state, lang) {
|
|
336
|
+
return state.state === 'failed' ? { state: 'failed', message: state.message[lang] } : { ...state };
|
|
337
|
+
}
|
|
265
338
|
/** Run one handler; failures become `{ ok: false, message }` in the caller's language. */
|
|
266
339
|
export async function handle(handler, request, fixedLang) {
|
|
267
340
|
let body = {};
|
package/lib/dsh/config.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import Schema from '@deepseek-ai/schemastery';
|
|
2
|
-
import { CLOSING_REASONS, DEFAULT_HOME, DEFAULT_LEAD_DAYS } from "../core/index.js";
|
|
2
|
+
import { CLOSING_REASONS, DEFAULT_HOME, GITHUB_CLIENT_ID, DEFAULT_LEAD_DAYS } from "../core/index.js";
|
|
3
3
|
export const Config = Schema.object({
|
|
4
4
|
home: Schema.string().default(DEFAULT_HOME).description('Notebook directory (mishu.db)'),
|
|
5
5
|
language: Schema.union(['auto', 'zh', 'en']).default('auto').description('Language: auto (system locale), zh (中文) or en (English)'),
|
|
@@ -8,6 +8,7 @@ export const Config = Schema.object({
|
|
|
8
8
|
intervalMinutes: Schema.natural().min(5).default(15).description('Minutes between GitHub syncs'),
|
|
9
9
|
tokenEnv: Schema.string().default('GITHUB_TOKEN').description('Environment variable with a GitHub token'),
|
|
10
10
|
useGhCli: Schema.boolean().default(true).description('Fall back to `gh auth token`'),
|
|
11
|
+
clientId: Schema.string().default(GITHUB_CLIENT_ID).description('GitHub OAuth App client id for "Sign in with GitHub" (device flow)'),
|
|
11
12
|
markRead: Schema.union(['off', 'shadow', 'on']).default('shadow').description('Mark resolved notifications read on GitHub: off / shadow (only record) / on'),
|
|
12
13
|
markReadReasons: Schema.array(Schema.union([...CLOSING_REASONS])).default(['merged', 'closed', 'recovered', 'superseded', 'ref-gone'])
|
|
13
14
|
.description('Closing reasons allowed to mark read'),
|
package/lib/dsh/plugin.js
CHANGED
|
@@ -64,12 +64,16 @@ export function apply(ctx, config, runtime = new Runtime(config, ctx.logger)) {
|
|
|
64
64
|
firstSync.unref();
|
|
65
65
|
const syncTimer = setInterval(() => { void runtime.syncAll(); }, config.github.intervalMinutes * 60_000);
|
|
66
66
|
syncTimer.unref();
|
|
67
|
+
// Reminders look at the clock every minute: the brief's time, the end of quiet hours.
|
|
68
|
+
const notifyTimer = setInterval(() => { void runtime.notify(); }, 60_000);
|
|
69
|
+
notifyTimer.unref();
|
|
67
70
|
const settings = runtime.settings();
|
|
68
71
|
ctx.logger.info(`dsh-mishu: notebook ${paths.db}; language ${runtime.lang()}; github ${settings.githubEnabled ? `every ${config.github.intervalMinutes} min, mark read ${settings.markRead}` : 'off'}; ${runtime.accounts().length} mail account(s); secrets in ${runtime.secrets.kind}`);
|
|
69
72
|
return async () => {
|
|
70
73
|
clearInterval(tickTimer);
|
|
71
74
|
clearTimeout(firstSync);
|
|
72
75
|
clearInterval(syncTimer);
|
|
76
|
+
clearInterval(notifyTimer);
|
|
73
77
|
await Promise.race([runtime.idle(), new Promise(resolve => setTimeout(resolve, 5000).unref())]);
|
|
74
78
|
opened.close();
|
|
75
79
|
runtime.store = undefined;
|