@auto-mas/auto-mas-plugin-notification-qqbot 0.0.0-stage → 0.1.0

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,2 @@
1
+ .management-panel{border:1px solid var(--line);background:var(--mas-surface);border-radius:13px;min-width:0;overflow:hidden}.management-heading{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px 18px;min-height:56px;padding:14px 18px;display:flex}.management-heading h2{font-size:16px}.management-heading .el-input{width:min(100%,17rem)}.management-heading-actions{flex-wrap:wrap;align-items:center;gap:8px;display:flex}.management-count{color:var(--muted);white-space:nowrap;font-size:12px}.management-empty{color:var(--muted);text-align:center;padding:26px 16px;font-size:13px;line-height:1.65}.management-error{width:auto;margin:0 16px 12px}.management-actions{flex-wrap:wrap;align-items:center;gap:8px 14px;display:flex}.management-actions .el-button{margin-left:0}.management-action{min-height:32px;color:var(--el-color-primary);justify-content:center;align-items:center;gap:5px;font-size:13px;font-weight:600;display:inline-flex}.management-action:hover{color:var(--el-color-primary-dark-2);text-decoration:underline}.management-action-primary{color:var(--mas-on-primary);background:var(--el-color-primary);border-radius:7px;padding:0 11px}.management-action-primary:hover{color:var(--mas-on-primary);background:var(--el-color-primary-dark-2);text-decoration:none}.management-status{flex:none}.management-log{white-space:pre-wrap;overflow-wrap:anywhere;background:var(--mas-console);max-height:65vh;color:var(--mas-console-text);margin:0;padding:16px 18px;font-size:12px;line-height:1.65;overflow:auto}.management-icon{background:var(--mas-selected);width:40px;height:40px;color:var(--mas-primary);border-radius:9px;flex:none;place-items:center;font-size:20px;display:grid}@media (width<=560px){.management-heading{padding-inline:13px}.management-heading .el-input{width:100%}.management-actions .management-action,.management-actions .el-button{min-height:40px}}.qqbot-panel[data-v-f4942fbc]{gap:16px;padding:20px;display:grid}.qqbot-panel p[data-v-f4942fbc]{margin:0}.qqbot-actions[data-v-f4942fbc]{flex-wrap:wrap;gap:8px;display:flex}.qqbot-actions[data-v-f4942fbc] .el-button+.el-button{margin-left:0}.qqbot-code[data-v-f4942fbc]{background:#fff;max-width:100%;height:auto;display:block}
2
+ /*$vite$:1*/
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./server/builtin-plugins/notification-qqbot.js";
@@ -0,0 +1,60 @@
1
+ import { Schema } from '../schema.js';
2
+ import { text, ui } from '../features.js';
3
+ import { eventFields } from '../notifications/channel.js';
4
+ import { QqBot } from '../notifications/qqbot.js';
5
+ const id = 'notification-qqbot';
6
+ const route = '/settings/qqbot';
7
+ const Config = Schema.object({
8
+ mode: Schema.union(['qr', 'manual']).default('qr').description('机器人授权方式'),
9
+ direct: Schema.boolean().default(true).description('发送至 QQ 单聊'),
10
+ appId: Schema.string().default('').description('手动配置的机器人 AppID'),
11
+ clientSecret: Schema.string().role('secret').default('').description('手动配置的机器人 ClientSecret'),
12
+ userOpenId: Schema.string().default('').description('手动配置单聊目标的用户 OpenID'),
13
+ groupOpenIds: Schema.array(Schema.string()).default([]).description('群聊目标的群 OpenID 列表'),
14
+ ...eventFields,
15
+ });
16
+ export default function createFeature({ dataDir, database, publish }) {
17
+ return { id, name: 'QQ 官方机器人通知', description: '通过 QQ 官方机器人向单聊或群聊发送通知', component: {
18
+ Config, inject: ['mas.notifications'], apply(ctx, config) {
19
+ const bot = new QqBot(dataDir, database, config);
20
+ const notifications = ctx.get('mas.notifications');
21
+ const events = [];
22
+ if (config.task)
23
+ events.push('task');
24
+ if (config.community)
25
+ events.push('community');
26
+ ctx.effect(() => () => bot.close());
27
+ notifications.register(ctx, { id, label: 'QQ 官方机器人', events, failureOnly: config.failureOnly,
28
+ send: (message, signal) => bot.send(message, signal) });
29
+ ctx.inject(['mas.ui'], scope => {
30
+ const components = [{ type: 'choices', title: 'QQ 官方机器人', items: [
31
+ { label: '管理 QQ 官方机器人', href: route, description: '扫码绑定、查看连接配置或发送测试通知' },
32
+ ] }];
33
+ ui(scope).panel(scope, id, components);
34
+ ui(scope).scope(scope, { id, path: route, title: 'QQ 官方机器人', parent: '/settings', nav: false,
35
+ view: 'builtin:notification-qqbot', links: [{ label: '手动配置及接收目标', href: `/plugins?plugin=${id}` }], components: [],
36
+ }, { 'notification-qqbot.status': () => bot.status() }, {
37
+ 'notification-qqbot.start': () => bot.start(),
38
+ 'notification-qqbot.poll': async (input) => {
39
+ const result = await bot.poll(text(input, 'id', '扫码会话'));
40
+ if (result.status === 'paired')
41
+ publish();
42
+ return result;
43
+ },
44
+ 'notification-qqbot.cancel': input => bot.cancel(text(input, 'id', '扫码会话')),
45
+ 'notification-qqbot.unbind': input => {
46
+ if (input.confirmed !== true)
47
+ throw new Error('请确认解绑');
48
+ bot.unbind();
49
+ publish();
50
+ },
51
+ 'notification-qqbot.test': () => notifications.test(id),
52
+ });
53
+ scope.inject(['mas.settings'], settingsScope => {
54
+ const settings = settingsScope.get('mas.settings');
55
+ settings.section(settingsScope, 'notifications', { title: '通知设置', order: 10, components });
56
+ });
57
+ });
58
+ },
59
+ } };
60
+ }
@@ -0,0 +1,365 @@
1
+ // Pure TypeScript ISO/IEC 18004 QR Code encoder (Byte mode, EC level M, Versions 1-16).
2
+ const VERSIONS = [
3
+ { version: 1, ecPerBlock: 10, g1Blocks: 1, g1Data: 16, g2Blocks: 0, g2Data: 0, alignments: [] },
4
+ { version: 2, ecPerBlock: 16, g1Blocks: 1, g1Data: 28, g2Blocks: 0, g2Data: 0, alignments: [6, 18] },
5
+ { version: 3, ecPerBlock: 26, g1Blocks: 1, g1Data: 44, g2Blocks: 0, g2Data: 0, alignments: [6, 22] },
6
+ { version: 4, ecPerBlock: 18, g1Blocks: 2, g1Data: 32, g2Blocks: 0, g2Data: 0, alignments: [6, 26] },
7
+ { version: 5, ecPerBlock: 24, g1Blocks: 2, g1Data: 43, g2Blocks: 0, g2Data: 0, alignments: [6, 30] },
8
+ { version: 6, ecPerBlock: 16, g1Blocks: 4, g1Data: 27, g2Blocks: 0, g2Data: 0, alignments: [6, 34] },
9
+ { version: 7, ecPerBlock: 18, g1Blocks: 4, g1Data: 31, g2Blocks: 0, g2Data: 0, alignments: [6, 22, 38] },
10
+ { version: 8, ecPerBlock: 22, g1Blocks: 2, g1Data: 38, g2Blocks: 2, g2Data: 39, alignments: [6, 24, 42] },
11
+ { version: 9, ecPerBlock: 22, g1Blocks: 3, g1Data: 36, g2Blocks: 2, g2Data: 37, alignments: [6, 26, 46] },
12
+ { version: 10, ecPerBlock: 26, g1Blocks: 4, g1Data: 43, g2Blocks: 1, g2Data: 44, alignments: [6, 28, 50] },
13
+ { version: 11, ecPerBlock: 30, g1Blocks: 1, g1Data: 50, g2Blocks: 4, g2Data: 51, alignments: [6, 30, 54] },
14
+ { version: 12, ecPerBlock: 22, g1Blocks: 6, g1Data: 36, g2Blocks: 2, g2Data: 37, alignments: [6, 32, 58] },
15
+ { version: 13, ecPerBlock: 22, g1Blocks: 8, g1Data: 37, g2Blocks: 1, g2Data: 38, alignments: [6, 34, 62] },
16
+ { version: 14, ecPerBlock: 24, g1Blocks: 4, g1Data: 40, g2Blocks: 5, g2Data: 41, alignments: [6, 26, 46, 66] },
17
+ { version: 15, ecPerBlock: 24, g1Blocks: 5, g1Data: 41, g2Blocks: 5, g2Data: 42, alignments: [6, 26, 48, 70] },
18
+ { version: 16, ecPerBlock: 28, g1Blocks: 7, g1Data: 45, g2Blocks: 3, g2Data: 46, alignments: [6, 26, 50, 74] },
19
+ ];
20
+ const GF_EXP = new Uint8Array(512);
21
+ const GF_LOG = new Uint8Array(256);
22
+ {
23
+ let value = 1;
24
+ for (let i = 0; i < 255; i++) {
25
+ GF_EXP[i] = value;
26
+ GF_LOG[value] = i;
27
+ value = value << 1;
28
+ if (value & 0x100)
29
+ value ^= 0x11d;
30
+ }
31
+ for (let i = 255; i < 512; i++)
32
+ GF_EXP[i] = GF_EXP[i - 255];
33
+ }
34
+ function gfMul(a, b) {
35
+ return a === 0 || b === 0 ? 0 : GF_EXP[GF_LOG[a] + GF_LOG[b]];
36
+ }
37
+ function rsGenerator(degree) {
38
+ let poly = new Uint8Array([1]);
39
+ for (let i = 0; i < degree; i++) {
40
+ const next = new Uint8Array(poly.length + 1);
41
+ const root = GF_EXP[i];
42
+ for (let j = 0; j < poly.length; j++) {
43
+ next[j] ^= poly[j];
44
+ next[j + 1] ^= gfMul(poly[j], root);
45
+ }
46
+ poly = next;
47
+ }
48
+ return poly;
49
+ }
50
+ function rsEncode(data, ecCount) {
51
+ const gen = rsGenerator(ecCount);
52
+ const remainder = new Uint8Array(ecCount);
53
+ for (const byte of data) {
54
+ const factor = byte ^ remainder[0];
55
+ remainder.copyWithin(0, 1);
56
+ remainder[ecCount - 1] = 0;
57
+ if (factor !== 0) {
58
+ for (let i = 0; i < ecCount; i++)
59
+ remainder[i] ^= gfMul(gen[i + 1], factor);
60
+ }
61
+ }
62
+ return remainder;
63
+ }
64
+ function dataCapacity(spec) {
65
+ return spec.g1Blocks * spec.g1Data + spec.g2Blocks * spec.g2Data;
66
+ }
67
+ function selectVersion(byteLength) {
68
+ for (const spec of VERSIONS) {
69
+ const countBits = spec.version <= 9 ? 8 : 16;
70
+ const maxDataBytes = Math.floor((dataCapacity(spec) * 8 - 4 - countBits) / 8);
71
+ if (byteLength <= maxDataBytes)
72
+ return spec;
73
+ }
74
+ throw new Error('二维码内容过长,超出支持的容量上限');
75
+ }
76
+ function buildCodewords(bytes, spec) {
77
+ const capacity = dataCapacity(spec);
78
+ const bits = [];
79
+ const pushBits = (value, width) => {
80
+ for (let i = width - 1; i >= 0; i--)
81
+ bits.push((value >>> i) & 1);
82
+ };
83
+ pushBits(0b0100, 4); // Byte mode
84
+ pushBits(bytes.length, spec.version <= 9 ? 8 : 16);
85
+ for (const byte of bytes)
86
+ pushBits(byte, 8);
87
+ const totalBits = capacity * 8;
88
+ const terminator = Math.min(4, totalBits - bits.length);
89
+ for (let i = 0; i < terminator; i++)
90
+ bits.push(0);
91
+ while (bits.length % 8 !== 0)
92
+ bits.push(0);
93
+ const data = new Uint8Array(capacity);
94
+ for (let i = 0; i < bits.length / 8; i++) {
95
+ let byte = 0;
96
+ for (let b = 0; b < 8; b++)
97
+ byte = (byte << 1) | bits[i * 8 + b];
98
+ data[i] = byte;
99
+ }
100
+ const padBytes = [0xec, 0x11];
101
+ for (let i = bits.length / 8, p = 0; i < capacity; i++, p = 1 - p)
102
+ data[i] = padBytes[p];
103
+ const dataBlocks = [];
104
+ const ecBlocks = [];
105
+ let offset = 0;
106
+ for (let i = 0; i < spec.g1Blocks; i++) {
107
+ const block = data.subarray(offset, offset + spec.g1Data);
108
+ dataBlocks.push(block);
109
+ ecBlocks.push(rsEncode(block, spec.ecPerBlock));
110
+ offset += spec.g1Data;
111
+ }
112
+ for (let i = 0; i < spec.g2Blocks; i++) {
113
+ const block = data.subarray(offset, offset + spec.g2Data);
114
+ dataBlocks.push(block);
115
+ ecBlocks.push(rsEncode(block, spec.ecPerBlock));
116
+ offset += spec.g2Data;
117
+ }
118
+ const maxData = Math.max(spec.g1Data, spec.g2Data);
119
+ const interleaved = new Uint8Array(capacity + (spec.g1Blocks + spec.g2Blocks) * spec.ecPerBlock);
120
+ let cursor = 0;
121
+ for (let i = 0; i < maxData; i++) {
122
+ for (const block of dataBlocks) {
123
+ if (i < block.length)
124
+ interleaved[cursor++] = block[i];
125
+ }
126
+ }
127
+ for (let i = 0; i < spec.ecPerBlock; i++) {
128
+ for (const block of ecBlocks)
129
+ interleaved[cursor++] = block[i];
130
+ }
131
+ return interleaved;
132
+ }
133
+ function formatBits(mask) {
134
+ const data = (0b00 << 3) | (mask & 7); // EC level M = 00
135
+ let rem = data << 10;
136
+ for (let bit = 14; bit >= 10; bit--) {
137
+ if ((rem >>> bit) & 1)
138
+ rem ^= 0x537 << (bit - 10);
139
+ }
140
+ return ((data << 10) | rem) ^ 0x5412;
141
+ }
142
+ function versionBits(version) {
143
+ let rem = version << 12;
144
+ for (let bit = 17; bit >= 12; bit--) {
145
+ if ((rem >>> bit) & 1)
146
+ rem ^= 0x1f25 << (bit - 12);
147
+ }
148
+ return (version << 12) | rem;
149
+ }
150
+ function maskBit(mask, row, col) {
151
+ switch (mask) {
152
+ case 0: return (row + col) % 2 === 0;
153
+ case 1: return row % 2 === 0;
154
+ case 2: return col % 3 === 0;
155
+ case 3: return (row + col) % 3 === 0;
156
+ case 4: return (Math.floor(row / 2) + Math.floor(col / 3)) % 2 === 0;
157
+ case 5: return ((row * col) % 2) + ((row * col) % 3) === 0;
158
+ case 6: return (((row * col) % 2) + ((row * col) % 3)) % 2 === 0;
159
+ default: return (((row + col) % 2) + ((row * col) % 3)) % 2 === 0;
160
+ }
161
+ }
162
+ function createBaseMatrix(spec) {
163
+ const size = spec.version * 4 + 17;
164
+ const modules = Array.from({ length: size }, () => Array(size).fill(false));
165
+ const reserved = Array.from({ length: size }, () => Array(size).fill(false));
166
+ const set = (r, c, dark) => {
167
+ if (r < 0 || c < 0 || r >= size || c >= size)
168
+ return;
169
+ modules[r][c] = dark;
170
+ reserved[r][c] = true;
171
+ };
172
+ const finder = (top, left) => {
173
+ for (let dr = -1; dr <= 7; dr++) {
174
+ for (let dc = -1; dc <= 7; dc++) {
175
+ const inside = dr >= 0 && dr <= 6 && dc >= 0 && dc <= 6;
176
+ const border = dr === 0 || dr === 6 || dc === 0 || dc === 6;
177
+ const center = dr >= 2 && dr <= 4 && dc >= 2 && dc <= 4;
178
+ set(top + dr, left + dc, inside && (border || center));
179
+ }
180
+ }
181
+ };
182
+ finder(0, 0);
183
+ finder(0, size - 7);
184
+ finder(size - 7, 0);
185
+ for (let i = 8; i < size - 8; i++) {
186
+ set(6, i, i % 2 === 0);
187
+ set(i, 6, i % 2 === 0);
188
+ }
189
+ for (const r of spec.alignments) {
190
+ for (const c of spec.alignments) {
191
+ if ((r <= 8 && c <= 8) || (r <= 8 && c >= size - 8) || (r >= size - 8 && c <= 8))
192
+ continue;
193
+ for (let dr = -2; dr <= 2; dr++) {
194
+ for (let dc = -2; dc <= 2; dc++) {
195
+ set(r + dr, c + dc, Math.max(Math.abs(dr), Math.abs(dc)) !== 1);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ // Reserve format info strips and dark module.
201
+ for (let i = 0; i <= 8; i++) {
202
+ if (i !== 6) {
203
+ reserved[8][i] = true;
204
+ reserved[i][8] = true;
205
+ }
206
+ }
207
+ for (let i = 0; i < 8; i++) {
208
+ reserved[8][size - 1 - i] = true;
209
+ reserved[size - 1 - i][8] = true;
210
+ }
211
+ set(spec.version * 4 + 9, 8, true);
212
+ if (spec.version >= 7) {
213
+ const bits = versionBits(spec.version);
214
+ for (let i = 0; i < 18; i++) {
215
+ const dark = Boolean((bits >>> i) & 1);
216
+ const a = Math.floor(i / 3);
217
+ const b = size - 11 + (i % 3);
218
+ set(a, b, dark);
219
+ set(b, a, dark);
220
+ }
221
+ }
222
+ return { size, modules, reserved };
223
+ }
224
+ function writeFormat(modules, mask) {
225
+ const size = modules.length;
226
+ const bits = formatBits(mask);
227
+ const bit = (i) => Boolean((bits >>> i) & 1);
228
+ for (let i = 0; i <= 5; i++)
229
+ modules[8][i] = bit(14 - i);
230
+ modules[8][7] = bit(8);
231
+ modules[8][8] = bit(7);
232
+ modules[7][8] = bit(6);
233
+ for (let i = 0; i <= 5; i++)
234
+ modules[5 - i][8] = bit(5 - i);
235
+ for (let i = 0; i < 8; i++)
236
+ modules[8][size - 1 - i] = bit(i);
237
+ for (let i = 0; i < 7; i++)
238
+ modules[size - 1 - i][8] = bit(14 - i);
239
+ }
240
+ function placeData(modules, reserved, codewords, mask) {
241
+ const size = modules.length;
242
+ let bitIndex = 0;
243
+ const totalBits = codewords.length * 8;
244
+ let upward = true;
245
+ for (let col = size - 1; col >= 1; col -= 2) {
246
+ if (col === 6)
247
+ col--;
248
+ for (let offset = 0; offset < size; offset++) {
249
+ const row = upward ? size - 1 - offset : offset;
250
+ for (let dc = 0; dc < 2; dc++) {
251
+ const c = col - dc;
252
+ if (reserved[row][c])
253
+ continue;
254
+ let dark = false;
255
+ if (bitIndex < totalBits) {
256
+ const byte = codewords[bitIndex >>> 3];
257
+ dark = Boolean((byte >>> (7 - (bitIndex & 7))) & 1);
258
+ bitIndex++;
259
+ }
260
+ modules[row][c] = maskBit(mask, row, c) ? !dark : dark;
261
+ }
262
+ }
263
+ upward = !upward;
264
+ }
265
+ }
266
+ function penalty(modules) {
267
+ const size = modules.length;
268
+ let score = 0;
269
+ const finderA = [true, false, true, true, true, false, true, false, false, false, false];
270
+ const finderB = [false, false, false, false, true, false, true, true, true, false, true];
271
+ const linePenalty = (line) => {
272
+ let runColor = line[0];
273
+ let runLen = 1;
274
+ for (let i = 1; i < size; i++) {
275
+ if (line[i] === runColor) {
276
+ runLen++;
277
+ }
278
+ else {
279
+ if (runLen >= 5)
280
+ score += 3 + (runLen - 5);
281
+ runColor = line[i];
282
+ runLen = 1;
283
+ }
284
+ }
285
+ if (runLen >= 5)
286
+ score += 3 + (runLen - 5);
287
+ for (let i = 0; i <= size - 11; i++) {
288
+ let matchA = true;
289
+ let matchB = true;
290
+ for (let k = 0; k < 11; k++) {
291
+ if (line[i + k] !== finderA[k])
292
+ matchA = false;
293
+ if (line[i + k] !== finderB[k])
294
+ matchB = false;
295
+ if (!matchA && !matchB)
296
+ break;
297
+ }
298
+ if (matchA || matchB)
299
+ score += 40;
300
+ }
301
+ };
302
+ for (let r = 0; r < size; r++)
303
+ linePenalty(modules[r]);
304
+ for (let c = 0; c < size; c++) {
305
+ const col = Array.from({ length: size }, (_, r) => modules[r][c]);
306
+ linePenalty(col);
307
+ }
308
+ let darkCount = 0;
309
+ for (let r = 0; r < size; r++) {
310
+ for (let c = 0; c < size; c++) {
311
+ if (modules[r][c])
312
+ darkCount++;
313
+ if (r < size - 1 && c < size - 1) {
314
+ const v = modules[r][c];
315
+ if (v === modules[r][c + 1] && v === modules[r + 1][c] && v === modules[r + 1][c + 1])
316
+ score += 3;
317
+ }
318
+ }
319
+ }
320
+ const percent = (darkCount * 100) / (size * size);
321
+ const deviation = Math.floor(Math.abs(percent - 50) / 5);
322
+ return score + deviation * 10;
323
+ }
324
+ export function encodeQrMatrix(text) {
325
+ if (!text)
326
+ throw new Error('二维码内容不能为空');
327
+ const bytes = Buffer.from(text, 'utf8');
328
+ const spec = selectVersion(bytes.length);
329
+ const codewords = buildCodewords(bytes, spec);
330
+ const base = createBaseMatrix(spec);
331
+ let bestMatrix;
332
+ let bestScore = Number.POSITIVE_INFINITY;
333
+ for (let mask = 0; mask < 8; mask++) {
334
+ const candidate = base.modules.map(row => row.slice());
335
+ placeData(candidate, base.reserved, codewords, mask);
336
+ writeFormat(candidate, mask);
337
+ const score = penalty(candidate);
338
+ if (score < bestScore) {
339
+ bestScore = score;
340
+ bestMatrix = candidate;
341
+ }
342
+ }
343
+ return bestMatrix;
344
+ }
345
+ export function renderQrSvgDataUrl(text, quietZone = 4) {
346
+ const matrix = encodeQrMatrix(text);
347
+ const size = matrix.length;
348
+ const total = size + quietZone * 2;
349
+ const paths = [];
350
+ for (let r = 0; r < size; r++) {
351
+ let c = 0;
352
+ while (c < size) {
353
+ if (!matrix[r][c]) {
354
+ c++;
355
+ continue;
356
+ }
357
+ const start = c;
358
+ while (c < size && matrix[r][c])
359
+ c++;
360
+ paths.push(`M${start + quietZone} ${r + quietZone}h${c - start}v1h-${c - start}z`);
361
+ }
362
+ }
363
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${total} ${total}" shape-rendering="crispEdges"><rect width="${total}" height="${total}" fill="#ffffff"/><path fill="#000000" d="${paths.join('')}"/></svg>`;
364
+ return `data:image/svg+xml;base64,${Buffer.from(svg, 'utf8').toString('base64')}`;
365
+ }
@@ -0,0 +1,65 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
2
+ import { lstat, readFile, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ export class CredentialVault {
5
+ path;
6
+ namespace;
7
+ pending;
8
+ constructor(dataDir, scope = 'community') {
9
+ this.path = join(dataDir, scope === 'community' ? '.community-key' : '.plugin-config-key');
10
+ this.namespace = scope === 'community' ? 'Cordis MAS community sign-in v1:cloud-genshin' : 'AUTO-MASC plugin configuration v1';
11
+ }
12
+ async load(create) {
13
+ try {
14
+ const info = await lstat(this.path);
15
+ if (!info.isFile() || info.size !== 32 || (process.platform !== 'win32' && (info.mode & 0o077) !== 0)) {
16
+ throw new Error('本机加密密钥文件无效或权限过宽');
17
+ }
18
+ return await readFile(this.path);
19
+ }
20
+ catch (error) {
21
+ if (error.code !== 'ENOENT')
22
+ throw error;
23
+ if (!create)
24
+ throw new Error('找不到本机加密密钥,请重新配置');
25
+ const key = randomBytes(32);
26
+ try {
27
+ await writeFile(this.path, key, { flag: 'wx', mode: 0o600 });
28
+ }
29
+ catch (writeError) {
30
+ if (writeError.code !== 'EEXIST')
31
+ throw writeError;
32
+ return this.load(false);
33
+ }
34
+ return key;
35
+ }
36
+ }
37
+ key(create) {
38
+ this.pending ??= this.load(create).catch(error => { this.pending = undefined; throw error; });
39
+ return this.pending;
40
+ }
41
+ context(id) {
42
+ return Buffer.from(`${this.namespace}:${id}`);
43
+ }
44
+ async seal(id, secret) {
45
+ const nonce = randomBytes(12);
46
+ const cipher = createCipheriv('aes-256-gcm', await this.key(true), nonce);
47
+ cipher.setAAD(this.context(id));
48
+ const data = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
49
+ return { version: 1, nonce: nonce.toString('base64'), cipher: data.toString('base64'), tag: cipher.getAuthTag().toString('base64') };
50
+ }
51
+ async reveal(id, secret) {
52
+ const key = await this.key(false);
53
+ try {
54
+ if (secret.version !== 1)
55
+ throw new Error('Unrecognized credential');
56
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(secret.nonce, 'base64'), { authTagLength: 16 });
57
+ decipher.setAAD(this.context(id));
58
+ decipher.setAuthTag(Buffer.from(secret.tag, 'base64'));
59
+ return Buffer.concat([decipher.update(Buffer.from(secret.cipher, 'base64')), decipher.final()]).toString('utf8');
60
+ }
61
+ catch {
62
+ throw new Error('无法解密本机配置,请重新配置');
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,31 @@
1
+ export const ui = (ctx) => ctx.get('mas.ui');
2
+ export const store = (ctx) => ctx.get('mas.store');
3
+ export const runner = (ctx) => ctx.get('mas.runner');
4
+ export function text(input, key, label, required = true) {
5
+ const value = input[key];
6
+ if (typeof value === 'string' && value.trim())
7
+ return value.trim();
8
+ if (required)
9
+ throw new Error(`请输入${label}`);
10
+ return '';
11
+ }
12
+ export function strings(value) {
13
+ if (!value)
14
+ return [];
15
+ if (Array.isArray(value) && value.every(item => typeof item === 'string'))
16
+ return value;
17
+ if (typeof value === 'string') {
18
+ if (value.trim().startsWith('[')) {
19
+ const parsed = JSON.parse(value);
20
+ if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string'))
21
+ return parsed;
22
+ throw new Error('JSON 必须是字符串数组');
23
+ }
24
+ return value.split(/[\n,]+/).map(item => item.trim()).filter(Boolean);
25
+ }
26
+ throw new Error('请输入字符串列表');
27
+ }
28
+ export const field = (key, label, extra = {}) => ({ key, label, ...extra });
29
+ export const columns = (...pairs) => pairs.map(([key, label]) => ({ key, label }));
30
+ export const action = (id, label) => ({ id, label });
31
+ export const runColumns = columns(['name', '托管'], ['status', '状态'], ['started', '开始时间'], ['finished', '结束时间'], ['error', '结果详情']);
@@ -0,0 +1,99 @@
1
+ import { Schema } from '../schema.js';
2
+ import { ui } from '../features.js';
3
+ import { NotificationError } from './service.js';
4
+ export const eventFields = {
5
+ task: Schema.boolean().default(true).description('发送任务运行结果'),
6
+ community: Schema.boolean().default(true).description('发送游戏社区签到汇总'),
7
+ failureOnly: Schema.boolean().default(false).description('仅发送包含失败或验证项的通知'),
8
+ };
9
+ export function channelFeature(options) {
10
+ const { id, name, description, config } = options;
11
+ return { id, name, description, component: { Config: config, inject: ['mas.notifications'], apply(ctx, current) {
12
+ const notifications = ctx.get('mas.notifications');
13
+ options.prepare?.(ctx, current);
14
+ const unavailable = options.available?.(current);
15
+ notifications.register(ctx, { id, label: name, events: [...current.task ? ['task'] : [], ...current.community ? ['community'] : []],
16
+ failureOnly: current.failureOnly, send: (message, signal) => {
17
+ if (unavailable)
18
+ throw new NotificationError(unavailable);
19
+ return options.send(current, message, signal);
20
+ } });
21
+ ctx.inject(['mas.ui'], scope => {
22
+ const action = `${id}.test`;
23
+ const components = [
24
+ { type: 'choices', title: name, items: [{ label: '配置渠道', description, href: `/plugins?plugin=${id}` }] },
25
+ ...(unavailable ? [{ type: 'text', title: '渠道状态', text: unavailable }] : [
26
+ { type: 'form', title: name, action, fields: [], result: true, submitLabel: '发送测试通知' },
27
+ ]),
28
+ ];
29
+ ui(scope).panel(scope, id, components, {}, { [action]: () => notifications.test(id) });
30
+ scope.inject(['mas.settings'], settingsScope => {
31
+ const settings = settingsScope.get('mas.settings');
32
+ settings.section(settingsScope, 'notifications', { title: '通知设置', components, order: 10 });
33
+ });
34
+ });
35
+ } } };
36
+ }
37
+ export function notificationText(message) {
38
+ return `${message.title}\n${message.text}`;
39
+ }
40
+ export function httpAddress(value, message = '请配置有效的 HTTP(S) 服务地址') {
41
+ const url = URL.parse(value);
42
+ if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash)
43
+ throw new NotificationError(message);
44
+ return url;
45
+ }
46
+ export async function postJson(address, payload, signal, headers = {}, request = fetch) {
47
+ let response;
48
+ try {
49
+ response = await request(address, { method: 'POST', redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]),
50
+ headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(payload) });
51
+ }
52
+ catch {
53
+ throw new NotificationError('连接通知服务失败或超时');
54
+ }
55
+ if (!response.ok) {
56
+ await response.body?.cancel();
57
+ throw new NotificationHttpError(response.status);
58
+ }
59
+ return response;
60
+ }
61
+ export class NotificationHttpError extends NotificationError {
62
+ status;
63
+ constructor(status) {
64
+ super(`通知服务返回 HTTP ${status}`);
65
+ this.status = status;
66
+ }
67
+ }
68
+ export async function notificationJson(response) {
69
+ const reader = response.body?.getReader();
70
+ if (!reader)
71
+ throw new NotificationError('通知服务返回空响应');
72
+ const chunks = [];
73
+ let size = 0;
74
+ try {
75
+ for (;;) {
76
+ const chunk = await reader.read();
77
+ if (chunk.done)
78
+ break;
79
+ size += chunk.value.byteLength;
80
+ if (size > 256 * 1024) {
81
+ await reader.cancel();
82
+ throw new NotificationError('通知服务返回的数据过大');
83
+ }
84
+ chunks.push(chunk.value);
85
+ }
86
+ return JSON.parse(Buffer.concat(chunks, size).toString('utf8'));
87
+ }
88
+ catch (error) {
89
+ if (error instanceof NotificationError)
90
+ throw error;
91
+ throw new NotificationError('通知服务返回无效响应');
92
+ }
93
+ finally {
94
+ reader.releaseLock();
95
+ }
96
+ }
97
+ export function jsonObject(value) {
98
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
99
+ }