codesign-mcp-next 0.0.0-stage → 0.3.3
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/CHANGELOG.md +137 -0
- package/LICENSE +21 -0
- package/README.md +457 -2
- package/dist/browser/manager.js +204 -0
- package/dist/browser/session.js +62 -0
- package/dist/codesign/cache.js +85 -0
- package/dist/codesign/errors.js +47 -0
- package/dist/codesign/integrity.js +197 -0
- package/dist/codesign/meta.js +57 -0
- package/dist/codesign/parser.js +56 -0
- package/dist/codesign/platform.js +232 -0
- package/dist/codesign/selection.js +205 -0
- package/dist/codesign/sharing.js +153 -0
- package/dist/codesign/slices.js +34 -0
- package/dist/codesign/types.js +1 -0
- package/dist/config.js +94 -0
- package/dist/index.js +16 -0
- package/dist/logger.js +68 -0
- package/dist/mcp/result.js +151 -0
- package/dist/mcp/schema.js +122 -0
- package/dist/mcp/server.js +313 -0
- package/dist/prompts/design-to-code.js +128 -0
- package/dist/resources/workflow.js +33 -0
- package/dist/server.js +61 -0
- package/dist/tools/artboards.js +96 -0
- package/dist/tools/diagnostics.js +192 -0
- package/dist/tools/image.js +134 -0
- package/dist/tools/login.js +136 -0
- package/dist/tools/slices.js +228 -0
- package/dist/tools/spec.js +236 -0
- package/dist/tools/status.js +62 -0
- package/dist/utils/download.js +290 -0
- package/dist/utils/filename.js +16 -0
- package/dist/utils/http.js +54 -0
- package/dist/utils/rate-limit.js +120 -0
- package/dist/utils/redact.js +110 -0
- package/dist/utils/retry.js +97 -0
- package/dist/utils/url.js +98 -0
- package/package.json +56 -4
- package/userscripts/codesign-ai-selection.user.js +445 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { objectSchema } from '../mcp/schema.js';
|
|
2
|
+
import { browserManager } from '../browser/manager.js';
|
|
3
|
+
import { getCachedSharingDetail, fetchCachedSpec, fetchCachedSliceManifest } from '../codesign/cache.js';
|
|
4
|
+
import { normalizeSpec, findLayerByObjectId } from '../codesign/parser.js';
|
|
5
|
+
import { inspectSpec, integrityView } from '../codesign/integrity.js';
|
|
6
|
+
import { buildPlatformSpec, supportedTargetPlatforms } from '../codesign/platform.js';
|
|
7
|
+
import { buildLayerSelection, LAYER_SELECTION_SCOPES, } from '../codesign/selection.js';
|
|
8
|
+
import { CodesignError } from '../codesign/errors.js';
|
|
9
|
+
import { parseSharingId } from '../utils/url.js';
|
|
10
|
+
import { errorResult } from './artboards.js';
|
|
11
|
+
import { toolSuccess, summarizeSpecPayload } from '../mcp/result.js';
|
|
12
|
+
import { getLogger } from '../logger.js';
|
|
13
|
+
const log = getLogger();
|
|
14
|
+
const inputSchema = objectSchema({
|
|
15
|
+
sharingUrl: { type: 'string', minLength: 1 },
|
|
16
|
+
password: { type: 'string' },
|
|
17
|
+
screenId: { anyOf: [{ type: 'integer' }, { type: 'string' }] },
|
|
18
|
+
objectId: { type: 'string' },
|
|
19
|
+
screenName: { type: 'string' },
|
|
20
|
+
layerObjectId: {
|
|
21
|
+
type: 'string',
|
|
22
|
+
description: 'Optional object_id of the selected CoDesign layer or group.',
|
|
23
|
+
},
|
|
24
|
+
selectionScope: {
|
|
25
|
+
type: 'string',
|
|
26
|
+
enum: [...LAYER_SELECTION_SCOPES],
|
|
27
|
+
default: 'layer',
|
|
28
|
+
description: 'Selection scope used with layerObjectId: layer returns the matching node, subtree adds strict descendants, and region returns all non-ancestor nodes fully contained by the selected bounds.',
|
|
29
|
+
},
|
|
30
|
+
targetPlatform: {
|
|
31
|
+
type: 'string',
|
|
32
|
+
description: 'Optional natural-language target platform for presentation metadata, e.g. web, Android, 安卓, iOS, 微信小程序, mini program, or raw. The raw CoDesign spec is still returned unchanged.',
|
|
33
|
+
},
|
|
34
|
+
targetUnit: {
|
|
35
|
+
type: 'string',
|
|
36
|
+
description: 'Optional target unit for platformSpec, e.g. px, rem, dp, pt, or rpx. Must be supported by targetPlatform.',
|
|
37
|
+
},
|
|
38
|
+
customScale: {
|
|
39
|
+
type: 'number',
|
|
40
|
+
minimum: 0,
|
|
41
|
+
description: 'Optional explicit conversion multiplier, equivalent to CoDesign custom scale such as 0.75 or 2. Cannot be combined with customWidth.',
|
|
42
|
+
},
|
|
43
|
+
customWidth: {
|
|
44
|
+
type: 'number',
|
|
45
|
+
minimum: 0,
|
|
46
|
+
description: 'Optional target artboard width for conversion, equivalent to CoDesign custom width. Scale is customWidth divided by the source artboard width. Cannot be combined with customScale.',
|
|
47
|
+
},
|
|
48
|
+
remBasePx: {
|
|
49
|
+
type: 'number',
|
|
50
|
+
minimum: 0,
|
|
51
|
+
description: 'Optional px-per-rem divisor used only when targetUnit is rem. Defaults to 16 and is returned in platformSpec.conversion.',
|
|
52
|
+
},
|
|
53
|
+
includeSlices: { type: 'boolean', default: true },
|
|
54
|
+
includeFullText: {
|
|
55
|
+
type: 'boolean',
|
|
56
|
+
default: false,
|
|
57
|
+
description: 'Set true only if your client cannot read structuredContent. Then content[0].text carries the full JSON instead of a short summary.',
|
|
58
|
+
},
|
|
59
|
+
}, ['sharingUrl']);
|
|
60
|
+
export function registerSpecTool(server) {
|
|
61
|
+
server.registerTool('get_artboard_spec', {
|
|
62
|
+
title: 'Get CoDesign Artboard Spec',
|
|
63
|
+
description: 'Canonical CoDesign source for design-to-code: fetches the official meta_url JSON with layer positions, text, fills, colors, CSS, groups, and slice manifest. ' +
|
|
64
|
+
'Returns raw CoDesign fields; when css and fills disagree, inspect both fields and the screenshot instead of assuming one is always authoritative. ' +
|
|
65
|
+
'If targetPlatform is provided in natural language, also returns platformSpec with normalized platform id, unit, converted rects, and unit-adjusted CSS. targetUnit, customScale, customWidth, and remBasePx mirror CoDesign platform settings. ' +
|
|
66
|
+
'Use this before writing HTML/CSS from a CoDesign URL. Do not crop or OCR preview screenshots when this tool can return the spec. ' +
|
|
67
|
+
'Selector precedence: screenId > objectId > screenName. Multiple screens without a selector return SCREEN_SELECTOR_REQUIRED with options. ' +
|
|
68
|
+
'When layerObjectId is provided, selectionScope=layer preserves the single-node response, subtree returns the strict child hierarchy, and region returns the complete visual area inside the selected bounds with relative coordinates. ' +
|
|
69
|
+
'includeSlices defaults to true so available designer-exported slice metadata is returned with the spec.',
|
|
70
|
+
inputSchema,
|
|
71
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
72
|
+
}, async (args) => {
|
|
73
|
+
const { sharingUrl, password, screenId, objectId, screenName, layerObjectId, selectionScope, targetPlatform, targetUnit, customScale, customWidth, remBasePx, includeSlices, includeFullText, } = args;
|
|
74
|
+
let sharingId;
|
|
75
|
+
try {
|
|
76
|
+
sharingId = parseSharingId(sharingUrl);
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
return errorResult(err);
|
|
80
|
+
}
|
|
81
|
+
if (!layerObjectId && selectionScope !== 'layer') {
|
|
82
|
+
return errorResult(new CodesignError('INVALID_SELECTION', 'layerObjectId is required when selectionScope is subtree or region', { selectionScope }));
|
|
83
|
+
}
|
|
84
|
+
const call = await browserManager.acquireHeadless();
|
|
85
|
+
try {
|
|
86
|
+
const { detail } = await getCachedSharingDetail(call.page, sharingId, password);
|
|
87
|
+
const allScreens = [];
|
|
88
|
+
for (const d of detail.designs ?? []) {
|
|
89
|
+
for (const s of d.screens ?? [])
|
|
90
|
+
allScreens.push(s);
|
|
91
|
+
}
|
|
92
|
+
if (allScreens.length === 0) {
|
|
93
|
+
return errorResult(new CodesignError('SHARING_NOT_FOUND', 'sharing has no screens', { sharingId }));
|
|
94
|
+
}
|
|
95
|
+
const selector = { screenId, objectId, screenName };
|
|
96
|
+
const picked = pickScreen(allScreens, selector);
|
|
97
|
+
if (!picked) {
|
|
98
|
+
if (anyProvided(selector)) {
|
|
99
|
+
return errorResult(new CodesignError('SCREEN_NOT_FOUND', 'no screen matches the given selector', {
|
|
100
|
+
selector,
|
|
101
|
+
available: summarizeScreens(allScreens),
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
// 多画板未指定
|
|
105
|
+
if (allScreens.length === 1) {
|
|
106
|
+
// 单画板默认 picked,逻辑不到这里。但保险起见。
|
|
107
|
+
return errorResult(new CodesignError('SCREEN_NOT_FOUND', 'no screen matched (unexpected)', {}));
|
|
108
|
+
}
|
|
109
|
+
return errorResult(new CodesignError('SCREEN_SELECTOR_REQUIRED', 'multiple screens present; specify screenId / objectId / screenName', { available: summarizeScreens(allScreens) }));
|
|
110
|
+
}
|
|
111
|
+
// 拉 meta JSON;缓存入口已做 schema + 完整性校验,失败结果不会入缓存。
|
|
112
|
+
let spec;
|
|
113
|
+
try {
|
|
114
|
+
spec = await fetchCachedSpec(picked.meta_url);
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
log.warn({ err: errMsg(err) }, 'spec schema or integrity mismatch');
|
|
118
|
+
return errorResult(err);
|
|
119
|
+
}
|
|
120
|
+
const specIntegrity = integrityView(inspectSpec(spec));
|
|
121
|
+
let slices = undefined;
|
|
122
|
+
if (includeSlices && picked.slices_url) {
|
|
123
|
+
slices = await fetchCachedSliceManifest(picked.slices_url);
|
|
124
|
+
}
|
|
125
|
+
const hasPlatformOptions = targetUnit != null || customScale != null || customWidth != null || remBasePx != null;
|
|
126
|
+
if (!targetPlatform && hasPlatformOptions) {
|
|
127
|
+
return errorResult(new CodesignError('INVALID_PLATFORM', 'targetPlatform is required when targetUnit, customScale, customWidth, or remBasePx is set', { targetUnit, customScale, customWidth, remBasePx }));
|
|
128
|
+
}
|
|
129
|
+
const platformSpec = targetPlatform
|
|
130
|
+
? buildPlatformSpec(spec, targetPlatform, {
|
|
131
|
+
targetUnit,
|
|
132
|
+
customScale,
|
|
133
|
+
customWidth,
|
|
134
|
+
remBasePx,
|
|
135
|
+
})
|
|
136
|
+
: undefined;
|
|
137
|
+
const normalized = normalizeSpec(spec, slices, platformSpec);
|
|
138
|
+
if (layerObjectId) {
|
|
139
|
+
const layer = findLayerByObjectId(normalized, layerObjectId);
|
|
140
|
+
const selection = buildLayerSelection(normalized, layerObjectId, selectionScope);
|
|
141
|
+
if (!layer || !selection) {
|
|
142
|
+
return errorResult(new CodesignError('SCREEN_NOT_FOUND', 'layer not found by objectId', {
|
|
143
|
+
layerObjectId,
|
|
144
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
return toolSuccess({
|
|
148
|
+
sharingId,
|
|
149
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
150
|
+
integrity: specIntegrity,
|
|
151
|
+
layer,
|
|
152
|
+
selection,
|
|
153
|
+
platformLayer: platformSpec
|
|
154
|
+
? [...platformSpec.layers, ...platformSpec.groups].find((l) => l.objectId === layerObjectId)
|
|
155
|
+
: undefined,
|
|
156
|
+
platformSelection: platformSpec
|
|
157
|
+
? buildPlatformSelection(platformSpec, selection)
|
|
158
|
+
: undefined,
|
|
159
|
+
platform: platformSpec
|
|
160
|
+
? {
|
|
161
|
+
requested: platformSpec.requested,
|
|
162
|
+
id: platformSpec.id,
|
|
163
|
+
label: platformSpec.label,
|
|
164
|
+
unit: platformSpec.unit,
|
|
165
|
+
scale: platformSpec.scale,
|
|
166
|
+
conversion: platformSpec.conversion,
|
|
167
|
+
}
|
|
168
|
+
: undefined,
|
|
169
|
+
}, includeFullText, summarizeSpecPayload);
|
|
170
|
+
}
|
|
171
|
+
return toolSuccess({
|
|
172
|
+
sharingId,
|
|
173
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
174
|
+
integrity: specIntegrity,
|
|
175
|
+
supportedTargetPlatforms: supportedTargetPlatforms(),
|
|
176
|
+
spec: normalized,
|
|
177
|
+
}, includeFullText, summarizeSpecPayload);
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
log.warn({ err: errMsg(err), sharingId }, 'get_artboard_spec failed');
|
|
181
|
+
return errorResult(err);
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
await call.done();
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
function anyProvided(sel) {
|
|
189
|
+
return sel.screenId != null || sel.objectId != null || sel.screenName != null;
|
|
190
|
+
}
|
|
191
|
+
export function pickScreen(screens, sel) {
|
|
192
|
+
if (sel.screenId != null) {
|
|
193
|
+
const idStr = String(sel.screenId);
|
|
194
|
+
return screens.find((s) => String(s.id) === idStr);
|
|
195
|
+
}
|
|
196
|
+
if (sel.objectId) {
|
|
197
|
+
return screens.find((s) => s.object_id === sel.objectId);
|
|
198
|
+
}
|
|
199
|
+
if (sel.screenName) {
|
|
200
|
+
return screens.find((s) => s.name === sel.screenName);
|
|
201
|
+
}
|
|
202
|
+
// 单画板时默认选第一个
|
|
203
|
+
if (screens.length === 1)
|
|
204
|
+
return screens[0];
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
export function summarizeScreens(screens) {
|
|
208
|
+
return screens.map((s) => ({
|
|
209
|
+
id: s.id,
|
|
210
|
+
objectId: s.object_id,
|
|
211
|
+
name: s.name,
|
|
212
|
+
width: s.width,
|
|
213
|
+
height: s.height,
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
function errMsg(err) {
|
|
217
|
+
if (err instanceof Error)
|
|
218
|
+
return err.message;
|
|
219
|
+
return String(err);
|
|
220
|
+
}
|
|
221
|
+
function buildPlatformSelection(platformSpec, selection) {
|
|
222
|
+
const selectedIds = new Set([...selection.layers, ...selection.groups].map((layer) => layer.object_id));
|
|
223
|
+
const root = [...platformSpec.layers, ...platformSpec.groups].find((layer) => layer.objectId === selection.rootObjectId);
|
|
224
|
+
if (!root) {
|
|
225
|
+
throw new CodesignError('META_SCHEMA_MISMATCH', 'platform selection root is missing', {
|
|
226
|
+
rootObjectId: selection.rootObjectId,
|
|
227
|
+
platform: platformSpec.id,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
return {
|
|
231
|
+
scope: selection.scope,
|
|
232
|
+
root,
|
|
233
|
+
layers: platformSpec.layers.filter((layer) => selectedIds.has(layer.objectId)),
|
|
234
|
+
groups: platformSpec.groups.filter((layer) => selectedIds.has(layer.objectId)),
|
|
235
|
+
};
|
|
236
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { existsSync, statSync } from 'node:fs';
|
|
2
|
+
import { objectSchema } from '../mcp/schema.js';
|
|
3
|
+
import { config } from '../config.js';
|
|
4
|
+
import { browserManager } from '../browser/manager.js';
|
|
5
|
+
import { cacheStats } from '../codesign/cache.js';
|
|
6
|
+
import { rateLimitStats } from '../utils/rate-limit.js';
|
|
7
|
+
const inputSchema = objectSchema({});
|
|
8
|
+
export function registerStatusTool(server) {
|
|
9
|
+
server.registerTool('codesign_status', {
|
|
10
|
+
title: 'CoDesign Status',
|
|
11
|
+
description: 'Return MCP server config (profile path, idle settings) and current browser/login status. ' +
|
|
12
|
+
'Use this first to verify whether the user has logged in.',
|
|
13
|
+
inputSchema,
|
|
14
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
15
|
+
}, async () => {
|
|
16
|
+
const profileExists = existsSync(config.profileDir);
|
|
17
|
+
let profileSize = 0;
|
|
18
|
+
try {
|
|
19
|
+
if (profileExists)
|
|
20
|
+
profileSize = statSync(config.profileDir).size;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
/* ignore */
|
|
24
|
+
}
|
|
25
|
+
const browser = browserManager.snapshot();
|
|
26
|
+
const status = {
|
|
27
|
+
version: config.packageVersion,
|
|
28
|
+
config: {
|
|
29
|
+
packageRoot: config.packageRoot,
|
|
30
|
+
packageVersion: config.packageVersion,
|
|
31
|
+
workspaceRoot: config.workspaceRoot,
|
|
32
|
+
workspaceRootSource: config.workspaceRootSource,
|
|
33
|
+
dataDir: config.dataDir,
|
|
34
|
+
dataDirSource: config.dataDirSource,
|
|
35
|
+
profileDir: config.profileDir,
|
|
36
|
+
artifactsDir: config.artifactsDir,
|
|
37
|
+
idleMs: config.idleMs,
|
|
38
|
+
keepBrowser: config.keepBrowser,
|
|
39
|
+
retryMaxAttempts: config.retryMaxAttempts,
|
|
40
|
+
apiRps: config.apiRps,
|
|
41
|
+
cdnRps: config.cdnRps,
|
|
42
|
+
},
|
|
43
|
+
profile: {
|
|
44
|
+
exists: profileExists,
|
|
45
|
+
byteSize: profileSize,
|
|
46
|
+
},
|
|
47
|
+
browser,
|
|
48
|
+
cache: cacheStats(),
|
|
49
|
+
rateLimit: rateLimitStats(),
|
|
50
|
+
notes: 'Runtime files default to <workspaceRoot>/.codesign-mcp and are created only when a tool needs local state or artifacts. Login state is persisted in profileDir. CoDesign design-to-code tasks should use list_artboards, get_artboard_spec, and download_slice instead of cropping preview screenshots.',
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
structuredContent: status,
|
|
54
|
+
content: [
|
|
55
|
+
{
|
|
56
|
+
type: 'text',
|
|
57
|
+
text: JSON.stringify(status, null, 2),
|
|
58
|
+
},
|
|
59
|
+
],
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve, dirname, extname, basename, relative, isAbsolute, sep } from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { config } from '../config.js';
|
|
5
|
+
import { CodesignError } from '../codesign/errors.js';
|
|
6
|
+
import { assertAllowedRemoteUrl, normalizeCodesignAssetUrl } from './url.js';
|
|
7
|
+
import { throttle } from './rate-limit.js';
|
|
8
|
+
import { assertNotRateLimited, withRetry } from './retry.js';
|
|
9
|
+
const DEFAULT_HEADERS = {
|
|
10
|
+
'User-Agent': 'Mozilla/5.0 (CodesignMcp/0.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
|
|
11
|
+
Accept: '*/*',
|
|
12
|
+
};
|
|
13
|
+
const FILE_COMMIT_RETRY_DELAYS_MS = [50, 150, 350];
|
|
14
|
+
// 把 URL 下载到 data/artifacts/<subdir>/<filename>。filename 为空时根据 URL 推断或哈希。
|
|
15
|
+
export async function downloadToArtifact(url, subdir, filename, errorCode = 'SLICE_FETCH_FAILED', options = {}) {
|
|
16
|
+
const remoteUrl = normalizeCodesignAssetUrl(url);
|
|
17
|
+
assertAllowedRemoteUrl(remoteUrl, 'download');
|
|
18
|
+
const targetDir = resolveInside(config.artifactsDir, subdir);
|
|
19
|
+
mkdirSync(targetDir, { recursive: true });
|
|
20
|
+
const finalName = filename ?? deriveFilename(url);
|
|
21
|
+
const finalPath = resolveInside(targetDir, finalName);
|
|
22
|
+
mkdirSync(dirname(finalPath), { recursive: true });
|
|
23
|
+
const existing = getExistingArtifact(finalPath, options.expectedBytes);
|
|
24
|
+
if (existing) {
|
|
25
|
+
const buf = readExistingArtifact(finalPath);
|
|
26
|
+
return {
|
|
27
|
+
url,
|
|
28
|
+
path: finalPath,
|
|
29
|
+
bytes: existing.bytes,
|
|
30
|
+
mime: null,
|
|
31
|
+
reusedExisting: true,
|
|
32
|
+
writeAttempts: 0,
|
|
33
|
+
verified: {
|
|
34
|
+
bytes: existing.bytes,
|
|
35
|
+
sha256: sha256(buf),
|
|
36
|
+
format: detectArtifactFormat(buf),
|
|
37
|
+
reused: true,
|
|
38
|
+
contentLength: null,
|
|
39
|
+
contentEncoding: null,
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
const headers = { ...DEFAULT_HEADERS, ...options.headers };
|
|
45
|
+
const resp = await withRetry(async () => {
|
|
46
|
+
await throttle(remoteUrl);
|
|
47
|
+
if (options.request) {
|
|
48
|
+
const result = await fetchWithBrowserContext(options.request, remoteUrl, headers);
|
|
49
|
+
assertNotRateLimited(result.status, 'artifact download', result.retryAfter);
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
const controller = new AbortController();
|
|
53
|
+
const timer = setTimeout(() => controller.abort(), config.metaTimeoutMs);
|
|
54
|
+
try {
|
|
55
|
+
const result = await fetchWithNode(remoteUrl, headers, controller.signal);
|
|
56
|
+
assertNotRateLimited(result.status, 'artifact download', result.retryAfter);
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
if (!resp.ok || resp.status !== 200) {
|
|
64
|
+
throw new CodesignError(errorCode, `download failed: HTTP ${resp.status}`, {
|
|
65
|
+
url: remoteUrl,
|
|
66
|
+
status: resp.status,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
const buf = resp.body;
|
|
70
|
+
const format = assertArtifactIntegrity(buf, remoteUrl, {
|
|
71
|
+
expectedBytes: options.expectedBytes,
|
|
72
|
+
expectedMime: options.expectedMime,
|
|
73
|
+
expectedFormat: options.expectedFormat,
|
|
74
|
+
mime: resp.mime,
|
|
75
|
+
contentLength: resp.contentLength,
|
|
76
|
+
contentEncoding: resp.contentEncoding,
|
|
77
|
+
});
|
|
78
|
+
const writeAttempts = await commitArtifactWithRetry(finalPath, buf);
|
|
79
|
+
const committedBytes = statSync(finalPath).size;
|
|
80
|
+
if (committedBytes !== buf.byteLength) {
|
|
81
|
+
rmSync(finalPath, { force: true });
|
|
82
|
+
throw new CodesignError('ARTIFACT_SIZE_MISMATCH', 'committed artifact size differs from downloaded bytes', {
|
|
83
|
+
url: remoteUrl,
|
|
84
|
+
path: finalPath,
|
|
85
|
+
expected: buf.byteLength,
|
|
86
|
+
actual: committedBytes,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
url: remoteUrl,
|
|
91
|
+
path: finalPath,
|
|
92
|
+
bytes: buf.byteLength,
|
|
93
|
+
mime: resp.mime,
|
|
94
|
+
writeAttempts,
|
|
95
|
+
verified: {
|
|
96
|
+
bytes: buf.byteLength,
|
|
97
|
+
sha256: sha256(buf),
|
|
98
|
+
format,
|
|
99
|
+
reused: false,
|
|
100
|
+
contentLength: resp.contentLength,
|
|
101
|
+
contentEncoding: resp.contentEncoding,
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
if (err instanceof CodesignError)
|
|
107
|
+
throw err;
|
|
108
|
+
throw new CodesignError(errorCode, `download threw: ${err.message}`, {
|
|
109
|
+
url: remoteUrl,
|
|
110
|
+
path: finalPath,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function resolveInside(root, child) {
|
|
115
|
+
const resolvedRoot = resolve(root);
|
|
116
|
+
const resolvedTarget = resolve(resolvedRoot, child);
|
|
117
|
+
const rel = relative(resolvedRoot, resolvedTarget);
|
|
118
|
+
if (rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))) {
|
|
119
|
+
return resolvedTarget;
|
|
120
|
+
}
|
|
121
|
+
throw new CodesignError('ARTIFACT_PATH_INVALID', 'artifact path escapes artifactsDir', {
|
|
122
|
+
root: resolvedRoot,
|
|
123
|
+
child,
|
|
124
|
+
resolvedTarget,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
function getExistingArtifact(path, expectedBytes) {
|
|
128
|
+
if (typeof expectedBytes !== 'number' || !Number.isSafeInteger(expectedBytes) || expectedBytes < 0) {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const stat = statSync(path);
|
|
133
|
+
if (stat.isFile() && stat.size === expectedBytes)
|
|
134
|
+
return { bytes: stat.size };
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
if (isErrnoException(err) && err.code === 'ENOENT')
|
|
139
|
+
return undefined;
|
|
140
|
+
throw err;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
async function commitArtifactWithRetry(finalPath, buf) {
|
|
144
|
+
for (let attempt = 0; attempt <= FILE_COMMIT_RETRY_DELAYS_MS.length; attempt += 1) {
|
|
145
|
+
const tempPath = `${finalPath}.${process.pid}.${Date.now()}.${attempt}.tmp`;
|
|
146
|
+
try {
|
|
147
|
+
writeFileSync(tempPath, buf);
|
|
148
|
+
renameSync(tempPath, finalPath);
|
|
149
|
+
return attempt + 1;
|
|
150
|
+
}
|
|
151
|
+
catch (err) {
|
|
152
|
+
rmSync(tempPath, { force: true });
|
|
153
|
+
if (!isRetryableFileCommitError(err) || attempt === FILE_COMMIT_RETRY_DELAYS_MS.length) {
|
|
154
|
+
throw err;
|
|
155
|
+
}
|
|
156
|
+
await delay(FILE_COMMIT_RETRY_DELAYS_MS[attempt]);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
throw new Error('artifact write retry loop exhausted');
|
|
160
|
+
}
|
|
161
|
+
function isRetryableFileCommitError(err) {
|
|
162
|
+
if (!isErrnoException(err))
|
|
163
|
+
return false;
|
|
164
|
+
return err.code === 'EPERM' || err.code === 'EBUSY' || err.code === 'EACCES';
|
|
165
|
+
}
|
|
166
|
+
function isErrnoException(err) {
|
|
167
|
+
return err instanceof Error && 'code' in err;
|
|
168
|
+
}
|
|
169
|
+
function delay(ms) {
|
|
170
|
+
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
|
|
171
|
+
}
|
|
172
|
+
async function fetchWithNode(url, headers, signal) {
|
|
173
|
+
const resp = await fetch(url, { headers, signal });
|
|
174
|
+
return {
|
|
175
|
+
ok: resp.ok,
|
|
176
|
+
status: resp.status,
|
|
177
|
+
body: Buffer.from(await resp.arrayBuffer()),
|
|
178
|
+
mime: resp.headers.get('content-type'),
|
|
179
|
+
contentLength: resp.headers.get('content-length'),
|
|
180
|
+
contentEncoding: resp.headers.get('content-encoding'),
|
|
181
|
+
retryAfter: resp.headers.get('retry-after'),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
async function fetchWithBrowserContext(request, url, headers) {
|
|
185
|
+
const resp = await request.get(url, { headers, timeout: config.metaTimeoutMs });
|
|
186
|
+
const responseHeaders = resp.headers();
|
|
187
|
+
return {
|
|
188
|
+
ok: resp.ok(),
|
|
189
|
+
status: resp.status(),
|
|
190
|
+
body: await resp.body(),
|
|
191
|
+
mime: responseHeaders['content-type'] ?? null,
|
|
192
|
+
contentLength: responseHeaders['content-length'] ?? null,
|
|
193
|
+
contentEncoding: responseHeaders['content-encoding'] ?? null,
|
|
194
|
+
retryAfter: responseHeaders['retry-after'] ?? null,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
function sha256(buf) {
|
|
198
|
+
return createHash('sha256').update(buf).digest('hex');
|
|
199
|
+
}
|
|
200
|
+
function readExistingArtifact(path) {
|
|
201
|
+
return readFileSync(path);
|
|
202
|
+
}
|
|
203
|
+
// 魔数嗅探:识别真实图片格式,同时识别 HTML/XML 错误页。
|
|
204
|
+
export function detectArtifactFormat(buf) {
|
|
205
|
+
if (buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
|
|
206
|
+
return 'png';
|
|
207
|
+
if (buf.length > 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff)
|
|
208
|
+
return 'jpeg';
|
|
209
|
+
if (buf.length > 12 &&
|
|
210
|
+
buf.subarray(0, 4).toString('ascii') === 'RIFF' &&
|
|
211
|
+
buf.subarray(8, 12).toString('ascii') === 'WEBP')
|
|
212
|
+
return 'webp';
|
|
213
|
+
if (buf.subarray(0, 4).toString('ascii') === 'GIF8')
|
|
214
|
+
return 'gif';
|
|
215
|
+
const head = buf.subarray(0, 512).toString('utf8').replace(/^\uFEFF/, '');
|
|
216
|
+
if (/^(?:\s|<\?xml[^>]*>|<!--[\s\S]*?-->|<!DOCTYPE[^>]*>)*<svg[\s>]/i.test(head))
|
|
217
|
+
return 'svg';
|
|
218
|
+
if (/^\s*(?:<\?xml|<!DOCTYPE\s+html|<html)/i.test(head))
|
|
219
|
+
return 'error-page';
|
|
220
|
+
return 'unknown';
|
|
221
|
+
}
|
|
222
|
+
function formatMatches(format, expected) {
|
|
223
|
+
const normalized = expected.toLowerCase().replace(/^image\//, '');
|
|
224
|
+
if (normalized === 'jpg' || normalized === 'jpeg')
|
|
225
|
+
return format === 'jpeg';
|
|
226
|
+
if (normalized === 'svg' || normalized === 'svg+xml')
|
|
227
|
+
return format === 'svg';
|
|
228
|
+
return format === normalized;
|
|
229
|
+
}
|
|
230
|
+
export function assertArtifactIntegrity(buf, url, opts) {
|
|
231
|
+
const encoding = opts.contentEncoding?.toLowerCase() ?? '';
|
|
232
|
+
if (opts.expectedBytes != null && Number.isSafeInteger(opts.expectedBytes) && opts.expectedBytes > 0) {
|
|
233
|
+
if (buf.byteLength !== opts.expectedBytes) {
|
|
234
|
+
throw new CodesignError('ARTIFACT_SIZE_MISMATCH', 'downloaded size differs from declared size', {
|
|
235
|
+
url,
|
|
236
|
+
expected: opts.expectedBytes,
|
|
237
|
+
actual: buf.byteLength,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (opts.contentLength && !encoding) {
|
|
242
|
+
const declared = Number(opts.contentLength);
|
|
243
|
+
if (Number.isSafeInteger(declared) && declared >= 0 && buf.byteLength !== declared) {
|
|
244
|
+
throw new CodesignError('ARTIFACT_SIZE_MISMATCH', 'downloaded size differs from Content-Length', {
|
|
245
|
+
url,
|
|
246
|
+
expected: declared,
|
|
247
|
+
actual: buf.byteLength,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const format = detectArtifactFormat(buf);
|
|
252
|
+
if (format === 'error-page') {
|
|
253
|
+
throw new CodesignError('ARTIFACT_MAGIC_MISMATCH', 'downloaded body looks like an HTML/XML error page', {
|
|
254
|
+
url,
|
|
255
|
+
mime: opts.mime,
|
|
256
|
+
bytes: buf.byteLength,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
if (opts.expectedFormat && format !== 'unknown' && !formatMatches(format, opts.expectedFormat)) {
|
|
260
|
+
throw new CodesignError('ARTIFACT_MAGIC_MISMATCH', 'downloaded format differs from manifest format', {
|
|
261
|
+
url,
|
|
262
|
+
expected: opts.expectedFormat,
|
|
263
|
+
actual: format,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
if (opts.expectedMime && format !== 'unknown' && !formatMatches(format, opts.expectedMime)) {
|
|
267
|
+
throw new CodesignError('ARTIFACT_MAGIC_MISMATCH', 'downloaded format differs from declared MIME type', {
|
|
268
|
+
url,
|
|
269
|
+
expected: opts.expectedMime,
|
|
270
|
+
actual: format,
|
|
271
|
+
mime: opts.mime,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
return format;
|
|
275
|
+
}
|
|
276
|
+
function deriveFilename(url) {
|
|
277
|
+
try {
|
|
278
|
+
const u = new URL(url);
|
|
279
|
+
const last = basename(u.pathname);
|
|
280
|
+
if (last && extname(last))
|
|
281
|
+
return last;
|
|
282
|
+
const ext = extname(last) || '';
|
|
283
|
+
const hash = createHash('sha256').update(url).digest('hex').slice(0, 12);
|
|
284
|
+
return `${hash}${ext || '.bin'}`;
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
const hash = createHash('sha256').update(url).digest('hex').slice(0, 12);
|
|
288
|
+
return `${hash}.bin`;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const SAFE_FILENAME_BYTE = /^[A-Za-z0-9._~-]$/;
|
|
2
|
+
/**
|
|
3
|
+
* Encode an arbitrary identifier as one reversible, cross-platform filename component.
|
|
4
|
+
* Percent signs are encoded too, so distinct source identifiers cannot collapse onto the
|
|
5
|
+
* same Windows-safe filename.
|
|
6
|
+
*/
|
|
7
|
+
export function encodeFilenameComponent(value) {
|
|
8
|
+
let encoded = '';
|
|
9
|
+
for (const byte of Buffer.from(value, 'utf8')) {
|
|
10
|
+
const char = String.fromCharCode(byte);
|
|
11
|
+
encoded += SAFE_FILENAME_BYTE.test(char)
|
|
12
|
+
? char
|
|
13
|
+
: `%${byte.toString(16).toUpperCase().padStart(2, '0')}`;
|
|
14
|
+
}
|
|
15
|
+
return encoded;
|
|
16
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// 用 Playwright BrowserContext 绑定的 APIRequestContext 发请求。
|
|
2
|
+
// 它复用浏览器上下文 cookie,避免在页面里动态执行 fetch。
|
|
3
|
+
import { CodesignError } from '../codesign/errors.js';
|
|
4
|
+
import { config } from '../config.js';
|
|
5
|
+
import { assertCodesignOriginUrl } from './url.js';
|
|
6
|
+
import { throttle } from './rate-limit.js';
|
|
7
|
+
import { assertNotRateLimited, withRetry } from './retry.js';
|
|
8
|
+
export async function requestJson(request, req) {
|
|
9
|
+
assertCodesignOriginUrl(req.url, 'same-origin request', config.origin);
|
|
10
|
+
const headers = {
|
|
11
|
+
Accept: 'application/json',
|
|
12
|
+
...(req.headers ?? {}),
|
|
13
|
+
};
|
|
14
|
+
if (req.body !== undefined) {
|
|
15
|
+
headers['Content-Type'] = 'application/json;charset=UTF-8';
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
const response = await withRetry(async () => {
|
|
19
|
+
await throttle(req.url);
|
|
20
|
+
const resp = await request.fetch(req.url, {
|
|
21
|
+
method: req.method ?? 'GET',
|
|
22
|
+
headers,
|
|
23
|
+
data: req.body === undefined ? undefined : JSON.stringify(req.body),
|
|
24
|
+
timeout: config.apiTimeoutMs,
|
|
25
|
+
});
|
|
26
|
+
const responseHeaders = typeof resp.headers === 'function' ? resp.headers() : {};
|
|
27
|
+
assertNotRateLimited(resp.status(), 'same-origin request', responseHeaders['retry-after']);
|
|
28
|
+
return resp;
|
|
29
|
+
});
|
|
30
|
+
const rawText = await response.text();
|
|
31
|
+
return {
|
|
32
|
+
status: response.status(),
|
|
33
|
+
body: parseJsonBody(rawText),
|
|
34
|
+
rawText,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
if (err instanceof CodesignError)
|
|
39
|
+
throw err;
|
|
40
|
+
throw new CodesignError('SHARING_FETCH_FAILED', `same-origin request failed: ${err.message}`, {
|
|
41
|
+
url: req.url,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function parseJsonBody(text) {
|
|
46
|
+
if (!text)
|
|
47
|
+
return null;
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(text);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
}
|