@auto-mas/auto-mas-plugin-maafw-projects 0.0.0-stage → 0.2.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,183 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, mkdtemp, open, rename, rm } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { Store } from './storage.js';
5
+ import { DownloadFile, UiRegistry } from './ui.js';
6
+ const maximum = 1024 * 1024 * 1024;
7
+ function secureUrl(value) {
8
+ const url = new URL(value);
9
+ if (url.protocol !== 'https:' || url.username || url.password)
10
+ throw new Error('更新发布源必须使用 HTTPS 地址');
11
+ return url;
12
+ }
13
+ function versionParts(value) {
14
+ const parts = /^(?:v)?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(alpha|beta|rc)\.(0|[1-9]\d*))?$/.exec(value);
15
+ if (!parts)
16
+ throw new Error('发行清单版本格式无效');
17
+ const numbers = [Number(parts[1]), Number(parts[2]), Number(parts[3]), ['alpha', 'beta', 'rc', undefined].indexOf(parts[4]), Number(parts[5] || 0)];
18
+ if (numbers.some(value => !Number.isSafeInteger(value)))
19
+ throw new Error('发行清单版本超出范围');
20
+ return numbers;
21
+ }
22
+ function newer(candidate, installed) {
23
+ const left = versionParts(candidate);
24
+ const right = versionParts(installed);
25
+ const index = left.findIndex((value, index) => value !== right[index]);
26
+ return index >= 0 && left[index] > right[index];
27
+ }
28
+ function validateAsset(asset) {
29
+ if (!asset || typeof asset.name !== 'string' || !/^[a-z0-9][\w .-]{0,100}\.(?:exe|dmg|zip|deb|appimage|tar\.gz)$/i.test(asset.name))
30
+ throw new Error('安装包文件名无效');
31
+ secureUrl(asset.url);
32
+ if (!/^[a-f0-9]{64}$/i.test(asset.sha256) || !Number.isSafeInteger(asset.size) || asset.size < 1 || asset.size > maximum)
33
+ throw new Error('发行清单缺少有效的 SHA-256 或文件大小');
34
+ }
35
+ async function fetchHttps(address, load, signal) {
36
+ let url = secureUrl(address);
37
+ for (let redirects = 0; redirects <= 3; redirects++) {
38
+ const response = await load(url, { redirect: 'manual', signal });
39
+ if (response.ok)
40
+ return response;
41
+ const location = response.headers.get('location');
42
+ await response.body?.cancel();
43
+ if (![301, 302, 303, 307, 308].includes(response.status) || !location)
44
+ throw new Error(`更新发布源返回 HTTP ${response.status}`);
45
+ url = secureUrl(new URL(location, url).href);
46
+ }
47
+ throw new Error('更新发布源重定向次数过多');
48
+ }
49
+ export async function fetchRelease(address, installed, platform, arch, load = fetch, signal = AbortSignal.timeout(15000)) {
50
+ const response = await fetchHttps(address, load, signal);
51
+ const parts = [];
52
+ let size = 0;
53
+ if (!response.body)
54
+ throw new Error('发布清单为空');
55
+ const reader = response.body.getReader();
56
+ try {
57
+ while (true) {
58
+ const chunk = await reader.read();
59
+ if (chunk.done)
60
+ break;
61
+ size += chunk.value.byteLength;
62
+ if (size > 128 * 1024)
63
+ throw new Error('发布清单过大');
64
+ parts.push(chunk.value);
65
+ }
66
+ }
67
+ finally {
68
+ await reader.cancel();
69
+ }
70
+ const manifest = JSON.parse(Buffer.concat(parts).toString());
71
+ if (typeof manifest?.version !== 'string' || !Array.isArray(manifest.assets))
72
+ throw new Error('发布清单结构无效');
73
+ const available = newer(manifest.version, installed);
74
+ const asset = manifest.assets.find((item) => item?.platform === platform && item.arch === arch) ?? null;
75
+ if (asset)
76
+ validateAsset(asset);
77
+ return { version: manifest.version, available, asset };
78
+ }
79
+ export async function stageAsset(directory, asset, load = fetch, signal = AbortSignal.timeout(600000)) {
80
+ validateAsset(asset);
81
+ await mkdir(directory, { recursive: true });
82
+ const staging = await mkdtemp(join(directory, '.stage-'));
83
+ try {
84
+ const temp = join(staging, asset.name);
85
+ const response = await fetchHttps(asset.url, load, signal);
86
+ if (!response.body)
87
+ throw new Error('安装包下载正文为空');
88
+ const reader = response.body.getReader();
89
+ const file = await open(temp, 'wx');
90
+ const hash = createHash('sha256');
91
+ let size = 0;
92
+ try {
93
+ while (true) {
94
+ const chunk = await reader.read();
95
+ if (chunk.done)
96
+ break;
97
+ size += chunk.value.byteLength;
98
+ if (size > asset.size)
99
+ throw new Error('安装包大小与发布清单不一致');
100
+ hash.update(chunk.value);
101
+ await file.writeFile(chunk.value);
102
+ }
103
+ }
104
+ finally {
105
+ await reader.cancel();
106
+ await file.close();
107
+ }
108
+ if (size !== asset.size)
109
+ throw new Error('安装包大小与发布清单不一致');
110
+ if (hash.digest('hex') !== asset.sha256.toLowerCase())
111
+ throw new Error('安装包 SHA-256 校验失败');
112
+ const target = join(directory, `${asset.sha256.toLowerCase()}-${asset.name}`);
113
+ await rename(temp, target);
114
+ return target;
115
+ }
116
+ finally {
117
+ await rm(staging, { recursive: true, force: true });
118
+ }
119
+ }
120
+ export function createUpdatesFeature(dataDir, installed) {
121
+ return { id: 'updates', name: '应用更新', description: '检查 AUTO-MASC 发布清单并验证平台安装包', component: {
122
+ inject: ['mas.ui', 'mas.store'],
123
+ apply(ctx) {
124
+ const ui = ctx.get('mas.ui');
125
+ const store = ctx.get('mas.store');
126
+ const lifetime = new AbortController();
127
+ let pending;
128
+ const readSettings = () => store.get('updates', 'settings');
129
+ const check = async () => {
130
+ const address = readSettings()?.url;
131
+ if (typeof address !== 'string' || !address)
132
+ throw new Error('请先配置 AUTO-MASC 发布清单');
133
+ return fetchRelease(address, installed, process.platform, process.arch, fetch, AbortSignal.any([lifetime.signal, AbortSignal.timeout(15000)]));
134
+ };
135
+ ctx.effect(() => async () => { lifetime.abort(); await pending?.catch(() => { }); });
136
+ ui.panel(ctx, 'updates', [
137
+ { type: 'metrics', title: '版本状态', query: 'updates.status' },
138
+ { type: 'form', title: '发布源', action: 'updates.source', query: 'updates.source', submitLabel: '保存发布源', fields: [
139
+ { key: 'url', label: '发布清单 HTTPS 地址', required: true, hint: '使用 AUTO-MASC 的发行清单。' },
140
+ ] },
141
+ { type: 'form', title: '检查新版', action: 'updates.check', result: true, submitLabel: '检查更新' },
142
+ { type: 'form', title: '下载安装包到主机', action: 'updates.stage', result: true, submitLabel: '下载并校验' },
143
+ { type: 'text', title: '安装', text: '校验通过后可在浏览器下载。关闭应用,再运行对应平台的安装包。', download: '/api/ui/v1/download/installer', downloadAvailableQuery: 'updates.hasStaged', binaryDownload: true },
144
+ ], {
145
+ 'updates.source': () => ({ url: readSettings()?.url ?? '' }),
146
+ 'updates.hasStaged': () => !!store.get('updates', 'staged')?.path,
147
+ 'updates.status': () => [{ label: '当前版本', value: installed }, { label: '运行平台', value: `${process.platform} ${process.arch}` },
148
+ { label: '已校验版本', value: store.get('updates', 'staged')?.version ?? '暂无' }],
149
+ }, {
150
+ 'updates.source': input => {
151
+ if (pending)
152
+ throw new Error('更新下载正在进行');
153
+ const url = secureUrl(String(input.url ?? '')).href;
154
+ store.transaction(() => { store.put('updates', { id: 'settings', url }); store.remove('updates', 'staged'); });
155
+ return { url };
156
+ },
157
+ 'updates.check': async () => {
158
+ const version = await check();
159
+ return { 当前版本: installed, 发布版本: version.version, 有新版: version.available, 平台安装包: version.asset?.name ?? '暂无' };
160
+ },
161
+ 'updates.stage': () => {
162
+ if (pending)
163
+ throw new Error('更新下载正在进行');
164
+ pending = (async () => {
165
+ const release = await check();
166
+ if (!release.available || !release.asset)
167
+ throw new Error('没有适用于本机的新版安装包');
168
+ const file = await stageAsset(join(dataDir, 'updates'), release.asset, fetch, AbortSignal.any([lifetime.signal, AbortSignal.timeout(600000)]));
169
+ store.put('updates', { id: 'staged', version: release.version, path: file, name: release.asset.name });
170
+ return { 版本: release.version, 文件: release.asset.name, SHA256: release.asset.sha256 };
171
+ })().finally(() => { pending = undefined; });
172
+ return pending;
173
+ },
174
+ });
175
+ ui.download(ctx, 'installer', () => {
176
+ const file = store.get('updates', 'staged');
177
+ if (typeof file?.path !== 'string' || typeof file.name !== 'string')
178
+ throw new Error('请先下载并校验安装包');
179
+ return new DownloadFile(file.path, file.name);
180
+ });
181
+ },
182
+ } };
183
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
- {
2
- "name": "@auto-mas/auto-mas-plugin-maafw-projects",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@auto-mas/auto-mas-plugin-maafw-projects",
3
+ "version": "0.2.0",
4
+ "license": "AGPL-3.0-only",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "exports": "./dist/index.js",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "engines": {
12
+ "node": ">=24"
13
+ },
14
+ "keywords": [
15
+ "auto-mas-plugin"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "description": "AUTO-MAS maafw-projects Cordis component",
21
+ "autoMas": {
22
+ "id": "maafw-projects",
23
+ "abi": 1,
24
+ "hostDependencies": {
25
+ "@maaxyz/maa-node": "5.16.1",
26
+ "cordis": "4.0.0-rc.13",
27
+ "jsonc-parser": "3.3.1",
28
+ "schemastery": "3.18.0",
29
+ "tar": "7.5.23",
30
+ "unzipper": "0.12.5"
31
+ },
32
+ "optionalHostDependencies": [
33
+ "@maaxyz/maa-node"
34
+ ]
35
+ }
36
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.