Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b1cadd0cc8 | |||
| 261228ed3f | |||
| 8c17e40d7d | |||
| 237e440057 | |||
| e3682fd06f | |||
| fc46cabb75 | |||
| 762f037150 | |||
| 48985d3447 |
@@ -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/
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { AuthUser } from '../../../../packages/shared/src/contracts/auth';
|
||||
import { resolveTauriInvoke } from '../app/tauri';
|
||||
import {
|
||||
clearStoredAuthAccessToken,
|
||||
getCurrentClientAuthUser,
|
||||
getStoredAuthAccessToken,
|
||||
isClientAuthAuthorityFailure,
|
||||
refreshClientAuthAccessToken,
|
||||
setStoredAuthAccessToken,
|
||||
} from './clientAuth';
|
||||
import { getClientServerBaseUrl } from './clientHttp';
|
||||
import {
|
||||
@@ -13,10 +15,8 @@ import {
|
||||
transitionClientOperation,
|
||||
} from './clientOperation';
|
||||
|
||||
const ACCESS_TOKEN_STORAGE_KEY = 'genarrative.auth.access-token.v1';
|
||||
|
||||
function readStoredAccessTokenOrThrow() {
|
||||
const accessToken = getStoredAuthAccessToken();
|
||||
function readStoredAccessTokenOrThrow(apiBaseUrl: string) {
|
||||
const accessToken = getStoredAuthAccessToken(apiBaseUrl);
|
||||
if (!accessToken) {
|
||||
throw new Error('陶泥儿登录凭据缺失,请重新登录');
|
||||
}
|
||||
@@ -94,18 +94,18 @@ export function getPlatformSessionOperation() {
|
||||
|
||||
function restoreCommittedAccessToken() {
|
||||
if (committedPlatformSession?.accessToken) {
|
||||
window.localStorage.setItem(
|
||||
ACCESS_TOKEN_STORAGE_KEY,
|
||||
setStoredAuthAccessToken(
|
||||
committedPlatformSession.accessToken,
|
||||
committedPlatformSession.apiBaseUrl,
|
||||
);
|
||||
return;
|
||||
}
|
||||
window.localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
|
||||
clearStoredAuthAccessToken();
|
||||
}
|
||||
|
||||
function restoreCurrentRendererAccessToken() {
|
||||
if (!desiredPlatformSession) {
|
||||
window.localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
|
||||
clearStoredAuthAccessToken();
|
||||
return;
|
||||
}
|
||||
restoreCommittedAccessToken();
|
||||
@@ -424,7 +424,7 @@ export async function commitAuthenticatedPlatformSession(
|
||||
expectedGeneration: number,
|
||||
apiBaseUrl = resolvePlatformApiBaseUrl(),
|
||||
) {
|
||||
const accessToken = readStoredAccessTokenOrThrow();
|
||||
const accessToken = readStoredAccessTokenOrThrow(apiBaseUrl);
|
||||
const operation = createClientOperation(
|
||||
'auth-transition',
|
||||
{ userId: user.id },
|
||||
@@ -508,7 +508,7 @@ export function requestPlatformSessionRefresh(expectedUserId?: string) {
|
||||
const committed = await enqueuePlatformSessionNativeMutation(() =>
|
||||
commitPlatformCredentialRefresh(
|
||||
user,
|
||||
readStoredAccessTokenOrThrow(),
|
||||
readStoredAccessTokenOrThrow(apiBaseUrl),
|
||||
apiBaseUrl,
|
||||
expectedGeneration,
|
||||
),
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { afterEach } from 'vitest';
|
||||
|
||||
import {
|
||||
AGC_DEVELOPMENT_API_BASE_URL,
|
||||
AGC_RELEASE_API_BASE_URL,
|
||||
resetClientServerSelectionForTests,
|
||||
setClientServerSelection,
|
||||
} from '../../src/services/clientHttp';
|
||||
import { setStoredAuthAccessToken } from '../../src/services/clientAuth';
|
||||
import { AGC_DEVELOPMENT_API_BASE_URL } from '../../src/services/clientHttp';
|
||||
import {
|
||||
beginPlatformSessionClearTransition,
|
||||
beginPlatformSessionTransition,
|
||||
@@ -33,7 +29,6 @@ import {
|
||||
export function registerAuthTests() {
|
||||
afterEach(() => {
|
||||
resetPlatformSessionStateForTests();
|
||||
resetClientServerSelectionForTests();
|
||||
delete window.__TAURI__;
|
||||
});
|
||||
|
||||
@@ -151,7 +146,6 @@ export function registerAuthTests() {
|
||||
});
|
||||
|
||||
it('keeps login HTTP and native commit bound to the origin frozen before the request', async () => {
|
||||
setClientServerSelection({ preset: 'dev', customBaseUrl: '' });
|
||||
const invoke = vi.fn(async () => null);
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
let resolveLogin: ((response: Response) => void) | null = null;
|
||||
@@ -184,11 +178,12 @@ export function registerAuthTests() {
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: '登录' }));
|
||||
await waitFor(() => expect(resolveLogin).not.toBeNull());
|
||||
expect(
|
||||
(screen.getByLabelText('服务器') as HTMLSelectElement).disabled,
|
||||
).toBe(true);
|
||||
expect(screen.queryByLabelText('服务器')).toBeNull();
|
||||
|
||||
setClientServerSelection({ preset: 'release', customBaseUrl: '' });
|
||||
window.localStorage.setItem(
|
||||
'genarrative.client.server-selection.v1',
|
||||
JSON.stringify({ preset: 'release', customBaseUrl: '' }),
|
||||
);
|
||||
resolveLogin?.(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
@@ -211,7 +206,7 @@ export function registerAuthTests() {
|
||||
);
|
||||
expect(invoke).not.toHaveBeenCalledWith(
|
||||
'install_platform_account_session',
|
||||
expect.objectContaining({ apiBaseUrl: AGC_RELEASE_API_BASE_URL }),
|
||||
expect.objectContaining({ apiBaseUrl: 'https://www.genarrative.world' }),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -257,10 +252,7 @@ export function registerAuthTests() {
|
||||
const installFloor = nativeFloor.revision;
|
||||
const installIdentityFloor = nativeFloor.identityGeneration;
|
||||
const loginGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'renderer-reload-token',
|
||||
);
|
||||
setStoredAuthAccessToken('renderer-reload-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, loginGeneration);
|
||||
expect(mutations[0]?.command).toBe('install_platform_account_session');
|
||||
expect(mutations[0]?.identityGeneration).toBeGreaterThan(
|
||||
@@ -310,10 +302,7 @@ export function registerAuthTests() {
|
||||
});
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const firstGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'retry-floor-token',
|
||||
);
|
||||
setStoredAuthAccessToken('retry-floor-token');
|
||||
|
||||
await expect(
|
||||
commitAuthenticatedPlatformSession(testAuthUser, firstGeneration),
|
||||
@@ -321,10 +310,7 @@ export function registerAuthTests() {
|
||||
|
||||
// 瞬时读取失败不能被缓存成永久失败:第二次登录必须重新读取并成功。
|
||||
const secondGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'retry-floor-token',
|
||||
);
|
||||
setStoredAuthAccessToken('retry-floor-token');
|
||||
await expect(
|
||||
commitAuthenticatedPlatformSession(testAuthUser, secondGeneration),
|
||||
).resolves.toEqual(expect.any(Number));
|
||||
@@ -358,10 +344,7 @@ export function registerAuthTests() {
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
|
||||
const stalledGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'stalled-token',
|
||||
);
|
||||
setStoredAuthAccessToken('stalled-token');
|
||||
const stalled = commitAuthenticatedPlatformSession(
|
||||
testAuthUser,
|
||||
stalledGeneration,
|
||||
@@ -370,10 +353,7 @@ export function registerAuthTests() {
|
||||
expect(installedTokens).toEqual(['stalled-token']);
|
||||
|
||||
const retryGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'retry-token',
|
||||
);
|
||||
setStoredAuthAccessToken('retry-token');
|
||||
const retry = commitAuthenticatedPlatformSession(
|
||||
testAuthUser,
|
||||
retryGeneration,
|
||||
@@ -477,17 +457,11 @@ export function registerAuthTests() {
|
||||
});
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const accountAGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-a-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-a-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, accountAGeneration);
|
||||
const accountB = { ...testAuthUser, id: 'user-b', displayName: '用户 B' };
|
||||
const accountBGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-b-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-b-token');
|
||||
|
||||
await expect(
|
||||
commitAuthenticatedPlatformSession(accountB, accountBGeneration),
|
||||
@@ -513,17 +487,11 @@ export function registerAuthTests() {
|
||||
});
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const accountAGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-a-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-a-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, accountAGeneration);
|
||||
const accountB = { ...testAuthUser, id: 'user-b', displayName: '用户 B' };
|
||||
const accountBGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-b-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-b-token');
|
||||
const accountBCommit = commitAuthenticatedPlatformSession(
|
||||
accountB,
|
||||
accountBGeneration,
|
||||
@@ -562,17 +530,11 @@ export function registerAuthTests() {
|
||||
});
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const accountAGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-a-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-a-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, accountAGeneration);
|
||||
const accountB = { ...testAuthUser, id: 'user-b', displayName: '用户 B' };
|
||||
const accountBGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-b-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-b-token');
|
||||
const accountBCommit = commitAuthenticatedPlatformSession(
|
||||
accountB,
|
||||
accountBGeneration,
|
||||
@@ -613,18 +575,12 @@ export function registerAuthTests() {
|
||||
});
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const accountAGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-a-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-a-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, accountAGeneration);
|
||||
|
||||
const accountB = { ...testAuthUser, id: 'user-b', displayName: '用户 B' };
|
||||
const accountBGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-b-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-b-token');
|
||||
const accountBCommit = commitAuthenticatedPlatformSession(
|
||||
accountB,
|
||||
accountBGeneration,
|
||||
@@ -633,10 +589,7 @@ export function registerAuthTests() {
|
||||
|
||||
const accountC = { ...testAuthUser, id: 'user-c', displayName: '用户 C' };
|
||||
const accountCGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-c-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-c-token');
|
||||
const accountCCommit = commitAuthenticatedPlatformSession(
|
||||
accountC,
|
||||
accountCGeneration,
|
||||
@@ -661,18 +614,12 @@ export function registerAuthTests() {
|
||||
const invoke = vi.fn(async () => null);
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const accountAGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-a-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-a-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, accountAGeneration);
|
||||
|
||||
const accountB = { ...testAuthUser, id: 'user-b', displayName: '用户 B' };
|
||||
const accountBGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-b-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-b-token');
|
||||
const accountBCommit = commitAuthenticatedPlatformSession(
|
||||
accountB,
|
||||
accountBGeneration,
|
||||
@@ -694,10 +641,7 @@ export function registerAuthTests() {
|
||||
const invoke = vi.fn(async () => null);
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const initialGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-a-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-a-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, initialGeneration);
|
||||
|
||||
let resolveRefresh: ((response: Response) => void) | null = null;
|
||||
@@ -731,10 +675,7 @@ export function registerAuthTests() {
|
||||
|
||||
const accountB = { ...testAuthUser, id: 'user-b', displayName: '用户 B' };
|
||||
const accountBGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-b-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-b-token');
|
||||
await commitAuthenticatedPlatformSession(accountB, accountBGeneration);
|
||||
resolveRefresh?.(
|
||||
new Response(JSON.stringify({ token: 'late-account-a-token' }), {
|
||||
@@ -768,10 +709,7 @@ export function registerAuthTests() {
|
||||
const invoke = vi.fn(async () => null);
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const initialGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-a-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-a-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, initialGeneration);
|
||||
|
||||
let rejectRefresh: ((error: Error) => void) | null = null;
|
||||
@@ -788,10 +726,7 @@ export function registerAuthTests() {
|
||||
const staleRefresh = requestPlatformSessionRefresh(testAuthUser.id);
|
||||
const accountB = { ...testAuthUser, id: 'user-b', displayName: '用户 B' };
|
||||
const accountBGeneration = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'account-b-token',
|
||||
);
|
||||
setStoredAuthAccessToken('account-b-token');
|
||||
await commitAuthenticatedPlatformSession(accountB, accountBGeneration);
|
||||
rejectRefresh?.(new Error('late account A refresh failed'));
|
||||
|
||||
@@ -805,10 +740,7 @@ export function registerAuthTests() {
|
||||
const invoke = vi.fn(async () => null);
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const generation = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'expired-token',
|
||||
);
|
||||
setStoredAuthAccessToken('expired-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, generation);
|
||||
let refreshCalls = 0;
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(
|
||||
@@ -862,10 +794,7 @@ export function registerAuthTests() {
|
||||
});
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const generation = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'expired-token',
|
||||
);
|
||||
setStoredAuthAccessToken('expired-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, generation);
|
||||
const identityGenerationAfterLogin =
|
||||
currentPlatformNativeIdentityGenerationForTests();
|
||||
@@ -915,10 +844,7 @@ export function registerAuthTests() {
|
||||
const invoke = vi.fn(async () => null);
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const generation = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'still-valid-token',
|
||||
);
|
||||
setStoredAuthAccessToken('still-valid-token');
|
||||
await commitAuthenticatedPlatformSession(testAuthUser, generation);
|
||||
const sessionGeneration = currentPlatformSessionGeneration();
|
||||
|
||||
@@ -947,14 +873,10 @@ export function registerAuthTests() {
|
||||
});
|
||||
|
||||
it('keeps refresh, current-user lookup, and native commit on the frozen origin', async () => {
|
||||
setClientServerSelection({ preset: 'dev', customBaseUrl: '' });
|
||||
const invoke = vi.fn(async () => null);
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const generation = beginPlatformSessionTransition();
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'expired-token',
|
||||
);
|
||||
setStoredAuthAccessToken('expired-token');
|
||||
await commitAuthenticatedPlatformSession(
|
||||
testAuthUser,
|
||||
generation,
|
||||
@@ -983,7 +905,10 @@ export function registerAuthTests() {
|
||||
},
|
||||
);
|
||||
const refresh = requestPlatformSessionRefresh(testAuthUser.id);
|
||||
setClientServerSelection({ preset: 'release', customBaseUrl: '' });
|
||||
window.localStorage.setItem(
|
||||
'genarrative.client.server-selection.v1',
|
||||
JSON.stringify({ preset: 'release', customBaseUrl: '' }),
|
||||
);
|
||||
resolveRefresh?.(
|
||||
new Response(JSON.stringify({ token: 'replacement-token' }), {
|
||||
status: 200,
|
||||
@@ -1074,7 +999,7 @@ export function registerAuthTests() {
|
||||
expect(screen.queryByLabelText('已登录')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows release, dev, and custom server choices on the login screen', async () => {
|
||||
it('shows login without server selection or custom platform address', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(
|
||||
async (input: RequestInfo | URL) => {
|
||||
if (String(input) === '/api/auth/refresh') {
|
||||
@@ -1091,22 +1016,74 @@ export function registerAuthTests() {
|
||||
);
|
||||
|
||||
await screen.findByRole('main', { name: '登录' });
|
||||
const server = screen.getByRole('combobox', { name: '服务器' });
|
||||
expect(server).not.toBeNull();
|
||||
expect(screen.getByRole('option', { name: 'release' })).not.toBeNull();
|
||||
expect(screen.getByRole('option', { name: 'dev' })).not.toBeNull();
|
||||
expect(screen.getByRole('option', { name: 'custom' })).not.toBeNull();
|
||||
|
||||
fireEvent.change(server, { target: { value: 'custom' } });
|
||||
expect(screen.getByLabelText('自定义服务器地址')).not.toBeNull();
|
||||
fireEvent.change(screen.getByLabelText('自定义服务器地址'), {
|
||||
target: { value: 'https://staging.example.com' },
|
||||
});
|
||||
expect(
|
||||
(screen.getByLabelText('自定义服务器地址') as HTMLInputElement).value,
|
||||
).toBe('https://staging.example.com');
|
||||
expect(screen.queryByRole('combobox', { name: '服务器' })).toBeNull();
|
||||
expect(screen.queryByLabelText('自定义服务器地址')).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['release', 'dev'])(
|
||||
'restores dev without forwarding a bare credential despite the %s preference',
|
||||
async (preset) => {
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'release-token',
|
||||
);
|
||||
window.localStorage.setItem(
|
||||
'genarrative.client.server-selection.v1',
|
||||
JSON.stringify({ preset, customBaseUrl: '' }),
|
||||
);
|
||||
const invoke = vi.fn(async () => null);
|
||||
window.__TAURI__ = { core: { invoke } };
|
||||
const fetchSpy = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockImplementation(
|
||||
async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
expect(new Headers(init?.headers).get('Authorization')).not.toBe(
|
||||
'Bearer release-token',
|
||||
);
|
||||
if (url === '/api/auth/refresh') {
|
||||
expect(
|
||||
new Headers(init?.headers).get('Authorization'),
|
||||
).toBeNull();
|
||||
return new Response(JSON.stringify({ token: 'dev-token' }), {
|
||||
status: 200,
|
||||
});
|
||||
}
|
||||
if (url === '/api/auth/me') {
|
||||
expect(new Headers(init?.headers).get('Authorization')).toBe(
|
||||
'Bearer dev-token',
|
||||
);
|
||||
return new Response(JSON.stringify({ user: testAuthUser }), {
|
||||
status: 200,
|
||||
});
|
||||
}
|
||||
throw new Error(`unexpected fetch ${url}`);
|
||||
},
|
||||
);
|
||||
|
||||
render(
|
||||
React.createElement(AuthenticatedClient, null, () =>
|
||||
React.createElement('main', { 'aria-label': '已登录' }),
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
await screen.findByRole('main', { name: '已登录' }),
|
||||
).not.toBeNull();
|
||||
expect(fetchSpy.mock.calls.map(([url]) => String(url))).toEqual([
|
||||
'/api/auth/refresh',
|
||||
'/api/auth/me',
|
||||
]);
|
||||
expect(invoke).toHaveBeenLastCalledWith(
|
||||
'install_platform_account_session',
|
||||
expect.objectContaining({
|
||||
accessToken: 'dev-token',
|
||||
apiBaseUrl: AGC_DEVELOPMENT_API_BASE_URL,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('logs in with a phone code and stores the returned token', async () => {
|
||||
const fetchSpy = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
@@ -1445,10 +1422,7 @@ export function registerAuthTests() {
|
||||
});
|
||||
|
||||
it('keeps the stored token when startup auth check cannot reach the service', async () => {
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'existing-token',
|
||||
);
|
||||
setStoredAuthAccessToken('existing-token');
|
||||
const fetchSpy = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockImplementation(async (input: RequestInfo | URL) => {
|
||||
@@ -1485,10 +1459,7 @@ export function registerAuthTests() {
|
||||
});
|
||||
|
||||
it('shows the HTTP maintenance error when startup auth receives a 503', async () => {
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'existing-token',
|
||||
);
|
||||
setStoredAuthAccessToken('existing-token');
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(
|
||||
async (input: RequestInfo | URL) => {
|
||||
if (String(input) === '/api/auth/me') {
|
||||
@@ -1516,10 +1487,7 @@ export function registerAuthTests() {
|
||||
});
|
||||
|
||||
it('still calls logout when token refresh fails during logout retry', async () => {
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'existing-token',
|
||||
);
|
||||
setStoredAuthAccessToken('existing-token');
|
||||
let logoutCalls = 0;
|
||||
const fetchSpy = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
@@ -1581,10 +1549,7 @@ export function registerAuthTests() {
|
||||
});
|
||||
|
||||
it('fails the renderer closed when native session clear is rejected during logout', async () => {
|
||||
window.localStorage.setItem(
|
||||
'genarrative.auth.access-token.v1',
|
||||
'existing-token',
|
||||
);
|
||||
setStoredAuthAccessToken('existing-token');
|
||||
window.__TAURI__ = {
|
||||
core: {
|
||||
invoke: vi.fn(async (command: string) => {
|
||||
|
||||
@@ -11,7 +11,10 @@ import {
|
||||
getStoredAuthAccessToken,
|
||||
refreshClientAuthAccessToken,
|
||||
} from '../src/services/clientAuth';
|
||||
import { CLIENT_HTTP_DEFAULT_TIMEOUT_MS } from '../src/services/clientHttp';
|
||||
import {
|
||||
AGC_DEVELOPMENT_API_BASE_URL,
|
||||
CLIENT_HTTP_DEFAULT_TIMEOUT_MS,
|
||||
} from '../src/services/clientHttp';
|
||||
import {
|
||||
cachedLlmModelCatalog,
|
||||
refreshLlmModelCatalog,
|
||||
@@ -266,16 +269,18 @@ it('响应体卡住超时后,下一次续期会重新发起请求', async () =
|
||||
);
|
||||
});
|
||||
|
||||
const first = refreshClientAuthAccessToken('http://localhost:3000');
|
||||
const first = refreshClientAuthAccessToken(AGC_DEVELOPMENT_API_BASE_URL);
|
||||
const firstAssertion = expect(first).rejects.toThrow();
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
await firstAssertion;
|
||||
expect(getClientAuthRefreshOperation('http://localhost:3000')).toMatchObject({
|
||||
expect(
|
||||
getClientAuthRefreshOperation(AGC_DEVELOPMENT_API_BASE_URL),
|
||||
).toMatchObject({
|
||||
kind: 'auth-refresh',
|
||||
phase: 'retryable-failure',
|
||||
});
|
||||
|
||||
const second = refreshClientAuthAccessToken('http://localhost:3000');
|
||||
const second = refreshClientAuthAccessToken(AGC_DEVELOPMENT_API_BASE_URL);
|
||||
const secondAssertion = expect(second).rejects.toThrow();
|
||||
expect(refreshCalls).toBe(2);
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
getStoredAuthAccessToken as getApiAccessToken,
|
||||
requestClientApi,
|
||||
} from '../src/services/clientApi';
|
||||
import {
|
||||
clearStoredAuthAccessToken,
|
||||
getStoredAuthAccessToken,
|
||||
setStoredAuthAccessToken,
|
||||
} from '../src/services/clientAuth';
|
||||
import { AGC_DEVELOPMENT_API_BASE_URL } from '../src/services/clientHttp';
|
||||
|
||||
vi.mock('@tauri-apps/plugin-http', () => ({ fetch: vi.fn() }));
|
||||
vi.mock('../src/services/errorReporting', () => ({
|
||||
captureClientError: vi.fn(),
|
||||
}));
|
||||
|
||||
const tokenKey = 'genarrative.auth.access-token.v1';
|
||||
const originKey = 'genarrative.auth.access-token-origin.v1';
|
||||
const selectionKey = 'genarrative.client.server-selection.v1';
|
||||
|
||||
describe('AGC platform credential origin', () => {
|
||||
afterEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('preserves a credential already marked as dev', () => {
|
||||
window.localStorage.setItem(tokenKey, 'existing-dev-token');
|
||||
window.localStorage.setItem(originKey, AGC_DEVELOPMENT_API_BASE_URL);
|
||||
|
||||
expect(getStoredAuthAccessToken()).toBe('existing-dev-token');
|
||||
expect(getApiAccessToken()).toBe('existing-dev-token');
|
||||
expect(window.localStorage.getItem(originKey)).toBe(
|
||||
AGC_DEVELOPMENT_API_BASE_URL,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
JSON.stringify({ preset: 'dev', customBaseUrl: '' }),
|
||||
JSON.stringify({
|
||||
preset: 'custom',
|
||||
customBaseUrl: `${AGC_DEVELOPMENT_API_BASE_URL}/`,
|
||||
}),
|
||||
JSON.stringify({ preset: 'release', customBaseUrl: '' }),
|
||||
JSON.stringify({ preset: 'custom', customBaseUrl: 'https://example.com' }),
|
||||
JSON.stringify({
|
||||
preset: 'custom',
|
||||
customBaseUrl: 'http://localhost:8082',
|
||||
}),
|
||||
JSON.stringify({ preset: 'unknown', customBaseUrl: '' }),
|
||||
'invalid-json',
|
||||
'null',
|
||||
])(
|
||||
'never infers a legacy credential origin from a saved preference: %s',
|
||||
async (selection) => {
|
||||
window.localStorage.setItem(tokenKey, 'other-server-token');
|
||||
window.localStorage.setItem(selectionKey, selection);
|
||||
vi.stubEnv('MODE', 'production');
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValue(
|
||||
new Response(JSON.stringify({ result: true }), { status: 200 }),
|
||||
);
|
||||
|
||||
await requestClientApi('/api/profile/dashboard', {}, '读取失败');
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe(`${AGC_DEVELOPMENT_API_BASE_URL}/api/profile/dashboard`);
|
||||
expect(new Headers(init?.headers).get('Authorization')).toBeNull();
|
||||
expect(window.localStorage.getItem(tokenKey)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([true, false])(
|
||||
'clears an unmarked credential without a preference (development=%s)',
|
||||
(development) => {
|
||||
// Vitest 0.34 stores stubbed env values as strings; use a falsy value for DEV=false.
|
||||
vi.stubEnv('DEV', development ? 'true' : '');
|
||||
window.localStorage.setItem(tokenKey, 'legacy-token');
|
||||
|
||||
expect(getStoredAuthAccessToken()).toBe('');
|
||||
},
|
||||
);
|
||||
|
||||
it('does not relabel a credential that already belongs to another origin', () => {
|
||||
window.localStorage.setItem(tokenKey, 'other-origin-token');
|
||||
window.localStorage.setItem(originKey, 'https://www.genarrative.world');
|
||||
window.localStorage.setItem(
|
||||
selectionKey,
|
||||
JSON.stringify({ preset: 'dev' }),
|
||||
);
|
||||
|
||||
expect(getApiAccessToken()).toBe('');
|
||||
expect(window.localStorage.getItem(tokenKey)).toBeNull();
|
||||
expect(window.localStorage.getItem(originKey)).toBeNull();
|
||||
});
|
||||
|
||||
it('stores new dev credentials with their origin and ignores old preferences', () => {
|
||||
vi.stubEnv('DEV', false);
|
||||
setStoredAuthAccessToken('new-token');
|
||||
window.localStorage.setItem(
|
||||
selectionKey,
|
||||
JSON.stringify({ preset: 'release' }),
|
||||
);
|
||||
|
||||
expect(getApiAccessToken()).toBe('new-token');
|
||||
expect(getStoredAuthAccessToken('https://www.genarrative.world')).toBe('');
|
||||
expect(() =>
|
||||
setStoredAuthAccessToken('wrong-token', 'https://example.com'),
|
||||
).toThrow('固定的 dev 服务');
|
||||
expect(getStoredAuthAccessToken()).toBe('new-token');
|
||||
clearStoredAuthAccessToken();
|
||||
expect(window.localStorage.getItem(tokenKey)).toBeNull();
|
||||
expect(window.localStorage.getItem(originKey)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { fetch as tauriHttpFetch } from '@tauri-apps/plugin-http';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -9,16 +10,11 @@ import {
|
||||
AGC_CLIENT_MARKER_HEADER,
|
||||
AGC_CLIENT_MARKER_VALUE,
|
||||
AGC_DEVELOPMENT_API_BASE_URL,
|
||||
AGC_RELEASE_API_BASE_URL,
|
||||
ClientHttpTimeoutError,
|
||||
fetchClientHttp,
|
||||
getClientServerBaseUrl,
|
||||
getClientServerSelection,
|
||||
normalizeClientServerBaseUrl,
|
||||
readClientHttpResponseText,
|
||||
resetClientServerSelectionForTests,
|
||||
resolveClientHttpTarget,
|
||||
setClientServerSelection,
|
||||
} from '../src/services/clientHttp';
|
||||
|
||||
vi.mock('@tauri-apps/plugin-http', () => ({
|
||||
@@ -31,7 +27,7 @@ describe('AGC client HTTP transport', () => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
vi.unstubAllGlobals();
|
||||
resetClientServerSelectionForTests();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it('adds the AGC marker while preserving and overriding request headers', async () => {
|
||||
@@ -123,37 +119,25 @@ describe('AGC client HTTP transport', () => {
|
||||
expect(forwardedHeaders.get('Authorization')).toBe('Bearer fixture-token');
|
||||
});
|
||||
|
||||
it('keeps local development requests on the Vite API proxy', () => {
|
||||
expect(
|
||||
resolveClientHttpTarget('/api/auth/me', {
|
||||
isDevelopment: true,
|
||||
isTauri: true,
|
||||
pageProtocol: 'http:',
|
||||
}),
|
||||
).toEqual({ transport: 'web', url: '/api/auth/me' });
|
||||
});
|
||||
it.each(['development', 'production'])(
|
||||
'routes %s Tauri requests through fixed dev',
|
||||
(mode) => {
|
||||
expect(
|
||||
resolveClientHttpTarget('/api/auth/me', {
|
||||
isTauri: true,
|
||||
mode,
|
||||
}),
|
||||
).toEqual({
|
||||
transport: 'tauri-http',
|
||||
url: `${AGC_DEVELOPMENT_API_BASE_URL}/api/auth/me`,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('routes release Tauri requests through the scoped dev API transport', () => {
|
||||
it('keeps test fixtures on relative requests after origin validation', () => {
|
||||
expect(
|
||||
resolveClientHttpTarget('/api/auth/me', {
|
||||
isDevelopment: false,
|
||||
isTauri: true,
|
||||
pageProtocol: 'tauri:',
|
||||
mode: 'production',
|
||||
serverBaseUrl: AGC_RELEASE_API_BASE_URL,
|
||||
}),
|
||||
).toEqual({
|
||||
transport: 'tauri-http',
|
||||
url: `${AGC_RELEASE_API_BASE_URL}/api/auth/me`,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps ordinary web releases on same-origin relative requests', () => {
|
||||
expect(
|
||||
resolveClientHttpTarget('/api/auth/me', {
|
||||
isDevelopment: false,
|
||||
isTauri: false,
|
||||
pageProtocol: 'https:',
|
||||
mode: 'test',
|
||||
}),
|
||||
).toEqual({ transport: 'web', url: '/api/auth/me' });
|
||||
@@ -162,97 +146,55 @@ describe('AGC client HTTP transport', () => {
|
||||
it('rejects release Tauri requests outside the fixed dev API origin', () => {
|
||||
expect(() =>
|
||||
resolveClientHttpTarget('https://example.com/api/auth/me', {
|
||||
isDevelopment: false,
|
||||
isTauri: true,
|
||||
pageProtocol: 'tauri:',
|
||||
mode: 'production',
|
||||
serverBaseUrl: AGC_RELEASE_API_BASE_URL,
|
||||
}),
|
||||
).toThrow('当前选择的服务器范围');
|
||||
).toThrow('固定的 dev 服务范围');
|
||||
});
|
||||
|
||||
it('persists release, dev, and custom server selection', () => {
|
||||
const release = setClientServerSelection({
|
||||
preset: 'release',
|
||||
customBaseUrl: '',
|
||||
});
|
||||
expect(release).toEqual({
|
||||
preset: 'release',
|
||||
customBaseUrl: '',
|
||||
});
|
||||
expect(getClientServerBaseUrl(release)).toBe(AGC_RELEASE_API_BASE_URL);
|
||||
const dev = setClientServerSelection({ preset: 'dev', customBaseUrl: '' });
|
||||
expect(getClientServerBaseUrl(dev)).toBe(AGC_DEVELOPMENT_API_BASE_URL);
|
||||
it.each(['release', 'dev', 'custom'])(
|
||||
'ignores persisted %s preference when resolving web requests',
|
||||
(preset) => {
|
||||
window.localStorage.setItem(
|
||||
'genarrative.client.server-selection.v1',
|
||||
JSON.stringify({
|
||||
preset,
|
||||
customBaseUrl: 'https://staging.example.com',
|
||||
}),
|
||||
);
|
||||
vi.stubEnv('DEV', false);
|
||||
expect(getClientServerBaseUrl()).toBe(AGC_DEVELOPMENT_API_BASE_URL);
|
||||
expect(
|
||||
resolveClientHttpTarget('/api/auth/me', {
|
||||
isTauri: false,
|
||||
mode: 'development',
|
||||
}),
|
||||
).toEqual({
|
||||
transport: 'web',
|
||||
url: `${AGC_DEVELOPMENT_API_BASE_URL}/api/auth/me`,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const custom = setClientServerSelection({
|
||||
preset: 'custom',
|
||||
customBaseUrl: 'https://staging.example.com/',
|
||||
});
|
||||
expect(custom).toEqual({
|
||||
preset: 'custom',
|
||||
customBaseUrl: 'https://staging.example.com',
|
||||
});
|
||||
expect(getClientServerSelection().preset).toBe('dev');
|
||||
expect(getClientServerBaseUrl(custom)).toBe('https://staging.example.com');
|
||||
});
|
||||
|
||||
it('accepts HTTPS custom servers and loopback HTTP only', () => {
|
||||
expect(normalizeClientServerBaseUrl('https://example.com/')).toBe(
|
||||
'https://example.com',
|
||||
);
|
||||
expect(normalizeClientServerBaseUrl('http://127.0.0.1:8080/')).toBe(
|
||||
'http://127.0.0.1:8080',
|
||||
);
|
||||
expect(() => normalizeClientServerBaseUrl('http://example.com')).toThrow(
|
||||
'必须使用 HTTPS',
|
||||
);
|
||||
expect(() =>
|
||||
normalizeClientServerBaseUrl('https://example.com/api'),
|
||||
).toThrow('纯 HTTP(S)');
|
||||
});
|
||||
|
||||
it('routes selected custom servers for both web and Tauri clients', () => {
|
||||
const serverBaseUrl = 'https://staging.example.com';
|
||||
expect(
|
||||
resolveClientHttpTarget('/api/auth/me', {
|
||||
isDevelopment: true,
|
||||
isTauri: false,
|
||||
pageProtocol: 'http:',
|
||||
mode: 'development',
|
||||
serverBaseUrl,
|
||||
}),
|
||||
).toEqual({
|
||||
transport: 'web',
|
||||
url: `${serverBaseUrl}/api/auth/me`,
|
||||
});
|
||||
expect(
|
||||
resolveClientHttpTarget('/api/auth/me', {
|
||||
isDevelopment: false,
|
||||
isTauri: true,
|
||||
pageProtocol: 'tauri:',
|
||||
mode: 'production',
|
||||
serverBaseUrl,
|
||||
}),
|
||||
).toEqual({
|
||||
transport: 'tauri-http',
|
||||
url: `${serverBaseUrl}/api/auth/me`,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps Tauri HTTP transport when the WebView reports an http page protocol', () => {
|
||||
expect(
|
||||
resolveClientHttpTarget('/api/auth/me', {
|
||||
isDevelopment: false,
|
||||
isTauri: true,
|
||||
pageProtocol: 'http:',
|
||||
mode: 'production',
|
||||
serverBaseUrl: AGC_DEVELOPMENT_API_BASE_URL,
|
||||
}),
|
||||
).toEqual({
|
||||
transport: 'tauri-http',
|
||||
url: `${AGC_DEVELOPMENT_API_BASE_URL}/api/auth/me`,
|
||||
});
|
||||
});
|
||||
it.each(['development', 'production', 'test'])(
|
||||
'rejects explicit origin overrides before transport in %s',
|
||||
async (mode) => {
|
||||
vi.stubEnv('MODE', mode);
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(
|
||||
fetchClientHttp(
|
||||
'/api/auth/me',
|
||||
{},
|
||||
{
|
||||
serverBaseUrl: 'https://www.genarrative.world',
|
||||
},
|
||||
),
|
||||
).rejects.toThrow('固定的 dev 服务范围');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(tauriHttpFetch).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('aborts a stalled Web request at the configured timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user