@auto-mas/auto-mas-plugin-adapter-bettergi 0.2.1 → 0.2.2

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,275 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { lstat, open, readdir, realpath, rename, unlink, writeFile } from 'node:fs/promises';
4
+ import { isAbsolute, join, relative, sep } from 'node:path';
5
+ import { CredentialVault } from '../community/vault.js';
6
+ import { field, store, text, ui } from '../features.js';
7
+ import { assertWindowsProgramIdle, windowsOnly } from './native.js';
8
+ const collection = 'native-config-backups';
9
+ const maxFiles = 256;
10
+ const maxBytes = 8 * 1024 * 1024;
11
+ const fileName = /^[^/\\:*?"<>|\u0000-\u001f]+\.json$/iu;
12
+ const explicitFileName = /^[^/\\:*?"<>|\u0000-\u001f]+\.(?:json|yaml|yml)$/iu;
13
+ function contained(root, candidate) {
14
+ const rel = relative(root, candidate);
15
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
16
+ throw new Error('原生配置目录必须位于已保存的安装目录内');
17
+ return rel;
18
+ }
19
+ async function configDirectory(source, allowMissing = false) {
20
+ const root = await realpath(source.root);
21
+ const rel = contained(root, source.directory);
22
+ let location = root;
23
+ for (const part of rel.split(sep)) {
24
+ location = join(location, part);
25
+ const info = await lstat(location).catch(error => {
26
+ if (allowMissing && error.code === 'ENOENT')
27
+ return undefined;
28
+ throw error;
29
+ });
30
+ if (!info)
31
+ return undefined;
32
+ if (!info.isDirectory() || info.isSymbolicLink())
33
+ throw new Error('原生配置目录路径无效或含重定向');
34
+ }
35
+ return location;
36
+ }
37
+ function validateName(name, targets) {
38
+ if (!(targets ? explicitFileName : fileName).test(name) || name.length > 160 || name.startsWith('.')
39
+ || name.startsWith(' ') || name !== name.trim() || (targets && !targets.includes(name)))
40
+ throw new Error('原生配置备份的文件名无效');
41
+ }
42
+ function targetsFor(source) { return source.files ?? (source.file ? [source.file] : undefined); }
43
+ async function configFiles(directory, targets) {
44
+ const entries = await readdir(directory, { withFileTypes: true });
45
+ return entries.filter(entry => targets ? targets.includes(entry.name) : fileName.test(entry.name));
46
+ }
47
+ async function readContent(directory, targets) {
48
+ for (const filename of targets ?? [])
49
+ validateName(filename, targets);
50
+ const files = await configFiles(directory, targets);
51
+ if (files.length > maxFiles)
52
+ throw new Error('原生配置文件数量超过可备份范围');
53
+ const content = Object.create(null);
54
+ let total = 0;
55
+ for (const entry of files) {
56
+ validateName(entry.name, targets);
57
+ if (!entry.isFile() || entry.isSymbolicLink())
58
+ throw new Error('原生配置含非普通文件');
59
+ const path = join(directory, entry.name);
60
+ const info = await lstat(path);
61
+ if (info.isSymbolicLink() || !info.isFile() || info.size > maxBytes - total)
62
+ throw new Error('原生配置含链接或超过可备份大小');
63
+ const handle = await open(path, 'r');
64
+ try {
65
+ const body = await handle.readFile();
66
+ total += body.length;
67
+ if (total > maxBytes)
68
+ throw new Error('原生配置超过可备份大小');
69
+ content[entry.name] = body.toString('base64');
70
+ }
71
+ finally {
72
+ await handle.close();
73
+ }
74
+ }
75
+ return content;
76
+ }
77
+ export async function readNativeConfigurationFile(source) {
78
+ const directory = await configDirectory(source);
79
+ const content = directory && (await readContent(directory, [source.file]))[source.file];
80
+ if (content === undefined)
81
+ throw new Error('原生配置文件不存在');
82
+ return Buffer.from(content, 'base64').toString('utf8');
83
+ }
84
+ function decode(snapshot, targets) {
85
+ const parsed = JSON.parse(snapshot);
86
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
87
+ throw new Error('原生配置备份格式无效');
88
+ const entries = Object.entries(parsed);
89
+ if (entries.length > maxFiles)
90
+ throw new Error('原生配置备份文件数量无效');
91
+ let total = 0;
92
+ for (const [name, value] of entries) {
93
+ validateName(name, targets);
94
+ if (typeof value !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/u.test(value) || value.length % 4 !== 0)
95
+ throw new Error('原生配置备份内容无效');
96
+ total += Buffer.byteLength(value, 'base64');
97
+ if (total > maxBytes)
98
+ throw new Error('原生配置备份大小无效');
99
+ }
100
+ return Object.fromEntries(entries);
101
+ }
102
+ async function replaceFile(directory, name, content) {
103
+ const destination = join(directory, name);
104
+ const temp = join(directory, `.masc-${randomUUID()}.tmp`);
105
+ const current = await lstat(destination).catch(error => {
106
+ if (error.code === 'ENOENT')
107
+ return undefined;
108
+ throw error;
109
+ });
110
+ if (current && (!current.isFile() || current.isSymbolicLink()))
111
+ throw new Error('目标配置不是普通文件');
112
+ await writeFile(temp, Buffer.from(content, 'base64'), { flag: 'wx', mode: current?.mode ?? 0o600 });
113
+ try {
114
+ await rename(temp, destination);
115
+ }
116
+ catch (error) {
117
+ await unlink(temp).catch(() => { });
118
+ throw error;
119
+ }
120
+ }
121
+ async function replaceNativeConfigurationFile(source, expected, updated) {
122
+ const directory = await configDirectory(source);
123
+ const files = directory && await readContent(directory, [source.file]);
124
+ const current = files && files[source.file];
125
+ if (!current || Buffer.from(current, 'base64').toString('utf8') !== expected)
126
+ throw new Error('原生配置已变化,请刷新后再保存');
127
+ if (Buffer.byteLength(updated) > maxBytes)
128
+ throw new Error('文件超过原生配置大小限制');
129
+ await replaceFile(directory, source.file, Buffer.from(updated, 'utf8').toString('base64'));
130
+ }
131
+ export function nativeConfigurationComponents(adapter, script, options = {}) {
132
+ const fixed = { scriptId: script.id };
133
+ return [
134
+ { type: 'metrics', title: '检测原生配置', query: `${adapter}.native.info`, queryInput: fixed },
135
+ ...(options.open === false ? [] : [{ type: 'form', title: '原生配置', action: `${adapter}.native.open`, fixed,
136
+ fields: options.confirmOpen ? [field('confirmed', options.confirmOpen, { kind: 'boolean' })] : [], submitLabel: '打开原生配置窗口', result: true }]),
137
+ { type: 'form', title: '备份原生配置', action: `${adapter}.native.backup`, fixed, fields: [], submitLabel: '保存原生配置备份', result: true },
138
+ { type: 'form', title: '恢复原生配置', action: `${adapter}.native.restore`, fixed, submitLabel: '恢复所选备份', result: true,
139
+ fields: [field('backupId', '备份', { kind: 'select', required: true, source: `${adapter}.native.snapshots`, sourceBy: 'scriptId' }),
140
+ field('confirmed', '确认覆盖所选备份中的同名配置文件', { kind: 'boolean' })] },
141
+ ];
142
+ }
143
+ export function registerNativeConfiguration(ctx, dataDir, adapter, resolve, edit) {
144
+ const vault = new CredentialVault(dataDir, 'plugin');
145
+ ctx.inject(['mas.ui', 'mas.scripts', 'mas.runner', 'mas.storage-core'], scope => {
146
+ const scripts = scope.get('mas.scripts');
147
+ const runner = scope.get('mas.runner');
148
+ const db = store(scope);
149
+ const sourceFor = (input) => {
150
+ const script = scripts.get(text(input, 'scriptId', '托管 ID'));
151
+ if (!script || script.adapter !== adapter)
152
+ throw new Error('未找到对应专项托管');
153
+ return resolve(script.adapterConfig ?? {}, input);
154
+ };
155
+ async function ownerFor(source) {
156
+ const root = await realpath(source.root);
157
+ const location = contained(root, source.directory);
158
+ const key = JSON.stringify([adapter, root.toLowerCase(), location.toLowerCase(), targetsFor(source) ?? []]);
159
+ return createHash('sha256').update(key).digest('hex');
160
+ }
161
+ async function writeSnapshot(owner, content) {
162
+ const id = randomUUID();
163
+ const date = new Date().toISOString();
164
+ const secret = await vault.seal(`${collection}:${id}`, JSON.stringify(content));
165
+ return db.put(collection, { id, owner, date, count: Object.keys(content).length, secret });
166
+ }
167
+ async function ensureIdle(source) {
168
+ const reason = windowsOnly();
169
+ if (reason)
170
+ throw new Error(reason);
171
+ for (const command of new Set([source.command, ...source.additionalPrograms ?? []])) {
172
+ await assertWindowsProgramIdle(command, AbortSignal.timeout(10_000));
173
+ }
174
+ }
175
+ async function useSource(input, action) {
176
+ const source = await sourceFor(input);
177
+ const release = runner.claimInstallation(source.root);
178
+ try {
179
+ await ensureIdle(source);
180
+ return await action(source);
181
+ }
182
+ finally {
183
+ release();
184
+ }
185
+ }
186
+ ui(scope).scope(scope, undefined, { [`${adapter}.native.info`]: async (input) => {
187
+ const source = await sourceFor(input);
188
+ const directory = await configDirectory(source, true);
189
+ const files = directory ? await configFiles(directory, targetsFor(source)) : [];
190
+ return [{ label: '配置目录', value: source.directory }, { label: '配置文件', value: files.length,
191
+ detail: files.length ? files.slice(0, 8).map(entry => entry.name).join('、') : '等待在原生程序中首次保存配置' }];
192
+ }, [`${adapter}.native.snapshots`]: async (input) => {
193
+ const owner = await ownerFor(await sourceFor(input));
194
+ return db.list(collection).filter(entry => entry.owner === owner && entry.count > 0).reverse()
195
+ .map(entry => ({ value: entry.id, label: `${entry.date.replace('T', ' ').replace(/\.\d+Z$/u, ' UTC')} · ${entry.count} 项` }));
196
+ } }, {
197
+ [`${adapter}.native.open`]: async (input) => {
198
+ const source = await sourceFor(input);
199
+ if (source.open === false)
200
+ throw new Error('此专项没有独立的原生配置窗口入口');
201
+ if (source.confirmOpen && input.confirmed !== true)
202
+ throw new Error('请确认允许按原生设置启动程序');
203
+ const release = runner.claimInstallation(source.root);
204
+ try {
205
+ await ensureIdle(source);
206
+ const directory = await configDirectory(source, true);
207
+ if (directory) {
208
+ const content = await readContent(directory, targetsFor(source));
209
+ if (Object.keys(content).length)
210
+ await writeSnapshot(await ownerFor(source), content);
211
+ }
212
+ const child = spawn(source.command, source.args ?? [], { cwd: source.cwd ?? source.root, shell: false,
213
+ detached: true, stdio: 'ignore' });
214
+ child.once('close', release);
215
+ await new Promise((accept, reject) => { child.once('spawn', accept); child.once('error', reject); });
216
+ child.unref();
217
+ return { message: '已在后端主机打开原生配置,关闭窗口后可恢复调度' };
218
+ }
219
+ catch (error) {
220
+ release();
221
+ throw error;
222
+ }
223
+ },
224
+ ...(edit ? { [`${adapter}.native.edit`]: (input) => useSource(input, async (source) => {
225
+ if (!source.file)
226
+ throw new Error('原生配置未指定单个编辑文件');
227
+ if (input.confirmed !== true)
228
+ throw new Error('请确认保存所选原生配置');
229
+ const file = { ...source, file: source.file };
230
+ const before = await readNativeConfigurationFile(file);
231
+ const updated = edit(before, input, file.file);
232
+ if (updated === before)
233
+ return { message: '原生配置无变化' };
234
+ const preserved = await writeSnapshot(await ownerFor(source), { [file.file]: Buffer.from(before, 'utf8').toString('base64') });
235
+ await replaceNativeConfigurationFile(file, before, updated);
236
+ return { message: '原生配置已保存', 操作前备份时间: preserved.date };
237
+ }) } : {}),
238
+ [`${adapter}.native.backup`]: input => useSource(input, async (source) => {
239
+ const directory = await configDirectory(source);
240
+ const content = await readContent(directory, targetsFor(source));
241
+ if (!Object.keys(content).length)
242
+ throw new Error('未找到可备份的原生配置,请先通过原生窗口保存设置');
243
+ const snapshot = await writeSnapshot(await ownerFor(source), content);
244
+ return { 备份时间: snapshot.date, 配置项: snapshot.count };
245
+ }),
246
+ [`${adapter}.native.restore`]: input => useSource(input, async (source) => {
247
+ if (input.confirmed !== true)
248
+ throw new Error('请确认覆盖所选备份中的同名配置文件');
249
+ const owner = await ownerFor(source);
250
+ const backup = db.get(collection, text(input, 'backupId', '备份'));
251
+ if (!backup || backup.owner !== owner || !backup.count)
252
+ throw new Error('该备份不属于当前原生配置目录');
253
+ const directory = (await configDirectory(source));
254
+ const before = await readContent(directory, targetsFor(source));
255
+ const snapshot = decode(await vault.reveal(`${collection}:${backup.id}`, backup.secret), targetsFor(source));
256
+ const preserved = await writeSnapshot(owner, before);
257
+ const published = [];
258
+ try {
259
+ for (const [name, content] of Object.entries(snapshot)) {
260
+ await replaceFile(directory, name, content);
261
+ published.push(name);
262
+ }
263
+ }
264
+ catch (error) {
265
+ const rolledBack = await Promise.allSettled(published.map(name => Object.hasOwn(before, name)
266
+ ? replaceFile(directory, name, before[name]) : unlink(join(directory, name))));
267
+ if (rolledBack.some(result => result.status === 'rejected'))
268
+ throw new Error(`恢复中断,部分配置未能回退。操作前备份时间为 ${preserved.date}`);
269
+ throw new Error('恢复失败,已撤回本次写入', { cause: error });
270
+ }
271
+ return { 已恢复: published.length, 操作前备份时间: preserved.date };
272
+ }),
273
+ });
274
+ });
275
+ }
@@ -0,0 +1,73 @@
1
+ export function maaAccountFields(id) {
2
+ const choice = (key, label, kind, source, sourceInputs = []) => ({
3
+ key, label, kind, source: `${id}.account.${source}`, sourceBy: 'scriptId', sourceInputs,
4
+ });
5
+ const selection = ['controller', 'resource'];
6
+ return [
7
+ choice('controller', '账号控制器覆盖', 'select', 'controllers'),
8
+ { ...choice('resource', '账号资源覆盖', 'select', 'resources', ['controller']), hint: '留空时继承托管资源。切换控制器时请核对资源。' },
9
+ { ...choice('preset', '账号项目预设覆盖', 'select', 'presets', selection), hint: '未选账号任务队列时,账号预设优先于任务计划和托管队列。' },
10
+ { ...choice('tasks', '账号任务队列覆盖', 'multiselect', 'tasks', selection), hint: '留空时按账号预设、任务计划或托管设置执行。' },
11
+ { ...choice('projectOptions', '账号 ProjectInterface 选项覆盖', 'json-object', 'options', selection), hint: '只覆盖已填写的值。专项账号字段优先于同名选项。' },
12
+ ];
13
+ }
14
+ function object(value) {
15
+ return !!value && typeof value === 'object' && !Array.isArray(value);
16
+ }
17
+ function selection(input, key) {
18
+ const value = input[key];
19
+ if (value === undefined)
20
+ return undefined;
21
+ if (typeof value !== 'string')
22
+ throw new Error('账号 ProjectInterface 选择必须为字符串');
23
+ return value.trim() || undefined;
24
+ }
25
+ function accountTasks(value) {
26
+ if (value === undefined)
27
+ return undefined;
28
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || !item.trim())) {
29
+ throw new Error('账号任务队列必须为任务名称列表');
30
+ }
31
+ return value.length ? value : undefined;
32
+ }
33
+ function accountOptions(value) {
34
+ if (value === undefined || typeof value === 'string' && !value.trim())
35
+ return undefined;
36
+ let parsed;
37
+ try {
38
+ parsed = typeof value === 'string' ? JSON.parse(value) : value;
39
+ }
40
+ catch {
41
+ throw new Error('账号 ProjectInterface 选项必须是有效的 JSON 对象');
42
+ }
43
+ if (!object(parsed))
44
+ throw new Error('账号 ProjectInterface 选项必须是有效的 JSON 对象');
45
+ for (const [key, option] of Object.entries(parsed)) {
46
+ if (typeof option === 'string' || typeof option === 'boolean')
47
+ continue;
48
+ if (Array.isArray(option) && option.every(item => typeof item === 'string'))
49
+ continue;
50
+ if (object(option) && Object.values(option).every(item => typeof item === 'string'))
51
+ continue;
52
+ throw new Error(`账号 ProjectInterface 选项格式无效:${key}`);
53
+ }
54
+ return parsed;
55
+ }
56
+ export function applyMaaAccountSettings(input, account) {
57
+ const preset = selection(account, 'preset');
58
+ const overrides = accountOptions(account.projectOptions);
59
+ const options = new Map(Object.entries(input.options ?? {}));
60
+ for (const [key, value] of Object.entries(overrides ?? {})) {
61
+ const inherited = options.get(key);
62
+ options.set(key, object(value) && object(inherited) ? { ...inherited, ...value } : value);
63
+ }
64
+ return {
65
+ ...input,
66
+ controller: selection(account, 'controller') ?? input.controller,
67
+ resource: selection(account, 'resource') ?? input.resource,
68
+ preset: preset ?? input.preset,
69
+ tasks: accountTasks(account.tasks) ?? (preset ? undefined : input.tasks),
70
+ options: options.size ? Object.fromEntries(options) : undefined,
71
+ requiredOptions: Object.keys(overrides ?? {}),
72
+ };
73
+ }