Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b1cadd0cc8 | |||
| 261228ed3f | |||
| 8c17e40d7d | |||
| 237e440057 | |||
| e3682fd06f | |||
| fc46cabb75 | |||
| 762f037150 | |||
| 48985d3447 |
@@ -102,7 +102,7 @@ Use OpenAPI as the final authority; these common values are a routing aid:
|
||||
|
||||
- Image `kind`: `spec`, `character`, `quick-edit`, `ui-design`, `publication-material`; ordinary image generation may omit it.
|
||||
- External v1 currently has no structured game-scene generation operation. Do not send `kind: "scene"` or `assetKind: "scene"` through generic image generation; the server rejects both before queueing.
|
||||
- Image `model`: `gpt-image-2.5`, `gemini-3.1-flash-image-preview`, `nanobanana2`, `nano-banana`. Persisted `gpt-image-2` / `gpt-image-2-c` are legacy values resolved only when submitting a new task.
|
||||
- Image `model`: `gpt-image-2`, `gemini-3.1-flash-image-preview`, `nanobanana2`, `nano-banana`.
|
||||
- Image `aspectRatio`: `1:1`, `2:3`, `3:2`, `9:16`, `16:9`.
|
||||
- Image `imageSize`: `0.5K`, `1K`, `2K`.
|
||||
- Video `model`: `seedance2.0`, `seedance2.0-fast`, `kling3.0`, `kling3.0-omni`, `veo3.1`, `veo3.1-fast`.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
---
|
||||
name: gpt-image-2-apimart
|
||||
description: Generate or inspect project image assets through this repository's image workflow using the GPT Image 2.5 business model. Use when Codex needs to create puzzle template sample images, reproduce the server-rs image request body, dry-run image prompts, batch-generate local project thumbnails, or debug VECTOR_ENGINE_BASE_URL / VECTOR_ENGINE_API_KEY image-generation configuration without exposing secrets. The directory name is historical.
|
||||
description: Generate or inspect project image assets through this repository's VectorEngine gpt-image-2 workflow with gpt-image-2-c fallback. Use when Codex needs to create puzzle template sample images, reproduce the server-rs image request body, dry-run image prompts, batch-generate local project thumbnails, or debug VECTOR_ENGINE_BASE_URL / VECTOR_ENGINE_API_KEY image-generation configuration without exposing secrets. The directory name is historical.
|
||||
---
|
||||
|
||||
# GPT Image 2.5 project image workflow
|
||||
# gpt-image-2 VectorEngine
|
||||
|
||||
Use this skill for project-local image asset generation that must match the repository's image request contract. Use the business model identifier `gpt-image-2.5`; provider concrete model routing is owned by `server-rs`, and this client must not perform a cross-model fallback. The folder still contains `apimart` in its name for compatibility with existing local plugin references.
|
||||
Use this skill for project-local image asset generation that must match the repository's `server-rs` VectorEngine image path. Keep the product/price model identifier and primary provider request as `gpt-image-2`, then fall back once to `gpt-image-2-c` for eligible provider failures. The folder still contains `apimart` in its name for compatibility with existing local plugin references.
|
||||
|
||||
## Workflow
|
||||
|
||||
@@ -40,7 +40,7 @@ Default body:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "gpt-image-2.5",
|
||||
"model": "gpt-image-2",
|
||||
"prompt": "<prompt>",
|
||||
"n": 1,
|
||||
"size": "1024x1024"
|
||||
@@ -58,14 +58,14 @@ Content-Type: multipart/form-data
|
||||
Multipart fields:
|
||||
|
||||
```text
|
||||
model=gpt-image-2.5
|
||||
model=gpt-image-2
|
||||
prompt=<prompt>
|
||||
n=1
|
||||
size=1024x1024
|
||||
image=@reference.png
|
||||
```
|
||||
|
||||
In this repository, calls with no reference images use `POST /v1/images/generations`; calls with any reference image use `POST /v1/images/edits` and pass references as one or more `image` form parts. Both paths send the business model `gpt-image-2.5`; provider routing and retry policy remain server-owned. Match3D container UI generation embeds `public/match3d-background-references/pot-fused-reference.png` into the edit request as an `image` part.
|
||||
In this repository, calls with no reference images use `POST /v1/images/generations`; calls with any reference image use `POST /v1/images/edits` and pass references as one or more `image` form parts. Both paths prefer `gpt-image-2`; on an eligible upstream/model failure they retry with `gpt-image-2-c`. Do not fall back for authentication, local validation, request-budget exhaustion, uncertain send/connection failure, content-safety rejection, or a generated image URL download failure. Match3D container UI generation embeds `public/match3d-background-references/pot-fused-reference.png` into the edit request as an `image` part.
|
||||
|
||||
Accept image output from `data[].url`, `data[].b64_json`, or direct nested `url` fields. VectorEngine image generation currently returns synchronously; do not poll APIMart task endpoints.
|
||||
|
||||
|
||||
@@ -9,7 +9,8 @@ const skillRoot = path.resolve(__dirname, '..');
|
||||
const repoRoot = path.resolve(skillRoot, '..', '..', '..');
|
||||
const defaultOutDir = path.join(repoRoot, 'public', 'anthro-cat-illustrations');
|
||||
const defaultTimeoutMs = 1000000;
|
||||
const preferredImageModel = 'gpt-image-2.5';
|
||||
const preferredImageModel = 'gpt-image-2';
|
||||
const fallbackImageModel = 'gpt-image-2-c';
|
||||
|
||||
const prompts = [
|
||||
{
|
||||
@@ -255,8 +256,41 @@ async function fetchJson(url, options, timeoutMs) {
|
||||
}
|
||||
}
|
||||
|
||||
function shouldFallbackImageModel(error) {
|
||||
const raw =
|
||||
`${error?.message || ''}\n${error?.vectorEngineBody || ''}`.toLowerCase();
|
||||
if (error?.vectorEngineResponseParse) {
|
||||
return !containsContentRejection(raw);
|
||||
}
|
||||
const status = Number(error?.vectorEngineStatus || 0);
|
||||
if (status === 408 || status >= 500) {
|
||||
return true;
|
||||
}
|
||||
if (status === 429) {
|
||||
return !containsContentRejection(raw);
|
||||
}
|
||||
const mentionsImageModel =
|
||||
raw.includes('model') ||
|
||||
raw.includes('模型') ||
|
||||
raw.includes(preferredImageModel) ||
|
||||
raw.includes(fallbackImageModel);
|
||||
return (
|
||||
[400, 404, 422].includes(status) &&
|
||||
mentionsImageModel &&
|
||||
/(not found|not supported|unsupported|unavailable|does not exist|invalid model|unknown model|不存在|不支持|不可用|未开通)/u.test(
|
||||
raw,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function containsContentRejection(raw) {
|
||||
return /(invalid_prompt|safety|content[_ ]policy|moderation|prompt rejected|content rejected|prompt refusal|content refusal|rejected by safety|rejected by moderation|敏感|违规|安全策略|内容审核|提示词拒绝|内容拒绝)/u.test(
|
||||
raw,
|
||||
);
|
||||
}
|
||||
|
||||
async function requestImagePayload(env, entry) {
|
||||
for (const model of [preferredImageModel]) {
|
||||
for (const model of [preferredImageModel, fallbackImageModel]) {
|
||||
const requestBody = {
|
||||
model,
|
||||
prompt: buildPrompt(entry),
|
||||
@@ -288,7 +322,12 @@ async function requestImagePayload(env, entry) {
|
||||
error.vectorEngineBody = JSON.stringify(payload).slice(0, 600);
|
||||
throw error;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
if (model !== preferredImageModel || !shouldFallbackImageModel(error)) {
|
||||
throw error;
|
||||
}
|
||||
console.warn(
|
||||
`VectorEngine ${preferredImageModel} failed, retrying with ${fallbackImageModel}: ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new Error(`VectorEngine returned no image for ${entry.id}`);
|
||||
@@ -369,7 +408,7 @@ if (dryRun) {
|
||||
requests: selectedPrompts.map((entry) => ({
|
||||
id: entry.id,
|
||||
title: entry.title,
|
||||
fallbackModel: null,
|
||||
fallbackModel: fallbackImageModel,
|
||||
body: {
|
||||
model: preferredImageModel,
|
||||
prompt: buildPrompt(entry),
|
||||
|
||||
@@ -18,7 +18,8 @@ const defaultOutDir = path.join(
|
||||
'puzzle-creation-templates',
|
||||
);
|
||||
const defaultTimeoutMs = 1000000;
|
||||
const preferredImageModel = 'gpt-image-2.5';
|
||||
const preferredImageModel = 'gpt-image-2';
|
||||
const fallbackImageModel = 'gpt-image-2-c';
|
||||
|
||||
const args = new Map();
|
||||
for (let index = 2; index < process.argv.length; index += 1) {
|
||||
@@ -225,8 +226,41 @@ async function fetchJson(url, options, timeoutMs) {
|
||||
}
|
||||
}
|
||||
|
||||
function shouldFallbackImageModel(error) {
|
||||
const raw =
|
||||
`${error?.message || ''}\n${error?.vectorEngineBody || ''}`.toLowerCase();
|
||||
if (error?.vectorEngineResponseParse) {
|
||||
return !containsContentRejection(raw);
|
||||
}
|
||||
const status = Number(error?.vectorEngineStatus || 0);
|
||||
if (status === 408 || status >= 500) {
|
||||
return true;
|
||||
}
|
||||
if (status === 429) {
|
||||
return !containsContentRejection(raw);
|
||||
}
|
||||
const mentionsImageModel =
|
||||
raw.includes('model') ||
|
||||
raw.includes('模型') ||
|
||||
raw.includes(preferredImageModel) ||
|
||||
raw.includes(fallbackImageModel);
|
||||
return (
|
||||
[400, 404, 422].includes(status) &&
|
||||
mentionsImageModel &&
|
||||
/(not found|not supported|unsupported|unavailable|does not exist|invalid model|unknown model|不存在|不支持|不可用|未开通)/u.test(
|
||||
raw,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function containsContentRejection(raw) {
|
||||
return /(invalid_prompt|safety|content[_ ]policy|moderation|prompt rejected|content rejected|prompt refusal|content refusal|rejected by safety|rejected by moderation|敏感|违规|安全策略|内容审核|提示词拒绝|内容拒绝)/u.test(
|
||||
raw,
|
||||
);
|
||||
}
|
||||
|
||||
async function requestImagePayload(env, template) {
|
||||
for (const model of [preferredImageModel]) {
|
||||
for (const model of [preferredImageModel, fallbackImageModel]) {
|
||||
const requestBody = {
|
||||
model,
|
||||
prompt: buildPrompt(template),
|
||||
@@ -260,7 +294,12 @@ async function requestImagePayload(env, template) {
|
||||
error.vectorEngineBody = JSON.stringify(payload).slice(0, 600);
|
||||
throw error;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
if (model !== preferredImageModel || !shouldFallbackImageModel(error)) {
|
||||
throw error;
|
||||
}
|
||||
console.warn(
|
||||
`VectorEngine ${preferredImageModel} failed, retrying with ${fallbackImageModel}: ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new Error(`VectorEngine returned no image for ${template.id}`);
|
||||
@@ -345,7 +384,7 @@ if (dryRun) {
|
||||
requests: selectedTemplates.map((template) => ({
|
||||
id: template.id,
|
||||
title: template.title,
|
||||
fallbackModel: null,
|
||||
fallbackModel: fallbackImageModel,
|
||||
body: {
|
||||
model: preferredImageModel,
|
||||
prompt: buildPrompt(template),
|
||||
|
||||
@@ -47,6 +47,8 @@ temp*build*/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-package.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/manifest.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/NOTICE.md
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/darwin-arm64/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/darwin-x64/
|
||||
/plugins/agc-cocos-editor/native/payload/
|
||||
/plugins/agc-unity-editor/dotnet/**/bin/
|
||||
/plugins/agc-unity-editor/dotnet/**/obj/
|
||||
|
||||
-29
@@ -44,35 +44,6 @@ _Avoid_: 把同一资源的全局元数据和某一次摆放坐标混在同一
|
||||
由图片生成或图片修改流程产生的画布资源,必须记录来源资源、提示词、实际提示词、模型、provider、任务 ID 和生成时间;本期 `/editor` 的生成修改先允许 mock 生成资源,但仍按生成资源元数据形状保存。
|
||||
_Avoid_: 无来源的静态素材、只显示在 UI 但不落工程资源记录的生成结果
|
||||
|
||||
**图片模型历史值与使用端解析**:
|
||||
图片资源中已持久化的 `gpt-image-2` 是历史业务事实,读回时保持原值;新任务使用业务模型值 `gpt-image-2.5`。当用户基于历史资源再次发起生成或编辑任务时,服务端只在新任务的使用端把历史值解析为当前业务模型,不改写历史资源。provider route 属于服务端执行与审计边界,前端不接收、不持久化、不展示,也不据此分支。
|
||||
_Avoid_: 读取数据库时改写历史模型值、把 provider route 暴露为前端模型选项或公开 DTO
|
||||
|
||||
**图片 provider 显式路由**:
|
||||
api-server 在任务入口按业务语义显式选择具体 provider model name(生成或编辑),并把同一具体名传给图片平台适配器和后台定价解析;图片平台适配器不从参考图数量或前端字段猜测任务。具体 provider model name 只存在于服务端调用、定价配置和审计边界。
|
||||
后台管理 Web/API 是明确例外,可以查看和编辑两个具体定价 key;主站普通前端与公开定价 API 不接收这些 key。
|
||||
_Avoid_: 让图片适配器隐式猜路由、让主站前端携带 provider model name
|
||||
|
||||
**业务模型**:
|
||||
面向任务与产品契约的稳定模型值;当前 GPT 图片新任务的业务模型是 `gpt-image-2.5`。业务模型不等同于 provider 的具体计费/请求 model,也不暴露 provider 凭证或 endpoint。
|
||||
_Avoid_: 把 provider concrete model 当作前端业务选项、用业务模型值直接推断 provider 凭证
|
||||
|
||||
**具体模型**:
|
||||
服务端发送请求和定价使用的 concrete model name。GPT Image 2.5 生成与编辑分别是 `gpt-image-2.5-flare-c` 和 `gpt-image-2.5-sunburst-c`;nanobanana 仍使用 `gemini-3.1-flash-image-preview`。具体模型只在服务端执行、定价和审计边界出现。
|
||||
_Avoid_: 把具体模型写入普通前端 DTO、让未知字符串自动选择 provider
|
||||
|
||||
**provider client**:
|
||||
按具体模型选出的外部图片 provider 连接配置,包含 provider identity、base URL 和 API key;VectorEngine 与 Tiantoken client 共享图片协议执行器,不复制请求/响应业务逻辑。两套 required client 在 api-server 启动时构造。
|
||||
_Avoid_: 在首次请求时才创建 client、在 provider client 中复制尺寸/重试/审计逻辑、跨 provider credential fallback
|
||||
|
||||
**历史模型值**:
|
||||
已持久化的 `gpt-image-2` 或 `gpt-image-2-c` 字符串,只作为历史事实原样读取和审计;基于历史资源提交新任务时,在使用端解析为当前 GPT Image 2.5 业务任务,不回写历史记录,也不把旧值作为现役 provider route。
|
||||
_Avoid_: 数据库批量改写历史值、把历史值重新路由到 VectorEngine、把兼容解析扩散到普通前端
|
||||
|
||||
**GPT Image 2.5 新生成展示名**:
|
||||
`GPT Image 2.5` 是新生成任务的产品展示名;历史资源与既有编辑上下文不因新模型上线而改写展示语义。
|
||||
_Avoid_: 把新生成展示名扩散到历史记录、历史生成器或旧编辑上下文
|
||||
|
||||
**系列素材图集生成**:
|
||||
一组同类素材的统一批量生成方式,采用批量规划、sheet 生图、后端切图、透明化、OSS 持久化和局部重生成的通用流水线。
|
||||
_Avoid_: 为每个玩法单独发明素材流水线、把系列素材建模成任一玩法专属 DTO
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
generateUpdateManifest,
|
||||
prepareReleaseVersion,
|
||||
resolveReleaseContext,
|
||||
runTauriBuild,
|
||||
} from './build-release.mjs';
|
||||
import { readReleaseDryRun, uploadReleaseArtifacts } from './release-oss.mjs';
|
||||
import {
|
||||
readUpdaterPubkey,
|
||||
verifyUpdaterSignature,
|
||||
} from './verify-updater-signature.mjs';
|
||||
|
||||
/**
|
||||
* AGC macOS 渠道(dev-mac)发布入口:构建 universal 包 → 双架构 smoke → 生成 universal DMG
|
||||
* → 生成渠道清单 latest.json → 用产物内烘焙的公钥验签 → 按 dry-run 决定是否上传 OSS。
|
||||
*
|
||||
* 边界:
|
||||
* - Apple 签名与公证暂缺,产物为未签名 + 未公证(`--no-sign`),必须显式记录而非静默通过;
|
||||
* - 更新包签名(TAURI_SIGNING_PRIVATE_KEY,minisign)是硬需求:缺了客户端一律拒绝安装,
|
||||
* 因此构建前要求凭据存在,构建后用内置公钥复核 `.sig` 才允许继续上传;
|
||||
* - 未通过验签绝不写 OSS:上传顺序为更新包、签名、首装包,全部成功后才覆盖渠道清单指针。
|
||||
*/
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
assert.equal(process.platform, 'darwin', '只能在 macOS Agent 执行');
|
||||
assert.equal(
|
||||
process.env.JENKINS_URL?.length > 0,
|
||||
true,
|
||||
'此入口仅用于 Jenkins 独立工作区',
|
||||
);
|
||||
assert.equal(
|
||||
fs.realpathSync(process.env.WORKSPACE || '.'),
|
||||
fs.realpathSync(repoRoot),
|
||||
'必须在 Jenkins workspace 根目录执行',
|
||||
);
|
||||
const space = fs.statfsSync(repoRoot);
|
||||
assert.ok(
|
||||
space.bavail * space.bsize >= 8 * 1024 ** 3,
|
||||
'构建前至少需要 8 GiB 可用空间;禁止自动清理开发缓存',
|
||||
);
|
||||
|
||||
// 仅剥离 Apple 签名/公证变量:本节点没有证书,误用只会让构建失败;
|
||||
// 更新包签名与 OSS 凭据必须保留,它们是本入口发布能力的组成部分。
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (/^APPLE_/u.test(key)) delete process.env[key];
|
||||
}
|
||||
assert.ok(
|
||||
process.env.TAURI_SIGNING_PRIVATE_KEY?.length > 0 ||
|
||||
process.env.TAURI_SIGNING_PRIVATE_KEY_PATH?.length > 0,
|
||||
'缺少更新包签名私钥(TAURI_SIGNING_PRIVATE_KEY / _PATH):无签名的更新包会被客户端拒绝,禁止继续',
|
||||
);
|
||||
|
||||
const bucket = process.env.AGC_OSS_BUCKET?.trim() || 'agc-dev';
|
||||
const endpoint =
|
||||
process.env.AGC_OSS_ENDPOINT?.trim() || 'oss-rg-china-mainland.aliyuncs.com';
|
||||
if (!/^[a-z0-9][a-z0-9.-]{1,62}$/u.test(bucket) || /[\r\n\0]/u.test(endpoint)) {
|
||||
throw new Error('OSS bucket 或 endpoint 配置无效');
|
||||
}
|
||||
process.env.AGC_UPDATE_OSS_BASE_URL ||= `https://${bucket}.${endpoint}/agc`;
|
||||
const dryRun = readReleaseDryRun();
|
||||
|
||||
process.env.CARGO_TARGET_DIR = path.join(appRoot, 'src-tauri/target');
|
||||
const context = resolveReleaseContext(['--target=universal-apple-darwin']);
|
||||
const version = await prepareReleaseVersion(context);
|
||||
|
||||
const args = [
|
||||
'--target=universal-apple-darwin',
|
||||
'--bundles',
|
||||
'app',
|
||||
'--ci',
|
||||
'--no-sign',
|
||||
// 基础配置已开启;这里显式声明,避免被其它配置来源关掉后静默失去更新能力。
|
||||
'--config',
|
||||
'{"bundle":{"createUpdaterArtifacts":true}}',
|
||||
];
|
||||
const command = (binary, argv, options = {}) =>
|
||||
execFileSync(binary, argv, { cwd: repoRoot, stdio: 'inherit', ...options });
|
||||
runTauriBuild(args, context);
|
||||
|
||||
const app = path.join(context.bundleRoot, 'macos/陶泥儿.app');
|
||||
for (const architecture of ['arm64', 'x86_64']) {
|
||||
command(process.execPath, [
|
||||
path.join(appRoot, 'scripts/check-macos-bundle.mjs'),
|
||||
app,
|
||||
architecture,
|
||||
'--universal',
|
||||
]);
|
||||
}
|
||||
|
||||
// DMG 放在 bundle 根目录下:渠道清单的首装包选择会扫描该目录,命名必须匹配 `_<version>_universal.dmg`。
|
||||
const dmgDirectory = path.join(context.bundleRoot, 'macos');
|
||||
fs.mkdirSync(dmgDirectory, { recursive: true });
|
||||
const dmg = path.join(dmgDirectory, `陶泥儿_${version}_universal.dmg`);
|
||||
const stage = fs.mkdtempSync(path.join(os.tmpdir(), 'agc-ci-dmg-'));
|
||||
try {
|
||||
command('ditto', [app, path.join(stage, '陶泥儿.app')]);
|
||||
fs.symlinkSync('/Applications', path.join(stage, 'Applications'));
|
||||
command('hdiutil', [
|
||||
'create',
|
||||
'-volname',
|
||||
'陶泥儿',
|
||||
'-srcfolder',
|
||||
stage,
|
||||
'-format',
|
||||
'UDZO',
|
||||
dmg,
|
||||
]);
|
||||
command('hdiutil', ['verify', dmg]);
|
||||
} finally {
|
||||
fs.rmSync(stage, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const release = await generateUpdateManifest(context);
|
||||
assert.equal(
|
||||
path.resolve(release.downloadArtifact),
|
||||
path.resolve(dmg),
|
||||
'首装包必须锁定本次生成的 universal DMG',
|
||||
);
|
||||
|
||||
// 上传前门禁:用产物里烘焙的公钥复核更新包签名。验不过就停在这里,绝不写 OSS。
|
||||
const signature = verifyUpdaterSignature({
|
||||
artifactPath: release.artifact,
|
||||
signaturePath: `${release.artifact}.sig`,
|
||||
pubkey: readUpdaterPubkey(),
|
||||
});
|
||||
console.log(
|
||||
`[agc-macos] 更新包签名校验通过:alg=${signature.algorithm},keyId=${signature.keyId}`,
|
||||
);
|
||||
|
||||
const artifacts = path.join(repoRoot, 'artifacts');
|
||||
// 只清理本 Job 的归档输出,不能把上次 DMG 当成本次成功产物。
|
||||
fs.rmSync(artifacts, { recursive: true, force: true });
|
||||
fs.mkdirSync(artifacts, { recursive: true });
|
||||
const sha256 = (file) => {
|
||||
const hash = createHash('sha256');
|
||||
hash.update(fs.readFileSync(file));
|
||||
return hash.digest('hex');
|
||||
};
|
||||
const dmgHash = sha256(dmg);
|
||||
fs.writeFileSync(`${dmg}.sha256`, `${dmgHash} ${path.basename(dmg)}\n`);
|
||||
|
||||
const uploadPlan = uploadReleaseArtifacts(release, {
|
||||
bucket,
|
||||
endpoint,
|
||||
binary: process.env.OSSUTIL_BIN?.trim() || 'ossutil',
|
||||
accessKeyId: process.env.AGC_OSS_ACCESS_KEY_ID?.trim(),
|
||||
accessKeySecret: process.env.AGC_OSS_ACCESS_KEY_SECRET,
|
||||
dryRun,
|
||||
});
|
||||
|
||||
const archived = [
|
||||
dmg,
|
||||
`${dmg}.sha256`,
|
||||
release.manifestPath,
|
||||
release.notesPath,
|
||||
`${release.artifact}.sig`,
|
||||
];
|
||||
for (const file of archived) {
|
||||
fs.copyFileSync(file, path.join(artifacts, path.basename(file)));
|
||||
}
|
||||
|
||||
const commit = execFileSync('git', ['rev-parse', 'HEAD'], {
|
||||
cwd: repoRoot,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
fs.writeFileSync(
|
||||
path.join(artifacts, 'build-manifest.json'),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
version,
|
||||
commit,
|
||||
target: context.target,
|
||||
channel: context.channel,
|
||||
// Apple 签名与公证暂缺:显式记录为未验证项,不静默通过。
|
||||
appleSigned: false,
|
||||
notarized: false,
|
||||
dryRun,
|
||||
uploaded: !dryRun,
|
||||
updaterSignature: {
|
||||
algorithm: signature.algorithm,
|
||||
keyId: signature.keyId,
|
||||
verified: true,
|
||||
},
|
||||
oss: {
|
||||
bucket,
|
||||
endpoint,
|
||||
latest: `oss://${bucket}/agc/${context.channel}/latest.json`,
|
||||
objects: uploadPlan.map(({ destination }) => destination),
|
||||
},
|
||||
artifacts: {
|
||||
updater: path.basename(release.artifact),
|
||||
updaterSha256: sha256(release.artifact),
|
||||
updaterBytes: fs.statSync(release.artifact).size,
|
||||
updaterSignature: path.basename(`${release.artifact}.sig`),
|
||||
firstInstall: path.basename(dmg),
|
||||
firstInstallSha256: dmgHash,
|
||||
manifest: 'latest.json',
|
||||
},
|
||||
smokes: ['arm64', 'x86_64'],
|
||||
intelSmoke: process.arch === 'arm64' ? 'Rosetta' : 'native',
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
console.log(
|
||||
dryRun
|
||||
? `[agc-macos] dry-run 完成:${context.channel} 渠道产物与清单已生成,未写入 OSS`
|
||||
: `[agc-macos] ${context.channel} 渠道更新包、签名、首装包与清单已上传 OSS`,
|
||||
);
|
||||
@@ -42,16 +42,12 @@ function explicitBuildTarget(args) {
|
||||
}
|
||||
|
||||
function validateReleaseTarget(target) {
|
||||
if (target === 'universal-apple-darwin') {
|
||||
throw new Error(
|
||||
'内置 Codex 资源仅支持 macOS 单架构构建,请使用 aarch64-apple-darwin 或 x86_64-apple-darwin',
|
||||
);
|
||||
}
|
||||
if (
|
||||
![
|
||||
'x86_64-pc-windows-msvc',
|
||||
'aarch64-apple-darwin',
|
||||
'x86_64-apple-darwin',
|
||||
'universal-apple-darwin',
|
||||
].includes(target)
|
||||
) {
|
||||
throw new Error(`不支持的发布目标:${target}`);
|
||||
@@ -198,10 +194,12 @@ export function updateManifestUrl(channel = resolveReleaseChannel()) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 单架构产物只登记实际目标,不能把同一原生资源映射为另一架构。
|
||||
* universal 主程序与双目录原生资源共用一个更新包;单架构只登记实际目标。
|
||||
*/
|
||||
export function resolveManifestPlatformKeys(target = defaultTarget()) {
|
||||
validateReleaseTarget(target);
|
||||
if (target === 'universal-apple-darwin')
|
||||
return ['darwin-aarch64', 'darwin-x86_64'];
|
||||
if (target === 'aarch64-apple-darwin') return ['darwin-aarch64'];
|
||||
if (target === 'x86_64-apple-darwin') return ['darwin-x86_64'];
|
||||
if (target.includes('windows')) {
|
||||
@@ -501,6 +499,53 @@ export function selectReleaseArtifact(files, target = defaultTarget()) {
|
||||
);
|
||||
}
|
||||
|
||||
export function selectFirstInstallArtifact(
|
||||
files,
|
||||
{ target, version, artifact },
|
||||
) {
|
||||
validateReleaseTarget(target);
|
||||
let selected;
|
||||
if (target.includes('windows')) {
|
||||
selected = artifact;
|
||||
if (!selected?.endsWith('.exe')) {
|
||||
throw new Error('Windows 首装包必须复用本次 NSIS .exe 更新包');
|
||||
}
|
||||
} else if (target === 'universal-apple-darwin') {
|
||||
// universal 主程序只产出一个 DMG,aarch64 与 x86_64 首装共用它(命名见 build-macos-ci.mjs)。
|
||||
const suffix = `_${version}_universal.dmg`;
|
||||
const candidates = files.filter((file) =>
|
||||
path.basename(file).endsWith(suffix),
|
||||
);
|
||||
if (candidates.length !== 1) {
|
||||
throw new Error(
|
||||
`首装 DMG 必须唯一匹配本次版本 ${version} 的 universal 产物,找到 ${candidates.length} 个`,
|
||||
);
|
||||
}
|
||||
selected = candidates[0];
|
||||
} else {
|
||||
// Tauri DMG 文件名使用 aarch64 / x64,而 updater 的 Intel 平台键是 x86_64。
|
||||
const architecture = target.startsWith('aarch64') ? 'aarch64' : 'x64';
|
||||
const suffix = `_${version}_${architecture}.dmg`;
|
||||
const candidates = files.filter((file) =>
|
||||
path.basename(file).endsWith(suffix),
|
||||
);
|
||||
if (candidates.length !== 1) {
|
||||
throw new Error(
|
||||
`首装 DMG 必须唯一匹配本次版本 ${version} 和架构 ${architecture},找到 ${candidates.length} 个`,
|
||||
);
|
||||
}
|
||||
selected = candidates[0];
|
||||
}
|
||||
if (
|
||||
!fs.existsSync(selected) ||
|
||||
!fs.statSync(selected).isFile() ||
|
||||
fs.statSync(selected).size === 0
|
||||
) {
|
||||
throw new Error(`首装包不存在或为空:${selected}`);
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
function readUpdaterSignature(artifactPath) {
|
||||
const signaturePath = `${artifactPath}.sig`;
|
||||
if (!fs.existsSync(signaturePath)) {
|
||||
@@ -521,23 +566,32 @@ export function createUpdateManifest(
|
||||
publishedAt = new Date().toISOString(),
|
||||
notes = readReleaseNotes(),
|
||||
commit = readHeadCommit(),
|
||||
downloadArtifact,
|
||||
} = {},
|
||||
) {
|
||||
validateReleaseTarget(target);
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }, target);
|
||||
const signature = readUpdaterSignature(artifactPath);
|
||||
const version = readPackageJson().version;
|
||||
const firstInstallArtifact = selectFirstInstallArtifact(
|
||||
downloadArtifact ? [downloadArtifact] : [],
|
||||
{ target, version, artifact: artifactPath },
|
||||
);
|
||||
const fileName = path.basename(artifactPath);
|
||||
const url = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`;
|
||||
const downloadUrl = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(path.basename(firstInstallArtifact))}`;
|
||||
const platforms = {};
|
||||
const downloads = {};
|
||||
for (const key of resolveManifestPlatformKeys(target)) {
|
||||
platforms[key] = { signature, url };
|
||||
downloads[key] = { url: downloadUrl };
|
||||
}
|
||||
return {
|
||||
version,
|
||||
...(notes ? { notes } : {}),
|
||||
pub_date: publishedAt,
|
||||
platforms,
|
||||
downloads,
|
||||
// 非标准字段:更新插件会忽略,发布脚本用它定位下一次自动更新摘要的起点。
|
||||
...(commit ? { commit } : {}),
|
||||
};
|
||||
@@ -676,10 +730,16 @@ export async function generateUpdateManifest(
|
||||
context = resolveReleaseContext(),
|
||||
) {
|
||||
const { channel, target, bundleRoot } = context;
|
||||
const artifact = selectReleaseArtifact(listFiles(bundleRoot), target);
|
||||
const files = listFiles(bundleRoot);
|
||||
const artifact = selectReleaseArtifact(files, target);
|
||||
if (!artifact) {
|
||||
throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`);
|
||||
}
|
||||
const downloadArtifact = selectFirstInstallArtifact(files, {
|
||||
target,
|
||||
version: readPackageJson().version,
|
||||
artifact,
|
||||
});
|
||||
const manualNotes = readReleaseNotes();
|
||||
const previousCommit = await resolvePreviousReleaseCommit(channel);
|
||||
const commits = collectReleaseCommits(previousCommit);
|
||||
@@ -693,7 +753,12 @@ export async function generateUpdateManifest(
|
||||
`[ai-game-creator-shell] 未生成自动更新摘要(上一发布 commit=${previousCommit ?? '未知'},客户端相关提交=${commits ? commits.length : '不可判定'},最近提交=${recentCommits ? recentCommits.length : '不可判定'})`,
|
||||
);
|
||||
}
|
||||
const manifest = createUpdateManifest(artifact, { channel, target, notes });
|
||||
const manifest = createUpdateManifest(artifact, {
|
||||
channel,
|
||||
target,
|
||||
notes,
|
||||
downloadArtifact,
|
||||
});
|
||||
const manifestPath = path.join(bundleRoot, 'latest.json');
|
||||
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
const notesPath = path.join(bundleRoot, 'release-notes.txt');
|
||||
@@ -718,6 +783,7 @@ export async function generateUpdateManifest(
|
||||
`[ai-game-creator-shell] 渠道 ${channel}:已生成 ${manifestPath}`,
|
||||
);
|
||||
console.log(`[ai-game-creator-shell] 安装包:${artifact}`);
|
||||
console.log(`[ai-game-creator-shell] 首装包:${downloadArtifact}`);
|
||||
console.log(
|
||||
manualNotes
|
||||
? '[ai-game-creator-shell] 更新摘要:使用 AGC_UPDATE_RELEASE_NOTES 手动文案'
|
||||
@@ -734,6 +800,7 @@ export async function generateUpdateManifest(
|
||||
return {
|
||||
channel,
|
||||
artifact,
|
||||
downloadArtifact,
|
||||
manifest,
|
||||
manifestPath,
|
||||
notes,
|
||||
|
||||
@@ -32,20 +32,34 @@ import {
|
||||
resolveReleaseContext,
|
||||
resolveRemoteHighWaterVersion,
|
||||
runTauriBuild,
|
||||
selectFirstInstallArtifact,
|
||||
selectReleaseArtifact,
|
||||
updateManifestUrl,
|
||||
} from './build-release.mjs';
|
||||
|
||||
const windowsTarget = 'x86_64-pc-windows-msvc';
|
||||
const universalTarget = 'universal-apple-darwin';
|
||||
const packageVersion = JSON.parse(
|
||||
readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
|
||||
).version;
|
||||
|
||||
test('native sidecar builds reject universal targets and accept each macOS architecture', () => {
|
||||
assert.throws(() => buildTauriBuildArguments([], universalTarget), /单架构/);
|
||||
assert.throws(
|
||||
() => buildTauriBuildArguments(['--target=universal-apple-darwin']),
|
||||
/单架构/,
|
||||
);
|
||||
for (const target of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {
|
||||
function createDmgFixture(root, target, version = packageVersion) {
|
||||
const architecture = target.startsWith('aarch64')
|
||||
? 'aarch64'
|
||||
: target === universalTarget
|
||||
? 'universal'
|
||||
: 'x64';
|
||||
const dmg = path.join(root, `陶泥儿_${version}_${architecture}.dmg`);
|
||||
writeFileSync(dmg, 'first installation disk image');
|
||||
return dmg;
|
||||
}
|
||||
|
||||
test('native sidecar builds accept universal and each macOS architecture', () => {
|
||||
for (const target of [
|
||||
universalTarget,
|
||||
'aarch64-apple-darwin',
|
||||
'x86_64-apple-darwin',
|
||||
]) {
|
||||
assert.deepEqual(buildTauriBuildArguments([], target), [
|
||||
'build',
|
||||
'--target',
|
||||
@@ -152,8 +166,11 @@ test('channel manifest URL and build-time endpoint follow the channel', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('macOS manifests only advertise the architecture actually built', () => {
|
||||
assert.throws(() => resolveManifestPlatformKeys(universalTarget), /单架构/);
|
||||
test('macOS manifests advertise exactly the architectures actually built', () => {
|
||||
assert.deepEqual(resolveManifestPlatformKeys(universalTarget), [
|
||||
'darwin-aarch64',
|
||||
'darwin-x86_64',
|
||||
]);
|
||||
assert.deepEqual(resolveManifestPlatformKeys('aarch64-apple-darwin'), [
|
||||
'darwin-aarch64',
|
||||
]);
|
||||
@@ -197,7 +214,6 @@ test('release context resolves explicit targets before environment/default and f
|
||||
['--target='],
|
||||
['--target', '--no-bundle'],
|
||||
['--target', windowsTarget, '--target=aarch64-apple-darwin'],
|
||||
['--target', universalTarget],
|
||||
['--target', 'unknown'],
|
||||
])
|
||||
assert.throws(() => resolveReleaseContext(args, {}));
|
||||
@@ -254,7 +270,13 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
||||
),
|
||||
artifact,
|
||||
);
|
||||
const manifest = createUpdateManifest(artifact, context);
|
||||
const manifest = createUpdateManifest(artifact, {
|
||||
...context,
|
||||
downloadArtifact: createDmgFixture(
|
||||
path.dirname(artifact),
|
||||
context.target,
|
||||
),
|
||||
});
|
||||
assert.deepEqual(Object.keys(manifest.platforms), [
|
||||
'darwin-aarch64',
|
||||
]);
|
||||
@@ -272,29 +294,118 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
||||
assert.ok(seenContexts.every((context) => context === seenContexts[0]));
|
||||
});
|
||||
|
||||
test('real manifest writer uses the resolved bundle root and does not emit Windows artifacts', async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
|
||||
for (const target of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {
|
||||
test(`real manifest writer publishes the ${target} updater and first installer separately`, async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
|
||||
try {
|
||||
const artifact = path.join(root, '陶泥儿.app.tar.gz');
|
||||
writeFileSync(artifact, 'mac package');
|
||||
writeFileSync(`${artifact}.sig`, 'mac signature');
|
||||
writeFileSync(path.join(root, 'windows.exe'), 'wrong platform');
|
||||
const downloadArtifact = createDmgFixture(root, target);
|
||||
const context = {
|
||||
...resolveReleaseContext([`--target=${target}`], {}),
|
||||
bundleRoot: root,
|
||||
};
|
||||
const result = await withStubbedFetch(
|
||||
(url) => {
|
||||
assert.match(url, /\/dev-mac\/latest\.json$/);
|
||||
return jsonResponse({}, 404);
|
||||
},
|
||||
() => generateUpdateManifest(context),
|
||||
);
|
||||
assert.equal(result.artifact, artifact);
|
||||
assert.equal(result.downloadArtifact, downloadArtifact);
|
||||
assert.equal(result.manifestPath, path.join(root, 'latest.json'));
|
||||
assert.equal(result.legacyManifestPath, null);
|
||||
const key = target.startsWith('aarch64')
|
||||
? 'darwin-aarch64'
|
||||
: 'darwin-x86_64';
|
||||
assert.deepEqual(Object.keys(result.manifest.platforms), [key]);
|
||||
assert.deepEqual(Object.keys(result.manifest.downloads), [key]);
|
||||
assert.match(
|
||||
result.manifest.platforms[key].url,
|
||||
/\/dev-mac\/.*\.app\.tar\.gz$/,
|
||||
);
|
||||
assert.equal(
|
||||
decodeURIComponent(
|
||||
new URL(result.manifest.downloads[key].url).pathname,
|
||||
),
|
||||
`/agc/dev-mac/${packageVersion}/${path.basename(downloadArtifact)}`,
|
||||
);
|
||||
assert.deepEqual(
|
||||
JSON.parse(readFileSync(result.manifestPath, 'utf8')),
|
||||
result.manifest,
|
||||
);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('DMG selection ignores other versions and architectures but rejects missing, empty and ambiguous current packages', () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-dmg-selection-'));
|
||||
try {
|
||||
const target = 'aarch64-apple-darwin';
|
||||
const options = {
|
||||
target,
|
||||
version: '2.3.4',
|
||||
artifact: path.join(root, '陶泥儿.app.tar.gz'),
|
||||
};
|
||||
const oldVersion = createDmgFixture(root, target, '2.3.3');
|
||||
const wrongArchitecture = createDmgFixture(
|
||||
root,
|
||||
'x86_64-apple-darwin',
|
||||
'2.3.4',
|
||||
);
|
||||
assert.throws(() => selectFirstInstallArtifact([], options), /找到 0 个/u);
|
||||
assert.throws(
|
||||
() =>
|
||||
selectFirstInstallArtifact([oldVersion, wrongArchitecture], options),
|
||||
/找到 0 个/u,
|
||||
);
|
||||
const current = createDmgFixture(root, target, '2.3.4');
|
||||
assert.equal(
|
||||
selectFirstInstallArtifact(
|
||||
[oldVersion, wrongArchitecture, current],
|
||||
options,
|
||||
),
|
||||
current,
|
||||
);
|
||||
writeFileSync(current, '');
|
||||
assert.throws(
|
||||
() => selectFirstInstallArtifact([current], options),
|
||||
/不存在或为空/u,
|
||||
);
|
||||
writeFileSync(current, 'valid dmg');
|
||||
const second = path.join(root, '另一包_2.3.4_aarch64.dmg');
|
||||
writeFileSync(second, 'ambiguous dmg');
|
||||
assert.throws(
|
||||
() => selectFirstInstallArtifact([current, second], options),
|
||||
/找到 2 个/u,
|
||||
);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('manifest writer refuses to create latest when the current Mac DMG is missing', async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-missing-dmg-'));
|
||||
try {
|
||||
const artifact = path.join(root, '陶泥儿.app.tar.gz');
|
||||
writeFileSync(artifact, 'mac package');
|
||||
writeFileSync(`${artifact}.sig`, 'mac signature');
|
||||
writeFileSync(path.join(root, 'windows.exe'), 'wrong platform');
|
||||
writeFileSync(artifact, 'updater archive');
|
||||
writeFileSync(`${artifact}.sig`, 'signature');
|
||||
const context = {
|
||||
...resolveReleaseContext(['--target=x86_64-apple-darwin'], {}),
|
||||
...resolveReleaseContext(['--target=aarch64-apple-darwin'], {}),
|
||||
bundleRoot: root,
|
||||
};
|
||||
const result = await withStubbedFetch(
|
||||
(url) => {
|
||||
assert.match(url, /\/dev-mac\/latest\.json$/);
|
||||
return jsonResponse({}, 404);
|
||||
},
|
||||
await assert.rejects(
|
||||
() => generateUpdateManifest(context),
|
||||
/首装 DMG 必须唯一匹配/u,
|
||||
);
|
||||
assert.equal(result.artifact, artifact);
|
||||
assert.equal(result.manifestPath, path.join(root, 'latest.json'));
|
||||
assert.equal(result.legacyManifestPath, null);
|
||||
assert.deepEqual(Object.keys(result.manifest.platforms), ['darwin-x86_64']);
|
||||
assert.match(result.manifest.platforms['darwin-x86_64'].url, /\/dev-mac\//);
|
||||
assert.throws(() => readFileSync(path.join(root, 'latest.json')), {
|
||||
code: 'ENOENT',
|
||||
});
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
@@ -314,8 +425,8 @@ test('invalid target or mismatched channel fails before any release side effect'
|
||||
},
|
||||
};
|
||||
await assert.rejects(
|
||||
() => buildRelease(['--target', universalTarget], sideEffects),
|
||||
/单架构/,
|
||||
() => buildRelease(['--target', 'unknown'], sideEffects),
|
||||
/不支持的发布目标/,
|
||||
);
|
||||
await withEnv({ AGC_UPDATE_CHANNEL: 'dev-win' }, () =>
|
||||
assert.rejects(
|
||||
@@ -326,6 +437,38 @@ test('invalid target or mismatched channel fails before any release side effect'
|
||||
assert.equal(touched, false);
|
||||
});
|
||||
|
||||
test('universal uses the Mac channel and the same signed artifact for both architectures', () => {
|
||||
const context = resolveReleaseContext(['--target', universalTarget], {
|
||||
AGC_BUILD_TARGET: windowsTarget,
|
||||
});
|
||||
assert.equal(context.channel, 'dev-mac');
|
||||
assert.ok(context.bundleRoot.includes(universalTarget));
|
||||
withSignedArtifact('陶泥儿.app.tar.gz', (artifact) => {
|
||||
const manifest = createUpdateManifest(artifact, {
|
||||
...context,
|
||||
downloadArtifact: createDmgFixture(
|
||||
path.dirname(artifact),
|
||||
universalTarget,
|
||||
),
|
||||
});
|
||||
assert.deepEqual(Object.keys(manifest.platforms), [
|
||||
'darwin-aarch64',
|
||||
'darwin-x86_64',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
manifest.platforms['darwin-aarch64'],
|
||||
manifest.platforms['darwin-x86_64'],
|
||||
);
|
||||
assert.match(manifest.platforms['darwin-aarch64'].url, /\/dev-mac\//);
|
||||
// 两个平台键共用同一个 universal 首装包,不能要求出两份架构 DMG。
|
||||
assert.deepEqual(
|
||||
manifest.downloads['darwin-aarch64'].url,
|
||||
manifest.downloads['darwin-x86_64'].url,
|
||||
);
|
||||
assert.match(manifest.downloads['darwin-aarch64'].url, /_universal\.dmg$/u);
|
||||
});
|
||||
});
|
||||
|
||||
test('Windows remains the default and explicit Windows overrides macOS environment', () => {
|
||||
const files = ['/tmp/mac.app.tar.gz', '/tmp/windows.exe', '/tmp/mac.dmg'];
|
||||
for (const context of [
|
||||
@@ -393,6 +536,9 @@ test('channel manifest carries version, platform keys and signature', () => {
|
||||
assert.equal(manifest.notes, '修复与改进');
|
||||
assert.equal(manifest.pub_date, '2026-09-17T00:00:00.000Z');
|
||||
assert.deepEqual(Object.keys(manifest.platforms), ['windows-x86_64']);
|
||||
assert.deepEqual(manifest.downloads, {
|
||||
'windows-x86_64': { url: manifest.platforms['windows-x86_64'].url },
|
||||
});
|
||||
assert.equal(
|
||||
manifest.platforms['windows-x86_64'].signature,
|
||||
'signature-content',
|
||||
@@ -573,18 +719,18 @@ test('recent commit fallback marks that entries may repeat the previous release'
|
||||
}
|
||||
});
|
||||
|
||||
test('release upload forces overwrite for artifact, signature and channel pointers', () => {
|
||||
test('release entry forwards the built artifacts and dry-run mode to the uploader', () => {
|
||||
const source = readFileSync(
|
||||
new URL('./release-upload.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.equal(
|
||||
(source.match(/runOssutil\(\[\s*'cp',\s*'--force'/gu) ?? []).length,
|
||||
4,
|
||||
assert.match(
|
||||
source,
|
||||
/const release = await buildRelease\(process\.argv\.slice\(2\)\)/u,
|
||||
);
|
||||
assert.match(source, /agc\/\$\{channel\}\/latest\.json/u);
|
||||
assert.match(source, /agc\/latest\.json/u);
|
||||
assert.match(source, /await buildRelease\(process\.argv\.slice\(2\)\)/u);
|
||||
assert.match(source, /uploadReleaseArtifacts\(release, \{/u);
|
||||
assert.match(source, /const dryRun = readReleaseDryRun\(\);/u);
|
||||
assert.ok(source.includes('\n dryRun,\n'));
|
||||
});
|
||||
|
||||
test('release notes list client commits with short sha and bound their size', () => {
|
||||
|
||||
@@ -1366,18 +1366,20 @@ if (windowsTauriConfig.bundle?.useLocalToolsDir !== true) {
|
||||
assert.deepEqual(
|
||||
macosTauriConfig.bundle?.resources,
|
||||
Object.fromEntries([
|
||||
...[
|
||||
'bin/codex',
|
||||
'bin/codex-code-mode-host',
|
||||
'codex-path/rg',
|
||||
'codex-resources/zsh/bin/zsh',
|
||||
'codex-package.json',
|
||||
'NOTICE.md',
|
||||
'manifest.json',
|
||||
].map((file) => [
|
||||
`resources/codex/mac-native/${file}`,
|
||||
`coding-agent/mac-native/${file}`,
|
||||
]),
|
||||
...['darwin-arm64', 'darwin-x64'].flatMap((arch) =>
|
||||
[
|
||||
'bin/codex',
|
||||
'bin/codex-code-mode-host',
|
||||
'codex-path/rg',
|
||||
'codex-resources/zsh/bin/zsh',
|
||||
'codex-package.json',
|
||||
'NOTICE.md',
|
||||
'manifest.json',
|
||||
].map((file) => [
|
||||
`resources/codex/mac-native/${arch}/${file}`,
|
||||
`coding-agent/mac-native/${arch}/${file}`,
|
||||
]),
|
||||
),
|
||||
['resources/plugins', 'plugins'],
|
||||
]),
|
||||
'macOS must bundle the complete native Codex layout and plugin workspace',
|
||||
|
||||
@@ -8,6 +8,13 @@ import path from 'node:path';
|
||||
// 只操作临时复制品;不启动 GUI、不读取开发机凭据、不访问 Provider。
|
||||
assert.equal(process.platform, 'darwin', '此验证必须在 macOS 执行');
|
||||
const source = path.resolve(process.argv[2] || '');
|
||||
const architecture =
|
||||
process.argv[3] || (process.arch === 'arm64' ? 'arm64' : 'x86_64');
|
||||
assert.ok(
|
||||
['arm64', 'x86_64'].includes(architecture),
|
||||
'架构只接受 arm64 / x86_64',
|
||||
);
|
||||
const requireUniversal = process.argv.includes('--universal');
|
||||
assert.ok(
|
||||
source.endsWith('.app') && fs.statSync(source).isDirectory(),
|
||||
'请传入 .app 绝对路径',
|
||||
@@ -31,13 +38,19 @@ const env = {
|
||||
};
|
||||
|
||||
function run(command, args) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: root,
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
timeout: 30_000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
});
|
||||
// 只强制被测应用切片;本机 Xcode 检查工具可能仅提供宿主架构。
|
||||
const useSlice = command.startsWith(`${app}${path.sep}`);
|
||||
const result = spawnSync(
|
||||
useSlice ? '/usr/bin/arch' : command,
|
||||
useSlice ? [`-${architecture}`, command, ...args] : args,
|
||||
{
|
||||
cwd: root,
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
timeout: 120_000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
},
|
||||
);
|
||||
assert.ifError(result.error);
|
||||
return result;
|
||||
}
|
||||
@@ -60,7 +73,7 @@ async function handshake(executable) {
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error('app-server 初始化超时')),
|
||||
15_000,
|
||||
120_000,
|
||||
);
|
||||
const finish = (error) => {
|
||||
clearTimeout(timer);
|
||||
@@ -129,20 +142,39 @@ async function handshake(executable) {
|
||||
try {
|
||||
fs.cpSync(source, app, { recursive: true });
|
||||
const resources = path.join(app, 'Contents/Resources');
|
||||
const bundle = path.join(resources, 'coding-agent/mac-native');
|
||||
const platform = architecture === 'arm64' ? 'darwin-arm64' : 'darwin-x64';
|
||||
const bundle = path.join(resources, 'coding-agent/mac-native', platform);
|
||||
const executable = path.join(bundle, 'bin/codex');
|
||||
const main = path.join(
|
||||
app,
|
||||
'Contents/MacOS/genarrative-ai-game-creator-shell',
|
||||
);
|
||||
const mainArchitectures = run('/usr/bin/lipo', ['-archs', main]);
|
||||
assert.equal(mainArchitectures.status, 0);
|
||||
assert.ok(mainArchitectures.stdout.split(/\s+/).includes(architecture));
|
||||
if (requireUniversal) {
|
||||
assert.deepEqual(mainArchitectures.stdout.trim().split(/\s+/).sort(), [
|
||||
'arm64',
|
||||
'x86_64',
|
||||
]);
|
||||
for (const platform of ['darwin-arm64', 'darwin-x64']) {
|
||||
assert.ok(
|
||||
fs.existsSync(
|
||||
path.join(
|
||||
resources,
|
||||
'coding-agent/mac-native',
|
||||
platform,
|
||||
'manifest.json',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(path.join(bundle, 'manifest.json'), 'utf8'),
|
||||
);
|
||||
assert.equal(manifest.schemaVersion, 'genarrative-codex-sidecar.v2');
|
||||
assert.equal(
|
||||
manifest.platform,
|
||||
process.arch === 'arm64' ? 'darwin-arm64' : 'darwin-x64',
|
||||
);
|
||||
assert.equal(manifest.platform, platform);
|
||||
assert.equal(manifest.version, 'codex-cli 0.147.0');
|
||||
const components = [
|
||||
'bin/codex',
|
||||
@@ -159,11 +191,7 @@ try {
|
||||
fs.accessSync(file, fs.constants.X_OK);
|
||||
const arch = run('/usr/bin/lipo', ['-archs', file]);
|
||||
assert.equal(arch.status, 0, component);
|
||||
assert.equal(
|
||||
arch.stdout.trim(),
|
||||
process.arch === 'arm64' ? 'arm64' : 'x86_64',
|
||||
component,
|
||||
);
|
||||
assert.equal(arch.stdout.trim(), architecture, component);
|
||||
}
|
||||
}
|
||||
assert.ok(fs.existsSync(path.join(bundle, 'NOTICE.md')));
|
||||
@@ -212,7 +240,7 @@ try {
|
||||
assert.notEqual(broken.status, 0);
|
||||
assert.match(`${broken.stdout}\n${broken.stderr}`, /Codex CLI 未安装/);
|
||||
console.log(
|
||||
'PASS: 隔离安装包资源、架构、摘要、权限、正式 Codex 查找、app-server 握手及缺组件拒绝',
|
||||
`PASS (${architecture}): 隔离安装包资源、架构、摘要、权限、正式 Codex 查找、app-server 握手及缺组件拒绝`,
|
||||
);
|
||||
console.log(
|
||||
'未验证:GUI、真实登录/Provider 对话、Cocos macOS 原生桥接;插件 Node 仍为外部前提',
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
const platforms = {
|
||||
arm64: 'aarch64-apple-darwin',
|
||||
x64: 'x86_64-apple-darwin',
|
||||
};
|
||||
|
||||
export function lockedMacPackage(lock, arch, version) {
|
||||
assert.ok(Object.hasOwn(platforms, arch), '未知 macOS 架构');
|
||||
const alias = `@openai/codex-darwin-${arch}`;
|
||||
const entry = lock.packages?.[`node_modules/${alias}`];
|
||||
assert.equal(
|
||||
entry?.version,
|
||||
`${version}-darwin-${arch}`,
|
||||
'原生依赖必须与应用锁定版本一致',
|
||||
);
|
||||
assert.deepEqual(entry.os, ['darwin']);
|
||||
assert.deepEqual(entry.cpu, [arch]);
|
||||
const url = new URL(entry.resolved);
|
||||
assert.equal(url.protocol, 'https:');
|
||||
assert.equal(
|
||||
url.hostname,
|
||||
'registry.npmjs.org',
|
||||
'只下载锁定的官方 npm 原生包',
|
||||
);
|
||||
assert.equal(url.username + url.password + url.search + url.hash, '');
|
||||
assert.match(entry.integrity, /^sha512-[A-Za-z0-9+/]+={0,2}$/);
|
||||
return { alias, target: platforms[arch], ...entry };
|
||||
}
|
||||
|
||||
export function verifyPackageIntegrity(bytes, expected) {
|
||||
const actual = `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
|
||||
assert.equal(actual, expected, 'Codex 下载包 lockfile integrity 不匹配');
|
||||
}
|
||||
|
||||
export function validateArchiveListing(listing) {
|
||||
const files = listing.trim().split(/\r?\n/u);
|
||||
assert.ok(files.length > 0);
|
||||
for (const file of files) {
|
||||
assert.ok(file.startsWith('package/'), '原生包必须只有 package 根目录');
|
||||
assert.ok(
|
||||
!file.split('/').includes('..') && !file.includes('\\'),
|
||||
'压缩包路径不安全',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareMacosCodex() {
|
||||
assert.equal(process.platform, 'darwin', '该入口仅用于 macOS 构建机');
|
||||
const lock = JSON.parse(
|
||||
fs.readFileSync(path.join(repoRoot, 'package-lock.json'), 'utf8'),
|
||||
);
|
||||
const app = JSON.parse(
|
||||
fs.readFileSync(path.join(appRoot, 'package.json'), 'utf8'),
|
||||
);
|
||||
const version = app.devDependencies['@openai/codex'];
|
||||
assert.match(version, /^\d+\.\d+\.\d+$/u, 'Codex 必须锁定精确版本');
|
||||
const cache = path.join(appRoot, 'src-tauri/target/.macos-native-cache');
|
||||
fs.mkdirSync(cache, { recursive: true });
|
||||
for (const arch of Object.keys(platforms)) {
|
||||
const entry = lockedMacPackage(lock, arch, version);
|
||||
const archive = path.join(cache, `codex-${entry.version}.tgz`);
|
||||
if (!fs.existsSync(archive)) {
|
||||
const response = await fetch(entry.resolved, {
|
||||
signal: AbortSignal.timeout(300_000),
|
||||
});
|
||||
assert.ok(response.ok, `原生包下载失败 HTTP ${response.status}`);
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
verifyPackageIntegrity(bytes, entry.integrity);
|
||||
const partial = `${archive}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(partial, bytes);
|
||||
fs.renameSync(partial, archive);
|
||||
}
|
||||
verifyPackageIntegrity(fs.readFileSync(archive), entry.integrity);
|
||||
validateArchiveListing(
|
||||
execFileSync('tar', ['-tzf', archive], { encoding: 'utf8' }),
|
||||
);
|
||||
// 拒绝链接、设备及其它特殊条目,不能让 tar 在包目录之外写入。
|
||||
const entries = execFileSync('tar', ['-tvzf', archive], {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.ok(
|
||||
entries
|
||||
.trim()
|
||||
.split(/\r?\n/u)
|
||||
.every((line) => /^[-d]/u.test(line)),
|
||||
'原生包禁止链接或特殊文件',
|
||||
);
|
||||
const parent = path.join(repoRoot, 'node_modules/@openai');
|
||||
fs.mkdirSync(parent, { recursive: true });
|
||||
const stage = fs.mkdtempSync(path.join(parent, '.mac-native-'));
|
||||
try {
|
||||
execFileSync(
|
||||
'tar',
|
||||
['-xzf', archive, '-C', stage, '--strip-components=1'],
|
||||
{ stdio: 'pipe' },
|
||||
);
|
||||
const metadata = JSON.parse(
|
||||
fs.readFileSync(
|
||||
path.join(stage, 'vendor', entry.target, 'codex-package.json'),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.equal(metadata.version, version);
|
||||
assert.equal(metadata.target, entry.target);
|
||||
assert.equal(metadata.entrypoint, 'bin/codex');
|
||||
const destination = path.join(repoRoot, 'node_modules', entry.alias);
|
||||
assert.ok(
|
||||
!fs.existsSync(destination) ||
|
||||
!fs.lstatSync(destination).isSymbolicLink(),
|
||||
'拒绝覆盖链接依赖',
|
||||
);
|
||||
fs.rmSync(destination, { recursive: true, force: true });
|
||||
fs.renameSync(stage, destination);
|
||||
} finally {
|
||||
fs.rmSync(stage, { recursive: true, force: true });
|
||||
}
|
||||
console.log(`[macOS Codex] ${entry.version}: lockfile integrity 已验证`);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
process.argv[1] &&
|
||||
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
) {
|
||||
await prepareMacosCodex();
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import {
|
||||
lockedMacPackage,
|
||||
validateArchiveListing,
|
||||
verifyPackageIntegrity,
|
||||
} from './prepare-macos-codex.mjs';
|
||||
|
||||
const lock = JSON.parse(
|
||||
fs.readFileSync(new URL('../../../package-lock.json', import.meta.url)),
|
||||
);
|
||||
const version = JSON.parse(
|
||||
fs.readFileSync(new URL('../package.json', import.meta.url)),
|
||||
).devDependencies['@openai/codex'];
|
||||
|
||||
test('both macOS dependencies resolve from the lockfile without floating versions', () => {
|
||||
assert.equal(
|
||||
lockedMacPackage(lock, 'arm64', version).target,
|
||||
'aarch64-apple-darwin',
|
||||
);
|
||||
assert.equal(
|
||||
lockedMacPackage(lock, 'x64', version).target,
|
||||
'x86_64-apple-darwin',
|
||||
);
|
||||
assert.throws(() => lockedMacPackage(lock, 'other', version));
|
||||
assert.throws(() => lockedMacPackage(lock, 'x64', '0.0.0'));
|
||||
});
|
||||
|
||||
test('native package integrity rejects tampering', () => {
|
||||
const bytes = Buffer.from('pinned package');
|
||||
const integrity = `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
|
||||
verifyPackageIntegrity(bytes, integrity);
|
||||
assert.throws(() =>
|
||||
verifyPackageIntegrity(Buffer.from('modified'), integrity),
|
||||
);
|
||||
});
|
||||
|
||||
test('archive traversal and non-package entries fail closed', () => {
|
||||
validateArchiveListing(
|
||||
'package/package.json\npackage/vendor/target/bin/codex\n',
|
||||
);
|
||||
for (const listing of [
|
||||
'',
|
||||
'/tmp/payload',
|
||||
'package/../private',
|
||||
'other/file',
|
||||
'package/..\\file',
|
||||
]) {
|
||||
assert.throws(() => validateArchiveListing(listing));
|
||||
}
|
||||
});
|
||||
|
||||
test('CI pipeline is manual, publishes the dev-mac channel and never reuses a developer workspace', () => {
|
||||
const pipeline = fs.readFileSync(
|
||||
new URL(
|
||||
'../../../jenkins/Jenkinsfile.ai-game-creator-shell-macos-build',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
for (const required of [
|
||||
'genarrative-agc-macos',
|
||||
'disableConcurrentBuilds()',
|
||||
'$AGC_AGENT_ROOT',
|
||||
'StrictHostKeyChecking=yes',
|
||||
'git merge-base --is-ancestor',
|
||||
'allowEmptyArchive: false',
|
||||
"AGC_UPDATE_CHANNEL = 'dev-mac'",
|
||||
"string(credentialsId: 'AgcUpdaterSigningKey'",
|
||||
"string(credentialsId: 'AgcUpdaterSigningKeyPassword'",
|
||||
"string(credentialsId: 'AliyunAccessKeyId'",
|
||||
"string(credentialsId: 'AliyunaccessKeySecret'",
|
||||
'AGC_RELEASE_VERSION',
|
||||
'OSSUTIL_BIN',
|
||||
]) {
|
||||
assert.ok(pipeline.includes(required), required);
|
||||
}
|
||||
// dry-run 必须是默认值:不显式取消勾选就不得写入 OSS。
|
||||
assert.match(
|
||||
pipeline,
|
||||
/booleanParam\(name: 'AGC_RELEASE_DRY_RUN', defaultValue: true/u,
|
||||
);
|
||||
for (const forbidden of [
|
||||
'triggers {',
|
||||
'cron(',
|
||||
'pollSCM(',
|
||||
'git clean -fdx',
|
||||
// release:upload 会重新触发一次完整构建,既翻倍耗时也绕过本 Job 的验签门禁。
|
||||
'release:upload',
|
||||
]) {
|
||||
assert.ok(!pipeline.includes(forbidden), forbidden);
|
||||
}
|
||||
});
|
||||
|
||||
test('macOS release entry verifies the updater signature before uploading', () => {
|
||||
const entry = fs.readFileSync(
|
||||
new URL('./build-macos-ci.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const verifyIndex = entry.indexOf('verifyUpdaterSignature({');
|
||||
const uploadIndex = entry.indexOf('uploadReleaseArtifacts(release');
|
||||
assert.ok(verifyIndex > 0, '必须调用更新包验签');
|
||||
assert.ok(uploadIndex > 0, '必须调用 OSS 上传');
|
||||
assert.ok(verifyIndex < uploadIndex, '必须先验签再上传,验不过不得写 OSS');
|
||||
// 无签名私钥时禁止构建:未签名的更新包会被客户端一律拒绝。
|
||||
assert.ok(entry.includes('TAURI_SIGNING_PRIVATE_KEY'));
|
||||
});
|
||||
@@ -1,3 +1,6 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* 发布上传的 OSS 命令行整理:把 ossutil 参数与凭据整理成可执行或可打印的形式,
|
||||
* 便于在 dry-run 下核对将要执行的上传,同时保证任何输出都不回显凭据明文。
|
||||
@@ -25,3 +28,89 @@ export function formatOssutilCommand({ binary, args, endpoint, credentials }) {
|
||||
}
|
||||
return parts.map(quoteArgument).join(' ');
|
||||
}
|
||||
|
||||
export function createReleaseUploadPlan(
|
||||
{
|
||||
artifact,
|
||||
downloadArtifact,
|
||||
channel,
|
||||
manifest,
|
||||
manifestPath,
|
||||
legacyManifestPath,
|
||||
},
|
||||
bucket,
|
||||
) {
|
||||
if (!artifact || !downloadArtifact || !manifestPath || !manifest?.version) {
|
||||
throw new Error('发布结果缺少更新包、首装包或清单');
|
||||
}
|
||||
const prefix = `oss://${bucket}/agc/${channel}`;
|
||||
const artifacts = [
|
||||
...new Set(
|
||||
[artifact, `${artifact}.sig`, downloadArtifact].map((file) =>
|
||||
path.resolve(file),
|
||||
),
|
||||
),
|
||||
];
|
||||
const plan = artifacts.map((source) => ({
|
||||
source,
|
||||
destination: `${prefix}/${manifest.version}/${path.basename(source)}`,
|
||||
}));
|
||||
plan.push({ source: manifestPath, destination: `${prefix}/latest.json` });
|
||||
if (legacyManifestPath) {
|
||||
plan.push({
|
||||
source: legacyManifestPath,
|
||||
destination: `oss://${bucket}/agc/latest.json`,
|
||||
});
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
export function uploadReleaseArtifacts(
|
||||
release,
|
||||
{
|
||||
bucket,
|
||||
endpoint,
|
||||
binary = 'ossutil',
|
||||
accessKeyId,
|
||||
accessKeySecret,
|
||||
dryRun = false,
|
||||
spawn = spawnSync,
|
||||
log = console.log,
|
||||
},
|
||||
) {
|
||||
if (Boolean(accessKeyId) !== Boolean(accessKeySecret)) {
|
||||
throw new Error('OSS AccessKey ID 和 Secret 必须同时提供');
|
||||
}
|
||||
const plan = createReleaseUploadPlan(release, bucket);
|
||||
for (const { source, destination } of plan) {
|
||||
// 全部安装对象成功后才执行 latest 指针;失败立即终止,不发布悬空链接。
|
||||
const args = ['cp', '--force', source, destination];
|
||||
if (dryRun) {
|
||||
log(
|
||||
`[dry-run] ${formatOssutilCommand({ binary, args, endpoint, credentials: Boolean(accessKeyId) })}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const credentials = accessKeyId
|
||||
? ['--access-key-id', accessKeyId, '--access-key-secret', accessKeySecret]
|
||||
: [];
|
||||
const result = spawn(
|
||||
binary,
|
||||
[...args, '--endpoint', endpoint, ...credentials],
|
||||
{
|
||||
stdio: 'inherit',
|
||||
shell: false,
|
||||
},
|
||||
);
|
||||
if (result.error)
|
||||
throw new Error(`无法执行 ${binary},请先安装并配置 ossutil`);
|
||||
if (result.status !== 0) {
|
||||
throw new Error(
|
||||
`OSS 上传失败(退出码 ${result.status ?? 1}):${destination}`,
|
||||
);
|
||||
}
|
||||
log(`[ai-game-creator-shell] 已上传 ${destination}`);
|
||||
}
|
||||
if (dryRun) log('[ai-game-creator-shell] dry-run:未写入任何 OSS 对象');
|
||||
return plan;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import { formatOssutilCommand, readReleaseDryRun } from './release-oss.mjs';
|
||||
import {
|
||||
createReleaseUploadPlan,
|
||||
formatOssutilCommand,
|
||||
readReleaseDryRun,
|
||||
uploadReleaseArtifacts,
|
||||
} from './release-oss.mjs';
|
||||
|
||||
test('dry run only accepts explicit truthy values', () => {
|
||||
assert.equal(readReleaseDryRun({}), false);
|
||||
@@ -33,12 +40,158 @@ test('printed upload command keeps arguments and hides credentials', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('uploader gates every ossutil call behind the dry run switch', () => {
|
||||
const source = readFileSync(
|
||||
new URL('./release-upload.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(source, /const dryRun = readReleaseDryRun\(\);/u);
|
||||
assert.match(source, /if \(dryRun\) \{/u);
|
||||
assert.match(source, /dry-run:未写入任何 OSS 对象/u);
|
||||
function withReleaseFixture(channel, architecture, run) {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-upload-plan-'));
|
||||
try {
|
||||
const artifact = path.join(
|
||||
root,
|
||||
channel === 'dev-win'
|
||||
? '陶泥儿_1.2.3_x64-setup.exe'
|
||||
: '陶泥儿.app.tar.gz',
|
||||
);
|
||||
const downloadArtifact =
|
||||
channel === 'dev-win'
|
||||
? artifact
|
||||
: path.join(root, `陶泥儿_1.2.3_${architecture}.dmg`);
|
||||
const manifestPath = path.join(root, 'latest.json');
|
||||
const legacyManifestPath =
|
||||
channel === 'dev-win' ? path.join(root, 'legacy-latest.json') : null;
|
||||
for (const file of [
|
||||
artifact,
|
||||
`${artifact}.sig`,
|
||||
downloadArtifact,
|
||||
manifestPath,
|
||||
legacyManifestPath,
|
||||
].filter(Boolean)) {
|
||||
writeFileSync(file, 'fixture');
|
||||
}
|
||||
return run({
|
||||
artifact,
|
||||
downloadArtifact,
|
||||
channel,
|
||||
manifest: { version: '1.2.3' },
|
||||
manifestPath,
|
||||
legacyManifestPath,
|
||||
});
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const uploadOptions = {
|
||||
bucket: 'agc-dev',
|
||||
endpoint: 'oss-rg-china-mainland.aliyuncs.com',
|
||||
log: () => {},
|
||||
};
|
||||
|
||||
for (const architecture of ['aarch64', 'x64']) {
|
||||
test(`uploads every ${architecture} Mac object before the channel pointer`, () => {
|
||||
withReleaseFixture('dev-mac', architecture, (release) => {
|
||||
const calls = [];
|
||||
uploadReleaseArtifacts(release, {
|
||||
...uploadOptions,
|
||||
spawn: (binary, args, options) => {
|
||||
assert.equal(binary, 'ossutil');
|
||||
assert.equal(options.shell, false);
|
||||
assert.deepEqual(args.slice(0, 2), ['cp', '--force']);
|
||||
calls.push({ source: args[2], destination: args[3] });
|
||||
return { status: 0 };
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
calls.map(({ source }) => source),
|
||||
[
|
||||
release.artifact,
|
||||
`${release.artifact}.sig`,
|
||||
release.downloadArtifact,
|
||||
release.manifestPath,
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
calls[2].destination,
|
||||
`oss://agc-dev/agc/dev-mac/1.2.3/陶泥儿_1.2.3_${architecture}.dmg`,
|
||||
);
|
||||
assert.equal(
|
||||
calls[3].destination,
|
||||
'oss://agc-dev/agc/dev-mac/latest.json',
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('Windows uploads the shared installer once and publishes migration metadata last', () => {
|
||||
withReleaseFixture('dev-win', 'x64', (release) => {
|
||||
const plan = createReleaseUploadPlan(release, 'agc-dev');
|
||||
assert.deepEqual(
|
||||
plan.map(({ source }) => source),
|
||||
[
|
||||
release.artifact,
|
||||
`${release.artifact}.sig`,
|
||||
release.manifestPath,
|
||||
release.legacyManifestPath,
|
||||
],
|
||||
);
|
||||
assert.equal(plan.at(-1).destination, 'oss://agc-dev/agc/latest.json');
|
||||
const calls = [];
|
||||
uploadReleaseArtifacts(release, {
|
||||
...uploadOptions,
|
||||
spawn: (_binary, args) => {
|
||||
assert.deepEqual(args.slice(0, 2), ['cp', '--force']);
|
||||
calls.push(args[3]);
|
||||
return { status: 0 };
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
calls,
|
||||
plan.map(({ destination }) => destination),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
for (const failedArtifactIndex of [0, 1, 2]) {
|
||||
test(`failed Mac object ${failedArtifactIndex} prevents both later objects and latest publication`, () => {
|
||||
withReleaseFixture('dev-mac', 'aarch64', (release) => {
|
||||
const destinations = [];
|
||||
assert.throws(
|
||||
() =>
|
||||
uploadReleaseArtifacts(release, {
|
||||
...uploadOptions,
|
||||
spawn: (_binary, args) => {
|
||||
destinations.push(args[3]);
|
||||
return {
|
||||
status: destinations.length - 1 === failedArtifactIndex ? 1 : 0,
|
||||
};
|
||||
},
|
||||
}),
|
||||
/OSS 上传失败/u,
|
||||
);
|
||||
assert.equal(destinations.length, failedArtifactIndex + 1);
|
||||
assert.ok(
|
||||
destinations.every(
|
||||
(destination) => !destination.endsWith('/latest.json'),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('dry run prints the complete plan without spawning uploads or exposing credentials', () => {
|
||||
withReleaseFixture('dev-mac', 'aarch64', (release) => {
|
||||
const output = [];
|
||||
uploadReleaseArtifacts(release, {
|
||||
...uploadOptions,
|
||||
dryRun: true,
|
||||
accessKeyId: 'fixture-id',
|
||||
accessKeySecret: 'fixture-secret',
|
||||
spawn: () => assert.fail('dry run must never execute ossutil'),
|
||||
log: (line) => output.push(line),
|
||||
});
|
||||
assert.equal(
|
||||
output.filter((line) => line.startsWith('[dry-run]')).length,
|
||||
4,
|
||||
);
|
||||
assert.match(output.join('\n'), /\.dmg/u);
|
||||
assert.match(output.at(-1), /未写入任何 OSS 对象/u);
|
||||
assert.doesNotMatch(output.join('\n'), /fixture-id|fixture-secret|已上传/u);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
|
||||
import { formatOssutilCommand, readReleaseDryRun } from './release-oss.mjs';
|
||||
import { readReleaseDryRun, uploadReleaseArtifacts } from './release-oss.mjs';
|
||||
|
||||
const bucket = process.env.AGC_OSS_BUCKET?.trim() || 'agc-dev';
|
||||
const endpoint =
|
||||
@@ -14,76 +11,12 @@ const dryRun = readReleaseDryRun();
|
||||
|
||||
const { buildRelease } = await import('./build-release.mjs');
|
||||
|
||||
function runOssutil(args) {
|
||||
const binary = process.env.OSSUTIL_BIN?.trim() || 'ossutil';
|
||||
const accessKeyId = process.env.AGC_OSS_ACCESS_KEY_ID?.trim();
|
||||
const accessKeySecret = process.env.AGC_OSS_ACCESS_KEY_SECRET;
|
||||
if (Boolean(accessKeyId) !== Boolean(accessKeySecret)) {
|
||||
throw new Error('OSS AccessKey ID 和 Secret 必须同时提供');
|
||||
}
|
||||
if (dryRun) {
|
||||
// 演练:只打印将要执行的上传,凭据以占位符呈现,不写入 OSS。
|
||||
console.log(
|
||||
`[dry-run] ${formatOssutilCommand({
|
||||
binary,
|
||||
args,
|
||||
endpoint,
|
||||
credentials: Boolean(accessKeyId),
|
||||
})}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const credentialArgs = accessKeyId
|
||||
? ['--access-key-id', accessKeyId, '--access-key-secret', accessKeySecret]
|
||||
: [];
|
||||
const result = spawnSync(
|
||||
binary,
|
||||
[...args, '--endpoint', endpoint, ...credentialArgs],
|
||||
{
|
||||
stdio: 'inherit',
|
||||
shell: false,
|
||||
},
|
||||
);
|
||||
if (result.error) {
|
||||
throw new Error(`无法执行 ${binary},请先安装并配置 ossutil`);
|
||||
}
|
||||
if (result.status !== 0) process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
const { artifact, channel, legacyManifestPath, manifest, manifestPath } =
|
||||
await buildRelease(process.argv.slice(2));
|
||||
const artifactKey = `agc/${channel}/${manifest.version}/${path.basename(artifact)}`;
|
||||
// Jenkins/ossutil 默认会在目标对象已存在时交互询问并按默认值跳过;
|
||||
// 发布清单是固定的 latest 指针,必须显式覆盖,否则流水线会误报成功但远端仍保留旧版本。
|
||||
runOssutil(['cp', '--force', artifact, `oss://${bucket}/${artifactKey}`]);
|
||||
runOssutil([
|
||||
'cp',
|
||||
'--force',
|
||||
`${artifact}.sig`,
|
||||
`oss://${bucket}/${artifactKey}.sig`,
|
||||
]);
|
||||
runOssutil([
|
||||
'cp',
|
||||
'--force',
|
||||
manifestPath,
|
||||
`oss://${bucket}/agc/${channel}/latest.json`,
|
||||
]);
|
||||
console.log(`[ai-game-creator-shell] 已上传 oss://${bucket}/${artifactKey}`);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 已上传 oss://${bucket}/agc/${channel}/latest.json`,
|
||||
);
|
||||
if (legacyManifestPath) {
|
||||
// 迁移桥:让仍走旧 sha256 清单的已发布客户端升级到新协议,一个版本周期后删除。
|
||||
runOssutil([
|
||||
'cp',
|
||||
'--force',
|
||||
legacyManifestPath,
|
||||
`oss://${bucket}/agc/latest.json`,
|
||||
]);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 已上传迁移指针 oss://${bucket}/agc/latest.json`,
|
||||
);
|
||||
}
|
||||
if (dryRun) {
|
||||
console.log('[ai-game-creator-shell] dry-run:未写入任何 OSS 对象');
|
||||
}
|
||||
const release = await buildRelease(process.argv.slice(2));
|
||||
uploadReleaseArtifacts(release, {
|
||||
bucket,
|
||||
endpoint,
|
||||
binary: process.env.OSSUTIL_BIN?.trim() || 'ossutil',
|
||||
accessKeyId: process.env.AGC_OSS_ACCESS_KEY_ID?.trim(),
|
||||
accessKeySecret: process.env.AGC_OSS_ACCESS_KEY_SECRET,
|
||||
dryRun,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import {
|
||||
createHash,
|
||||
createPublicKey,
|
||||
verify as cryptoVerify,
|
||||
} from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/**
|
||||
* 更新包签名门禁:用产物里烘焙的 updater 公钥校验 `.sig`,
|
||||
* 防止「发布出去的更新包没人装得上」——客户端校验失败会直接拒绝安装,
|
||||
* 而且公钥发布后不可更换,所以必须在构建期、上传前就失败关闭。
|
||||
*
|
||||
* 格式说明(与 Tauri 2 的实际产出对齐,均为实测):
|
||||
* - `tauri.conf.json` 的 `plugins.updater.pubkey` 是「minisign 公钥文本」的 base64;
|
||||
* - 产物旁的 `<artifact>.sig` 是「minisign 签名文本」的 base64;
|
||||
* - 公钥 blob 42 字节(alg `Ed` + 8 字节 keyId + 32 字节 Ed25519 公钥);
|
||||
* - 签名 blob 74 字节(alg `Ed` 或 `ED` + 8 字节 keyId + 64 字节签名);
|
||||
* - Tauri 产出的是 `ED`:先对文件做 BLAKE2b-512,再对摘要做 Ed25519 签名。
|
||||
*/
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const defaultTauriConfigPath = path.join(appRoot, 'src-tauri/tauri.conf.json');
|
||||
const defaultMacosConfigPath = path.join(
|
||||
appRoot,
|
||||
'src-tauri/tauri.macos.conf.json',
|
||||
);
|
||||
|
||||
const PUBLIC_KEY_ALGORITHM = 'Ed';
|
||||
const RAW_ALGORITHM = 'Ed';
|
||||
const PREHASHED_ALGORITHM = 'ED';
|
||||
|
||||
function unwrapMinisignText(value, label) {
|
||||
if (typeof value !== 'string' || value.trim().length === 0) {
|
||||
throw new Error(`${label} 为空`);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.startsWith('untrusted comment:')) return trimmed;
|
||||
const decoded = Buffer.from(trimmed, 'base64').toString('utf8');
|
||||
if (!decoded.startsWith('untrusted comment:')) {
|
||||
throw new Error(`${label} 不是 minisign 内容(缺少 untrusted comment 头)`);
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
|
||||
function contentLines(text) {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
}
|
||||
|
||||
/** 解析 updater 公钥(`tauri.conf.json` 里的 base64 值或 minisign 文本)。 */
|
||||
export function decodeUpdaterPublicKey(value, label = 'updater 公钥') {
|
||||
const lines = contentLines(unwrapMinisignText(value, label));
|
||||
if (lines.length < 2) throw new Error(`${label} 缺少密钥内容行`);
|
||||
const blob = Buffer.from(lines[1], 'base64');
|
||||
if (blob.length !== 42) {
|
||||
throw new Error(
|
||||
`${label} 长度异常:期望 42 字节,实际 ${blob.length} 字节`,
|
||||
);
|
||||
}
|
||||
const algorithm = blob.subarray(0, 2).toString('latin1');
|
||||
if (algorithm !== PUBLIC_KEY_ALGORITHM) {
|
||||
throw new Error(`${label} 算法不受支持:${algorithm}`);
|
||||
}
|
||||
return { algorithm, keyId: blob.subarray(2, 10), key: blob.subarray(10) };
|
||||
}
|
||||
|
||||
/** 解析 `.sig`(base64 值或 minisign 文本)。 */
|
||||
export function decodeUpdaterSignature(value, label = '更新包签名') {
|
||||
const lines = contentLines(unwrapMinisignText(value, label));
|
||||
if (lines.length < 2) throw new Error(`${label} 缺少签名内容行`);
|
||||
const blob = Buffer.from(lines[1], 'base64');
|
||||
if (blob.length !== 74) {
|
||||
throw new Error(
|
||||
`${label} 长度异常:期望 74 字节,实际 ${blob.length} 字节`,
|
||||
);
|
||||
}
|
||||
const algorithm = blob.subarray(0, 2).toString('latin1');
|
||||
if (algorithm !== RAW_ALGORITHM && algorithm !== PREHASHED_ALGORITHM) {
|
||||
throw new Error(`${label} 算法不受支持:${algorithm}`);
|
||||
}
|
||||
return {
|
||||
algorithm,
|
||||
keyId: blob.subarray(2, 10),
|
||||
signature: blob.subarray(10),
|
||||
trustedComment: lines[2] ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
function publicKeyObject(rawKey) {
|
||||
return createPublicKey({
|
||||
key: { kty: 'OKP', crv: 'Ed25519', x: rawKey.toString('base64url') },
|
||||
format: 'jwk',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验更新包签名;任何不一致都抛错(调用方据此失败关闭)。
|
||||
*/
|
||||
export function verifyUpdaterSignature({
|
||||
artifactPath,
|
||||
signaturePath,
|
||||
pubkey,
|
||||
}) {
|
||||
const publicKey = decodeUpdaterPublicKey(pubkey);
|
||||
const signature = decodeUpdaterSignature(
|
||||
fs.readFileSync(signaturePath, 'utf8'),
|
||||
);
|
||||
if (!publicKey.keyId.equals(signature.keyId)) {
|
||||
throw new Error(
|
||||
`更新包签名与内置公钥的 keyId 不一致:公钥 ${publicKey.keyId.toString('hex')},签名 ${signature.keyId.toString('hex')};` +
|
||||
'签名私钥与产物内烘焙的公钥不是同一对,发布后客户端会拒绝安装',
|
||||
);
|
||||
}
|
||||
const payload = fs.readFileSync(artifactPath);
|
||||
const message =
|
||||
signature.algorithm === PREHASHED_ALGORITHM
|
||||
? createHash('blake2b512').update(payload).digest()
|
||||
: payload;
|
||||
if (
|
||||
!cryptoVerify(
|
||||
null,
|
||||
message,
|
||||
publicKeyObject(publicKey.key),
|
||||
signature.signature,
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
`更新包签名校验失败:${path.basename(artifactPath)};该产物无法被客户端接受`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
algorithm: signature.algorithm,
|
||||
keyId: publicKey.keyId.toString('hex'),
|
||||
trustedComment: signature.trustedComment,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取该平台生效的 updater 公钥:macOS 配置可覆盖基础配置,与构建期行为一致。
|
||||
*/
|
||||
export function readUpdaterPubkey({
|
||||
configPath = defaultTauriConfigPath,
|
||||
platformConfigPath = defaultMacosConfigPath,
|
||||
} = {}) {
|
||||
const readPubkey = (file) => {
|
||||
if (!fs.existsSync(file)) return null;
|
||||
const config = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
return config?.plugins?.updater?.pubkey ?? null;
|
||||
};
|
||||
const pubkey = readPubkey(platformConfigPath) ?? readPubkey(configPath);
|
||||
if (!pubkey) throw new Error('未在 Tauri 配置中找到 plugins.updater.pubkey');
|
||||
return pubkey;
|
||||
}
|
||||
|
||||
if (
|
||||
process.argv[1] &&
|
||||
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
) {
|
||||
const [artifactPath, signaturePath = `${artifactPath}.sig`] =
|
||||
process.argv.slice(2);
|
||||
if (!artifactPath) {
|
||||
throw new Error(
|
||||
'用法:node verify-updater-signature.mjs <更新包> [<签名文件>]',
|
||||
);
|
||||
}
|
||||
const result = verifyUpdaterSignature({
|
||||
artifactPath,
|
||||
signaturePath,
|
||||
pubkey: readUpdaterPubkey(),
|
||||
});
|
||||
console.log(
|
||||
`[agc-macos] 更新包签名校验通过:${path.basename(artifactPath)}(alg=${result.algorithm},keyId=${result.keyId})`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
createHash,
|
||||
generateKeyPairSync,
|
||||
randomBytes,
|
||||
sign as cryptoSign,
|
||||
} from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
decodeUpdaterPublicKey,
|
||||
decodeUpdaterSignature,
|
||||
readUpdaterPubkey,
|
||||
verifyUpdaterSignature,
|
||||
} from './verify-updater-signature.mjs';
|
||||
|
||||
/**
|
||||
* 用进程内生成的 Ed25519 密钥自造 minisign 结构,
|
||||
* 覆盖 Tauri 实际使用的 `ED`(BLAKE2b-512 预哈希)与 `Ed`(原文)两种模式。
|
||||
*/
|
||||
function createKeyMaterial() {
|
||||
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
|
||||
const rawKey = Buffer.from(
|
||||
publicKey.export({ format: 'jwk' }).x,
|
||||
'base64url',
|
||||
);
|
||||
const keyId = randomBytes(8);
|
||||
const pubkey = Buffer.from(
|
||||
`untrusted comment: minisign public key: ${keyId.reverse().toString('hex').toUpperCase()}\n` +
|
||||
`${Buffer.concat([Buffer.from('Ed'), keyId, rawKey]).toString('base64')}\n`,
|
||||
).toString('base64');
|
||||
return { privateKey, keyId, rawKey, pubkey };
|
||||
}
|
||||
|
||||
function signFixture({ privateKey, keyId }, payload, algorithm) {
|
||||
const message =
|
||||
algorithm === 'ED'
|
||||
? createHash('blake2b512').update(payload).digest()
|
||||
: payload;
|
||||
const signature = cryptoSign(null, message, privateKey);
|
||||
const blob = Buffer.concat([Buffer.from(algorithm), keyId, signature]);
|
||||
const globalSignature = cryptoSign(null, blob, privateKey);
|
||||
return Buffer.from(
|
||||
'untrusted comment: signature from tauri secret key\n' +
|
||||
`${blob.toString('base64')}\n` +
|
||||
'trusted comment: timestamp:0\tfile:fixture\n' +
|
||||
`${globalSignature.toString('base64')}\n`,
|
||||
).toString('base64');
|
||||
}
|
||||
|
||||
function withFixture(run) {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'agc-sig-test-'));
|
||||
try {
|
||||
const artifactPath = path.join(directory, 'app.app.tar.gz');
|
||||
fs.writeFileSync(artifactPath, 'update payload');
|
||||
return run({ directory, artifactPath });
|
||||
} finally {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test('接受 Tauri 实际使用的 ED(BLAKE2b-512 预哈希)签名', () => {
|
||||
withFixture(({ directory, artifactPath }) => {
|
||||
const material = createKeyMaterial();
|
||||
const signaturePath = path.join(directory, 'app.app.tar.gz.sig');
|
||||
fs.writeFileSync(
|
||||
signaturePath,
|
||||
signFixture(material, fs.readFileSync(artifactPath), 'ED'),
|
||||
);
|
||||
const result = verifyUpdaterSignature({
|
||||
artifactPath,
|
||||
signaturePath,
|
||||
pubkey: material.pubkey,
|
||||
});
|
||||
assert.equal(result.algorithm, 'ED');
|
||||
assert.equal(result.keyId, material.keyId.toString('hex'));
|
||||
});
|
||||
});
|
||||
|
||||
test('接受原文 Ed 签名,两种算法互不通用', () => {
|
||||
withFixture(({ directory, artifactPath }) => {
|
||||
const material = createKeyMaterial();
|
||||
const payload = fs.readFileSync(artifactPath);
|
||||
const signaturePath = path.join(directory, 'app.app.tar.gz.sig');
|
||||
fs.writeFileSync(signaturePath, signFixture(material, payload, 'Ed'));
|
||||
assert.equal(
|
||||
verifyUpdaterSignature({
|
||||
artifactPath,
|
||||
signaturePath,
|
||||
pubkey: material.pubkey,
|
||||
}).algorithm,
|
||||
'Ed',
|
||||
);
|
||||
// 原文模式下签名的是别的载荷时必须失败:证明确实在校验内容而非只看结构。
|
||||
fs.writeFileSync(
|
||||
signaturePath,
|
||||
signFixture(material, Buffer.from('别的载荷'), 'Ed'),
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
verifyUpdaterSignature({
|
||||
artifactPath,
|
||||
signaturePath,
|
||||
pubkey: material.pubkey,
|
||||
}),
|
||||
/签名校验失败/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('产物被篡改时失败关闭', () => {
|
||||
withFixture(({ directory, artifactPath }) => {
|
||||
const material = createKeyMaterial();
|
||||
const signaturePath = path.join(directory, 'app.app.tar.gz.sig');
|
||||
fs.writeFileSync(
|
||||
signaturePath,
|
||||
signFixture(material, fs.readFileSync(artifactPath), 'ED'),
|
||||
);
|
||||
fs.writeFileSync(artifactPath, 'tampered payload');
|
||||
assert.throws(
|
||||
() =>
|
||||
verifyUpdaterSignature({
|
||||
artifactPath,
|
||||
signaturePath,
|
||||
pubkey: material.pubkey,
|
||||
}),
|
||||
/签名校验失败/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('签名私钥与内置公钥不是同一对时给出明确错误', () => {
|
||||
withFixture(({ directory, artifactPath }) => {
|
||||
const signing = createKeyMaterial();
|
||||
const baked = createKeyMaterial();
|
||||
const signaturePath = path.join(directory, 'app.app.tar.gz.sig');
|
||||
fs.writeFileSync(
|
||||
signaturePath,
|
||||
signFixture(signing, fs.readFileSync(artifactPath), 'ED'),
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
verifyUpdaterSignature({
|
||||
artifactPath,
|
||||
signaturePath,
|
||||
pubkey: baked.pubkey,
|
||||
}),
|
||||
/keyId 不一致/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('公钥或签名格式非法时拒绝解析', () => {
|
||||
assert.throws(() => decodeUpdaterPublicKey(''), /为空/u);
|
||||
assert.throws(
|
||||
() => decodeUpdaterPublicKey('bm90IGEgbWluaXNpZ24ga2V5'),
|
||||
/不是 minisign 内容/u,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
decodeUpdaterPublicKey(
|
||||
Buffer.from('untrusted comment: x\nAAAA\n').toString('base64'),
|
||||
),
|
||||
/长度异常/u,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
decodeUpdaterSignature(
|
||||
Buffer.from('untrusted comment: x\nAAAA\n').toString('base64'),
|
||||
),
|
||||
/长度异常/u,
|
||||
);
|
||||
});
|
||||
|
||||
test('仓库里配置的 updater 公钥可被解析(两平台共用)', () => {
|
||||
const decoded = decodeUpdaterPublicKey(readUpdaterPubkey());
|
||||
assert.equal(decoded.algorithm, 'Ed');
|
||||
assert.equal(decoded.key.length, 32);
|
||||
});
|
||||
@@ -31,7 +31,23 @@ fn sha256_file(path: &std::path::Path) -> Result<String, std::io::Error> {
|
||||
fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
|
||||
let target = env::var("TARGET").expect("Cargo TARGET");
|
||||
println!("cargo:rustc-env=AGC_BUILD_TARGET={target}");
|
||||
let Some(layout) = codex_bundle::for_target(&target) else {
|
||||
if target.contains("apple-darwin") {
|
||||
// Tauri 的 universal 两次 Cargo 编译共用 resource staging,
|
||||
// 每次都生成完整双架构目录,最终 bundle 不取决于最后编译的切片。
|
||||
let staging = manifest_dir.join("resources/codex/mac-native");
|
||||
if staging.exists() {
|
||||
fs::remove_dir_all(&staging).expect("清理 macOS Codex staging 失败");
|
||||
}
|
||||
for target in ["aarch64-apple-darwin", "x86_64-apple-darwin"] {
|
||||
stage_codex_target(manifest_dir, target);
|
||||
}
|
||||
} else {
|
||||
stage_codex_target(manifest_dir, &target);
|
||||
}
|
||||
}
|
||||
|
||||
fn stage_codex_target(manifest_dir: &std::path::Path, target: &str) {
|
||||
let Some(layout) = codex_bundle::for_target(target) else {
|
||||
assert!(
|
||||
!target.contains("windows") && !target.contains("apple-darwin"),
|
||||
"不支持的 Codex 随包目标:{target}"
|
||||
@@ -81,7 +97,7 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
|
||||
&fs::read(source.join("codex-package.json")).expect("读取 Codex 原生包元数据失败"),
|
||||
)
|
||||
.expect("Codex 原生包元数据无效");
|
||||
codex_bundle::validate_package_metadata(&metadata, &target, layout)
|
||||
codex_bundle::validate_package_metadata(&metadata, target, layout)
|
||||
.unwrap_or_else(|error| panic!("{error}"));
|
||||
let target_dir = manifest_dir.join("resources/codex").join(layout.directory);
|
||||
let notice = target_dir.join("NOTICE.md");
|
||||
|
||||
@@ -49,7 +49,11 @@ pub fn for_target(target: &str) -> Option<Layout> {
|
||||
} else {
|
||||
"codex-darwin-x64"
|
||||
},
|
||||
directory: "mac-native",
|
||||
directory: if target.starts_with("aarch64") {
|
||||
"mac-native/darwin-arm64"
|
||||
} else {
|
||||
"mac-native/darwin-x64"
|
||||
},
|
||||
executable: "bin/codex",
|
||||
files: MAC_FILES,
|
||||
}),
|
||||
@@ -90,6 +94,9 @@ mod tests {
|
||||
let intel = for_target("x86_64-apple-darwin").unwrap();
|
||||
assert_eq!(intel.platform, "darwin-x64");
|
||||
assert_eq!(intel.npm_package, "codex-darwin-x64");
|
||||
assert_eq!(mac.directory, "mac-native/darwin-arm64");
|
||||
assert_eq!(intel.directory, "mac-native/darwin-x64");
|
||||
assert_ne!(mac.directory, intel.directory);
|
||||
let windows = for_target("x86_64-pc-windows-msvc").unwrap();
|
||||
assert_eq!(windows.directory, "win-x64");
|
||||
assert_eq!(windows.files.len(), 6);
|
||||
|
||||
@@ -5,13 +5,20 @@
|
||||
"minimumSystemVersion": "15.0"
|
||||
},
|
||||
"resources": {
|
||||
"resources/codex/mac-native/bin/codex": "coding-agent/mac-native/bin/codex",
|
||||
"resources/codex/mac-native/bin/codex-code-mode-host": "coding-agent/mac-native/bin/codex-code-mode-host",
|
||||
"resources/codex/mac-native/codex-path/rg": "coding-agent/mac-native/codex-path/rg",
|
||||
"resources/codex/mac-native/codex-resources/zsh/bin/zsh": "coding-agent/mac-native/codex-resources/zsh/bin/zsh",
|
||||
"resources/codex/mac-native/codex-package.json": "coding-agent/mac-native/codex-package.json",
|
||||
"resources/codex/mac-native/NOTICE.md": "coding-agent/mac-native/NOTICE.md",
|
||||
"resources/codex/mac-native/manifest.json": "coding-agent/mac-native/manifest.json",
|
||||
"resources/codex/mac-native/darwin-arm64/bin/codex": "coding-agent/mac-native/darwin-arm64/bin/codex",
|
||||
"resources/codex/mac-native/darwin-arm64/bin/codex-code-mode-host": "coding-agent/mac-native/darwin-arm64/bin/codex-code-mode-host",
|
||||
"resources/codex/mac-native/darwin-arm64/codex-path/rg": "coding-agent/mac-native/darwin-arm64/codex-path/rg",
|
||||
"resources/codex/mac-native/darwin-arm64/codex-resources/zsh/bin/zsh": "coding-agent/mac-native/darwin-arm64/codex-resources/zsh/bin/zsh",
|
||||
"resources/codex/mac-native/darwin-arm64/codex-package.json": "coding-agent/mac-native/darwin-arm64/codex-package.json",
|
||||
"resources/codex/mac-native/darwin-arm64/NOTICE.md": "coding-agent/mac-native/darwin-arm64/NOTICE.md",
|
||||
"resources/codex/mac-native/darwin-arm64/manifest.json": "coding-agent/mac-native/darwin-arm64/manifest.json",
|
||||
"resources/codex/mac-native/darwin-x64/bin/codex": "coding-agent/mac-native/darwin-x64/bin/codex",
|
||||
"resources/codex/mac-native/darwin-x64/bin/codex-code-mode-host": "coding-agent/mac-native/darwin-x64/bin/codex-code-mode-host",
|
||||
"resources/codex/mac-native/darwin-x64/codex-path/rg": "coding-agent/mac-native/darwin-x64/codex-path/rg",
|
||||
"resources/codex/mac-native/darwin-x64/codex-resources/zsh/bin/zsh": "coding-agent/mac-native/darwin-x64/codex-resources/zsh/bin/zsh",
|
||||
"resources/codex/mac-native/darwin-x64/codex-package.json": "coding-agent/mac-native/darwin-x64/codex-package.json",
|
||||
"resources/codex/mac-native/darwin-x64/NOTICE.md": "coding-agent/mac-native/darwin-x64/NOTICE.md",
|
||||
"resources/codex/mac-native/darwin-x64/manifest.json": "coding-agent/mac-native/darwin-x64/manifest.json",
|
||||
"resources/plugins": "plugins"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -23,14 +23,7 @@ import {
|
||||
normalizeAuthPhoneInput,
|
||||
sendClientPhoneLoginCode,
|
||||
} from '../services/clientAuth';
|
||||
import {
|
||||
type ClientServerPreset,
|
||||
type ClientServerSelection,
|
||||
getClientServerBaseUrl,
|
||||
getClientServerSelection,
|
||||
normalizeClientServerBaseUrl,
|
||||
setClientServerSelection,
|
||||
} from '../services/clientHttp';
|
||||
import { getClientServerBaseUrl } from '../services/clientHttp';
|
||||
import {
|
||||
captureClientError,
|
||||
installWebviewLogBridge,
|
||||
@@ -158,13 +151,6 @@ export function AuthenticatedClient({
|
||||
const [loginBusy, setLoginBusy] = useState(false);
|
||||
const [codeBusy, setCodeBusy] = useState(false);
|
||||
const [codeCooldownSeconds, setCodeCooldownSeconds] = useState(0);
|
||||
const initialServerSelection = getClientServerSelection();
|
||||
const [serverSelection, setServerSelection] = useState<ClientServerSelection>(
|
||||
initialServerSelection,
|
||||
);
|
||||
const [customServerUrl, setCustomServerUrl] = useState(
|
||||
initialServerSelection.customBaseUrl,
|
||||
);
|
||||
useEffect(() => {
|
||||
const uninstallWebviewLogBridge = installWebviewLogBridge();
|
||||
const handleError = (event: ErrorEvent) => {
|
||||
@@ -184,37 +170,6 @@ export function AuthenticatedClient({
|
||||
};
|
||||
}, []);
|
||||
|
||||
function persistServerSelection() {
|
||||
try {
|
||||
const next = setClientServerSelection({
|
||||
preset: serverSelection.preset,
|
||||
customBaseUrl: customServerUrl,
|
||||
});
|
||||
setServerSelection(next);
|
||||
return next;
|
||||
} catch (error) {
|
||||
void captureClientError(error, {
|
||||
source: 'auth-hydrate',
|
||||
action: 'restore-session',
|
||||
});
|
||||
setLoginStatus(error instanceof Error ? error.message : String(error));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function handleServerPresetChange(preset: ClientServerPreset) {
|
||||
if (preset === 'custom') {
|
||||
setServerSelection((current) => ({ ...current, preset }));
|
||||
return;
|
||||
}
|
||||
const next = setClientServerSelection({
|
||||
preset,
|
||||
customBaseUrl: customServerUrl,
|
||||
});
|
||||
setServerSelection(next);
|
||||
setLoginStatus(`已选择 ${preset} 服务器`);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
async function hydrateAuth() {
|
||||
@@ -430,11 +385,7 @@ export function AuthenticatedClient({
|
||||
if (codeBusy || codeCooldownSeconds > 0) {
|
||||
return;
|
||||
}
|
||||
const persistedSelection = persistServerSelection();
|
||||
if (!persistedSelection) {
|
||||
return;
|
||||
}
|
||||
const apiBaseUrl = getClientServerBaseUrl(persistedSelection);
|
||||
const apiBaseUrl = getClientServerBaseUrl();
|
||||
const normalizedPhone = normalizeAuthPhoneInput(phone);
|
||||
if (!normalizedPhone) {
|
||||
setLoginStatus('请输入手机号');
|
||||
@@ -479,11 +430,7 @@ export function AuthenticatedClient({
|
||||
setLoginStatus('请输入密码');
|
||||
return;
|
||||
}
|
||||
const persistedSelection = persistServerSelection();
|
||||
if (!persistedSelection) {
|
||||
return;
|
||||
}
|
||||
const loginApiBaseUrl = getClientServerBaseUrl(persistedSelection);
|
||||
const loginApiBaseUrl = getClientServerBaseUrl();
|
||||
const loginAttempt = (loginAttemptRef.current += 1);
|
||||
setLoginBusy(true);
|
||||
setLoginStatus('正在登录');
|
||||
@@ -635,50 +582,6 @@ export function AuthenticatedClient({
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
<label>
|
||||
服务器
|
||||
<select
|
||||
aria-label="服务器"
|
||||
disabled={loginBusy || codeBusy}
|
||||
value={serverSelection.preset}
|
||||
onChange={(event) =>
|
||||
handleServerPresetChange(
|
||||
event.currentTarget.value as ClientServerPreset,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="release">release</option>
|
||||
<option value="dev">dev</option>
|
||||
<option value="custom">custom</option>
|
||||
</select>
|
||||
</label>
|
||||
{serverSelection.preset === 'custom' ? (
|
||||
<label>
|
||||
自定义服务器地址
|
||||
<input
|
||||
aria-label="自定义服务器地址"
|
||||
disabled={loginBusy || codeBusy}
|
||||
inputMode="url"
|
||||
placeholder="https://example.com"
|
||||
value={customServerUrl}
|
||||
onChange={(event) =>
|
||||
setCustomServerUrl(event.currentTarget.value)
|
||||
}
|
||||
onBlur={() => {
|
||||
if (customServerUrl.trim()) {
|
||||
try {
|
||||
normalizeClientServerBaseUrl(customServerUrl);
|
||||
persistServerSelection();
|
||||
} catch (error) {
|
||||
setLoginStatus(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
) : null}
|
||||
<div className="client-auth-tabs" role="group" aria-label="登录方式">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
RedeemProfileRewardCodeResponse,
|
||||
unwrapApiResponse,
|
||||
} from '../../../../packages/shared/src';
|
||||
import { getStoredAuthAccessToken } from './clientAuth';
|
||||
import { fetchClientHttp, readClientHttpResponseText } from './clientHttp';
|
||||
import { captureClientError } from './errorReporting';
|
||||
import {
|
||||
@@ -16,7 +17,11 @@ import {
|
||||
requestPlatformSessionRefresh,
|
||||
} from './platformSession';
|
||||
|
||||
const ACCESS_TOKEN_STORAGE_KEY = 'genarrative.auth.access-token.v1';
|
||||
export {
|
||||
clearStoredAuthAccessToken,
|
||||
getStoredAuthAccessToken,
|
||||
setStoredAuthAccessToken,
|
||||
} from './clientAuth';
|
||||
|
||||
export class ClientAuthRequestError extends Error {
|
||||
readonly status: number | null;
|
||||
@@ -32,23 +37,6 @@ export class ClientAuthRequestError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function getStoredAuthAccessToken() {
|
||||
return window.localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY)?.trim() || '';
|
||||
}
|
||||
|
||||
export function setStoredAuthAccessToken(token: string) {
|
||||
const nextToken = token.trim();
|
||||
if (nextToken) {
|
||||
window.localStorage.setItem(ACCESS_TOKEN_STORAGE_KEY, nextToken);
|
||||
return;
|
||||
}
|
||||
window.localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function clearStoredAuthAccessToken() {
|
||||
window.localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
async function readApiErrorMessage(
|
||||
response: Response,
|
||||
fallback: string,
|
||||
|
||||
@@ -29,6 +29,10 @@ import {
|
||||
} from './clientOperation';
|
||||
|
||||
const ACCESS_TOKEN_STORAGE_KEY = 'genarrative.auth.access-token.v1';
|
||||
const ACCESS_TOKEN_ORIGIN_STORAGE_KEY =
|
||||
'genarrative.auth.access-token-origin.v1';
|
||||
const LEGACY_SERVER_SELECTION_STORAGE_KEY =
|
||||
'genarrative.client.server-selection.v1';
|
||||
|
||||
export function normalizeAuthPhoneInput(phone: string) {
|
||||
const compactPhone = phone.replace(/[^\d+]/gu, '').trim();
|
||||
@@ -44,21 +48,44 @@ function buildClientAuthPhoneInput(phone: string): AuthPhoneNumberInput {
|
||||
};
|
||||
}
|
||||
|
||||
export function getStoredAuthAccessToken() {
|
||||
return window.localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY)?.trim() || '';
|
||||
export function getStoredAuthAccessToken(
|
||||
apiBaseUrl = getClientServerBaseUrl(),
|
||||
) {
|
||||
if (apiBaseUrl !== getClientServerBaseUrl()) return '';
|
||||
const token =
|
||||
window.localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY)?.trim() || '';
|
||||
if (!token) return '';
|
||||
const storedOrigin = window.localStorage.getItem(
|
||||
ACCESS_TOKEN_ORIGIN_STORAGE_KEY,
|
||||
);
|
||||
if (storedOrigin === apiBaseUrl) return token;
|
||||
// Old preferences were editable independently of the token, so they cannot
|
||||
// establish its origin. Recover an unmarked session through the dev cookie.
|
||||
clearStoredAuthAccessToken();
|
||||
window.localStorage.removeItem(LEGACY_SERVER_SELECTION_STORAGE_KEY);
|
||||
return '';
|
||||
}
|
||||
|
||||
function setStoredAuthAccessToken(token: string) {
|
||||
export function setStoredAuthAccessToken(
|
||||
token: string,
|
||||
apiBaseUrl = getClientServerBaseUrl(),
|
||||
) {
|
||||
if (apiBaseUrl !== getClientServerBaseUrl()) {
|
||||
throw new Error('登录凭据不属于客户端固定的 dev 服务');
|
||||
}
|
||||
const nextToken = token.trim();
|
||||
if (nextToken) {
|
||||
window.localStorage.setItem(ACCESS_TOKEN_STORAGE_KEY, nextToken);
|
||||
window.localStorage.setItem(ACCESS_TOKEN_ORIGIN_STORAGE_KEY, apiBaseUrl);
|
||||
window.localStorage.removeItem(LEGACY_SERVER_SELECTION_STORAGE_KEY);
|
||||
return;
|
||||
}
|
||||
window.localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
|
||||
clearStoredAuthAccessToken();
|
||||
}
|
||||
|
||||
export function clearStoredAuthAccessToken() {
|
||||
window.localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
|
||||
window.localStorage.removeItem(ACCESS_TOKEN_ORIGIN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
const clientAuthRefreshPromises = new Map<string, Promise<string>>();
|
||||
@@ -102,7 +129,7 @@ function getClientAuthNetworkErrorMessage(error: unknown) {
|
||||
return '无法连接登录服务:服务器拒绝连接,请确认服务已启动并检查端口';
|
||||
}
|
||||
if (/dns|resolve|name or service not known|无法解析/iu.test(detail)) {
|
||||
return '无法连接登录服务:服务器地址无法解析,请检查服务器选择';
|
||||
return '无法连接登录服务:服务器地址无法解析,请检查网络后重试';
|
||||
}
|
||||
if (/certificate|tls|ssl|证书/iu.test(detail)) {
|
||||
return '无法连接登录服务:安全连接失败,请检查服务器地址和证书';
|
||||
@@ -202,7 +229,7 @@ async function requestAuthJson<T>(
|
||||
const headers = new Headers(init.headers);
|
||||
headers.set(API_RESPONSE_ENVELOPE_HEADER, API_RESPONSE_ENVELOPE_VERSION);
|
||||
if (!options.skipAuth) {
|
||||
const token = getStoredAuthAccessToken();
|
||||
const token = getStoredAuthAccessToken(options.apiBaseUrl);
|
||||
if (token) {
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
@@ -284,7 +311,7 @@ export async function refreshClientAuthAccessToken(
|
||||
apiBaseUrl,
|
||||
transitionClientOperation(operation, 'success'),
|
||||
);
|
||||
setStoredAuthAccessToken(response.token);
|
||||
setStoredAuthAccessToken(response.token, apiBaseUrl);
|
||||
return response.token;
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -322,7 +349,7 @@ export async function loginClientWithPassword(
|
||||
'登录失败',
|
||||
{ skipAuth: true, apiBaseUrl },
|
||||
);
|
||||
setStoredAuthAccessToken(response.token);
|
||||
setStoredAuthAccessToken(response.token, apiBaseUrl);
|
||||
return response.user;
|
||||
}
|
||||
|
||||
@@ -365,7 +392,7 @@ export async function loginClientWithPhoneCode(
|
||||
'登录失败',
|
||||
{ skipAuth: true, apiBaseUrl },
|
||||
);
|
||||
setStoredAuthAccessToken(response.token);
|
||||
setStoredAuthAccessToken(response.token, apiBaseUrl);
|
||||
return response.user;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { fetch as tauriHttpFetch } from '@tauri-apps/plugin-http';
|
||||
|
||||
export const AGC_DEVELOPMENT_API_BASE_URL = 'https://dev.genarrative.world';
|
||||
export const AGC_RELEASE_API_BASE_URL = 'https://www.genarrative.world';
|
||||
export const AGC_CLIENT_MARKER_HEADER = 'X-Genarrative-Client';
|
||||
export const AGC_CLIENT_MARKER_VALUE = 'agc';
|
||||
/**
|
||||
* Upper bound for the initial network transaction (DNS/connect/response
|
||||
* headers). Callers may override this for a request that legitimately needs
|
||||
* more time; the default prevents auth/bootstrap requests from hanging
|
||||
* forever when the selected server or proxy is unavailable.
|
||||
* forever when the platform service is unavailable.
|
||||
*/
|
||||
export const CLIENT_HTTP_DEFAULT_TIMEOUT_MS = 15_000;
|
||||
|
||||
@@ -85,119 +84,12 @@ export async function readClientHttpResponseText(
|
||||
}
|
||||
}
|
||||
|
||||
export type ClientServerPreset = 'release' | 'dev' | 'custom';
|
||||
|
||||
export type ClientServerSelection = {
|
||||
preset: ClientServerPreset;
|
||||
customBaseUrl: string;
|
||||
};
|
||||
|
||||
const CLIENT_SERVER_SELECTION_STORAGE_KEY =
|
||||
'genarrative.client.server-selection.v1';
|
||||
|
||||
function defaultClientServerPreset(): Exclude<ClientServerPreset, 'custom'> {
|
||||
return import.meta.env.DEV ? 'dev' : 'release';
|
||||
}
|
||||
|
||||
function isClientServerPreset(value: unknown): value is ClientServerPreset {
|
||||
return value === 'release' || value === 'dev' || value === 'custom';
|
||||
}
|
||||
|
||||
export function normalizeClientServerBaseUrl(value: string) {
|
||||
const normalized = value.trim().replace(/\/+$/u, '');
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(normalized);
|
||||
} catch {
|
||||
throw new Error('服务器地址无效');
|
||||
}
|
||||
if (
|
||||
!['http:', 'https:'].includes(parsed.protocol) ||
|
||||
parsed.username ||
|
||||
parsed.password ||
|
||||
parsed.pathname !== '/' ||
|
||||
parsed.search ||
|
||||
parsed.hash
|
||||
) {
|
||||
throw new Error('服务器地址必须是纯 HTTP(S) 地址');
|
||||
}
|
||||
const isLoopback = ['localhost', '127.0.0.1', '[::1]'].includes(
|
||||
parsed.hostname,
|
||||
);
|
||||
if (parsed.protocol === 'http:' && !isLoopback) {
|
||||
throw new Error('非本机服务器必须使用 HTTPS');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function readStoredClientServerSelection(): ClientServerSelection {
|
||||
const fallback: ClientServerSelection = {
|
||||
preset: defaultClientServerPreset(),
|
||||
customBaseUrl: '',
|
||||
};
|
||||
if (typeof window === 'undefined') return fallback;
|
||||
try {
|
||||
const raw = window.localStorage.getItem(
|
||||
CLIENT_SERVER_SELECTION_STORAGE_KEY,
|
||||
);
|
||||
if (!raw) return fallback;
|
||||
const parsed = JSON.parse(raw) as {
|
||||
preset?: unknown;
|
||||
customBaseUrl?: unknown;
|
||||
};
|
||||
if (!isClientServerPreset(parsed.preset)) return fallback;
|
||||
const customBaseUrl =
|
||||
typeof parsed.customBaseUrl === 'string' ? parsed.customBaseUrl : '';
|
||||
if (parsed.preset === 'custom') {
|
||||
normalizeClientServerBaseUrl(customBaseUrl);
|
||||
}
|
||||
return { preset: parsed.preset, customBaseUrl };
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function getClientServerSelection() {
|
||||
return readStoredClientServerSelection();
|
||||
}
|
||||
|
||||
export function setClientServerSelection(
|
||||
selection: ClientServerSelection,
|
||||
): ClientServerSelection {
|
||||
const next: ClientServerSelection = {
|
||||
preset: selection.preset,
|
||||
customBaseUrl:
|
||||
selection.preset === 'custom'
|
||||
? normalizeClientServerBaseUrl(selection.customBaseUrl)
|
||||
: selection.customBaseUrl.trim(),
|
||||
};
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.setItem(
|
||||
CLIENT_SERVER_SELECTION_STORAGE_KEY,
|
||||
JSON.stringify(next),
|
||||
);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function resetClientServerSelectionForTests() {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.removeItem(CLIENT_SERVER_SELECTION_STORAGE_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
export function getClientServerBaseUrl(
|
||||
selection: ClientServerSelection = getClientServerSelection(),
|
||||
) {
|
||||
if (selection.preset === 'release') return AGC_RELEASE_API_BASE_URL;
|
||||
if (selection.preset === 'dev') return AGC_DEVELOPMENT_API_BASE_URL;
|
||||
return normalizeClientServerBaseUrl(selection.customBaseUrl);
|
||||
export function getClientServerBaseUrl() {
|
||||
return AGC_DEVELOPMENT_API_BASE_URL;
|
||||
}
|
||||
|
||||
type ClientHttpContext = {
|
||||
isDevelopment: boolean;
|
||||
isTauri: boolean;
|
||||
pageProtocol: string;
|
||||
mode?: string;
|
||||
serverBaseUrl?: string;
|
||||
};
|
||||
@@ -215,9 +107,7 @@ function withAgcClientMarker(init: RequestInit): RequestInit {
|
||||
|
||||
function currentClientHttpContext(): ClientHttpContext {
|
||||
return {
|
||||
isDevelopment: import.meta.env.DEV,
|
||||
isTauri: typeof window !== 'undefined' && Boolean(window.__TAURI__),
|
||||
pageProtocol: typeof window === 'undefined' ? '' : window.location.protocol,
|
||||
mode: import.meta.env.MODE,
|
||||
};
|
||||
}
|
||||
@@ -226,20 +116,20 @@ export function resolveClientHttpTarget(
|
||||
url: string,
|
||||
context: ClientHttpContext = currentClientHttpContext(),
|
||||
): ClientHttpTarget {
|
||||
// Existing unit fixtures omit mode; retain the Vite-relative transport for
|
||||
// them while real development/release clients use the selected server.
|
||||
const serverBaseUrl = getClientServerBaseUrl();
|
||||
const target = new URL(url, `${serverBaseUrl}/`);
|
||||
if (
|
||||
!context.serverBaseUrl &&
|
||||
(context.mode === 'test' || (!context.mode && context.isDevelopment))
|
||||
(context.serverBaseUrl && context.serverBaseUrl !== serverBaseUrl) ||
|
||||
target.origin !== serverBaseUrl ||
|
||||
target.username ||
|
||||
target.password
|
||||
) {
|
||||
return { transport: 'web', url };
|
||||
throw new Error('请求目标不在客户端固定的 dev 服务范围内');
|
||||
}
|
||||
|
||||
const serverBaseUrl =
|
||||
context.serverBaseUrl ?? getClientServerBaseUrl(getClientServerSelection());
|
||||
const target = new URL(url, `${serverBaseUrl}/`);
|
||||
if (target.origin !== serverBaseUrl) {
|
||||
throw new Error('请求目标不在当前选择的服务器范围内');
|
||||
// Unit fixtures use relative requests after the same origin validation.
|
||||
if (context.mode === 'test') {
|
||||
return { transport: 'web', url };
|
||||
}
|
||||
|
||||
if (!context.isTauri) {
|
||||
@@ -258,17 +148,10 @@ export async function fetchClientHttp(
|
||||
} = {},
|
||||
): Promise<Response> {
|
||||
const currentContext = currentClientHttpContext();
|
||||
const serverBaseUrl = options.serverBaseUrl
|
||||
? normalizeClientServerBaseUrl(options.serverBaseUrl)
|
||||
: undefined;
|
||||
// Unit fixtures intentionally use the relative Vite transport. Real clients bind every
|
||||
// auth transaction to the explicit origin captured before its first request.
|
||||
const target = resolveClientHttpTarget(
|
||||
url,
|
||||
currentContext.mode === 'test'
|
||||
? currentContext
|
||||
: { ...currentContext, serverBaseUrl },
|
||||
);
|
||||
const target = resolveClientHttpTarget(url, {
|
||||
...currentContext,
|
||||
serverBaseUrl: options.serverBaseUrl,
|
||||
});
|
||||
const markedInit = withAgcClientMarker(init);
|
||||
|
||||
// Always use a private controller so an internal timeout cannot mutate a
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user