@auto-mas/auto-mas-plugin-data-management 0.0.0-stage → 0.1.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,161 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { copyFile, mkdtemp, readdir, rm, stat } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { readSource, record, scrub, sourcePath, text } from './source.js';
7
+ const statuses = new Set(['success', 'error', 'skipped', 'cancelled']);
8
+ function parsed(value) {
9
+ if (typeof value !== 'string' || !value)
10
+ return undefined;
11
+ try {
12
+ return scrub(JSON.parse(value));
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ async function databaseFiles(root) {
19
+ const files = await Promise.all(['', '-wal', '-journal'].map(async (suffix) => {
20
+ const source = await sourcePath(root, join(root, 'data', `history.db${suffix}`));
21
+ if (!source)
22
+ return { suffix };
23
+ const info = await stat(source, { bigint: true });
24
+ if (!info.isFile())
25
+ throw new Error('Expected a history database file');
26
+ return { suffix, source, version: `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` };
27
+ }));
28
+ return files;
29
+ }
30
+ async function databaseHistory(root) {
31
+ const files = await databaseFiles(root);
32
+ if (!files[0].source)
33
+ return [];
34
+ // SQLite may update WAL sidecars even when opened read-only. Open only a private copy.
35
+ const scratch = await mkdtemp(join(tmpdir(), 'mas-history-preview-'));
36
+ let db;
37
+ try {
38
+ const database = join(scratch, 'history.db');
39
+ let copied = false;
40
+ for (let attempt = 0; attempt < 3; attempt++) {
41
+ const before = attempt === 0 ? files : await databaseFiles(root);
42
+ if (!before[0].source)
43
+ throw new Error('The history database disappeared');
44
+ for (const file of before) {
45
+ const destination = `${database}${file.suffix}`;
46
+ if (file.source)
47
+ await copyFile(file.source, destination);
48
+ else
49
+ await rm(destination, { force: true });
50
+ }
51
+ const after = await databaseFiles(root);
52
+ if (before.every((file, index) => file.source === after[index].source && file.version === after[index].version)) {
53
+ copied = true;
54
+ break;
55
+ }
56
+ }
57
+ if (!copied)
58
+ throw new Error('The history database changed during preview');
59
+ db = new DatabaseSync(database);
60
+ const records = db.prepare(`SELECT id, time, username, script_name, status, message, data, log_path, storage_errors
61
+ FROM records ORDER BY timestamp DESC, id`).all();
62
+ const attachments = new Map();
63
+ const hasAttachments = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'attachments'").get();
64
+ if (hasAttachments) {
65
+ for (const { record_id, ...attachment } of db.prepare(`SELECT record_id, id, kind, role, display_name,
66
+ relative_path, byte_size, saved_via, available, unavailable_reason FROM attachments ORDER BY archive_order`).all()) {
67
+ const key = String(record_id);
68
+ if (!attachments.has(key))
69
+ attachments.set(key, []);
70
+ attachments.get(key)?.push(record(scrub(attachment)));
71
+ }
72
+ }
73
+ return records.map(row => {
74
+ const id = String(row.id);
75
+ return {
76
+ id, time: text(row.time), username: text(row.username), scriptName: text(row.script_name),
77
+ status: text(row.status), message: text(row.message),
78
+ legacy: {
79
+ logPath: text(row.log_path), statistics: parsed(row.data), storageErrors: parsed(row.storage_errors),
80
+ attachments: attachments.get(id) ?? [],
81
+ },
82
+ };
83
+ });
84
+ }
85
+ finally {
86
+ db?.close();
87
+ await rm(scratch, { recursive: true, force: true });
88
+ }
89
+ }
90
+ const legacyResultNames = {
91
+ maa_result: 'MAA', maaend_result: 'MaaEnd', src_result: 'SRC', general_result: 'General',
92
+ };
93
+ async function folderHistory(root, warnings) {
94
+ const historyRoot = await sourcePath(root, join(root, 'history'));
95
+ if (!historyRoot)
96
+ return [];
97
+ const result = [];
98
+ let unreadable = 0;
99
+ for (const day of await readdir(historyRoot, { withFileTypes: true })) {
100
+ if (!day.isDirectory() || !/^\d{4}-\d{2}-\d{2}$/.test(day.name))
101
+ continue;
102
+ for (const user of await readdir(join(historyRoot, day.name), { withFileTypes: true })) {
103
+ if (!user.isDirectory())
104
+ continue;
105
+ for (const run of await readdir(join(historyRoot, day.name, user.name), { withFileTypes: true })) {
106
+ if (!run.isFile() || !/^\d{2}-\d{2}-\d{2}\.json$/.test(run.name))
107
+ continue;
108
+ try {
109
+ const source = ['history', day.name, user.name, run.name].join('/');
110
+ const input = await readSource(root, join(historyRoot, day.name, user.name, run.name));
111
+ const data = record(JSON.parse(input?.replace(/^\uFEFF/, '') ?? 'null'));
112
+ const resultKey = Object.keys(legacyResultNames).find(key => Object.hasOwn(data, key));
113
+ if (!resultKey)
114
+ continue;
115
+ // These older filenames were recorded in the legacy application's fixed UTC+4 clock.
116
+ const time = new Date(`${day.name}T${run.name.slice(0, 8).replaceAll('-', ':')}+04:00`).toISOString();
117
+ const message = text(data[resultKey]);
118
+ result.push({
119
+ id: text(data.id, 'legacy-' + createHash('sha256').update(source).digest('hex')),
120
+ time, username: text(user.name), scriptName: text(data.script_name, legacyResultNames[resultKey]),
121
+ status: message === 'Success!' ? 'success' : 'error', message,
122
+ legacy: { source: text(source), statistics: scrub(data) },
123
+ });
124
+ }
125
+ catch {
126
+ unreadable++;
127
+ }
128
+ }
129
+ }
130
+ }
131
+ if (unreadable)
132
+ warnings.push(`Could not read ${unreadable} legacy JSON history ${unreadable === 1 ? 'record' : 'records'}.`);
133
+ return result;
134
+ }
135
+ export async function previewHistory(root, scripts, warnings) {
136
+ const [database, files] = await Promise.all([
137
+ databaseHistory(root).catch(() => { warnings.push('Could not read data/history.db.'); return []; }),
138
+ folderHistory(root, warnings).catch(() => { warnings.push('Could not read the legacy history folder.'); return []; }),
139
+ ]);
140
+ const scriptIds = new Map();
141
+ for (const script of scripts)
142
+ scriptIds.set(script.name, scriptIds.has(script.name) ? '' : script.id);
143
+ const result = [];
144
+ const ids = new Set();
145
+ for (const item of [...database, ...files]) {
146
+ if (ids.has(item.id))
147
+ continue;
148
+ ids.add(item.id);
149
+ const status = statuses.has(item.status) ? item.status : 'error';
150
+ result.push({
151
+ id: item.id,
152
+ name: item.scriptName || item.username || 'Legacy run',
153
+ scriptId: scriptIds.get(item.scriptName) ?? '',
154
+ status, started: item.time, finished: item.time,
155
+ ...(status === 'error' && item.message ? { error: item.message } : {}),
156
+ logs: [],
157
+ legacy: { ...item.legacy, username: item.username, status: item.status, message: item.message },
158
+ });
159
+ }
160
+ return result.sort((a, b) => Date.parse(String(b.started)) - Date.parse(String(a.started)));
161
+ }
@@ -0,0 +1,260 @@
1
+ import { realpath, stat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { previewHistory } from './history.js';
5
+ import { readSource, record, scrub, text } from './source.js';
6
+ import { deviceReference, emulatorProfile, executable, gameProfile, hostPath, pathMetadata } from './targets.js';
7
+ function unpack(value, warnings, label = '') {
8
+ if (value == null)
9
+ return [];
10
+ const data = record(value);
11
+ const order = data.order ?? data.instances;
12
+ if (!Array.isArray(order))
13
+ throw new Error('Invalid collection index');
14
+ const byId = data.order === undefined ? data : record(data.data);
15
+ const entries = [];
16
+ const seen = new Set();
17
+ for (const index of order) {
18
+ const { uid, type } = record(index);
19
+ const entry = typeof uid === 'string' && Object.hasOwn(byId, uid) ? byId[uid] : undefined;
20
+ if (typeof uid !== 'string' || !uid.trim() || seen.has(uid) || !entry || entry !== record(entry)) {
21
+ warnings?.push(`Skipped an invalid or duplicate entry in ${label}.`);
22
+ continue;
23
+ }
24
+ seen.add(uid);
25
+ entries.push({ id: uid, type: typeof type === 'string' ? type : '', data: entry });
26
+ }
27
+ return entries;
28
+ }
29
+ async function configuration(root, yaml, json, warnings) {
30
+ const candidates = [`config/${yaml}`, `config/${json}`, `config/legacy-json/${json}`, `config/legacy-json/pre-upgrade/${json}`];
31
+ for (const candidate of candidates) {
32
+ try {
33
+ const input = await readSource(root, join(root, candidate));
34
+ if (input === undefined)
35
+ continue;
36
+ const clean = input.replace(/^\uFEFF/, '').trim();
37
+ const value = clean ? (candidate.endsWith('.yaml') ? parse(clean, { maxAliasCount: 25, logLevel: 'silent' }) : JSON.parse(clean)) : null;
38
+ return unpack(value, warnings, candidate);
39
+ }
40
+ catch {
41
+ warnings.push(`Could not read ${candidate}.`);
42
+ }
43
+ }
44
+ return [];
45
+ }
46
+ function nested(data, name, warnings) {
47
+ try {
48
+ return unpack(data[name] ?? record(data.SubConfigsInfo)[name], warnings, name);
49
+ }
50
+ catch {
51
+ warnings.push(`Could not read a nested ${name} collection.`);
52
+ return [];
53
+ }
54
+ }
55
+ function script({ id, type, data }, emulators, game) {
56
+ const info = record(data.Info);
57
+ const config = record(data.Script);
58
+ const gameConfig = record(data.Game);
59
+ const cwd = hostPath(info.RootPath) || hostPath(info.Path);
60
+ const scriptPath = hostPath(config.ScriptPath ?? info.ScriptPath, cwd);
61
+ const runnableGeneral = type === 'GeneralConfig' && executable(scriptPath) && !text(config.Arguments);
62
+ const maaProject = ['MaaFWConfig', 'M9AConfig', 'MSSConfig'].includes(type) ? hostPath(info.Path) : '';
63
+ const maaAdapter = type === 'M9AConfig' ? 'm9a' : type === 'MSSConfig' ? 'mss' : 'maafw';
64
+ const device = deviceReference(data);
65
+ const emulator = device && emulators.get(device.emulatorId);
66
+ const paths = {
67
+ ...pathMetadata({ scriptDirectory: cwd, scriptExecutable: scriptPath }),
68
+ ...record(record(emulator?.legacy).paths), ...record(record(game?.legacy).paths),
69
+ };
70
+ const scriptFields = { ...config };
71
+ const gameFields = { ...gameConfig };
72
+ delete scriptFields.Arguments;
73
+ delete gameFields.Arguments;
74
+ delete gameFields.URL;
75
+ const raw = { ...data, ...(data.Script ? { Script: scriptFields } : {}), ...(data.Game ? { Game: gameFields } : {}) };
76
+ return {
77
+ id,
78
+ name: text(info.Name, id),
79
+ adapter: runnableGeneral ? 'general' : maaProject ? maaAdapter : 'legacy',
80
+ command: executable(scriptPath) ? scriptPath : '',
81
+ args: [],
82
+ cwd,
83
+ ...(maaProject ? { projectPath: maaProject } : {}),
84
+ enabled: false,
85
+ ...(emulator ? { emulatorId: emulator.id } : {}),
86
+ ...(game ? { gameId: game.id } : {}),
87
+ legacy: { type, paths, ...(device ? { device } : {}),
88
+ ...(text(config.Arguments) || text(gameConfig.Arguments) ? { omittedArguments: true } : {}), config: scrub(raw) },
89
+ };
90
+ }
91
+ function maaLoginAccount(info) {
92
+ const login = text(info.Id).trim();
93
+ if (login.includes('[redacted]'))
94
+ return '';
95
+ return text(info.Server, 'Official') === 'Official' && /^\d{11}$/.test(login)
96
+ ? `${login.slice(0, 3)}****${login.slice(-4)}` : login;
97
+ }
98
+ function accounts(scripts, plans, warnings) {
99
+ const planIds = new Set(plans.map(plan => plan.id));
100
+ const seen = new Set();
101
+ const result = [];
102
+ for (const script of scripts) {
103
+ for (const { id, type, data } of nested(script.data, 'UserData', warnings)) {
104
+ if (seen.has(id)) {
105
+ warnings.push('Skipped a duplicate legacy account ID.');
106
+ continue;
107
+ }
108
+ seen.add(id);
109
+ const info = record(data.Info);
110
+ const loginAccount = type === 'MaaUserConfig' ? maaLoginAccount(info) : '';
111
+ const planId = [info.PlanMode, info.SanityMode, info.StageMode, record(data.Stage).StageMode]
112
+ .find(value => planIds.has(value));
113
+ result.push({
114
+ id, scriptId: script.id, name: text(info.Name, id), args: [], enabled: false,
115
+ ...(loginAccount ? { loginAccount } : {}),
116
+ ...(planId ? { planId } : {}), legacy: { type, config: scrub(data) },
117
+ });
118
+ }
119
+ }
120
+ return result;
121
+ }
122
+ function localTime(value) {
123
+ if (typeof value !== 'string')
124
+ return undefined;
125
+ const hourMinute = /^(\d{1,2}):([0-5]\d)(?::[0-5]\d)?$/.exec(value);
126
+ if (hourMinute && Number(hourMinute[1]) < 24)
127
+ return `${hourMinute[1].padStart(2, '0')}:${hourMinute[2]}`;
128
+ const wallTime = /^\d{4}-\d{2}-\d{2}[T ]([01]\d|2[0-3]):([0-5]\d)/.exec(value);
129
+ if (wallTime)
130
+ return `${wallTime[1]}:${wallTime[2]}`;
131
+ const instant = new Date(value);
132
+ if (Number.isNaN(instant.getTime()))
133
+ return undefined;
134
+ return `${String(instant.getHours()).padStart(2, '0')}:${String(instant.getMinutes()).padStart(2, '0')}`;
135
+ }
136
+ const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
137
+ function scheduleDays(value) {
138
+ if (!Array.isArray(value))
139
+ return undefined;
140
+ const days = value.map(day => typeof day === 'string' ? weekdays.indexOf(day) : day);
141
+ return days.every(day => typeof day === 'number' && Number.isInteger(day) && day >= 0 && day <= 6)
142
+ ? [...new Set(days)] : undefined;
143
+ }
144
+ function interval(value) {
145
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 10080 ? value : undefined;
146
+ }
147
+ function queue({ id, type, data }, warnings) {
148
+ const info = record(data.Info);
149
+ const name = text(info.Name, id);
150
+ const items = nested(data, 'QueueItem', warnings);
151
+ const timers = nested(data, 'TimeSet', warnings).map(item => {
152
+ const schedule = record(item.data.Info);
153
+ return { id: item.id, enabled: schedule.Enabled !== false, time: localTime(schedule.Time), weekdays: scheduleDays(schedule.Days),
154
+ validDays: schedule.Days === undefined || !!scheduleDays(schedule.Days) };
155
+ });
156
+ const enabledTimes = timers.filter(timer => timer.enabled);
157
+ const schedule = enabledTimes.find(timer => timer.time && timer.validDays);
158
+ const time = info.TimeEnabled === true ? schedule?.time : undefined;
159
+ const intervalSchedules = info.CycleEnabled === true
160
+ ? items.map(item => record(item.data.Schedule)).filter(item => item.Enabled !== false)
161
+ : [];
162
+ const itemInterval = interval(intervalSchedules[0]?.IntervalMinutes);
163
+ const fallbackInterval = itemInterval !== undefined && intervalSchedules.every(item => item.Mode === 'interval' && item.IntervalMinutes === itemInterval)
164
+ ? itemInterval : undefined;
165
+ const intervalMinutes = info.CycleEnabled === true ? interval(record(data.Cycle).IntervalMinutes) ?? fallbackInterval : undefined;
166
+ const startup = info.StartUpEnabled === true || ['Always', 'DailyFirst'].includes(String(info.StartUpMode));
167
+ const order = items.flatMap(item => {
168
+ const scriptId = record(item.data.Info).ScriptId;
169
+ const days = record(item.data.Schedule).Days;
170
+ const weekdays = days === undefined ? undefined : scheduleDays(days) ?? [];
171
+ return typeof scriptId === 'string' && scriptId && scriptId !== '-' ? [{ id: item.id, scriptId, weekdays }] : [];
172
+ });
173
+ const triggers = {
174
+ startup: info.StartUpMode === 'DailyFirst' ? 'daily-first' : startup ? 'always' : 'never',
175
+ daily: { enabled: info.TimeEnabled === true, slots: timers.flatMap(timer => timer.time && timer.validDays
176
+ ? [{ id: timer.id, time: timer.time, weekdays: timer.weekdays, enabled: timer.enabled }] : []) },
177
+ interval: { enabled: intervalMinutes !== undefined, minutes: intervalMinutes ?? 60, anchor: 'start' },
178
+ };
179
+ if ((info.TimeEnabled === true && !time) || timers.some(timer => !timer.time || !timer.validDays) ||
180
+ (info.CycleEnabled === true && intervalMinutes === undefined) ||
181
+ items.some(item => {
182
+ const days = record(item.data.Schedule).Days;
183
+ return days !== undefined && scheduleDays(days) === undefined;
184
+ }))
185
+ warnings.push(`Review invalid or incomplete schedule rules for ${name}.`);
186
+ if (info.IfScriptBeforeTask === true || info.IfScriptAfterTask === true ||
187
+ (info.AfterAccomplish && info.AfterAccomplish !== 'NoAction')) {
188
+ warnings.push(`Queue hooks or power actions require review for ${name}.`);
189
+ }
190
+ return {
191
+ id, name, items: order, triggers,
192
+ ...(info.ExecutionSession === 'desktop' ? { executionTarget: 'desktop-session' } : {}),
193
+ scriptIds: order.map(item => item.scriptId),
194
+ mode: intervalMinutes !== undefined ? 'interval' : time ? 'daily' : startup ? 'startup' : 'manual',
195
+ ...(intervalMinutes !== undefined ? { intervalMinutes } : {}),
196
+ ...(time ? { time, ...(schedule?.weekdays ? { weekdays: schedule.weekdays } : {}) } : {}),
197
+ enabled: false,
198
+ legacy: { type, schedule: { timers, timed: info.TimeEnabled === true, startOnLaunch: startup, intervalMinutes, items: order }, config: scrub(data) },
199
+ };
200
+ }
201
+ function plan({ id, type, data }) {
202
+ const info = record(data.Info);
203
+ return { id, name: text(info.Name, id), description: text(info.Description), legacy: { type, config: scrub(data) } };
204
+ }
205
+ export async function previewMigration(path, options = {}) {
206
+ const warnings = [];
207
+ let root;
208
+ try {
209
+ root = await realpath(path);
210
+ if (!(await stat(root)).isDirectory())
211
+ throw new Error('Expected a folder');
212
+ }
213
+ catch {
214
+ return { scripts: [], accounts: [], queues: [], plans: [], emulators: [], games: [], history: [], warnings: ['Choose an existing AUTO-MAS installation folder.'] };
215
+ }
216
+ const [legacyScripts, legacyQueues, legacyPlans, legacyEmulators] = await Promise.all([
217
+ configuration(root, 'scripts.yaml', 'ScriptConfig.json', warnings),
218
+ configuration(root, 'queues.yaml', 'QueueConfig.json', warnings),
219
+ configuration(root, 'plans.yaml', 'PlanConfig.json', warnings),
220
+ configuration(root, 'emulators.yaml', 'EmulatorConfig.json', warnings),
221
+ ]);
222
+ const emulators = legacyEmulators.map(emulatorProfile);
223
+ const emulatorById = new Map(emulators.map(row => [row.id, row]));
224
+ const games = [];
225
+ const scripts = legacyScripts.map(entry => {
226
+ const game = gameProfile(entry, text(record(entry.data.Info).Name, entry.id));
227
+ if (game)
228
+ games.push(game);
229
+ return script(entry, emulatorById, game);
230
+ });
231
+ const queues = legacyQueues.map(entry => queue(entry, warnings));
232
+ const plans = legacyPlans.map(plan);
233
+ const history = options.includeHistory === false ? [] : await previewHistory(root, scripts, warnings);
234
+ const importedAccounts = accounts(legacyScripts, legacyPlans, warnings);
235
+ if (scripts.length || queues.length)
236
+ warnings.push('Imported scripts, accounts and schedules are disabled until reviewed.');
237
+ if (emulators.length || games.length)
238
+ warnings.push('Imported emulator and game profiles are disabled until reviewed.');
239
+ const missingAddresses = emulators.filter(emulator => !emulator.address && !emulator.command).length;
240
+ if (missingAddresses)
241
+ warnings.push(`${missingAddresses} emulator records need an ADB address. Their legacy paths were retained for review.`);
242
+ if (!scripts.length && !queues.length && !plans.length && !emulators.length && !games.length && !history.length && !warnings.length) {
243
+ warnings.push('No migration records were found in this folder.');
244
+ }
245
+ return { scripts, accounts: importedAccounts, queues, plans, emulators, games, history, warnings };
246
+ }
247
+ export function migrationBackup(preview, options = {}) {
248
+ const metadataOnly = (rows) => rows.map(row => {
249
+ const legacy = { ...record(row.legacy) };
250
+ delete legacy.config;
251
+ return { ...row, legacy };
252
+ });
253
+ return {
254
+ format: 'cordis-mas-backup', version: 1, created: new Date().toISOString(), data: {
255
+ scripts: metadataOnly(preview.scripts), accounts: metadataOnly(preview.accounts), queues: metadataOnly(preview.queues),
256
+ plans: metadataOnly(preview.plans), emulators: metadataOnly(preview.emulators), games: metadataOnly(preview.games),
257
+ runs: options.includeHistory ? metadataOnly(preview.history) : [],
258
+ },
259
+ };
260
+ }
@@ -0,0 +1,79 @@
1
+ import { readFile, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, relative, sep } from 'node:path';
3
+ export function record(value) {
4
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
5
+ }
6
+ export function text(value, fallback = '') {
7
+ return typeof value === 'string' && value.trim() ? redactText(value) : fallback;
8
+ }
9
+ function redactText(value) {
10
+ if (/^\s*(?:DPAPI:|AQAAANCMnd8BFdERjHoAwECl)/i.test(value))
11
+ return '[redacted]';
12
+ return value
13
+ .replace(/(https?:\/\/)[^/\s@]+@/gi, '$1[redacted]@')
14
+ .replace(/(https?:\/\/[^\s]+?\/webhooks?\/)[^\s"']+/gi, '$1[redacted]')
15
+ .replace(/(https?:\/\/api\.telegram\.org\/bot)[^/\s]+/gi, '$1[redacted]')
16
+ .replace(/(\b(?:bearer|basic)\s+)[\w.+/=-]+/gi, '$1[redacted]')
17
+ .replace(/(\b(?:api[-_]?key|password|passwd|access[-_]?token|refresh[-_]?token|token|secret|cdk)(?:\s*[:=]\s*|\s+))(?:"[^"]*"|'[^']*'|[^\s&#;,]+)/gi, '$1[redacted]');
18
+ }
19
+ const sensitiveKey = /(?:password|passwd|passphrase|secret|credentials?|token|apikey|privatekey|accesskey|serverchankey|cdk|authorization|cookies?|headers)$/i;
20
+ const sensitiveOption = /^[-/]{1,2}[\w-]*(?:password|passwd|passphrase|secret|token|api[-_]?key|cdk)$/i;
21
+ export function scrub(value, webhook = false, ancestors = new Set()) {
22
+ if (typeof value === 'string') {
23
+ const input = value.trimStart();
24
+ if (input.startsWith('{') || input.startsWith('[')) {
25
+ try {
26
+ const parsed = JSON.parse(input);
27
+ const cleaned = JSON.stringify(scrub(parsed, webhook));
28
+ if (cleaned !== JSON.stringify(parsed))
29
+ return cleaned;
30
+ }
31
+ catch {
32
+ // Some opaque strings use brackets without representing JSON.
33
+ }
34
+ }
35
+ return redactText(value);
36
+ }
37
+ if (!value || typeof value !== 'object')
38
+ return value;
39
+ if (ancestors.has(value))
40
+ return '[recursive reference omitted]';
41
+ ancestors.add(value);
42
+ try {
43
+ if (Array.isArray(value)) {
44
+ return value.map((item, index) => typeof value[index - 1] === 'string' && sensitiveOption.test(value[index - 1])
45
+ ? '[redacted]' : scrub(item, webhook, ancestors));
46
+ }
47
+ const entries = [];
48
+ for (const [key, item] of Object.entries(value)) {
49
+ const normalized = key.replace(/[^a-z0-9]/gi, '').toLowerCase();
50
+ const isWebhook = normalized.includes('webhook');
51
+ if (sensitiveKey.test(normalized) || (webhook && normalized === 'url') || (isWebhook && typeof item === 'string' && /^https?:\/\//i.test(item)))
52
+ continue;
53
+ entries.push([key, scrub(item, webhook || isWebhook, ancestors)]);
54
+ }
55
+ return Object.fromEntries(entries);
56
+ }
57
+ finally {
58
+ ancestors.delete(value);
59
+ }
60
+ }
61
+ export async function sourcePath(root, path) {
62
+ try {
63
+ const absolute = await realpath(path);
64
+ const fromRoot = relative(root, absolute);
65
+ if (fromRoot === '..' || fromRoot.startsWith('..' + sep) || isAbsolute(fromRoot)) {
66
+ throw new Error('Source path is outside the chosen folder');
67
+ }
68
+ return absolute;
69
+ }
70
+ catch (error) {
71
+ if (error.code === 'ENOENT')
72
+ return undefined;
73
+ throw error;
74
+ }
75
+ }
76
+ export async function readSource(root, path) {
77
+ const absolute = await sourcePath(root, path);
78
+ return absolute === undefined ? undefined : readFile(absolute, 'utf8');
79
+ }
@@ -0,0 +1,85 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { posix, win32 } from 'node:path';
3
+ import { record, text } from './source.js';
4
+ export function hostPath(value, base = '') {
5
+ const path = text(value).trim().replace(/^"(.*)"$/, '$1');
6
+ if (!path || /^[\-[\]]/.test(path) || /[\u0000\r\n"<>|]/.test(path) || /:\/\//.test(path))
7
+ return '';
8
+ if (posix.isAbsolute(path) || win32.isAbsolute(path))
9
+ return path;
10
+ if (!base || /^\w:/.test(path))
11
+ return '';
12
+ return posix.isAbsolute(base) ? posix.resolve(base, path) : win32.resolve(base, path);
13
+ }
14
+ export function executable(path) { return /\.exe$/i.test(path); }
15
+ function parent(path) { return posix.isAbsolute(path) ? posix.dirname(path) : win32.dirname(path); }
16
+ export function pathMetadata(paths) {
17
+ return Object.fromEntries(Object.entries(paths).filter(([, value]) => value));
18
+ }
19
+ function adbAddress(data) {
20
+ const value = text(data.AdbAddress ?? data.ADBAddress ?? data.Address ?? data.DeviceAddress ?? data.Serial).trim();
21
+ return /^(?![-])([\w.:\[\]-]{1,256})$/.test(value) && !/^unknown$/i.test(value) ? value : '';
22
+ }
23
+ function seconds(value) {
24
+ const count = Number(value);
25
+ return Number.isSafeInteger(count) && count >= 1 ? Math.min(count, 300) : 90;
26
+ }
27
+ function list(value) {
28
+ if (Array.isArray(value))
29
+ return value;
30
+ if (typeof value !== 'string')
31
+ return [];
32
+ try {
33
+ const decoded = JSON.parse(value);
34
+ return Array.isArray(decoded) ? decoded : [];
35
+ }
36
+ catch {
37
+ return [];
38
+ }
39
+ }
40
+ export function emulatorProfile({ id, type, data }) {
41
+ const info = { ...record(data.Data), ...record(data.Info) };
42
+ const product = text(info.Type);
43
+ const manager = hostPath(info.Path ?? info.EmulatorPath);
44
+ const adbExecutable = hostPath(info.AdbPath ?? info.ADBPath);
45
+ const address = adbAddress(info);
46
+ const installs = list(info.Paths).map(item => hostPath(record(item).installPath)).filter(Boolean);
47
+ const paths = pathMetadata({ emulatorExecutable: manager, adbExecutable });
48
+ const managerName = win32.basename(manager).toLowerCase();
49
+ const kind = managerName === 'mumumanager.exe' ? 'mumu' : ['ldconsole.exe', 'dnconsole.exe'].includes(managerName) ? 'ldplayer'
50
+ : managerName === 'modavd.exe' && win32.basename(win32.dirname(manager)).toLowerCase() === 'tools' ? 'modavd' : undefined;
51
+ return {
52
+ id, name: text(info.Name, id), address, timeoutSeconds: seconds(info.MaxWaitTime), enabled: false,
53
+ ...(adbExecutable ? { adbPath: adbExecutable } : {}), ...(kind ? { kind, command: manager } : {}),
54
+ // Older records may only have the application or installation folder. Keep these paths for discovery and review.
55
+ legacy: { type, product, paths, ...(installs.length ? { installations: installs } : {}), slotCount: list(info.Slots).length },
56
+ };
57
+ }
58
+ export function deviceReference(data) {
59
+ const emulator = record(data.Emulator);
60
+ const game = record(data.Game);
61
+ const id = text(emulator.Id).trim();
62
+ const gameId = text(game.EmulatorId).trim();
63
+ const emulatorId = id && id !== '-' ? id : gameId && gameId !== '-' ? gameId : '';
64
+ const index = emulator.Index ?? game.EmulatorIndex;
65
+ const selected = typeof index === 'number' && Number.isSafeInteger(index) && index >= 0 ? String(index) : text(index).trim();
66
+ return emulatorId ? { emulatorId, ...(/^[\w.-]{1,64}$/.test(selected) && selected !== '-' ? { index: selected } : {}) } : undefined;
67
+ }
68
+ export function gameProfile({ id, data }, scriptName) {
69
+ const config = record(data.Game);
70
+ const launch = text(config.Type);
71
+ const path = hostPath(config.Path ?? config.GamePath, hostPath(record(data.Info).RootPath));
72
+ const packageName = text(config.PackageName ?? config.Package).trim();
73
+ const packageId = /^[A-Za-z][\w]*(?:\.[A-Za-z][\w]*)+$/.test(packageName) ? packageName : '';
74
+ if (!path && !packageId && config.Enabled !== true)
75
+ return undefined;
76
+ const command = executable(path) ? path : '';
77
+ const idSuffix = createHash('sha256').update(id).digest('hex').slice(0, 24);
78
+ const name = text(config.Name) || scriptName;
79
+ return {
80
+ id: `legacy-game-${idSuffix}`, name, kind: command || launch === 'Client' ? 'desktop' : 'adb', enabled: false,
81
+ timeoutSeconds: seconds(config.WaitTime), ...(command ? { command, cwd: parent(command), args: [] } : {}),
82
+ ...(packageId ? { packageName: packageId } : {}),
83
+ legacy: { type: launch, sourceScriptId: id, paths: pathMetadata({ gameExecutable: path }), omittedArguments: !!text(config.Arguments) },
84
+ };
85
+ }
@@ -0,0 +1,76 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ export class Store {
5
+ db;
6
+ lease;
7
+ constructor(directory) {
8
+ mkdirSync(directory, { recursive: true });
9
+ this.lease = new DatabaseSync(join(directory, 'session.db'));
10
+ try {
11
+ this.lease.exec('PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE');
12
+ }
13
+ catch (error) {
14
+ this.lease.close();
15
+ if (error.errcode === 5)
16
+ throw new Error('该数据目录已有 MAS 后端在运行');
17
+ throw error;
18
+ }
19
+ try {
20
+ this.db = new DatabaseSync(join(directory, 'mas.db'));
21
+ this.db.exec(`PRAGMA journal_mode = WAL;
22
+ CREATE TABLE IF NOT EXISTS entries (
23
+ collection TEXT NOT NULL, id TEXT NOT NULL, value TEXT NOT NULL,
24
+ PRIMARY KEY (collection, id)
25
+ );
26
+ CREATE INDEX IF NOT EXISTS run_start ON entries (
27
+ unixepoch(json_extract(value, '$.started'), 'subsec') DESC
28
+ ) WHERE collection = 'runs'`);
29
+ }
30
+ catch (error) {
31
+ this.lease.close();
32
+ throw error;
33
+ }
34
+ }
35
+ recentRuns() {
36
+ return this.db.prepare(`SELECT value FROM entries WHERE collection = 'runs'
37
+ ORDER BY unixepoch(json_extract(value, '$.started'), 'subsec') DESC, rowid DESC LIMIT 200`)
38
+ .all().map(row => JSON.parse(String(row.value)));
39
+ }
40
+ list(collection) {
41
+ const rows = this.db.prepare('SELECT value FROM entries WHERE collection = ? ORDER BY rowid').all(collection);
42
+ return rows.map(row => JSON.parse(String(row.value)));
43
+ }
44
+ get(collection, id) {
45
+ const row = this.db.prepare('SELECT value FROM entries WHERE collection = ? AND id = ?').get(collection, id);
46
+ return row && JSON.parse(String(row.value));
47
+ }
48
+ put(collection, entry) {
49
+ this.db.prepare('INSERT INTO entries VALUES (?, ?, ?) ON CONFLICT(collection, id) DO UPDATE SET value = excluded.value')
50
+ .run(collection, entry.id, JSON.stringify(entry));
51
+ return entry;
52
+ }
53
+ remove(collection, id) {
54
+ this.db.prepare('DELETE FROM entries WHERE collection = ? AND id = ?').run(collection, id);
55
+ }
56
+ transaction(callback) {
57
+ this.db.exec('BEGIN IMMEDIATE');
58
+ try {
59
+ const result = callback();
60
+ this.db.exec('COMMIT');
61
+ return result;
62
+ }
63
+ catch (error) {
64
+ this.db.exec('ROLLBACK');
65
+ throw error;
66
+ }
67
+ }
68
+ close() {
69
+ try {
70
+ this.db.close();
71
+ }
72
+ finally {
73
+ this.lease.close();
74
+ }
75
+ }
76
+ }