@quecue/dev-notify 0.0.0-stage → 0.1.0-alpha.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/dist/setup.js ADDED
@@ -0,0 +1,250 @@
1
+ import { readFile, mkdir, open, rename, unlink } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { ConfigError, decodeUtf8, example, parseConfig } from './config.js';
5
+ import { encodeBundle, nativeStore } from './credentials.js';
6
+ import { terminalPrompts } from './prompts.js';
7
+ const yes = (text) => /^(y|yes)$/i.test(text.trim());
8
+ export async function snapshot(file) {
9
+ try {
10
+ return await readFile(file);
11
+ }
12
+ catch (error) {
13
+ if (error.code === 'ENOENT')
14
+ return null;
15
+ throw new ConfigError('无法读取现有配置,未修改');
16
+ }
17
+ }
18
+ function same(left, right) { return left === null ? right === null : right !== null && left.equals(right); }
19
+ export function readRaw(raw) {
20
+ if (raw === null)
21
+ return structuredClone(example);
22
+ let data;
23
+ try {
24
+ data = JSON.parse(decodeUtf8(raw));
25
+ }
26
+ catch {
27
+ throw new ConfigError('现有配置损坏,未覆盖;请先修复 JSON');
28
+ }
29
+ parseConfig(data, {}, () => ({}));
30
+ return data;
31
+ }
32
+ async function removeFile(file) {
33
+ try {
34
+ await unlink(file);
35
+ }
36
+ catch (error) {
37
+ if (error.code !== 'ENOENT')
38
+ throw error;
39
+ }
40
+ }
41
+ export async function commitConfig(file, data, expected, store, values, options = {}) {
42
+ const warn = options.warn ?? (text => console.error(text));
43
+ const target = structuredClone(data);
44
+ const old = target.credentials;
45
+ const id = randomBytes(16).toString('hex');
46
+ if (values !== null) {
47
+ encodeBundle(values);
48
+ target.credentials = { backend: 'keyring', id };
49
+ parseConfig(target, {}, () => values);
50
+ }
51
+ else {
52
+ delete target.credentials;
53
+ parseConfig(target, {});
54
+ }
55
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
56
+ const lockPath = file + '.setup.lock';
57
+ let lock;
58
+ try {
59
+ lock = await open(lockPath, 'wx', 0o600);
60
+ }
61
+ catch {
62
+ throw new ConfigError('配置写入锁不可用;请检查权限,或确认没有运行中的向导后处理残留 .setup.lock');
63
+ }
64
+ const temporary = path.join(path.dirname(file), `.config-${id}.tmp`);
65
+ let created = false, committed = false, tempCreated = false;
66
+ try {
67
+ await lock.close();
68
+ if (!same(await snapshot(file), expected))
69
+ throw new ConfigError('配置在向导期间已变化,未覆盖,请重试');
70
+ if (values !== null) {
71
+ store.create(id, values);
72
+ created = true;
73
+ const check = store.read(id);
74
+ if (check === null || JSON.stringify(check) !== JSON.stringify(values))
75
+ throw new ConfigError('凭据写入校验失败,未切换配置');
76
+ }
77
+ const stream = await open(temporary, 'wx', 0o600);
78
+ tempCreated = true;
79
+ try {
80
+ await stream.writeFile(JSON.stringify(target, null, 2) + '\n', 'utf8');
81
+ await stream.sync();
82
+ }
83
+ finally {
84
+ await stream.close();
85
+ }
86
+ if (!same(await snapshot(file), expected))
87
+ throw new ConfigError('配置在保存期间已变化,未覆盖,请重试');
88
+ await (options.replace ?? rename)(temporary, file);
89
+ committed = true;
90
+ }
91
+ finally {
92
+ if (tempCreated) {
93
+ try {
94
+ await removeFile(temporary);
95
+ }
96
+ catch {
97
+ warn(`临时配置清理失败:${path.basename(temporary)}`);
98
+ }
99
+ }
100
+ if (created && !committed) {
101
+ try {
102
+ store.remove(id);
103
+ }
104
+ catch {
105
+ warn(`配置未切换,但新凭据清理失败;引用 ID:${id}`);
106
+ }
107
+ }
108
+ try {
109
+ await removeFile(lockPath);
110
+ }
111
+ catch {
112
+ warn('配置写入锁清理失败,请确认没有向导运行后处理 .setup.lock');
113
+ }
114
+ }
115
+ if (old?.backend === 'keyring') {
116
+ try {
117
+ store.remove(old.id);
118
+ }
119
+ catch {
120
+ warn(`配置已保存,但旧凭据清理失败;引用 ID:${old.id}`);
121
+ }
122
+ }
123
+ else if (old?.backend === 'system') {
124
+ warn('Python 原型旧凭据未删除;仍由原型管理,避免跨实现误删');
125
+ }
126
+ }
127
+ export async function wizard(file, options = {}) {
128
+ const prompts = options.prompts ?? terminalPrompts();
129
+ const before = await snapshot(file), data = readRaw(before);
130
+ const { out } = prompts;
131
+ out(`配置路径:${file}`);
132
+ out('密钥隐藏输入并存入 Windows Credential Manager / macOS Keychain;JSON 只保存引用。');
133
+ out('不安装 hooks,不启用远程控制;只有额外同意测试时才发送消息。');
134
+ if (before && !yes(await prompts.text('已有配置,继续编辑?[y/N] ')))
135
+ return false;
136
+ const selection = await prompts.text('选择渠道:1 Telegram,2 飞书,3 两者;其他输入取消:');
137
+ if (!['1', '2', '3'].includes(selection))
138
+ return false;
139
+ const store = options.store ?? nativeStore();
140
+ let previous = {};
141
+ const reference = data.credentials;
142
+ if (reference?.backend === 'keyring') {
143
+ try {
144
+ const existing = store.read(reference.id);
145
+ if (!existing)
146
+ throw new Error();
147
+ previous = existing;
148
+ }
149
+ catch {
150
+ out('原凭据无法读取,可能缺失、锁定或权限不足。');
151
+ if (!yes(await prompts.text('放弃旧值,重新输入所选渠道凭据?[y/N] ')))
152
+ return false;
153
+ }
154
+ }
155
+ else if (reference?.backend === 'system')
156
+ out('检测到 Python 原型凭据;本次重新输入保存,旧凭据不读取、不删除。');
157
+ data.telegram ??= {};
158
+ data.feishu ??= {};
159
+ data.telegram.enabled = selection !== '2';
160
+ data.feishu.enabled = selection !== '1';
161
+ const values = {};
162
+ const readValue = async (label, key, required) => {
163
+ while (true) {
164
+ const hint = previous[key] ? '留空保留已存值' : '不从环境变量自动复制';
165
+ const answer = await prompts.secret(`${label}(${hint}${required ? '' : ';输入 - 清除'}):`);
166
+ const value = !required && answer === '-' ? '' : answer || previous[key] || '';
167
+ if (required && !value) {
168
+ out('此项不能为空,请重试,或 Ctrl+C 取消。');
169
+ continue;
170
+ }
171
+ try {
172
+ const check = { telegram: { enabled: key === 'telegram_token', chat_ids: ['1'] },
173
+ feishu: { enabled: key !== 'telegram_token' }, credentials: { backend: 'keyring', id: '0'.repeat(32) } };
174
+ parseConfig(check, {}, () => ({ [key]: value }));
175
+ return value;
176
+ }
177
+ catch {
178
+ out('格式不正确,请检查后重新输入;不会显示秘密。');
179
+ }
180
+ }
181
+ };
182
+ if (data.telegram.enabled) {
183
+ values.telegram_token = await readValue('Telegram Bot Token', 'telegram_token', true);
184
+ out('接收人需要先启动 Bot;本轮手动填写数字 chat_id,不启动 getUpdates 或自动配对。');
185
+ while (true) {
186
+ const entered = await prompts.text('接收人 chat_id,多个用逗号分隔(留空保留原名单):');
187
+ const ids = entered ? entered.split(',').map(item => item.trim()) : data.telegram.chat_ids ?? [];
188
+ try {
189
+ if (!ids.length)
190
+ throw new Error();
191
+ const check = parseConfig({ telegram: { chat_ids: ids } }, {});
192
+ data.telegram.chat_ids = check.telegram.chatIds;
193
+ break;
194
+ }
195
+ catch {
196
+ out('请填写至少一个有效数字 chat_id,或 Ctrl+C 取消。');
197
+ }
198
+ }
199
+ }
200
+ if (data.feishu.enabled) {
201
+ values.feishu_webhook = await readValue('飞书 webhook', 'feishu_webhook', true);
202
+ values.feishu_secret = await readValue('飞书签名密钥(可选)', 'feishu_secret', false);
203
+ }
204
+ encodeBundle(values);
205
+ const preview = { ...data, credentials: { backend: 'keyring', id: '0'.repeat(32) } };
206
+ parseConfig(preview, {}, () => values);
207
+ const env = options.env ?? process.env;
208
+ out(`将启用:${data.telegram.enabled ? `Telegram(${data.telegram.chat_ids.length} 个接收人)` : ''}${data.feishu.enabled ? ' 飞书' : ''}`);
209
+ out('环境变量仍优先(含显式空值);测试通知会使用最终生效的配置,不一定是刚输入的值。');
210
+ const overrides = [data.telegram.token_env ?? 'TELEGRAM_BOT_TOKEN', data.feishu.webhook_env ?? 'FEISHU_WEBHOOK',
211
+ data.feishu.secret_env ?? 'FEISHU_SECRET', 'TELEGRAM_CHAT_ID', 'TELEGRAM_CHAT_IDS'].filter(name => Object.hasOwn(env, name));
212
+ if (overrides.length)
213
+ out('当前存在环境覆盖:' + overrides.join('、'));
214
+ if (reference?.backend === 'keyring')
215
+ out('保存成功后删除旧凭据;共享旧引用 ID 的配置副本也需更新。');
216
+ out('未选中的渠道会禁用;新条目只保存所选渠道凭据。');
217
+ if (!yes(await prompts.text('确认保存配置和系统凭据?[y/N] ')))
218
+ return false;
219
+ await commitConfig(file, data, before, store, values, { warn: out });
220
+ out('配置和系统凭据已保存。');
221
+ if (options.testSend && yes(await prompts.text('发送固定内容的测试通知到生效的接收目标?[y/N] '))) {
222
+ try {
223
+ const effective = parseConfig(preview, env, () => values);
224
+ const ok = await options.testSend(effective);
225
+ out(ok ? '测试通知发送成功。' : '配置已保存,但测试通知失败或没有可用渠道;请运行 doctor 检查。');
226
+ }
227
+ catch {
228
+ out('配置已保存,但环境覆盖或网络导致测试失败;请运行 doctor 检查。');
229
+ }
230
+ }
231
+ else
232
+ out('未发送测试通知。');
233
+ return true;
234
+ }
235
+ export async function clearCredentials(file, prompts, store) {
236
+ const before = await snapshot(file), data = readRaw(before);
237
+ const reference = data.credentials;
238
+ if (!reference) {
239
+ prompts.out('此配置没有系统凭据引用,未修改。');
240
+ return true;
241
+ }
242
+ if (reference.backend !== 'keyring')
243
+ throw new ConfigError('这是 Python 原型的凭据,Node 不执行跨实现删除');
244
+ prompts.out('将移除当前配置的系统凭据引用并删除其条目;环境变量不变,共享引用的配置副本将失效。');
245
+ if (!yes(await prompts.text('确认清除?[y/N] ')))
246
+ return false;
247
+ await commitConfig(file, data, before, store ?? nativeStore(), null, { warn: prompts.out });
248
+ prompts.out('凭据引用已移除;如删除条目失败,上方会显示警告。');
249
+ return true;
250
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@quecue/dev-notify",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "跨平台开发任务通知工具,支持 Telegram 与飞书",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.0.0"
9
+ },
10
+ "bin": {
11
+ "dev-notify": "dist/cli.js"
12
+ },
13
+ "files": [
14
+ "dist/*.js",
15
+ "README.md",
16
+ "SECURITY.md",
17
+ "LICENSE"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.json",
21
+ "test": "npm run build && node --test test-js/*.test.mjs",
22
+ "start": "node dist/cli.js",
23
+ "prepack": "npm run build"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^22.0.0",
27
+ "typescript": "^5.9.0"
28
+ },
29
+ "dependencies": {
30
+ "@napi-rs/keyring": "2.1.2"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "registry": "https://registry.npmjs.org/"
35
+ }
36
+ }