From 93477f2b1b9cd86b28219e5df2668f5a9e4ad2f7 Mon Sep 17 00:00:00 2001 From: suzmii Date: Sun, 30 Aug 2026 14:21:18 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=95=B4AGC=E5=AE=98=E6=96=B9?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E4=B8=8E=E5=AE=89=E5=85=A8=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E9=93=BE=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 记录当前 AGC 客户端、Tauri、API Server、后台查询和契约改动 保留后续按新 Router 后端方案重构的检查点 --- apps/admin-web/src/api/adminApiClient.ts | 35 + apps/admin-web/src/api/adminApiTypes.ts | 48 + .../pages/AdminDatabaseTablesPage.test.tsx | 73 +- .../src/pages/AdminDatabaseTablesPage.tsx | 487 +++- .../src-tauri/src/agent/codex_app_server.rs | 207 +- .../src-tauri/src/agent/codex_cli.rs | 9 +- .../src-tauri/src/agent/direct_runtime.rs | 53 +- .../src-tauri/src/agent/direct_tool_bridge.rs | 11 +- .../src-tauri/src/agent/direct_tools_mcp.rs | 3 +- .../src-tauri/src/agent/generation.rs | 3 +- .../src/agent/generation/canvas_generation.rs | 102 +- .../src/agent/generation/draft_writer.rs | 75 +- .../agent/generation/loop_orchestration.rs | 43 +- .../src/agent/generation/pass_artifacts.rs | 15 +- .../src/agent/generation/role_briefs.rs | 27 +- .../src/agent/generation/run_lifecycle.rs | 22 +- .../src-tauri/src/agent/generation/trace.rs | 31 +- .../runtime_actions/autonomous_policy.rs | 16 +- .../pending_confirmation_ledger.rs | 20 +- .../agent/runtime_actions/project_gates.rs | 6 +- .../runtime_actions/provider_action_batch.rs | 16 +- .../provider_request_builders.rs | 48 +- .../runtime_actions/provider_tool_plan.rs | 28 +- .../src/agent/runtime_driver/finalization.rs | 89 +- .../src/agent/runtime_driver/main_loop.rs | 307 +-- .../agent/runtime_driver/provider_recovery.rs | 43 +- .../src/agent/runtime_driver/recovery_scan.rs | 27 +- .../src/agent/runtime_driver/task_start.rs | 41 +- .../runtime_protocol/autonomous_completion.rs | 26 +- .../agent/runtime_protocol/context_bundle.rs | 1 + .../agent/runtime_protocol/json_sidecar.rs | 42 +- .../runtime_protocol/planning_storage.rs | 12 + .../runtime_protocol/provider_control.rs | 23 +- .../runtime_protocol/real_e2e_checkpoint.rs | 6 +- .../src/agent/runtime_protocol/steering.rs | 15 +- .../src-tauri/src/agent/runtime_state.rs | 101 +- .../src-tauri/src/agent/skill_pack.rs | 19 +- .../src-tauri/src/assets.rs | 206 +- .../src-tauri/src/browser/evidence.rs | 21 +- .../src-tauri/src/cli.rs | 95 +- .../src-tauri/src/command_exec.rs | 53 +- .../src-tauri/src/command_output.rs | 29 +- .../src-tauri/src/commands.rs | 178 +- .../src-tauri/src/config.rs | 2357 ++++++++++++++++- .../src-tauri/src/debug/debug_drafts.rs | 22 +- .../src-tauri/src/image_inspect.rs | 8 +- .../src-tauri/src/main.rs | 19 +- .../src-tauri/src/platform_session.rs | 27 +- .../src-tauri/src/preview.rs | 3 +- .../src-tauri/src/project/agent_db.rs | 194 +- .../src-tauri/src/project/asset_canvas.rs | 80 +- .../src-tauri/src/project/checkpoint.rs | 88 +- .../src-tauri/src/project/conversation.rs | 146 +- .../src-tauri/src/project/export.rs | 30 +- .../src/project/external_editor_bindings.rs | 6 + .../src-tauri/src/project/filesystem.rs | 89 +- .../src-tauri/src/project/manifest.rs | 120 +- .../src-tauri/src/project/memory.rs | 32 +- .../src-tauri/src/project/resource_editor.rs | 71 +- .../src-tauri/src/project/resource_layout.rs | 8 +- .../src-tauri/src/project/verification.rs | 36 +- .../src-tauri/src/resource_inspect.rs | 8 +- .../src-tauri/src/runner.rs | 6 +- .../src-tauri/src/runner/endpoint.rs | 92 +- .../src-tauri/src/runner/project_owner.rs | 29 +- .../src-tauri/src/tests/configuration.rs | 137 +- .../src-tauri/src/ui_editor/persistence.rs | 24 +- .../src/ui_editor/resource_bridge.rs | 17 +- .../src-tauri/src/ui_editor/workflow.rs | 80 +- apps/ai-game-creator-shell/src/App.tsx | 5 +- apps/ai-game-creator-shell/src/app/types.ts | 6 +- .../app-shell/useDeveloperAgentPanel.ts | 6 +- .../project-summary/agentPresentation.ts | 10 +- .../runtime-config/RuntimeConfigDialog.tsx | 770 +----- .../appSurface/project-commands.suite.ts | 116 +- .../assert-project-and-design-shortcuts.ts | 17 +- .../preview-shortcuts/invoke-mock.ts | 45 +- .../appSurface/runtime-settings.suite.ts | 290 +- .../shared-memory/decision-log.md | 9 + ...】server-rs与SpacetimeDB数据契约-2026-05-15.md | 3 +- ...构】外部OpenAPI与APIKey接入方案-2026-06-19.md | 17 + server-rs/crates/api-server/src/admin.rs | 632 ++++- server-rs/crates/api-server/src/config.rs | 86 + .../api-server/src/external_api_keys.rs | 676 +++++ server-rs/crates/api-server/src/llm/mod.rs | 474 +++- .../crates/api-server/src/modules/admin.rs | 18 +- .../crates/api-server/src/modules/platform.rs | 9 +- .../crates/api-server/src/modules/profile.rs | 12 +- .../crates/api-server/src/password_entry.rs | 10 + server-rs/crates/api-server/src/phone_auth.rs | 10 + server-rs/crates/api-server/src/tracking.rs | 1 + .../crates/api-server/src/wechat/auth.rs | 25 + .../crates/shared-contracts/src/admin.rs | 51 + .../src/active/mapper/external_api_key.rs | 47 +- .../src/mapper/external_api_key.rs | 47 +- ...llet_refund_outbox_and_return_procedure.rs | 16 +- .../external_api_key_create_input_type.rs | 5 + .../external_api_key_snapshot_type.rs | 5 + .../module_bindings/external_api_key_type.rs | 18 + ...llet_refund_outbox_and_return_procedure.rs | 16 +- ...ration_job_history_and_return_procedure.rs | 16 +- .../validate_auth_session_procedure.rs | 16 +- .../src/external_api_key_storage.rs | 53 + .../crates/spacetime-module/src/migration.rs | 20 + 104 files changed, 7715 insertions(+), 2283 deletions(-) diff --git a/apps/admin-web/src/api/adminApiClient.ts b/apps/admin-web/src/api/adminApiClient.ts index 9912b9cf7..d2e5fa292 100644 --- a/apps/admin-web/src/api/adminApiClient.ts +++ b/apps/admin-web/src/api/adminApiClient.ts @@ -23,6 +23,8 @@ import type { AdminEditorShowcaseListQuery, AdminEditorShowcaseListResponse, AdminEditorShowcaseReviewRequest, + AdminExternalApiKeyListQuery, + AdminExternalApiKeyListResponse, AdminFeatureGateConfigResponse, AdminLoginResponse, AdminMeResponse, @@ -246,6 +248,16 @@ export function getAdminDatabaseTableRows( ); } +export function getAdminExternalApiKeys( + token: string, + query: AdminExternalApiKeyListQuery = {}, +) { + return request( + `/admin/api/external-api-keys${buildExternalApiKeyQuery(query)}`, + { token }, + ); +} + export function debugAdminHttp(token: string, payload: AdminDebugHttpRequest) { return request('/admin/api/debug/http', { method: 'POST', @@ -861,6 +873,29 @@ function buildDatabaseTableRowsQuery(query: AdminDatabaseTableRowsQuery) { return queryString ? `?${queryString}` : ''; } +function buildExternalApiKeyQuery(query: AdminExternalApiKeyListQuery) { + const params = new URLSearchParams(); + appendQueryParam(params, 'ownerUserId', query.ownerUserId); + appendQueryParam(params, 'publicUserCode', query.publicUserCode); + appendQueryParam(params, 'keyId', query.keyId); + appendQueryParam(params, 'name', query.name); + appendQueryParam(params, 'keyPrefix', query.keyPrefix); + appendQueryParam(params, 'createdAfter', query.createdAfter); + appendQueryParam(params, 'createdBefore', query.createdBefore); + appendQueryParam(params, 'status', query.status); + appendQueryParam(params, 'purpose', query.purpose); + if (typeof query.limit === 'number' && Number.isFinite(query.limit)) { + params.set('limit', String(Math.floor(query.limit))); + } + if (typeof query.offset === 'number' && Number.isFinite(query.offset)) { + params.set('offset', String(Math.floor(query.offset))); + } + appendQueryParam(params, 'sortColumn', query.sortColumn); + appendQueryParam(params, 'sortDirection', query.sortDirection); + const queryString = params.toString(); + return queryString ? `?${queryString}` : ''; +} + function buildEditorAssetListQuery(query: AdminEditorAssetListQuery) { const params = new URLSearchParams(); appendQueryParam(params, 'cursor', query.cursor); diff --git a/apps/admin-web/src/api/adminApiTypes.ts b/apps/admin-web/src/api/adminApiTypes.ts index bcd2ee1db..765278ed7 100644 --- a/apps/admin-web/src/api/adminApiTypes.ts +++ b/apps/admin-web/src/api/adminApiTypes.ts @@ -243,6 +243,54 @@ export interface AdminDatabaseTableStatPayload { errorMessage: string | null; } +export interface AdminExternalApiKeyListQuery { + ownerUserId?: string; + publicUserCode?: string; + keyId?: string; + name?: string; + keyPrefix?: string; + createdAfter?: string; + createdBefore?: string; + status?: 'active' | 'revoked'; + purpose?: 'external-editor' | 'agc-llm'; + limit?: number; + offset?: number; + sortColumn?: + | 'keyId' + | 'ownerUserId' + | 'name' + | 'keyPrefix' + | 'purpose' + | 'createdAt' + | 'lastUsedAt' + | 'updatedAt'; + sortDirection?: 'asc' | 'desc'; +} + +export interface AdminExternalApiKeyPayload { + keyId: string; + ownerUserId: string; + name: string; + keyPrefix: string; + purpose: string; + scopes: string[]; + createdAt: string; + lastUsedAt: string | null; + revokedAt: string | null; + updatedAt: string; + status: 'active' | 'revoked'; +} + +export interface AdminExternalApiKeyListResponse { + keys: AdminExternalApiKeyPayload[]; + total: number; + limit: number; + offset: number; + scannedCount: number; + scanLimit: number; + scanLimitReached: boolean; +} + export interface AdminDebugHeaderInput { name: string; value: string; diff --git a/apps/admin-web/src/pages/AdminDatabaseTablesPage.test.tsx b/apps/admin-web/src/pages/AdminDatabaseTablesPage.test.tsx index d6bf2e71f..89561b438 100644 --- a/apps/admin-web/src/pages/AdminDatabaseTablesPage.test.tsx +++ b/apps/admin-web/src/pages/AdminDatabaseTablesPage.test.tsx @@ -7,6 +7,7 @@ import { beforeEach, expect, test, vi } from 'vitest'; import { getAdminDatabaseTableRows, getAdminDatabaseTables, + getAdminExternalApiKeys, } from '../api/adminApiClient'; import { AdminDatabaseTablesPage, @@ -19,11 +20,15 @@ vi.mock('../api/adminApiClient', () => ({ ), getAdminDatabaseTableRows: vi.fn(), getAdminDatabaseTables: vi.fn(), + getAdminExternalApiKeys: vi.fn(), isAdminApiError: vi.fn(() => false), })); vi.mock('../components/AdminUserReferenceButton', () => ({ - AdminUserReferenceButton: ({ userId, publicUserCode }: { + AdminUserReferenceButton: ({ + userId, + publicUserCode, + }: { userId?: string; publicUserCode?: string; }) => ( @@ -69,6 +74,7 @@ const referralRows = [ beforeEach(() => { window.location.hash = '#tables?table=profile_referral_relation'; + vi.mocked(getAdminExternalApiKeys).mockReset(); vi.mocked(getAdminDatabaseTables).mockResolvedValue({ fetchErrors: [], tables: ['profile_referral_relation'], @@ -87,6 +93,56 @@ beforeEach(() => { }); }); +test('external_api_key 使用专用安全查询且详情不展示原始 JSON', async () => { + const user = userEvent.setup(); + window.location.hash = '#tables?table=external_api_key'; + vi.mocked(getAdminDatabaseTables).mockResolvedValue({ + fetchErrors: [], + tables: ['external_api_key'], + }); + vi.mocked(getAdminExternalApiKeys).mockResolvedValue({ + keys: [ + { + keyId: 'external-api-key-1', + ownerUserId: 'user-1', + name: '陶泥儿 AGC 官方 LLM(本机)', + keyPrefix: 'tnr_sk_fixture', + purpose: 'agc-llm', + scopes: ['llm:responses'], + createdAt: '2026-08-29T00:00:00Z', + lastUsedAt: null, + revokedAt: null, + updatedAt: '2026-08-29T00:00:00Z', + status: 'active', + }, + ], + total: 1, + limit: 100, + offset: 0, + scannedCount: 1, + scanLimit: 5000, + scanLimitReached: false, + }); + + render( + , + ); + + await user.type(screen.getByPlaceholderText('精确 ownerUserId'), 'user-1'); + await user.click(screen.getByRole('button', { name: '安全查询' })); + await waitFor(() => { + expect(getAdminExternalApiKeys).toHaveBeenLastCalledWith( + 'admin-token', + expect.objectContaining({ ownerUserId: 'user-1', purpose: undefined }), + ); + }); + expect(await screen.findByText('tnr_sk_fixture')).toBeTruthy(); + await user.click(screen.getByRole('button', { name: '详情' })); + expect(screen.getByRole('dialog')).toBeTruthy(); + expect(screen.queryByText('复制 JSON')).toBeNull(); + expect(screen.queryByText('key_hash')).toBeNull(); +}); + test('后台表查询页通过页面级固定栏翻页并提示扫描结果可能不完整', async () => { const user = userEvent.setup(); vi.mocked(getAdminDatabaseTableRows).mockResolvedValue({ @@ -124,7 +180,10 @@ test('后台表查询页通过页面级固定栏翻页并提示扫描结果可 ), ).toBeTruthy(); - await user.type(screen.getByRole('textbox', { name: '关键词' }), '未执行条件'); + await user.type( + screen.getByRole('textbox', { name: '关键词' }), + '未执行条件', + ); await user.click(screen.getByRole('button', { name: '下一页' })); await waitFor(() => { @@ -227,7 +286,9 @@ test('数据库用户字段显示查看按钮且点击不会打开行详情', as , ); - const userButton = await screen.findByRole('button', { name: '查看用户 u-b' }); + const userButton = await screen.findByRole('button', { + name: '查看用户 u-b', + }); await user.click(userButton); expect(screen.queryByRole('dialog')).toBeNull(); }); @@ -250,7 +311,11 @@ test('数据库用户字段识别会排除后台操作者与合成邀请码字 resolveAdminDatabaseUserReference('audit_log', 'admin_user_id', 'u-1'), ).toBeNull(); expect( - resolveAdminDatabaseUserReference('profile_wallet', 'user_id', 'admin:root'), + resolveAdminDatabaseUserReference( + 'profile_wallet', + 'user_id', + 'admin:root', + ), ).toBeNull(); expect( resolveAdminDatabaseUserReference('profile_invite_code', 'user_id', 'u-1'), diff --git a/apps/admin-web/src/pages/AdminDatabaseTablesPage.tsx b/apps/admin-web/src/pages/AdminDatabaseTablesPage.tsx index f0d114373..0629b4f27 100644 --- a/apps/admin-web/src/pages/AdminDatabaseTablesPage.tsx +++ b/apps/admin-web/src/pages/AdminDatabaseTablesPage.tsx @@ -21,10 +21,12 @@ import { import { getAdminDatabaseTableRows, getAdminDatabaseTables, + getAdminExternalApiKeys, } from '../api/adminApiClient'; import type { AdminDatabaseTableRowPayload, AdminDatabaseTableRowsResponse, + AdminExternalApiKeyListResponse, } from '../api/adminApiTypes'; import { AdminUserReferenceButton } from '../components/AdminUserReferenceButton'; import { handlePageError } from './pageUtils'; @@ -35,6 +37,16 @@ interface AdminDatabaseTablesPageProps { } type SortDirection = 'asc' | 'desc'; +type ExternalApiKeySortColumn = + | '' + | 'keyId' + | 'ownerUserId' + | 'name' + | 'keyPrefix' + | 'purpose' + | 'createdAt' + | 'lastUsedAt' + | 'updatedAt'; export function AdminDatabaseTablesPage({ token, @@ -64,6 +76,7 @@ export function AdminDatabaseTablesPage({ const [sortDirection, setSortDirection] = useState('asc'); const [isLoadingTables, setIsLoadingTables] = useState(false); const [isLoadingRows, setIsLoadingRows] = useState(false); + const isExternalApiKeyTable = tableName === 'external_api_key'; useEffect(() => { void loadTables(); @@ -93,7 +106,7 @@ export function AdminDatabaseTablesPage({ }, [tableName, tables]); useEffect(() => { - if (tableName) { + if (tableName && tableName !== 'external_api_key') { void refreshRows(tableName); } // eslint-disable-next-line react-hooks/exhaustive-deps @@ -312,6 +325,50 @@ export function AdminDatabaseTablesPage({ } } + if (isExternalApiKeyTable) { + return ( +
+
+
+

表查询

+

external_api_key 使用专用安全查询

+
+
+ + +
+
+ +
+ ); + } + return (
void; +}) { + const [ownerUserId, setOwnerUserId] = useState(''); + const [publicUserCode, setPublicUserCode] = useState(''); + const [keyId, setKeyId] = useState(''); + const [name, setName] = useState(''); + const [keyPrefix, setKeyPrefix] = useState(''); + const [createdAfter, setCreatedAfter] = useState(''); + const [createdBefore, setCreatedBefore] = useState(''); + const [status, setStatus] = useState<'' | 'active' | 'revoked'>(''); + const [purpose, setPurpose] = useState<'' | 'external-editor' | 'agc-llm'>( + '', + ); + const [limit, setLimit] = useState('100'); + const [sortColumn, setSortColumn] = useState(''); + const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc'); + const [result, setResult] = useState( + null, + ); + const [selectedKey, setSelectedKey] = useState< + AdminExternalApiKeyListResponse['keys'][number] | null + >(null); + const [errorMessage, setErrorMessage] = useState(''); + const [isLoading, setIsLoading] = useState(false); + + async function submit(event?: FormEvent, nextOffset = 0) { + event?.preventDefault(); + const normalizedOwner = ownerUserId.trim(); + const normalizedPublicCode = publicUserCode.trim(); + const normalizedKeyId = keyId.trim(); + const normalizedPrefix = keyPrefix.trim(); + if ( + !normalizedOwner && + !normalizedPublicCode && + !normalizedKeyId && + !normalizedPrefix + ) { + setErrorMessage( + '请提供 owner、公开用户编号、keyId 或精确 Key 前缀后再查询。', + ); + setResult(null); + return; + } + if (normalizedOwner && normalizedPublicCode) { + setErrorMessage('owner 与公开用户编号不能同时提供。'); + setResult(null); + return; + } + setIsLoading(true); + setErrorMessage(''); + try { + const response = await getAdminExternalApiKeys(token, { + ownerUserId: normalizedOwner || undefined, + publicUserCode: normalizedPublicCode || undefined, + keyId: normalizedKeyId || undefined, + name: name.trim() || undefined, + keyPrefix: normalizedPrefix || undefined, + createdAfter: createdAfter.trim() || undefined, + createdBefore: createdBefore.trim() || undefined, + status: status || undefined, + purpose: purpose || undefined, + limit: parseLimit(limit), + offset: nextOffset, + sortColumn: sortColumn || undefined, + sortDirection: sortColumn ? sortDirection : undefined, + }); + setResult(response); + setSelectedKey(null); + } catch (error: unknown) { + handlePageError(error, onUnauthorized, setErrorMessage); + setResult(null); + } finally { + setIsLoading(false); + } + } + + function reset() { + setOwnerUserId(''); + setPublicUserCode(''); + setKeyId(''); + setName(''); + setKeyPrefix(''); + setCreatedAfter(''); + setCreatedBefore(''); + setStatus(''); + setPurpose(''); + setLimit('100'); + setSortColumn(''); + setSortDirection('desc'); + setResult(null); + setSelectedKey(null); + setErrorMessage(''); + } + + const resultLimit = result?.limit ?? parseLimit(limit); + const resultOffset = result?.offset ?? 0; + const keyTotalPages = result + ? Math.max(1, Math.ceil(result.total / Math.max(1, resultLimit))) + : 1; + const keyCurrentPage = + Math.floor(resultOffset / Math.max(1, resultLimit)) + 1; + const canGoToPreviousKeyPage = Boolean(result && resultOffset > 0); + const canGoToNextKeyPage = Boolean( + result && resultOffset + result.keys.length < result.total, + ); + + return ( + <> +
+
+ + + + + + + + + + + + +
+
+ + + + 必须提供 owner、公开用户编号、keyId 或精确前缀;只返回安全元数据。 + +
+
+ + {errorMessage ? ( +
+ {errorMessage} +
+ ) : null} + +
+
+

External API Key 安全视图

+ {result ? `匹配 ${result.total} 条` : '尚未查询'} +
+
+ + + + + + + + + + + + + + + + {result?.keys.length ? ( + result.keys.map((key) => ( + + + + + + + + + + + + )) + ) : ( + + + + )} + +
Key IDOwner名称前缀用途Scope创建时间状态详情
{key.keyId}{key.ownerUserId}{key.name}{key.keyPrefix}{key.purpose}{key.scopes.join(', ')}{formatSafeDate(key.createdAt)}{key.status} + +
+ {result ? '暂无数据' : '请先提供精确范围并查询'} +
+
+ {result?.scanLimitReached ? ( +
+ 当前查询达到 {result.scanLimit} 条安全扫描上限,已扫描{' '} + {result.scannedCount} 条; 总数和分页可能不完整,请缩小 owner、Key + ID 或精确前缀范围。 +
+ ) : null} + {result ? ( + + ) : null} +
+ + {selectedKey ? ( +
+
+
+

API Key 安全详情

+ +
+
+
Key ID
+
{selectedKey.keyId}
+
Owner
+
{selectedKey.ownerUserId}
+
名称
+
{selectedKey.name}
+
前缀
+
{selectedKey.keyPrefix}
+
用途
+
{selectedKey.purpose}
+
Scope
+
{selectedKey.scopes.join(', ') || '-'}
+
创建时间
+
{formatSafeDate(selectedKey.createdAt)}
+
最近使用
+
{formatSafeDate(selectedKey.lastUsedAt)}
+
撤销时间
+
{formatSafeDate(selectedKey.revokedAt)}
+
更新时间
+
{formatSafeDate(selectedKey.updatedAt)}
+
状态
+
{selectedKey.status}
+
+
+
+ ) : null} + + ); +} + +function formatSafeDate(value: string | null) { + return value ? value : '-'; +} + function readHashTableName() { const hash = window.location.hash; const queryIndex = hash.indexOf('?'); @@ -744,13 +1220,10 @@ export function resolveAdminDatabaseUserReference( normalizedColumn === 'public_user_code' || normalizedColumn.endsWith('_public_user_code') ) { - return {publicUserCode: normalizedValue}; + return { publicUserCode: normalizedValue }; } - if ( - normalizedColumn === 'user_id' || - normalizedColumn.endsWith('_user_id') - ) { - return {userId: normalizedValue}; + if (normalizedColumn === 'user_id' || normalizedColumn.endsWith('_user_id')) { + return { userId: normalizedValue }; } return null; } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/codex_app_server.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/codex_app_server.rs index 5a1d30e9f..729fdebf8 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/codex_app_server.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/codex_app_server.rs @@ -50,6 +50,18 @@ struct CodexPendingRpc { } enum CodexAppServerCredential { + PlatformSession { + api_base_url: String, + access_token: String, + fingerprint: String, + }, + AccountKey { + route_origin: String, + api_key: String, + key_id: String, + storage_path: std::path::PathBuf, + fingerprint: String, + }, AppDataKey { fingerprint: String, }, @@ -63,7 +75,10 @@ enum CodexAppServerCredential { impl CodexAppServerCredential { fn fingerprint(&self) -> &str { match self { - Self::AppDataKey { fingerprint } | Self::AuthBridge { fingerprint, .. } => fingerprint, + Self::PlatformSession { fingerprint, .. } + | Self::AccountKey { fingerprint, .. } + | Self::AppDataKey { fingerprint } + | Self::AuthBridge { fingerprint, .. } => fingerprint, } } @@ -89,6 +104,12 @@ impl CodexAppServerCredential { llm: &'a GameCreatorLlmConfig, ) -> Option<(&'a str, &'a str)> { match self { + Self::PlatformSession { .. } => None, + Self::AccountKey { + route_origin, + api_key, + .. + } => Some((route_origin.as_str(), api_key.as_str())), Self::AppDataKey { .. } => (!llm.api_key.trim().is_empty()) .then_some((llm.base_url.trim_end_matches('/'), llm.api_key.trim())), Self::AuthBridge { api_key, .. } => api_key @@ -437,7 +458,9 @@ pub(super) fn resolve_direct_codex_project_authority( if !project_root.is_absolute() { return Err("AGC 直连项目根目录必须是绝对路径".to_string()); } - let project_metadata = std::fs::metadata(project_root) + crate::prepare_game_creator_private_path_for_read(project_root, true, "AGC 直连项目根目录") + .map_err(|error| format!("AGC 直连项目根目录无法安全访问:{error}"))?; + let project_metadata = std::fs::symlink_metadata(project_root) .map_err(|_| "AGC 直连项目根目录不存在或无法读取".to_string())?; if !project_metadata.is_dir() { return Err("AGC 直连项目根目录不是目录".to_string()); @@ -778,17 +801,52 @@ async fn stage_codex_app_server_image( )); } let image_dir = workspace_path.join("input-images"); - tokio::fs::create_dir_all(&image_dir) - .await - .map_err(|error| { - platform_llm::LlmError::Transport(format!("创建 app-server 图片暂存目录失败:{error}")) - })?; + crate::ensure_game_creator_private_directory_tree(&image_dir, "app-server 图片暂存目录") + .map_err(platform_llm::LlmError::Transport)?; + crate::prepare_game_creator_private_path_for_read(&image_dir, true, "app-server 图片暂存目录") + .map_err(platform_llm::LlmError::Transport)?; let digest = Sha256::digest(&bytes); let path = image_dir.join(format!("{:x}-{image_index}.{extension}", digest)); - if !path.exists() { - tokio::fs::write(&path, bytes).await.map_err(|error| { - platform_llm::LlmError::Transport(format!("写入 app-server 图片暂存文件失败:{error}")) - })?; + let mut image_options = tokio::fs::OpenOptions::new(); + image_options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + image_options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + match image_options.open(&path).await { + Ok(mut file) => { + if let Err(error) = + crate::harden_new_game_creator_private_path(&path, false, "app-server 图片暂存文件") + { + drop(file); + let _ = std::fs::remove_file(&path); + return Err(platform_llm::LlmError::Transport(error)); + } + file.write_all(&bytes).await.map_err(|error| { + platform_llm::LlmError::Transport(format!( + "写入 app-server 图片暂存文件失败:{error}" + )) + })?; + file.sync_all().await.map_err(|error| { + platform_llm::LlmError::Transport(format!( + "同步 app-server 图片暂存文件失败:{error}" + )) + })?; + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + crate::prepare_game_creator_private_path_for_read( + &path, + false, + "app-server 图片暂存文件", + ) + .map_err(platform_llm::LlmError::Transport)?; + } + Err(error) => { + return Err(platform_llm::LlmError::Transport(format!( + "写入 app-server 图片暂存文件失败:{error}" + ))); + } } Ok(path) } @@ -975,6 +1033,8 @@ fn find_game_creator_codex_auth_path() -> Option { fn read_game_creator_codex_auth_bridge( source_auth: &std::path::Path, ) -> Result { + crate::prepare_game_creator_private_path_for_read(source_auth, false, "Codex CLI 登录态") + .map_err(platform_llm::LlmError::InvalidConfig)?; let mut auth_json = Vec::new(); { use std::io::Read; @@ -1279,6 +1339,8 @@ fn prepare_isolated_game_creator_codex_home( std::fs::create_dir(&isolated_home).map_err(|error| { platform_llm::LlmError::Transport(format!("创建隔离 Codex app-server HOME 失败:{error}")) })?; + crate::harden_new_game_creator_private_path(&isolated_home, true, "隔离 Codex app-server HOME") + .map_err(platform_llm::LlmError::Transport)?; let CodexAppServerCredential::AuthBridge { auth_json, .. } = credential else { return Ok(isolated_home); }; @@ -1286,20 +1348,8 @@ fn prepare_isolated_game_creator_codex_home( return Ok(isolated_home); } let target_auth = isolated_home.join("auth.json"); - std::fs::write(&target_auth, auth_json).map_err(|error| { - platform_llm::LlmError::Transport(format!( - "桥接 Codex 登录态到隔离 app-server 失败:{error}" - )) - })?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&target_auth, std::fs::Permissions::from_mode(0o600)).map_err( - |error| { - platform_llm::LlmError::Transport(format!("收紧隔离 Codex 登录态权限失败:{error}")) - }, - )?; - } + crate::write_game_creator_private_file(&target_auth, auth_json.as_slice(), "隔离 Codex 登录态") + .map_err(platform_llm::LlmError::Transport)?; Ok(isolated_home) } @@ -1310,11 +1360,13 @@ fn trust_isolated_game_creator_codex_workspace( let workspace = workspace.to_string_lossy(); let quoted_workspace = quoted_toml_string(&workspace)?; let config = format!("[projects.{quoted_workspace}]\ntrust_level = \"trusted\"\n"); - std::fs::write(codex_home.join("config.toml"), config).map_err(|error| { - platform_llm::LlmError::Transport(format!( - "写入隔离 Codex app-server 项目信任配置失败:{error}" - )) - }) + let config_path = codex_home.join("config.toml"); + crate::write_game_creator_private_file( + &config_path, + config.as_bytes(), + "隔离 Codex 项目信任配置", + ) + .map_err(platform_llm::LlmError::Transport) } impl CodexAppServerConnection { @@ -1337,9 +1389,35 @@ impl CodexAppServerConnection { } let codex_cli_version = game_creator_codex_cli_version_identity() .map_err(platform_llm::LlmError::InvalidConfig)?; - let credential = resolve_game_creator_codex_app_server_credential(llm)?; + let mut effective_llm = llm.clone(); + let credential = if game_creator_official_llm_route_locked() { + let session = current_platform_session().ok_or_else(|| { + platform_llm::LlmError::InvalidConfig( + "authentication-required: 请先登录陶泥儿账号".to_string(), + ) + })?; + effective_llm.base_url = + format!("{}/api/llm", session.api_base_url.trim_end_matches('/')); + effective_llm.api_key.clear(); + effective_llm.model = OFFICIAL_AGC_LLM_MODEL.to_string(); + CodexAppServerCredential::PlatformSession { + fingerprint: format!( + "platform-session:{}:{}:{}", + session.user_id, + session.api_base_url, + Sha256::digest(session.access_token.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::() + ), + api_base_url: session.api_base_url, + access_token: session.access_token, + } + } else { + resolve_game_creator_codex_app_server_credential(llm)? + }; let key = game_creator_codex_app_server_pool_key( - llm, + &effective_llm, &codex_cli_version, snapshot, credential.fingerprint(), @@ -1383,7 +1461,7 @@ impl CodexAppServerConnection { let executable = game_creator_codex_cli_executable_path() .map_err(platform_llm::LlmError::InvalidConfig)?; Self::spawn_with_executable_and_credential_at_workspace( - llm, + &effective_llm, &credential, executable.as_os_str(), Some(workspace), @@ -1395,7 +1473,7 @@ impl CodexAppServerConnection { let executable = game_creator_codex_cli_executable_path() .map_err(platform_llm::LlmError::InvalidConfig)?; Self::spawn_with_executable_and_credential_at_workspace( - llm, + &effective_llm, &credential, executable.as_os_str(), None, @@ -1455,10 +1533,29 @@ impl CodexAppServerConnection { "创建 Codex app-server 临时目录失败:{error}" )) })?; - let direct_provider_route = (workspace_mode == CodexAppServerWorkspaceMode::DirectProject) - .then(|| credential.direct_provider_route(llm)) - .flatten() - .map(|(base_url, api_key)| (base_url.to_string(), api_key.to_string())); + crate::harden_new_game_creator_private_path( + working_dir.path(), + true, + "Codex app-server 临时目录", + ) + .map_err(platform_llm::LlmError::Transport)?; + let direct_provider_route = match credential { + CodexAppServerCredential::PlatformSession { + api_base_url, + access_token, + .. + } => Some(( + format!("{}/api/llm", api_base_url.trim_end_matches('/')), + access_token.clone(), + )), + CodexAppServerCredential::AccountKey { .. } => credential + .direct_provider_route(llm) + .map(|(base_url, api_key)| (base_url.to_string(), api_key.to_string())), + _ => (workspace_mode == CodexAppServerWorkspaceMode::DirectProject) + .then(|| credential.direct_provider_route(llm)) + .flatten() + .map(|(base_url, api_key)| (base_url.to_string(), api_key.to_string())), + }; let remote_control_disable_reason = credential.remote_control_disable_reason(direct_provider_route.is_some()); let isolated_codex_home = prepare_isolated_game_creator_codex_home( @@ -1473,11 +1570,24 @@ impl CodexAppServerConnection { "创建 Codex app-server 隔离工作目录失败:{error}" )) })?; - std::fs::create_dir(isolated_workspace.join(".git")).map_err(|error| { + crate::harden_new_game_creator_private_path( + &isolated_workspace, + true, + "Codex app-server 隔离工作目录", + ) + .map_err(platform_llm::LlmError::Transport)?; + let isolated_git = isolated_workspace.join(".git"); + std::fs::create_dir(&isolated_git).map_err(|error| { platform_llm::LlmError::Transport(format!( "创建 Codex app-server 隔离仓库边界失败:{error}" )) })?; + crate::harden_new_game_creator_private_path( + &isolated_git, + true, + "Codex app-server 隔离仓库边界", + ) + .map_err(platform_llm::LlmError::Transport)?; } let (tool_bridge_root, workspace_path) = if workspace_mode == CodexAppServerWorkspaceMode::DirectProject { @@ -1502,16 +1612,21 @@ impl CodexAppServerConnection { let isolated_os_home = working_dir.path().join("home"); let isolated_app_data = isolated_os_home.join("appdata"); let isolated_local_app_data = isolated_os_home.join("local-appdata"); - for path in [ - &isolated_os_home, - &isolated_app_data, - &isolated_local_app_data, + for (path, label) in [ + (&isolated_os_home, "Codex app-server 隔离用户目录"), + (&isolated_app_data, "Codex app-server 隔离 AppData 目录"), + ( + &isolated_local_app_data, + "Codex app-server 隔离 LocalAppData 目录", + ), ] { - std::fs::create_dir_all(path).map_err(|error| { + std::fs::create_dir(path).map_err(|error| { platform_llm::LlmError::Transport(format!( "创建 Codex app-server 隔离用户目录失败:{error}" )) })?; + crate::harden_new_game_creator_private_path(path, true, label) + .map_err(platform_llm::LlmError::Transport)?; } let skill_root = if workspace_mode == CodexAppServerWorkspaceMode::DirectProject { install_agc_skill_pack(&isolated_os_home) @@ -1520,9 +1635,7 @@ impl CodexAppServerConnection { } else { None }; - let provider_proxy = if workspace_mode != CodexAppServerWorkspaceMode::DirectProject { - None - } else if let Some((base_url, api_key)) = direct_provider_route.as_ref() { + let provider_proxy = if let Some((base_url, api_key)) = direct_provider_route.as_ref() { Some( start_codex_provider_proxy(base_url, api_key) .await diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/codex_cli.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/codex_cli.rs index 15d7d45c0..1418e9afa 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/codex_cli.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/codex_cli.rs @@ -608,6 +608,8 @@ async fn request_game_creator_agent_codex_cli_with_executable( .map_err(|error| { platform_llm::LlmError::Transport(format!("创建 Codex CLI Agent 临时目录失败:{error}")) })?; + crate::harden_new_game_creator_private_path(temp_dir.path(), true, "Codex CLI Agent 临时目录") + .map_err(platform_llm::LlmError::Transport)?; let schema_path = if let Some(schema) = game_creator_codex_cli_tool_output_schema(&request) { let path = temp_dir.path().join("tool-output.schema.json"); let content = serde_json::to_vec(&schema).map_err(|error| { @@ -615,11 +617,8 @@ async fn request_game_creator_agent_codex_cli_with_executable( "序列化 Codex CLI Agent output schema 失败:{error}" )) })?; - std::fs::write(&path, content).map_err(|error| { - platform_llm::LlmError::Transport(format!( - "写入 Codex CLI Agent output schema 失败:{error}" - )) - })?; + crate::write_game_creator_private_file(&path, &content, "Codex CLI Agent output schema") + .map_err(platform_llm::LlmError::Transport)?; Some(path) } else { None diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_runtime.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_runtime.rs index e515babc1..69210a45f 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_runtime.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_runtime.rs @@ -1136,6 +1136,7 @@ fn direct_taonier_manifest_entry_at( fn direct_taonier_asset_sha256_at(root: &Path, local_path: &str) -> Result { let path = resolve_local_project_path(root, local_path)?; + prepare_game_creator_private_path_for_read(&path, false, "整包重生成素材")?; let bytes = std::fs::read(&path) .map_err(|error| format!("读取整包重生成素材失败:{}: {error}", path.display()))?; Ok(format!("{:x}", Sha256::digest(bytes))) @@ -1146,6 +1147,11 @@ fn direct_taonier_optional_contract_file_sha256_at( local_path: &str, ) -> Result, String> { let path = resolve_local_project_path(root, local_path)?; + let prepared = + prepare_game_creator_private_path_for_read(&path, false, "整包重生成严格合同文件")?; + if !prepared { + return Ok(None); + } let metadata = match std::fs::symlink_metadata(&path) { Ok(metadata) => metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), @@ -1198,6 +1204,7 @@ impl DirectTaonierRegenerationRollback { .into_iter() .map(|local_path| { let path = resolve_local_project_path(root, local_path)?; + prepare_game_creator_private_path_for_read(&path, false, "整包重生成旧素材")?; let previous_bytes = std::fs::read(&path).map_err(|error| { format!("读取整包重生成旧素材失败:{}: {error}", path.display()) })?; @@ -1909,7 +1916,8 @@ fn direct_taonier_art_asset_identity( return None; } let asset_path = resolve_local_project_path(root, &asset.local_path).ok()?; - if !asset_path.is_file() { + if !prepare_game_creator_private_path_for_read(&asset_path, false, "陶泥儿平台素材").ok()? + { return None; } let bytes = std::fs::read(asset_path).ok()?; @@ -2061,13 +2069,16 @@ fn direct_taonier_strict_art_package_is_valid(root: &Path) -> bool { return false; } let expected_art_manifest = art_manifest_content(); - if std::fs::read(root.join("assets/manifest.art.json")) + let art_manifest_path = root.join("assets/manifest.art.json"); + if !prepare_game_creator_private_path_for_read(&art_manifest_path, false, "美术 manifest") .ok() - .as_deref() - != Some(expected_art_manifest.as_bytes()) + .unwrap_or(false) { return false; } + if std::fs::read(&art_manifest_path).ok().as_deref() != Some(expected_art_manifest.as_bytes()) { + return false; + } let Ok(manifest) = read_manifest_for_project(root) else { return false; }; @@ -2177,9 +2188,7 @@ fn direct_registered_taonier_slice_paths(root: &Path) -> Vec { fn direct_game_sources_referenced_taonier_assets(root: &Path) -> Vec { let sources = direct_codex_game_outputs(root) .into_iter() - .filter_map(|(relative_path, _, _)| { - std::fs::read_to_string(root.join(relative_path)).ok() - }) + .filter_map(|(relative_path, _, _)| std::fs::read_to_string(root.join(relative_path)).ok()) .collect::>(); let mut available_paths = Vec::new(); if direct_taonier_art_base_is_valid(root) { @@ -2267,9 +2276,7 @@ fn direct_browser_evidence_needs_art_repair( fn direct_game_output_completion_error(root: &Path) -> Option { let entry = agent_runtime_game_entry_relative_path(root); if !root.join(entry).is_file() { - return Some(format!( - "Codex 返回后未找到 {entry},项目未进入可运行状态" - )); + return Some(format!("Codex 返回后未找到 {entry},项目未进入可运行状态")); } if !direct_game_sources_reference_taonier_art_package(root) { return Some( @@ -2450,6 +2457,7 @@ async fn recover_direct_taonier_spritesheet_read_only_at( .find(|asset| asset.local_path == DIRECT_CODEX_ART_SPEC_ASSET_PATH) .ok_or_else(|| "陶泥儿规范图 manifest 记录缺失".to_string())?; let source_path = resolve_local_project_path(root, &source_asset.local_path)?; + prepare_game_creator_private_path_for_read(&source_path, false, "陶泥儿规范图")?; let source_bytes = fs::read(source_path).map_err(|error| format!("读取陶泥儿规范图失败:{error}"))?; let source_identity = new_external_editor_source_identity( @@ -2572,14 +2580,25 @@ async fn recover_direct_taonier_spritesheet_read_only_at( return Err("本地图集文件已存在但合同不完整,已拒绝覆盖并保持失败状态".to_string()); } if let Some(parent) = output.parent() { - std::fs::create_dir_all(parent) - .map_err(|error| format!("创建陶泥儿图集目录失败:{error}"))?; + ensure_game_creator_private_directory_tree(parent, "陶泥儿图集目录")?; + prepare_game_creator_private_path_for_read(parent, true, "陶泥儿图集目录")?; } - let mut output_file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) + let mut output_options = std::fs::OpenOptions::new(); + output_options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + output_options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut output_file = output_options .open(&output) .map_err(|error| format!("创建恢复的陶泥儿图集文件失败:{error}"))?; + if let Err(error) = harden_new_game_creator_private_path(&output, false, "恢复的陶泥儿图集") + { + drop(output_file); + let _ = std::fs::remove_file(&output); + return Err(error); + } output_file .write_all(&download.bytes) .and_then(|_| output_file.sync_all()) @@ -3169,7 +3188,9 @@ fn direct_codex_output_fingerprint(root: &Path) -> String { for (local_path, _, _) in direct_codex_game_outputs(root) { hasher.update(local_path.as_bytes()); hasher.update([0]); - match std::fs::read(root.join(local_path)) { + let path = root.join(local_path); + let _ = prepare_game_creator_private_path_for_read(&path, false, "游戏输出文件"); + match std::fs::read(path) { Ok(bytes) => { hasher.update([1]); hasher.update((bytes.len() as u64).to_le_bytes()); diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tool_bridge.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tool_bridge.rs index 7330dd43b..516302e80 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tool_bridge.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tool_bridge.rs @@ -6,6 +6,7 @@ use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _}; use serde::Deserialize; use serde_json::{json, Value}; use std::collections::BTreeMap; +use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex as StdMutex}; use unicode_normalization::UnicodeNormalization; @@ -1073,6 +1074,10 @@ fn bridge_art_preparation_mode( } fn bridge_png_content(root: &Path, path: &Path) -> Result { + crate::validate_game_creator_private_path_ancestors(root, "工具桥项目根")?; + crate::prepare_game_creator_private_path_for_read(root, true, "工具桥项目根")?; + crate::validate_game_creator_private_path_ancestors(path, "工具桥图片")?; + crate::prepare_game_creator_private_path_for_read(path, false, "工具桥图片")?; let root = root .canonicalize() .map_err(|_| "工具桥项目根无法安全解析".to_string())?; @@ -1082,6 +1087,7 @@ fn bridge_png_content(root: &Path, path: &Path) -> Result { if !path.starts_with(&root) { return Err("工具桥图片越出当前项目边界".to_string()); } + crate::prepare_game_creator_private_path_for_read(&path, false, "工具桥图片")?; let metadata = std::fs::symlink_metadata(&path).map_err(|_| "读取工具桥图片失败".to_string())?; if metadata.file_type().is_symlink() @@ -1090,7 +1096,10 @@ fn bridge_png_content(root: &Path, path: &Path) -> Result { { return Err("工具桥图片不满足普通文件或大小边界".to_string()); } - let bytes = std::fs::read(&path).map_err(|_| "读取工具桥图片失败".to_string())?; + let (mut file, _) = open_project_private_regular_file(&path, "工具桥图片")?; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes) + .map_err(|_| "读取工具桥图片失败".to_string())?; if !bytes.starts_with(b"\x89PNG\r\n\x1a\n") { return Err("工具桥图片不是有效 PNG".to_string()); } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tools_mcp.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tools_mcp.rs index 7c896bd3a..6006dac4d 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tools_mcp.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tools_mcp.rs @@ -1178,8 +1178,7 @@ mod tests { #[test] fn tool_catalog_preserves_reviewed_resource_contracts() { assert!( - DIRECT_TOOLS_MCP_MAX_REQUEST_BYTES - > DIRECT_TOOLS_MCP_MAX_WRITE_CONTENT_BYTES + 1024, + DIRECT_TOOLS_MCP_MAX_REQUEST_BYTES > DIRECT_TOOLS_MCP_MAX_WRITE_CONTENT_BYTES + 1024, "MCP request envelope must fit the advertised file-write payload" ); let specs = direct_tools_mcp_specs(); diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation.rs index 11fb9e900..f9c5a4ab3 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation.rs @@ -24,8 +24,7 @@ pub(crate) use canvas_generation::{ ExternalGenerationInitialResponse, }; pub(in crate::agent) use canvas_generation::{ - commit_prepared_platform_art_asset_at, - commit_prepared_platform_art_asset_strict_slices_at, + commit_prepared_platform_art_asset_at, commit_prepared_platform_art_asset_strict_slices_at, generate_platform_art_asset_with_retained_runtime_options_at, generate_platform_art_asset_with_runtime_options_at, platform_art_generation_error_result_unknown, register_existing_platform_art_slices_at, diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/canvas_generation.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/canvas_generation.rs index ee9b32f60..4c8fd67ef 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/canvas_generation.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/canvas_generation.rs @@ -475,7 +475,11 @@ fn prepare_platform_art_asset_output_path_for_mode( return Err("图片生成 outputPath 只允许 png、jpg、jpeg 或 webp 文件".to_string()); } let absolute = resolve_local_project_path(root, &normalized)?; - let existing = if absolute.exists() { + let existing = if crate::prepare_game_creator_private_path_for_read( + &absolute, + false, + "图片生成 outputPath", + )? { if !replace_existing { return Err(format!( "图片生成 outputPath 已存在,禁止静默覆盖:{normalized}" @@ -3118,6 +3122,10 @@ fn cleanup_interrupted_platform_art_contract_files_at(root: &Path) -> Result<(), } fn write_new_platform_art_slice(path: &Path, bytes: &[u8]) -> Result { + if let Some(parent) = path.parent() { + crate::ensure_game_creator_private_directory_tree(parent, "平台图集切片目录")?; + crate::prepare_game_creator_private_path_for_read(parent, true, "平台图集切片目录")?; + } let mut output = fs::OpenOptions::new(); output.write(true).create_new(true); #[cfg(unix)] @@ -3126,9 +3134,15 @@ fn write_new_platform_art_slice(path: &Path, bytes: &[u8]) -> Result output, Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + crate::prepare_game_creator_private_path_for_read(path, false, "平台图集切片")?; let existing = fs::read(path) .map_err(|read_error| format!("回读既有平台图集切片失败:{read_error}"))?; if existing == bytes { @@ -3143,6 +3157,12 @@ fn write_new_platform_art_slice(path: &Path, bytes: &[u8]) -> Result Result Result<(), String> { + if let Some(parent) = path.parent() { + crate::ensure_game_creator_private_directory_tree(parent, "平台图集切片目录")?; + crate::prepare_game_creator_private_path_for_read(parent, true, "平台图集切片目录")?; + } let file_name = path .file_name() .and_then(|value| value.to_str()) @@ -3158,8 +3182,10 @@ fn replace_platform_art_slice_file(path: &Path, bytes: &[u8], suffix: &str) -> R let temporary = path.with_file_name(format!(".{file_name}.replacement.{suffix}")); let backup = path.with_file_name(format!(".{file_name}.previous.{suffix}")); write_new_platform_art_slice(&temporary, bytes)?; - let had_previous = path.is_file(); + let had_previous = + crate::prepare_game_creator_private_path_for_read(path, false, "平台图集切片")?; if had_previous { + crate::prepare_game_creator_private_path_for_read(path, false, "平台图集切片")?; if let Err(error) = fs::rename(path, &backup) { let _ = fs::remove_file(&temporary); return Err(format!("准备替换平台图集切片文件失败:{error}")); @@ -3239,6 +3265,10 @@ fn write_durable_platform_art_transaction_file( bytes: &[u8], label: &str, ) -> Result<(), String> { + if let Some(parent) = path.parent() { + crate::ensure_game_creator_private_directory_tree(parent, "平台图集事务目录")?; + crate::prepare_game_creator_private_path_for_read(parent, true, "平台图集事务目录")?; + } let mut options = fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] @@ -3247,12 +3277,23 @@ fn write_durable_platform_art_transaction_file( options.custom_flags(libc::O_NOFOLLOW); options.mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options .open(path) .map_err(|error| format!("创建{label}失败:{}: {error}", path.display()))?; + if let Err(error) = crate::harden_new_game_creator_private_path(path, false, label) { + drop(file); + let _ = fs::remove_file(path); + return Err(error); + } file.write_all(bytes) .and_then(|_| file.sync_all()) - .map_err(|error| format!("持久化{label}失败:{}: {error}", path.display())) + .map_err(|error| format!("持久化{label}失败:{}: {error}", path.display()))?; + Ok(()) } #[cfg(test)] @@ -6857,12 +6898,12 @@ fn commit_strict_platform_art_slices_at( )?); let absolute_path = resolve_local_project_path(root, &local_path)?; if let Some(parent) = absolute_path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建正式平台图集切片目录失败:{}: {error}", - parent.display() - ) - })?; + crate::ensure_game_creator_private_directory_tree(parent, "正式平台图集切片目录")?; + crate::prepare_game_creator_private_path_for_read( + parent, + true, + "正式平台图集切片目录", + )?; } replace_platform_art_slice_file(&absolute_path, &slice.download.bytes, suffix)?; content_sha256s.push(slice.content_sha256.clone()); @@ -6931,12 +6972,8 @@ fn commit_prepared_platform_art_slices_at( sanitize_file_name(generation_key) ); let directory_path = resolve_local_project_path(root, &directory)?; - fs::create_dir_all(&directory_path).map_err(|error| { - format!( - "创建平台图集切片目录失败:{}: {error}", - directory_path.display() - ) - })?; + crate::ensure_game_creator_private_directory_tree(&directory_path, "平台图集切片目录")?; + crate::prepare_game_creator_private_path_for_read(&directory_path, true, "平台图集切片目录")?; let mut generated = Vec::with_capacity(slices.len()); let mut created_paths = Vec::with_capacity(slices.len()); let mut slice_paths = Vec::with_capacity(slices.len()); @@ -7131,8 +7168,8 @@ fn commit_prepared_platform_art_asset_with_before_replace_hook( } }; if let Some(parent) = absolute_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建平台生成素材目录失败:{}: {error}", parent.display()))?; + crate::ensure_game_creator_private_directory_tree(parent, "平台生成素材目录")?; + crate::prepare_game_creator_private_path_for_read(parent, true, "平台生成素材目录")?; } absolute_path = resolve_local_project_path(root, &local_path)?; let replacement_suffix = format!( @@ -7185,13 +7222,29 @@ fn commit_prepared_platform_art_asset_with_before_replace_hook( output.custom_flags(libc::O_NOFOLLOW); output.mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + output.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut output = output.open(&output_path).map_err(|error| { format!("创建平台生成素材失败:{}: {error}", output_path.display()) })?; + if let Err(error) = + crate::harden_new_game_creator_private_path(&output_path, false, "平台生成素材") + { + drop(output); + let _ = fs::remove_file(&output_path); + return Err(error); + } output.write_all(&download.bytes).map_err(|error| { let _ = fs::remove_file(&output_path); format!("写入平台生成素材失败:{}: {error}", output_path.display()) })?; + output.sync_all().map_err(|error| { + let _ = fs::remove_file(&output_path); + format!("同步平台生成素材失败:{}: {error}", output_path.display()) + })?; drop(output); } let replacement_backup_path = @@ -7306,12 +7359,15 @@ fn commit_prepared_platform_art_asset_with_before_replace_hook( let receipt_path = resolve_local_project_path(root, ".agent/runtime/art-spritesheet-contract.json")?; if let Some(parent) = receipt_path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建平台图集私有合同回执目录失败:{}: {error}", - parent.display() - ) - })?; + crate::ensure_game_creator_private_directory_tree( + parent, + "平台图集私有合同回执目录", + )?; + crate::prepare_game_creator_private_path_for_read( + parent, + true, + "平台图集私有合同回执目录", + )?; } let receipt_bytes = strict_game_art_contract_receipt_bytes( resource_id diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/draft_writer.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/draft_writer.rs index b3a84948e..037cb2d2e 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/draft_writer.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/draft_writer.rs @@ -37,63 +37,56 @@ pub(crate) fn write_local_game_draft_at( &format!("- {timestamp}: {prompt}\n"), "写入长期记忆失败", )?; - fs::write( + write_game_creator_private_file( &design_path, format!( "# 游戏设计草案\n\n## 原始想法\n\n{prompt}\n\n## Agent 协作交接\n\n{handoff_summary}\n\n## LLM 生成草案\n\n{}\n", draft.design_markdown.trim() - ), - ) - .map_err(|error| format!("写入游戏设计失败:{}: {error}", design_path.display()))?; - fs::write( + ) + .as_bytes(), + "游戏设计", + )?; + write_game_creator_private_file( &balance_path, serde_json::to_string_pretty(&draft.balance) - .map_err(|error| format!("生成数值配置失败:{error}"))?, - ) - .map_err(|error| format!("写入数值配置失败:{}: {error}", balance_path.display()))?; - fs::write( + .map_err(|error| format!("生成数值配置失败:{error}"))? + .as_bytes(), + "数值配置", + )?; + write_game_creator_private_file( &art_manifest_path, serde_json::to_string_pretty(&draft.art_manifest) - .map_err(|error| format!("生成美术清单失败:{error}"))?, - ) - .map_err(|error| format!("写入美术清单失败:{}: {error}", art_manifest_path.display()))?; - fs::write( + .map_err(|error| format!("生成美术清单失败:{error}"))? + .as_bytes(), + "美术清单", + )?; + write_game_creator_private_file( &audio_manifest_path, serde_json::to_string_pretty(&draft.audio_manifest) - .map_err(|error| format!("生成音乐音效清单失败:{error}"))?, - ) - .map_err(|error| { - format!( - "写入音乐音效清单失败:{}: {error}", - audio_manifest_path.display() - ) - })?; - fs::write( + .map_err(|error| format!("生成音乐音效清单失败:{error}"))? + .as_bytes(), + "音乐音效清单", + )?; + write_game_creator_private_file( &publish_readme_path, format!( "# 发布包装草案\n\n## 标题\n\n{title}\n\n## 简介\n\n{prompt}\n\n## Agent 协作交接\n\n{handoff_summary}\n\n{}\n", draft.publish_readme.trim() - ), - ) - .map_err(|error| { - format!( - "写入发布包装草案失败:{}: {error}", - publish_readme_path.display() ) - })?; + .as_bytes(), + "发布包装草案", + )?; - fs::write(&game_index_path, draft.game_html.trim()) - .map_err(|error| format!("写入游戏入口失败:{}: {error}", game_index_path.display()))?; - fs::OpenOptions::new() - .create(true) - .append(true) - .open(&agent_log_path) - .and_then(|mut file| { - file.write_all( - format!("{timestamp} game.generate_draft llm\n{handoff_summary}\n").as_bytes(), - ) - }) - .map_err(|error| format!("写入 Agent 日志失败:{}: {error}", agent_log_path.display()))?; + write_game_creator_private_file( + &game_index_path, + draft.game_html.trim().as_bytes(), + "游戏入口", + )?; + append_game_creator_private_file( + &agent_log_path, + format!("{timestamp} game.generate_draft llm\n{handoff_summary}\n").as_bytes(), + "Agent 日志", + )?; append_agent_db_record( root, serde_json::json!({ diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/loop_orchestration.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/loop_orchestration.rs index 43a6aa0ed..9e9909787 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/loop_orchestration.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/loop_orchestration.rs @@ -61,8 +61,7 @@ pub(crate) async fn run_game_creator_agent_loop_at( ) .await .map(|spec| render_planner_spec(prompt, &spec))?; - fs::write(&spec_path, &planner_spec) - .map_err(|error| format!("写入 Planner 规格失败:{}: {error}", spec_path.display()))?; + write_game_creator_private_file(&spec_path, planner_spec.as_bytes(), "Planner 规格")?; emit_agent_progress(progress, "llm.planner.done", "Planner 规格已生成"); steps.push(with_task_context( agent_trace_step( @@ -89,12 +88,7 @@ pub(crate) async fn run_game_creator_agent_loop_at( let mut latest_findings = render_evaluator_findings(0, &["暂无上一轮问题,Generator 可开始首轮实现。"]); - fs::write(&findings_path, &latest_findings).map_err(|error| { - format!( - "写入 Evaluator 结果失败:{}: {error}", - findings_path.display() - ) - })?; + write_game_creator_private_file(&findings_path, latest_findings.as_bytes(), "Evaluator 结果")?; steps.push(agent_trace_step( 0, "Evaluator", @@ -169,12 +163,11 @@ pub(crate) async fn run_game_creator_agent_loop_at( "agent.role.brief", )); latest_findings = render_evaluator_findings(pass, &issues); - fs::write(&findings_path, &latest_findings).map_err(|write_error| { - format!( - "写入 Evaluator 结果失败:{}: {write_error}", - findings_path.display() - ) - })?; + write_game_creator_private_file( + &findings_path, + latest_findings.as_bytes(), + "Evaluator 结果", + )?; steps.push(with_task_context( agent_trace_step( pass, @@ -271,12 +264,11 @@ pub(crate) async fn run_game_creator_agent_loop_at( append_collaboration_steps(pass, &draft, &pass_artifacts, &mut steps); let issues = evaluate_game_draft(prompt, &draft); latest_findings = render_evaluator_findings(pass, &issues); - fs::write(&findings_path, &latest_findings).map_err(|error| { - format!( - "写入 Evaluator 结果失败:{}: {error}", - findings_path.display() - ) - })?; + write_game_creator_private_file( + &findings_path, + latest_findings.as_bytes(), + "Evaluator 结果", + )?; steps.push(with_task_context( agent_trace_step_owned( pass, @@ -344,12 +336,11 @@ pub(crate) async fn run_game_creator_agent_loop_at( "llm.chat.generator", )); latest_findings = render_evaluator_findings(pass, &issues); - fs::write(&findings_path, &latest_findings).map_err(|write_error| { - format!( - "写入 Evaluator 结果失败:{}: {write_error}", - findings_path.display() - ) - })?; + write_game_creator_private_file( + &findings_path, + latest_findings.as_bytes(), + "Evaluator 结果", + )?; steps.push(with_task_context( agent_trace_step( pass, diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/pass_artifacts.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/pass_artifacts.rs index bdc1046b5..cea5cf4f9 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/pass_artifacts.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/pass_artifacts.rs @@ -186,8 +186,8 @@ pub(crate) fn write_agent_pass_artifacts( ) -> Result { let relative_dir = format!(".agent/passes/pass-{pass}"); let pass_dir = root.join(&relative_dir); - fs::create_dir_all(&pass_dir) - .map_err(|error| format!("创建 Agent pass 目录失败:{}: {error}", pass_dir.display()))?; + ensure_game_creator_private_directory_tree(&pass_dir, "Agent pass 目录")?; + prepare_game_creator_private_path_for_read(&pass_dir, true, "Agent pass 目录")?; let paths = AgentPassArtifactPaths { draft_json: format!("{relative_dir}/draft.json"), @@ -262,16 +262,7 @@ pub(crate) fn write_agent_pass_file( content: &str, ) -> Result<(), String> { let path = root.join(relative_path); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 Agent pass 文件目录失败:{}: {error}", - parent.display() - ) - })?; - } - fs::write(&path, content) - .map_err(|error| format!("写入 Agent pass 文件失败:{}: {error}", path.display())) + write_game_creator_private_file(&path, content.as_bytes(), "Agent pass 文件") } pub(crate) fn write_agent_group_brief( diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/role_briefs.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/role_briefs.rs index 2139ddfe1..516680147 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/role_briefs.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/role_briefs.rs @@ -714,22 +714,17 @@ pub(crate) fn append_agent_loop_log( ) -> Result<(), String> { let agent_log_path = root.join(".agent/logs/agent.log"); let timestamp = unix_timestamp(); - fs::OpenOptions::new() - .create(true) - .append(true) - .open(&agent_log_path) - .and_then(|mut file| { - file.write_all( - format!( - "{timestamp} agent.loop passes={}\nPlanner -> .agent/spec.md\n组内角色 briefs -> .agent/passes/pass-*/groups//*.md\n专业组汇总 -> .agent/passes/pass-*/groups/*.md\nGenerator -> .agent/passes/pass-*/draft.json\n专业组 handoffs -> .agent/passes/pass-*/handoff.md\nEvaluator -> .agent/findings.md\n{}\n{}\n", - loop_result.passes, - loop_result.spec_markdown.trim(), - loop_result.findings_markdown.trim() - ) - .as_bytes(), - ) - }) - .map_err(|error| format!("写入 Agent loop 日志失败:{}: {error}", agent_log_path.display()))?; + append_game_creator_private_file( + &agent_log_path, + format!( + "{timestamp} agent.loop passes={}\nPlanner -> .agent/spec.md\n组内角色 briefs -> .agent/passes/pass-*/groups//*.md\n专业组汇总 -> .agent/passes/pass-*/groups/*.md\nGenerator -> .agent/passes/pass-*/draft.json\n专业组 handoffs -> .agent/passes/pass-*/handoff.md\nEvaluator -> .agent/findings.md\n{}\n{}\n", + loop_result.passes, + loop_result.spec_markdown.trim(), + loop_result.findings_markdown.trim() + ) + .as_bytes(), + "Agent loop 日志", + )?; append_agent_loop_memory(root, loop_result) } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/run_lifecycle.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/run_lifecycle.rs index 697fd2c81..93765f080 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/run_lifecycle.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/run_lifecycle.rs @@ -191,26 +191,12 @@ pub(crate) fn write_agent_run_trace_payload( let payload = serde_json::to_string_pretty(&trace) .map_err(|error| format!("生成 Agent run trace 失败:{error}"))?; let latest_path = root.join(".agent/run.latest.json"); - fs::write(&latest_path, &payload).map_err(|error| { - format!( - "写入 Agent run trace 失败:{}: {error}", - latest_path.display() - ) - })?; + write_game_creator_private_file(&latest_path, payload.as_bytes(), "Agent run trace")?; let run_dir = root.join(".agent/runs"); - fs::create_dir_all(&run_dir).map_err(|error| { - format!( - "创建 Agent run history 目录失败:{}: {error}", - run_dir.display() - ) - })?; + ensure_game_creator_private_directory_tree(&run_dir, "Agent run history 目录")?; + prepare_game_creator_private_path_for_read(&run_dir, true, "Agent run history 目录")?; let run_path = run_dir.join(format!("{}.json", trace.run_id)); - fs::write(&run_path, payload).map_err(|error| { - format!( - "写入 Agent run history 失败:{}: {error}", - run_path.display() - ) - })?; + write_game_creator_private_file(&run_path, payload.as_bytes(), "Agent run history")?; prune_agent_run_history(&run_dir) } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/trace.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/trace.rs index 4b172857c..2a7f54ea8 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/trace.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/trace.rs @@ -309,20 +309,11 @@ pub(crate) fn append_preview_log( url: Option<&str>, ) -> Result<(), String> { let log_path = root.join(".agent/logs/preview.log"); - if let Some(parent) = log_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建预览日志目录失败:{}: {error}", parent.display()))?; - } let line = match url { Some(url) => format!("{} preview.{status} {url}\n", unix_timestamp()), None => format!("{} preview.{status}\n", unix_timestamp()), }; - fs::OpenOptions::new() - .create(true) - .append(true) - .open(&log_path) - .and_then(|mut file| file.write_all(line.as_bytes())) - .map_err(|error| format!("写入预览日志失败:{}: {error}", log_path.display())) + append_game_creator_private_file(&log_path, line.as_bytes(), "预览日志") } pub(crate) fn record_replaced_preview_stop(preview: &LocalPreviewResult) { @@ -340,6 +331,7 @@ pub(crate) fn append_agent_run_trace_step( error: Option<&str>, ) -> Result<(), String> { let trace_path = root.join(".agent/run.latest.json"); + prepare_game_creator_private_path_for_read(&trace_path, false, "Agent run trace")?; let content = match fs::read_to_string(&trace_path) { Ok(content) => content, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), @@ -781,8 +773,8 @@ pub(crate) fn append_agent_run_jsonl( ) -> Result<(), String> { let path = root.join(relative_path); if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建 Agent 事件目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "Agent 事件目录")?; + prepare_game_creator_private_path_for_read(parent, true, "Agent 事件目录")?; } let line = serde_json::to_string(value).map_err(|error| format!("序列化 Agent 事件失败:{error}"))?; @@ -795,12 +787,8 @@ pub(crate) fn write_agent_run_context_bundle( ) -> Result<(), String> { let bundle_path = root.join(".agent/context.bundle.json"); if let Some(parent) = bundle_path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 Agent context bundle 目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, "Agent context bundle 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "Agent context bundle 目录")?; } let manifest = read_manifest_for_project(root).ok(); let payload = serde_json::json!({ @@ -825,10 +813,5 @@ pub(crate) fn write_agent_run_context_bundle( }); let content = serde_json::to_string_pretty(&payload) .map_err(|error| format!("生成 Agent context bundle 失败:{error}"))?; - fs::write(&bundle_path, content).map_err(|error| { - format!( - "写入 Agent context bundle 失败:{}: {error}", - bundle_path.display() - ) - }) + write_game_creator_private_file(&bundle_path, content.as_bytes(), "Agent context bundle") } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/autonomous_policy.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/autonomous_policy.rs index eeb2f00ff..3fa69f520 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/autonomous_policy.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/autonomous_policy.rs @@ -48,7 +48,9 @@ pub(in crate::agent) fn validate_agent_runtime_autonomous_complete_game_index_wr ) -> Result<(), String> { if path .and_then(serde_json::Value::as_str) - .map_or(true, |path| !is_agent_runtime_game_entry_relative_path(path)) + .map_or(true, |path| { + !is_agent_runtime_game_entry_relative_path(path) + }) { return Ok(()); } @@ -793,7 +795,7 @@ fn autonomous_manifest_parent_has_active_ready_task_at( let records = latest_game_creator_agent_runtime_tasks(read_all_game_creator_agent_runtime_tasks( &game_creator_agent_runtime_task_path(root, task_id), - )?); + )?); for record in records { if record.source != "agent-ready-task-scheduler" || game_creator_agent_runtime_terminal_status(&record).is_some() @@ -806,10 +808,9 @@ fn autonomous_manifest_parent_has_active_ready_task_at( // binding's root id solely to associate an in-flight child with // this root; never reject or block the child for a mismatch. if record.run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD { - let parent_hint_matches = - record.parent_agent_id.as_deref() - == Some(GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID) - && record.parent_run_id.as_deref() == Some(parent_run_id); + let parent_hint_matches = record.parent_agent_id.as_deref() + == Some(GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID) + && record.parent_run_id.as_deref() == Some(parent_run_id); let binding_root_matches = read_game_creator_agent_runtime_run_profile_binding( root, &record.agent_id, @@ -821,8 +822,7 @@ fn autonomous_manifest_parent_has_active_ready_task_at( } continue; } - if record.parent_agent_id.as_deref() - != Some(GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID) + if record.parent_agent_id.as_deref() != Some(GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID) || record.parent_run_id.as_deref() != Some(parent_run_id) { continue; diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/pending_confirmation_ledger.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/pending_confirmation_ledger.rs index c1376c327..da897e1b8 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/pending_confirmation_ledger.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/pending_confirmation_ledger.rs @@ -338,7 +338,8 @@ pub(in crate::agent) fn validate_agent_runtime_pending_tool_action_record( validate_agent_runtime_pending_goal_binding(pending)?; match pending.planning_session_binding.as_ref() { Some(binding) => { - validate_plan_provider_session_binding(binding).map_err(|error| error.to_string())?; + validate_plan_provider_session_binding(binding) + .map_err(|error| error.to_string())?; if pending.action.tool.trim() != PLAN_SUBMIT_GDD_TOOL || binding.agent_id != pending.agent_id || binding.task_id != pending.task_id @@ -652,12 +653,8 @@ pub(crate) fn write_game_creator_agent_runtime_tool_confirmation( let path = game_creator_agent_runtime_tool_confirmation_path(root, agent_id, run_id, command_id); if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 Agent Runtime 工具确认目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, "Agent Runtime 工具确认目录")?; + prepare_game_creator_private_path_for_read(parent, true, "Agent Runtime 工具确认目录")?; } let payload = serde_json::json!({ "schemaVersion": AGENT_RUNTIME_SCHEMA_VERSION, @@ -670,12 +667,8 @@ pub(crate) fn write_game_creator_agent_runtime_tool_confirmation( }); let content = serde_json::to_string_pretty(&payload) .map_err(|error| format!("序列化 Agent Runtime 工具确认失败:{error}"))?; - fs::write(&path, content).map_err(|error| { - format!( - "写入 Agent Runtime 工具确认失败:{}: {error}", - path.display() - ) - }) + crate::write_game_creator_private_file(&path, content.as_bytes(), "Agent Runtime 工具确认")?; + Ok(()) } pub(in crate::agent) fn consume_game_creator_agent_runtime_tool_confirmation( @@ -690,6 +683,7 @@ pub(in crate::agent) fn consume_game_creator_agent_runtime_tool_confirmation( } let path = game_creator_agent_runtime_tool_confirmation_path(root, agent_id, run_id, command_id); + prepare_game_creator_private_path_for_read(&path, false, "Agent Runtime 工具确认")?; let content = match fs::read_to_string(&path) { Ok(content) => content, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/project_gates.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/project_gates.rs index 10b36970e..8f5b6eb8d 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/project_gates.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/project_gates.rs @@ -195,9 +195,9 @@ pub(crate) fn finish_agent_runtime_project_verification_locked( }; if passed && !html.contains(" 1); for tool in [ diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/provider_tool_plan.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/provider_tool_plan.rs index d2c75a829..e63d79b96 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/provider_tool_plan.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_actions/provider_tool_plan.rs @@ -439,19 +439,18 @@ pub(in crate::agent) async fn request_game_creator_agent_background_tool_plan_at let code_prototype_requires_static_smoke = !relaxed_autonomous && run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD && agent_id == "code-prototype"; - let verified_delivery = if !relaxed_autonomous - && run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD - { - let verification_gate = - read_game_creator_agent_runtime_verification_gate(root, agent_id, run_id)?; - runtime_owner_artifact_validation_available - || agent_runtime_autonomous_verified_delivery_allows_plan_completion( - agent_id, - &verification_gate, - ) - } else { - false - }; + let verified_delivery = + if !relaxed_autonomous && run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD { + let verification_gate = + read_game_creator_agent_runtime_verification_gate(root, agent_id, run_id)?; + runtime_owner_artifact_validation_available + || agent_runtime_autonomous_verified_delivery_allows_plan_completion( + agent_id, + &verification_gate, + ) + } else { + false + }; let allow_runtime_plan_completion = read_only_delivery || verified_delivery; let autonomous_project_verify_available = relaxed_autonomous || run_profile != AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD @@ -758,8 +757,7 @@ pub(in crate::agent) async fn request_game_creator_agent_background_tool_plan_at }; let parsed = match parsed { Ok((parsed, source_payload)) - if agent_id == GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID - && !relaxed_autonomous => + if agent_id == GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID && !relaxed_autonomous => { let collaboration_policy = resolve_supervisor_collaboration_policy_for_run_at(root, agent_id, run_id)? diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/finalization.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/finalization.rs index 5f146400a..6dae3634e 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/finalization.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/finalization.rs @@ -245,36 +245,39 @@ pub(in crate::agent) fn resume_game_creator_agent_finalization_at( let assistant_exists = game_creator_agent_runtime_finalization_assistant_exists(root, &journal)?; if !relaxed_autonomous { - match classify_game_creator_agent_runtime_finalization_goal_snapshot_at(root, &journal, &state)? - { - AgentRuntimeFinalizationGoalSnapshotRelation::Matches => {} - AgentRuntimeFinalizationGoalSnapshotRelation::StaleRevision { - journal_revision, - current_revision, - } if journal.status == AGENT_RUNTIME_FINALIZATION_STATUS_PREPARED && !assistant_exists => { - remove_game_creator_agent_runtime_finalization_recovery_sidecars( - root, - &journal.agent_id, - &journal.run_id, - )?; - let _ = append_agent_db_record( - root, - serde_json::json!({ - "recordType": "agent.runtime.background_task.finalization_stale_recovered", - "agentId": journal.agent_id, - "taskId": journal.task_id, - "sessionId": journal.session_id, - "runId": journal.run_id, - "source": journal.source, - "summary": "Goal revision 已更新,旧最终回复已丢弃", - "journalGoalRevision": journal_revision, - "currentGoalRevision": current_revision, - }), - ); - return Ok(AgentRuntimeFinalizationResume::NotFound(runtime_lock)); - } - relation => { - let detail = match relation { + match classify_game_creator_agent_runtime_finalization_goal_snapshot_at( + root, &journal, &state, + )? { + AgentRuntimeFinalizationGoalSnapshotRelation::Matches => {} + AgentRuntimeFinalizationGoalSnapshotRelation::StaleRevision { + journal_revision, + current_revision, + } if journal.status == AGENT_RUNTIME_FINALIZATION_STATUS_PREPARED + && !assistant_exists => + { + remove_game_creator_agent_runtime_finalization_recovery_sidecars( + root, + &journal.agent_id, + &journal.run_id, + )?; + let _ = append_agent_db_record( + root, + serde_json::json!({ + "recordType": "agent.runtime.background_task.finalization_stale_recovered", + "agentId": journal.agent_id, + "taskId": journal.task_id, + "sessionId": journal.session_id, + "runId": journal.run_id, + "source": journal.source, + "summary": "Goal revision 已更新,旧最终回复已丢弃", + "journalGoalRevision": journal_revision, + "currentGoalRevision": current_revision, + }), + ); + return Ok(AgentRuntimeFinalizationResume::NotFound(runtime_lock)); + } + relation => { + let detail = match relation { AgentRuntimeFinalizationGoalSnapshotRelation::StaleRevision { journal_revision, current_revision, @@ -284,14 +287,16 @@ pub(in crate::agent) fn resume_game_creator_agent_finalization_at( AgentRuntimeFinalizationGoalSnapshotRelation::Conflict(detail) => detail, AgentRuntimeFinalizationGoalSnapshotRelation::Matches => unreachable!(), }; - let error = format!("Agent Runtime finalization 恢复已阻断:Goal 快照冲突:{detail}"); - record_game_creator_agent_runtime_finalization_pending(root, &state, &error); - return read_game_creator_agent_runtime_at(root, agent_id) - .map(AgentRuntimeFinalizationResume::Blocked); - } + let error = + format!("Agent Runtime finalization 恢复已阻断:Goal 快照冲突:{detail}"); + record_game_creator_agent_runtime_finalization_pending(root, &state, &error); + return read_game_creator_agent_runtime_at(root, agent_id) + .map(AgentRuntimeFinalizationResume::Blocked); + } } } - if !relaxed_autonomous && assistant_exists + if !relaxed_autonomous + && assistant_exists && !state_reconstructed_from_task && !game_creator_agent_runtime_finalization_plan_matches_state(&journal, &state) { @@ -415,11 +420,13 @@ pub(in crate::agent) fn resume_game_creator_agent_finalization_at( goal_contract_acceptance_completion_blocker_at_locked(&root, &state) { Some(blocker) - } else if let Some(blocker) = agent_runtime_non_verification_completion_blocker_at_locked( - &root, - &journal.agent_id, - &journal.run_id, - ) { + } else if let Some(blocker) = + agent_runtime_non_verification_completion_blocker_at_locked( + &root, + &journal.agent_id, + &journal.run_id, + ) + { Some(blocker) } else if let Some(blocker) = autonomous_game_build_completion_blocker_at_locked(&root, &state) diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/main_loop.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/main_loop.rs index 611cfdc15..abcd741a8 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/main_loop.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/main_loop.rs @@ -810,101 +810,15 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( // impossible for a relaxed run to read the DAG and accidentally // re-enter `waiting-for-manifest-tasks`. if !relaxed_autonomous { - let autonomous_root_goal_contract_persisted = - if agent_id == GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID - && runtime.run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD - { - match autonomous_root_goal_contract_persisted_at( - &root, - &agent_id, - &runtime.run_id, - ) { - Ok(value) => value, - Err(error) => { - return fail_game_creator_agent_background_context_at( - &root, - &agent_id, - &session_id, - runtime, - &format!("读取自主构建根 Goal Contract 门失败:{error}"), - ); - } - } - } else { - false - }; - let autonomous_manifest_parent_can_wait = - autonomous_root_goal_contract_persisted - && agent_id == GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID - && runtime.run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD - && !game_creator_agent_runtime_provider_action_batch_exists( - &root, - &agent_id, - &runtime.run_id, - ) - && supervisor_collaboration_policy_completion_blocker_at_locked( - &root, - &agent_id, - &runtime.run_id, - ) - .is_none() - && isolated_join_completion_blocker_at(&root, &agent_id, &runtime.run_id) - .is_none() - && static_delegate_completion_blocker_at(&root, &agent_id, &runtime.run_id) - .is_none(); - if autonomous_manifest_parent_can_wait { - let manifest_state_before_schedule = match autonomous_manifest_dag_state_at(&root) { - Ok(value) => value, - Err(error) => { - return fail_game_creator_agent_background_context_at( - &root, - &agent_id, - &session_id, - runtime, - &format!("读取自主构建 manifest 等待屏障失败:{error}"), - ); - } - }; - // 已登记但损坏的派生视觉需要先由父 Run 规划修复,因此此时不再调度新的 - // manifest child;但已经持久化并运行的 child 仍是当前 DAG 的活跃工作, - // 父 Run 必须继续等待,不能提前结束。 - // 同理,已有失败任务时只能等待已在途 child 收束或立即安全失败,不能再 - // 启动新的 pending sibling 并用它遮蔽原始失败。 - let manifest_scheduler_blocked = matches!( - &manifest_state_before_schedule, - AutonomousManifestDagState::Completed - | AutonomousManifestDagState::Failed { .. } - ) || autonomous_registered_derived_visuals_block_manifest_scheduler_at( - &root, &runtime, - ); - let scheduled_ready_tasks = if manifest_scheduler_blocked { - Vec::new() - } else { - match schedule_autonomous_game_build_ready_tasks_at( + let autonomous_root_goal_contract_persisted = if agent_id + == GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID + && runtime.run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD + { + match autonomous_root_goal_contract_persisted_at( &root, &agent_id, &runtime.run_id, - 3, ) { - Ok(tasks) => tasks, - Err(error) => { - return fail_game_creator_agent_background_context_at( - &root, - &agent_id, - &session_id, - runtime, - &format!("调度自主构建 manifest 任务失败:{error}"), - ); - } - } - }; - let manifest_state = if matches!( - &manifest_state_before_schedule, - AutonomousManifestDagState::Failed { .. } - ) { - manifest_state_before_schedule - } else if scheduled_ready_tasks.is_empty() { - match autonomous_manifest_dag_state_at(&root) { Ok(value) => value, Err(error) => { return fail_game_creator_agent_background_context_at( @@ -912,68 +826,155 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( &agent_id, &session_id, runtime, - &format!("读取自主构建 manifest 等待屏障失败:{error}"), + &format!("读取自主构建根 Goal Contract 门失败:{error}"), ); } } } else { - AutonomousManifestDagState::InProgress + false }; - let manifest_parent_must_wait = matches!( - &manifest_state, - AutonomousManifestDagState::InProgress - | AutonomousManifestDagState::Failed { - has_active_children: true, - .. - } - ); - if manifest_parent_must_wait { - let blocker = - autonomous_game_build_completion_blocker_at_locked(&root, &runtime) - .unwrap_or_else(|| AgentRuntimeToolObservation { - tool: "runtime.autonomous_completion".to_string(), - status: "blocked".to_string(), - summary: "自主构建 manifest DAG 尚未完成".to_string(), - detail: Some("manifest 子任务仍在运行".to_string()), - }); - if let Err(error) = persist_waiting_autonomous_manifest_parent_context_at( + let autonomous_manifest_parent_can_wait = autonomous_root_goal_contract_persisted + && agent_id == GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID + && runtime.run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD + && !game_creator_agent_runtime_provider_action_batch_exists( &root, - &mut runtime, - &task, - &plan, - &mut observations, - loop_index, - &mut context_tracker, - blocker, + &agent_id, + &runtime.run_id, + ) + && supervisor_collaboration_policy_completion_blocker_at_locked( + &root, + &agent_id, + &runtime.run_id, + ) + .is_none() + && isolated_join_completion_blocker_at(&root, &agent_id, &runtime.run_id) + .is_none() + && static_delegate_completion_blocker_at(&root, &agent_id, &runtime.run_id) + .is_none(); + if autonomous_manifest_parent_can_wait { + let manifest_state_before_schedule = + match autonomous_manifest_dag_state_at(&root) { + Ok(value) => value, + Err(error) => { + return fail_game_creator_agent_background_context_at( + &root, + &agent_id, + &session_id, + runtime, + &format!("读取自主构建 manifest 等待屏障失败:{error}"), + ); + } + }; + // 已登记但损坏的派生视觉需要先由父 Run 规划修复,因此此时不再调度新的 + // manifest child;但已经持久化并运行的 child 仍是当前 DAG 的活跃工作, + // 父 Run 必须继续等待,不能提前结束。 + // 同理,已有失败任务时只能等待已在途 child 收束或立即安全失败,不能再 + // 启动新的 pending sibling 并用它遮蔽原始失败。 + let manifest_scheduler_blocked = matches!( + &manifest_state_before_schedule, + AutonomousManifestDagState::Completed + | AutonomousManifestDagState::Failed { .. } + ) + || autonomous_registered_derived_visuals_block_manifest_scheduler_at( + &root, &runtime, + ); + let scheduled_ready_tasks = if manifest_scheduler_blocked { + Vec::new() + } else { + match schedule_autonomous_game_build_ready_tasks_at( + &root, + &agent_id, + &runtime.run_id, + 3, + ) { + Ok(tasks) => tasks, + Err(error) => { + return fail_game_creator_agent_background_context_at( + &root, + &agent_id, + &session_id, + runtime, + &format!("调度自主构建 manifest 任务失败:{error}"), + ); + } + } + }; + let manifest_state = if matches!( + &manifest_state_before_schedule, + AutonomousManifestDagState::Failed { .. } ) { + manifest_state_before_schedule + } else if scheduled_ready_tasks.is_empty() { + match autonomous_manifest_dag_state_at(&root) { + Ok(value) => value, + Err(error) => { + return fail_game_creator_agent_background_context_at( + &root, + &agent_id, + &session_id, + runtime, + &format!("读取自主构建 manifest 等待屏障失败:{error}"), + ); + } + } + } else { + AutonomousManifestDagState::InProgress + }; + let manifest_parent_must_wait = matches!( + &manifest_state, + AutonomousManifestDagState::InProgress + | AutonomousManifestDagState::Failed { + has_active_children: true, + .. + } + ); + if manifest_parent_must_wait { + let blocker = + autonomous_game_build_completion_blocker_at_locked(&root, &runtime) + .unwrap_or_else(|| AgentRuntimeToolObservation { + tool: "runtime.autonomous_completion".to_string(), + status: "blocked".to_string(), + summary: "自主构建 manifest DAG 尚未完成".to_string(), + detail: Some("manifest 子任务仍在运行".to_string()), + }); + if let Err(error) = persist_waiting_autonomous_manifest_parent_context_at( + &root, + &mut runtime, + &task, + &plan, + &mut observations, + loop_index, + &mut context_tracker, + blocker, + ) { + return fail_game_creator_agent_background_context_at( + &root, + &agent_id, + &session_id, + runtime, + &format!("持久化 manifest 父 run 等待状态失败:{error}"), + ); + } + return AgentBackgroundTaskOutcome::WaitingForManifestTasks; + } + if let AutonomousManifestDagState::Failed { + failed_task_ids, .. + } = manifest_state + { return fail_game_creator_agent_background_context_at( &root, &agent_id, &session_id, runtime, - &format!("持久化 manifest 父 run 等待状态失败:{error}"), + &format!( + "自主构建 manifest 专业任务失败;failedTaskIds={}", + failed_task_ids.join(",") + ), ); } - return AgentBackgroundTaskOutcome::WaitingForManifestTasks; - } - if let AutonomousManifestDagState::Failed { - failed_task_ids, .. - } = manifest_state - { - return fail_game_creator_agent_background_context_at( - &root, - &agent_id, - &session_id, - runtime, - &format!( - "自主构建 manifest 专业任务失败;failedTaskIds={}", - failed_task_ids.join(",") - ), - ); } } } - } let mut resumed_provider_batch = if game_creator_agent_runtime_provider_action_batch_exists( &root, &agent_id, @@ -1706,7 +1707,9 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( &agent_id, &runtime.run_id, ) - .or_else(|| process_session_completion_blocker_at(&root, &agent_id, &runtime.run_id)) + .or_else(|| { + process_session_completion_blocker_at(&root, &agent_id, &runtime.run_id) + }) .or_else(|| autonomous_game_build_completion_blocker_at_locked(&root, &runtime)) } else { structured_plan_completion_blocker(&runtime) @@ -1731,7 +1734,9 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( .or_else(|| { game_creator_agent_goal_completion_blocker_at_locked(&root, &runtime) }) - .or_else(|| goal_contract_acceptance_completion_blocker_at_locked(&root, &runtime)) + .or_else(|| { + goal_contract_acceptance_completion_blocker_at_locked(&root, &runtime) + }) .or_else(|| { supervisor_collaboration_policy_completion_blocker_at_locked( &root, @@ -1790,26 +1795,22 @@ async fn run_game_creator_agent_background_task_pass_without_deadline( match art_wait_state { AutonomousCodePrototypeArtAssetWaitState::Waiting => { let next_loop_index = loop_index.saturating_add(1); - if let Err(error) = - persist_waiting_autonomous_manifest_child_context_at( - &root, - &mut runtime, - &task, - &plan, - &mut observations, - next_loop_index, - &mut context_tracker, - blocker, - ) - { + if let Err(error) = persist_waiting_autonomous_manifest_child_context_at( + &root, + &mut runtime, + &task, + &plan, + &mut observations, + next_loop_index, + &mut context_tracker, + blocker, + ) { return fail_game_creator_agent_background_context_at( &root, &agent_id, &session_id, runtime, - &format!( - "持久化 code-prototype 美术依赖等待状态失败:{error}" - ), + &format!("持久化 code-prototype 美术依赖等待状态失败:{error}"), ); } return AgentBackgroundTaskOutcome::WaitingForManifestTasks; diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/provider_recovery.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/provider_recovery.rs index 8e3368d3e..bc2ffdc35 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/provider_recovery.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/provider_recovery.rs @@ -178,13 +178,13 @@ async fn drive_waiting_autonomous_manifest_parent_wake_pass_with_budget( reconciliation_delay_ms: u64, request_deferred_rerun: bool, ) -> Result<(), String> { - if read_latest_game_creator_agent_runtime_task_by_run_id(root, agent_id, run_id)? - .is_some_and(|task| { + if read_latest_game_creator_agent_runtime_task_by_run_id(root, agent_id, run_id)?.is_some_and( + |task| { task.status == "running" && task.phase == "waiting-for-manifest-tasks" && autonomous_relaxed_run_profile(&task.run_profile) - }) - { + }, + ) { // Free-form autonomous runs never reconcile a manifest barrier. The // phase can only be legacy durable state, so make a bounded attempt to // resume it and leave any lane contention for the ordinary recovery @@ -317,7 +317,10 @@ pub(in crate::agent) fn autonomous_manifest_ready_task_waiting_child_record( && task.source == "agent-ready-task-scheduler" && task.run_profile == AGENT_RUNTIME_RUN_PROFILE_AUTONOMOUS_GAME_BUILD && task.parent_agent_id.as_deref() == Some(GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID) - && task.parent_run_id.as_deref().is_some_and(|value| !value.trim().is_empty()) + && task + .parent_run_id + .as_deref() + .is_some_and(|value| !value.trim().is_empty()) && task.delegation_id.is_none() } @@ -327,9 +330,9 @@ async fn drive_waiting_autonomous_manifest_child_wake_pass( run_id: &str, ) -> Result<(), String> { for _ in 0..AUTONOMOUS_MANIFEST_PARENT_WAKE_MAX_ATTEMPTS { - let Some(task) = read_latest_game_creator_agent_runtime_task_by_run_id( - root, agent_id, run_id, - )? else { + let Some(task) = + read_latest_game_creator_agent_runtime_task_by_run_id(root, agent_id, run_id)? + else { return Ok(()); }; if !autonomous_manifest_ready_task_waiting_child_record(&task) { @@ -1025,6 +1028,7 @@ fn read_raw_autonomous_manifest_parent_runtime_state_at( agent_id: &str, ) -> Result { let path = game_creator_agent_runtime_session_path(root, agent_id); + prepare_game_creator_private_path_for_read(&path, false, "项目任务图父 Runtime 原始状态")?; let content = fs::read_to_string(&path).map_err(|error| { format!( "读取项目任务图父 Runtime 原始状态失败:{}: {error}", @@ -1047,12 +1051,8 @@ fn write_raw_autonomous_manifest_parent_runtime_state_at( let parent = path .parent() .ok_or_else(|| "项目任务图父 Runtime 状态路径缺少父目录".to_string())?; - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建项目任务图父 Runtime 状态目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, "项目任务图父 Runtime 状态目录")?; + prepare_game_creator_private_path_for_read(parent, true, "项目任务图父 Runtime 状态目录")?; let content = serde_json::to_string_pretty(state) .map_err(|error| format!("序列化项目任务图父 Runtime 状态失败:{error}"))?; let temp_path = path.with_file_name(format!( @@ -1063,12 +1063,11 @@ fn write_raw_autonomous_manifest_parent_runtime_state_at( std::process::id(), unix_timestamp_nanos() )); - fs::write(&temp_path, format!("{content}\n")).map_err(|error| { - format!( - "写入项目任务图父 Runtime 临时状态失败:{}: {error}", - temp_path.display() - ) - })?; + crate::write_game_creator_private_file( + &temp_path, + format!("{content}\n").as_bytes(), + "项目任务图父 Runtime 临时状态", + )?; fs::rename(&temp_path, &path).map_err(|error| { let _ = fs::remove_file(&temp_path); format!( @@ -1076,7 +1075,9 @@ fn write_raw_autonomous_manifest_parent_runtime_state_at( temp_path.display(), path.display() ) - }) + })?; + prepare_game_creator_private_path_for_read(&path, false, "项目任务图父 Runtime 原始状态")?; + Ok(()) } fn append_autonomous_manifest_parent_wake_reconciliation_task_at_locked( diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs index 97b563b19..4d06d8a7a 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/recovery_scan.rs @@ -1628,23 +1628,24 @@ pub(in crate::agent) fn resume_game_creator_agent_background_tasks_unredacted_at continue; } AutonomousCodePrototypeArtAssetWaitState::NotWaiting => { - let parent_agent_id = task.parent_agent_id.as_deref().ok_or_else(|| { - "code-prototype 等待态缺少 parentAgentId".to_string() - })?; - let parent_run_id = task.parent_run_id.as_deref().ok_or_else(|| { - "code-prototype 等待态缺少 parentRunId".to_string() - })?; + let parent_agent_id = task + .parent_agent_id + .as_deref() + .ok_or_else(|| "code-prototype 等待态缺少 parentAgentId".to_string())?; + let parent_run_id = task + .parent_run_id + .as_deref() + .ok_or_else(|| "code-prototype 等待态缺少 parentRunId".to_string())?; // The child execution lane is held by this recovery // scan. Release it before the parent scheduler tries // to reacquire the deterministic child lane. drop(runtime_lock); - let scheduled_ready_tasks = - schedule_autonomous_game_build_ready_tasks_at( - root, - parent_agent_id, - parent_run_id, - 3, - )?; + let scheduled_ready_tasks = schedule_autonomous_game_build_ready_tasks_at( + root, + parent_agent_id, + parent_run_id, + 3, + )?; if !scheduled_ready_tasks.is_empty() { resumed.push(read_game_creator_agent_runtime_at(root, &agent_id)?); } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/task_start.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/task_start.rs index b2bf942d2..45571d8c9 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/task_start.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_driver/task_start.rs @@ -817,12 +817,10 @@ fn autonomous_root_goal_contract_persisted_for_binding_at( root: &Path, binding: &AgentRuntimeRunProfileBinding, ) -> Result { - Ok(read_game_creator_agent_runtime_goal_contract_at( - root, - &binding.agent_id, - &binding.run_id, - )? - .is_some()) + Ok( + read_game_creator_agent_runtime_goal_contract_at(root, &binding.agent_id, &binding.run_id)? + .is_some(), + ) } /// Return whether the trusted autonomous root has a valid, persisted Goal @@ -1099,11 +1097,7 @@ fn queue_or_recover_autonomous_manifest_ready_task_at( result.accepted_run_id = Some(record.run_id.clone()); return Ok((result, (*record).clone(), true)); } - let run_id = format!( - "autonomous-ready-{}-{}", - task.id, - unix_timestamp_nanos() - ); + let run_id = format!("autonomous-ready-{}-{}", task.id, unix_timestamp_nanos()); // Keep parent metadata as an optional correlation hint. Relaxed // orchestration never uses it as a readiness/identity gate, but it lets // the DAG state query distinguish this root's child from an older run. @@ -1222,16 +1216,13 @@ pub(crate) fn schedule_autonomous_game_build_ready_tasks_at( // status change makes subsequent passes ignore it. match existing { None => candidates.push((task.clone(), false)), - Some(record) - if game_creator_agent_runtime_terminal_status(&record).is_some() => - { + Some(record) if game_creator_agent_runtime_terminal_status(&record).is_some() => { terminal_records.push(record); } Some(_) => {} } } - for task_id in autonomous_manifest_ready_task_ids(&manifest.tasks, &parent_binding.source) - { + for task_id in autonomous_manifest_ready_task_ids(&manifest.tasks, &parent_binding.source) { if let Some(task) = manifest.tasks.iter().find(|task| task.id == task_id) { candidates.push((task.clone(), true)); } @@ -1504,7 +1495,9 @@ pub(in crate::agent) fn project_autonomous_manifest_ready_task_terminal_at_locke let manifest = read_manifest_for_project(root)?; let task_id = [state.task_id.trim(), state.agent_id.trim()] .into_iter() - .find(|candidate| !candidate.is_empty() && manifest.tasks.iter().any(|task| task.id == *candidate)); + .find(|candidate| { + !candidate.is_empty() && manifest.tasks.iter().any(|task| task.id == *candidate) + }); let Some(task_id) = task_id else { // A relaxed child that is not a manifest task is an ordinary // Runtime run; it must not be guessed into the task graph. @@ -1571,9 +1564,7 @@ pub(in crate::agent) fn project_autonomous_manifest_ready_task_terminal_at_locke { let status = match state.phase.as_str() { "completed" => GameCreationAppTaskStatus::Completed, - "failed" | "cancelled" | "budget-exhausted" => { - GameCreationAppTaskStatus::Failed - } + "failed" | "cancelled" | "budget-exhausted" => GameCreationAppTaskStatus::Failed, _ => return Ok(false), }; let manifest = read_manifest_for_project(root)?; @@ -1775,7 +1766,8 @@ pub(super) fn autonomous_manifest_ready_task_requires_visual_asset(task_id: &str fn render_autonomous_manifest_ready_task_owner_prompt(task: &GameCreationAppTaskState) -> String { let base = render_manifest_ready_task_background_prompt(task); let paths = autonomous_manifest_owner_artifact_paths(&task.id).join(", "); - let visual_usage_requirement = if task.id == "code-prototype" && editor_api_key_is_configured() { + let visual_usage_requirement = if task.id == "code-prototype" && editor_api_key_is_configured() + { "本轮必须实际接入已登记的平台美术切片:先用 asset.list 读取 assets/art-spritesheet-slices/manifest.json,再在 game/index.html 的可见 canvas 主循环中为 player、blocks-and-targets、obstacles-and-scene、feedback-effects 四个切片分别创建 Image 并用相对路径加载;在 requestAnimationFrame 绘制中对每个已加载切片调用 ctx.drawImage(image, dx, dy, dw, dh) 或九参数裁剪形式,目标区域必须可见且至少 32×32。只放置 /、只展示整张 assets/art-spritesheet.png、只写路径或只在注释中引用都不满足完成合同。" } else { "" @@ -1981,10 +1973,9 @@ mod tests { "art-director", &prompt )); - let art_asset_prompt = - render_autonomous_manifest_ready_task_background_prompt(&seed_task( - "art-asset-plan", - )); + let art_asset_prompt = render_autonomous_manifest_ready_task_background_prompt( + &seed_task("art-asset-plan"), + ); assert!(art_asset_prompt.contains("canvas.asset_generate")); assert!(art_asset_prompt.contains("asset.list")); assert!(art_asset_prompt.contains("file.write 写入 assets/manifest.art.json")); diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/autonomous_completion.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/autonomous_completion.rs index 455b56916..a1451e93a 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/autonomous_completion.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/autonomous_completion.rs @@ -60,8 +60,10 @@ pub(in crate::agent) fn autonomous_relaxed_run_at( { return Ok(autonomous_relaxed_run_profile(&binding.profile)); } - Ok(read_latest_game_creator_agent_runtime_task_by_run_id(root, agent_id, run_id)? - .is_some_and(|task| autonomous_relaxed_run_profile(&task.run_profile))) + Ok( + read_latest_game_creator_agent_runtime_task_by_run_id(root, agent_id, run_id)? + .is_some_and(|task| autonomous_relaxed_run_profile(&task.run_profile)), + ) } pub(crate) fn autonomous_game_build_root_run_active_at(root: &Path) -> bool { @@ -669,11 +671,11 @@ pub(in crate::agent) fn autonomous_code_prototype_art_asset_wait_state_at( .map(|task| task.status.clone()) .ok_or_else(|| "当前 seed manifest 缺少 art-asset-plan".to_string())?; match art_status { - GameCreationAppTaskStatus::Failed => Ok( - AutonomousCodePrototypeArtAssetWaitState::DependencyFailed( + GameCreationAppTaskStatus::Failed => { + Ok(AutonomousCodePrototypeArtAssetWaitState::DependencyFailed( "art-asset-plan 已失败,code-prototype 不能继续等待美术回执".to_string(), - ), - ), + )) + } GameCreationAppTaskStatus::Pending | GameCreationAppTaskStatus::Running | GameCreationAppTaskStatus::WaitingForConfirmation => { @@ -5398,12 +5400,10 @@ impl<'a> VisitJavascript<'a> for JavascriptCanvasVisualCollector<'_> { .static_property_name() .is_some_and(|name| name == "src") { - let Some((root, path)) = - javascript_expression_root_symbol_and_member_path( - member.object(), - self.scoping, - ) - else { + let Some((root, path)) = javascript_expression_root_symbol_and_member_path( + member.object(), + self.scoping, + ) else { oxc_ast_visit::walk::walk_assignment_expression(self, assignment); return; }; @@ -6655,7 +6655,7 @@ pub(in crate::agent) fn read_autonomous_evidence_file_at( Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(error) => return Err(format!("读取{label}元数据失败:{error}")), } - let (mut file, metadata) = open_project_snapshot_regular_file(&path, label)?; + let (mut file, metadata) = open_project_private_regular_file(&path, label)?; if metadata.len() > max_bytes { return Err(format!("{label}超过 {max_bytes} 字节上限")); } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/context_bundle.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/context_bundle.rs index f10caee1d..75ed45731 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/context_bundle.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/context_bundle.rs @@ -343,6 +343,7 @@ pub(crate) fn write_game_creator_agent_runtime_context_bundle( pub(in crate::agent) fn read_game_creator_agent_runtime_context_bundle_content( path: &Path, ) -> Result { + prepare_game_creator_private_path_for_read(path, false, "Agent Runtime context bundle")?; let mut options = fs::OpenOptions::new(); options.read(true); #[cfg(unix)] diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/json_sidecar.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/json_sidecar.rs index fa526579e..7b22c601d 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/json_sidecar.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/json_sidecar.rs @@ -17,8 +17,11 @@ pub(crate) fn remove_agent_runtime_json_sidecar_backup( Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => { Err(format!("{label} 恢复副本必须是普通文件")) } - Ok(_) => fs::remove_file(path) - .map_err(|error| format!("删除 {label} 恢复副本失败:{}: {error}", path.display())), + Ok(_) => { + crate::prepare_game_creator_private_path_for_read(path, false, label)?; + fs::remove_file(path) + .map_err(|error| format!("删除 {label} 恢复副本失败:{}: {error}", path.display())) + } Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(error) => Err(format!( "读取 {label} 恢复副本元数据失败:{}: {error}", @@ -53,10 +56,16 @@ where let primary_path = resolve_local_project_path(root, relative_path)?; let backup_path = agent_runtime_json_sidecar_backup_path(&primary_path); let (path, metadata) = match fs::symlink_metadata(&primary_path) { - Ok(metadata) => (primary_path, metadata), + Ok(metadata) => { + crate::prepare_game_creator_private_path_for_read(&primary_path, false, label)?; + (primary_path, metadata) + } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { match fs::symlink_metadata(&backup_path) { - Ok(metadata) => (backup_path, metadata), + Ok(metadata) => { + crate::prepare_game_creator_private_path_for_read(&backup_path, false, label)?; + (backup_path, metadata) + } Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(error) => { return Err(format!( @@ -137,10 +146,11 @@ where } let mut path = resolve_local_project_path(root, relative_path)?; if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建 {label} 目录失败:{}: {error}", parent.display()))?; + crate::ensure_game_creator_private_directory_tree(parent, label)?; + crate::prepare_game_creator_private_path_for_read(parent, true, label)?; } path = resolve_local_project_path(root, relative_path)?; + crate::prepare_game_creator_private_path_for_read(&path, false, label)?; if let Ok(metadata) = fs::symlink_metadata(&path) { if metadata.file_type().is_symlink() || !metadata.is_file() { return Err(format!("{label} 必须是普通文件")); @@ -163,12 +173,22 @@ where temp_options.custom_flags(libc::O_NOFOLLOW); temp_options.mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + temp_options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut temp_file = temp_options.open(&temp_path).map_err(|error| { format!( "创建 {label} 临时文件失败:{}: {error}", temp_path.display() ) })?; + if let Err(error) = crate::harden_new_game_creator_private_path(&temp_path, false, label) { + drop(temp_file); + let _ = fs::remove_file(&temp_path); + return Err(error); + } temp_file .write_all(content.as_bytes()) .and_then(|_| temp_file.sync_data()) @@ -184,6 +204,7 @@ where Ok(()) => { remove_agent_runtime_json_sidecar_backup(&backup_path, label)?; sync_agent_runtime_sidecar_parent(&path, label)?; + crate::prepare_game_creator_private_path_for_read(&path, false, label)?; Ok(()) } Err(replace_error) => { @@ -192,7 +213,13 @@ where Err(error) if error.kind() == std::io::ErrorKind::NotFound => { return match fs::rename(&temp_path, &path) { Ok(()) => remove_agent_runtime_json_sidecar_backup(&backup_path, label) - .and_then(|_| sync_agent_runtime_sidecar_parent(&path, label)), + .and_then(|_| sync_agent_runtime_sidecar_parent(&path, label)) + .and_then(|_| { + crate::prepare_game_creator_private_path_for_read( + &path, false, label, + ) + .map(|_| ()) + }), Err(retry_error) => { let _ = fs::remove_file(&temp_path); Err(format!( @@ -231,6 +258,7 @@ where Ok(()) => { remove_agent_runtime_json_sidecar_backup(&backup_path, label)?; sync_agent_runtime_sidecar_parent(&path, label)?; + crate::prepare_game_creator_private_path_for_read(&path, false, label)?; Ok(()) } Err(error) => { diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_storage.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_storage.rs index fba95f5d6..cfecae6f4 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_storage.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/planning_storage.rs @@ -3555,6 +3555,10 @@ fn ensure_planning_parent(path: &Path) -> Result<&Path, PlanningStorageError> { let parent = path .parent() .ok_or_else(|| PlanningStorageError::new("PLAN_INVALID_PATH", "规划文件缺少父目录"))?; + crate::ensure_game_creator_private_directory_tree(parent, "planning 父目录") + .map_err(|error| PlanningStorageError::new("PLAN_UNTRUSTED_PATH", error))?; + crate::prepare_game_creator_private_path_for_read(parent, true, "planning 父目录") + .map_err(|error| PlanningStorageError::new("PLAN_UNTRUSTED_PATH", error))?; // Create missing components one at a time. `create_dir_all` can follow a // directory symlink inserted between its internal component checks; the // explicit loop lets us reject every component immediately after creation. @@ -3650,6 +3654,8 @@ fn verify_regular_planning_file( path: &Path, label: &str, ) -> Result { + crate::prepare_game_creator_private_path_for_read(path, false, label) + .map_err(|error| PlanningStorageError::new("PLAN_UNTRUSTED_PATH", error))?; let metadata = fs::symlink_metadata(path) .map_err(|error| io_error(&format!("读取 {label} 元数据失败"), error))?; if planning_metadata_is_link_or_reparse(&metadata) || !metadata.is_file() { @@ -3810,11 +3816,17 @@ fn write_sync_new_file(path: &Path, bytes: &[u8], label: &str) -> Result<(), Pla .open(path) .map_err(|error| io_error(&format!("创建 {label} 临时文件失败"), error))?; #[cfg(windows)] + crate::prepare_game_creator_private_path_for_read(path, false, label) + .map_err(|error| PlanningStorageError::new("PLAN_UNTRUSTED_PATH", error))?; + #[cfg(windows)] crate::runner::validate_windows_regular_file_handle(&file, label) .map_err(|error| PlanningStorageError::new("PLAN_UNTRUSTED_PATH", error))?; file.write_all(bytes) .and_then(|_| file.sync_all()) .map_err(|error| io_error(&format!("写入 {label} 临时文件失败"), error))?; + #[cfg(windows)] + crate::prepare_game_creator_private_path_for_read(path, false, label) + .map_err(|error| PlanningStorageError::new("PLAN_UNTRUSTED_PATH", error))?; #[cfg(unix)] { use std::os::unix::fs::MetadataExt; diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/provider_control.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/provider_control.rs index 7d7ebc0f0..df2af105f 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/provider_control.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/provider_control.rs @@ -496,12 +496,13 @@ fn write_provider_reconciliation_diagnostic_in_dir( let directory = config_dir .join(PROVIDER_RECONCILIATION_DIAGNOSTIC_RELATIVE_ROOT) .join(&project_key); - fs::create_dir_all(&directory) - .map_err(|error| format!("创建本地 Provider 诊断目录失败:{error}"))?; + crate::ensure_game_creator_private_directory_tree(&directory, "本地 Provider 诊断目录")?; + crate::prepare_game_creator_private_path_for_read(&directory, true, "本地 Provider 诊断目录")?; let relative_path = format!( "{PROVIDER_RECONCILIATION_DIAGNOSTIC_RELATIVE_ROOT}/{project_key}/{request_key}.json" ); let path = directory.join(format!("{request_key}.json")); + crate::prepare_game_creator_private_path_for_read(&path, false, "本地 Provider 诊断")?; if let Ok(metadata) = fs::symlink_metadata(&path) { if metadata.file_type().is_symlink() || !metadata.is_file() { return Err("本地 Provider 诊断目标必须是普通文件".to_string()); @@ -550,6 +551,11 @@ fn write_provider_reconciliation_diagnostic_in_dir( )); } let temporary = path.with_file_name(format!(".{request_key}.tmp.{}", unix_timestamp_nanos())); + crate::prepare_game_creator_private_path_for_read( + &temporary, + false, + "本地 Provider 诊断临时文件", + )?; let mut options = fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] @@ -557,9 +563,21 @@ fn write_provider_reconciliation_diagnostic_in_dir( use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options .open(&temporary) .map_err(|error| format!("创建本地 Provider 诊断临时文件失败:{error}"))?; + if let Err(error) = + crate::harden_new_game_creator_private_path(&temporary, false, "本地 Provider 诊断临时文件") + { + drop(file); + let _ = fs::remove_file(&temporary); + return Err(error); + } if let Err(error) = file .write_all(content.as_bytes()) .and_then(|_| file.sync_data()) @@ -572,6 +590,7 @@ fn write_provider_reconciliation_diagnostic_in_dir( let _ = fs::remove_file(&temporary); return Err(format!("安装本地 Provider 诊断失败:{error}")); } + crate::prepare_game_creator_private_path_for_read(&path, false, "本地 Provider 诊断")?; Ok(relative_path) } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/real_e2e_checkpoint.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/real_e2e_checkpoint.rs index 16b519b90..154ba513a 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/real_e2e_checkpoint.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/real_e2e_checkpoint.rs @@ -305,8 +305,10 @@ impl AgentRuntimeRealE2eCheckpointAppData { .map_err(|_| ())?; crate::runner::validate_windows_regular_file_handle(&file, "real E2E 私有文件") .map_err(|_| ())?; - secure_windows_game_creator_path_for_current_user(&path, false, false) - .map_err(|_| ()) + secure_windows_game_creator_path_for_current_user_with_auto_elevation( + &path, false, false, + ) + .map_err(|_| ()) })(); if secured.is_err() { drop(file); diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/steering.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/steering.rs index 6ec369a4e..2a4831d9c 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/steering.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_protocol/steering.rs @@ -334,12 +334,15 @@ pub(in crate::agent) fn append_game_creator_agent_runtime_steer_record( ) -> Result<(), String> { let path = game_creator_agent_runtime_steer_ledger_path(root, &record.agent_id, &record.run_id); if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 Agent Runtime steer ledger 目录失败:{}: {error}", - parent.display() - ) - })?; + crate::ensure_game_creator_private_directory_tree( + parent, + "Agent Runtime steer ledger 目录", + )?; + crate::prepare_game_creator_private_path_for_read( + parent, + true, + "Agent Runtime steer ledger 目录", + )?; } if fs::symlink_metadata(&path) .ok() diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_state.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_state.rs index 2321d48a6..314de29b6 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_state.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_state.rs @@ -2181,12 +2181,8 @@ pub(crate) fn write_game_creator_agent_runtime_cancel_request( ) -> Result<(), String> { let path = game_creator_agent_runtime_cancel_path(root, agent_id, run_id); if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 Agent Runtime 取消目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, "Agent Runtime 取消目录")?; + prepare_game_creator_private_path_for_read(parent, true, "Agent Runtime 取消目录")?; } let payload = serde_json::json!({ "agentId": agent_id, @@ -2196,12 +2192,12 @@ pub(crate) fn write_game_creator_agent_runtime_cancel_request( }); let content = serde_json::to_string_pretty(&payload) .map_err(|error| format!("序列化 Agent Runtime 取消请求失败:{error}"))?; - fs::write(&path, format!("{content}\n")).map_err(|error| { - format!( - "写入 Agent Runtime 取消请求失败:{}: {error}", - path.display() - ) - }) + crate::write_game_creator_private_file( + &path, + format!("{content}\n").as_bytes(), + "Agent Runtime 取消请求", + )?; + Ok(()) } pub(super) fn write_non_terminal_isolated_child_cancel_tombstones_for_parent_at( @@ -2731,13 +2727,10 @@ pub(crate) fn write_game_creator_agent_runtime_state( } let path = game_creator_agent_runtime_session_path(root, &state.agent_id); if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 Agent Runtime 状态目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, "Agent Runtime 状态目录")?; + prepare_game_creator_private_path_for_read(parent, true, "Agent Runtime 状态目录")?; } + prepare_game_creator_private_path_for_read(&path, false, "Agent Runtime 状态")?; let content = serde_json::to_string_pretty(state) .map_err(|error| format!("序列化 Agent Runtime 状态失败:{error}"))?; let temp_path = path.with_file_name(format!( @@ -2748,12 +2741,36 @@ pub(crate) fn write_game_creator_agent_runtime_state( std::process::id(), unix_timestamp_nanos() )); - fs::write(&temp_path, format!("{content}\n")).map_err(|error| { + let mut temp_options = fs::OpenOptions::new(); + temp_options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + temp_options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut temp_file = temp_options.open(&temp_path).map_err(|error| { format!( - "写入 Agent Runtime 临时状态失败:{}: {error}", + "创建 Agent Runtime 临时状态失败:{}: {error}", temp_path.display() ) })?; + if let Err(error) = + harden_new_game_creator_private_path(&temp_path, false, "Agent Runtime 临时状态") + { + drop(temp_file); + let _ = fs::remove_file(&temp_path); + return Err(error); + } + temp_file + .write_all(format!("{content}\n").as_bytes()) + .and_then(|_| temp_file.sync_all()) + .map_err(|error| { + format!( + "写入 Agent Runtime 临时状态失败:{}: {error}", + temp_path.display() + ) + })?; + drop(temp_file); fs::rename(&temp_path, &path).map_err(|error| { let _ = fs::remove_file(&temp_path); format!( @@ -2761,7 +2778,9 @@ pub(crate) fn write_game_creator_agent_runtime_state( temp_path.display(), path.display() ) - }) + })?; + prepare_game_creator_private_path_for_read(&path, false, "Agent Runtime 状态")?; + Ok(()) } pub(super) fn append_game_creator_agent_runtime_event( @@ -2812,12 +2831,8 @@ pub(super) fn append_game_creator_agent_runtime_event_with_action( ) -> Result<(), String> { let path = game_creator_agent_runtime_event_path(root, &state.agent_id); if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 Agent Runtime 事件目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, "Agent Runtime 事件目录")?; + prepare_game_creator_private_path_for_read(parent, true, "Agent Runtime 事件目录")?; } let failure_detail = matches!( event_type, @@ -3342,18 +3357,18 @@ fn append_unique_game_creator_agent_runtime_task_with_initial_state( // strict/legacy profiles preserves their existing recovery behavior. if !autonomous_relaxed_run_profile(&record.run_profile) { if let Err(error) = ensure_autonomous_completion_contract_for_task_at(root, &record) { - let public_error = redact_agent_runtime_project_paths(root, &error, 500); - let failed = AgentRuntimeTaskRecord { - status: "failed".to_string(), - phase: "completion-contract-failed".to_string(), - current_action: "自主构建完成合同未能建立,任务未执行".to_string(), - terminal_detail: Some(public_error.clone()), - error: Some(public_error), - updated_at: unix_timestamp(), - ..record.clone() - }; - append_game_creator_agent_runtime_task_record_unlocked(root, &failed)?; - return Err(format!("自主构建完成合同建立失败,任务未执行:{error}")); + let public_error = redact_agent_runtime_project_paths(root, &error, 500); + let failed = AgentRuntimeTaskRecord { + status: "failed".to_string(), + phase: "completion-contract-failed".to_string(), + current_action: "自主构建完成合同未能建立,任务未执行".to_string(), + terminal_detail: Some(public_error.clone()), + error: Some(public_error), + updated_at: unix_timestamp(), + ..record.clone() + }; + append_game_creator_agent_runtime_task_record_unlocked(root, &failed)?; + return Err(format!("自主构建完成合同建立失败,任务未执行:{error}")); } } Ok(record) @@ -3489,12 +3504,8 @@ pub(super) fn append_game_creator_agent_runtime_task_record_unlocked( } let path = game_creator_agent_runtime_task_path(root, &record.agent_id); if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 Agent Runtime 任务目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, "Agent Runtime 任务目录")?; + prepare_game_creator_private_path_for_read(parent, true, "Agent Runtime 任务目录")?; } let line = serde_json::to_string(&record) .map_err(|error| format!("序列化 Agent Runtime 任务失败:{error}"))?; diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/skill_pack.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/skill_pack.rs index b8ec6932a..ee516df4e 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/skill_pack.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/skill_pack.rs @@ -275,8 +275,8 @@ pub(crate) fn read_agc_skill_resource( pub(crate) fn install_agc_skill_pack(isolated_os_home: &Path) -> Result { let manifest = validated_skill_pack_manifest()?; let skills_root = isolated_os_home.join(".agents").join("skills"); - std::fs::create_dir_all(&skills_root) - .map_err(|error| format!("创建隔离 AGC Skill 目录失败:{error}"))?; + crate::ensure_game_creator_private_directory_tree(&skills_root, "隔离 AGC Skill 目录")?; + crate::prepare_game_creator_private_path_for_read(&skills_root, true, "隔离 AGC Skill 目录")?; for entry in &manifest.skills { for relative in &entry.files { let bundled_path = format!("{}/{}", entry.name, relative.replace('\\', "/")); @@ -285,11 +285,18 @@ pub(crate) fn install_agc_skill_pack(isolated_os_home: &Path) -> Result Result { fn private_external_editor_api_credentials_from_file_at( path: &Path, ) -> Result, String> { - let metadata = match fs::symlink_metadata(path) { - Ok(metadata) => metadata, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => { - return Err(format!("读取本机陶泥儿开发者 Key 配置失败:{error}")); - } - }; - if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err("本机陶泥儿开发者 Key 配置必须是普通文件".to_string()); + if !crate::prepare_game_creator_private_path_for_read(path, false, "本机陶泥儿开发者 Key 文件")? + { + return Ok(None); } + let metadata = fs::symlink_metadata(path) + .map_err(|error| format!("读取本机陶泥儿开发者 Key 配置失败:{error}"))?; if metadata.len() > PRIVATE_EXTERNAL_EDITOR_API_KEY_MAX_BYTES { return Err("本机陶泥儿开发者 Key 配置过大,已拒绝读取".to_string()); } - #[cfg(windows)] - secure_windows_game_creator_path_for_current_user(path, false, false)?; - let content = fs::read_to_string(path) - .map_err(|error| format!("读取本机陶泥儿开发者 Key 配置失败:{error}"))?; + let content = crate::read_game_creator_private_file_to_string( + path, + "本机陶泥儿开发者 Key 配置", + PRIVATE_EXTERNAL_EDITOR_API_KEY_MAX_BYTES, + )?; let parsed = serde_json::from_str::(&content) .map_err(|_| "本机陶泥儿开发者 Key 配置格式无效,请重新登录客户端后重试".to_string())?; let api_key = normalize_external_editor_api_key(&parsed.api_key)?; @@ -162,6 +159,22 @@ fn private_external_editor_api_credentials_from_file_at( .as_deref() .unwrap_or(DEFAULT_CANVAS_SYNC_API_BASE_URL), )?; + let expected_fingerprint = format!("{:x}", Sha256::digest(api_base_url.as_bytes())); + let actual_fingerprint = path + .file_name() + .and_then(|value| value.to_str()) + .and_then(|value| { + value + .strip_prefix(PRIVATE_EXTERNAL_EDITOR_API_KEY_FILE_PREFIX) + .and_then(|value| value.strip_suffix(".json")) + }) + .filter(|value| value.len() == 16 && value.bytes().all(|byte| byte.is_ascii_hexdigit())) + .ok_or_else(|| "本机陶泥儿开发者 Key 文件名身份无效,请重新登录客户端后重试".to_string())?; + if !actual_fingerprint.eq_ignore_ascii_case(&expected_fingerprint[..16]) { + return Err( + "本机陶泥儿开发者 Key 文件身份与服务器地址不一致,请重新登录客户端后重试".to_string(), + ); + } Ok(Some(ExternalEditorApiCredentials { api_base_url, api_key, @@ -171,18 +184,13 @@ fn private_external_editor_api_credentials_from_file_at( fn unique_private_external_editor_api_credentials_at( directory: &Path, ) -> Result, String> { - let metadata = match fs::symlink_metadata(directory) { - Ok(metadata) => metadata, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => { - return Err(format!("读取本机陶泥儿开发者 Key 目录失败:{error}")); - } - }; - if metadata.file_type().is_symlink() || !metadata.is_dir() { - return Err("本机陶泥儿开发者 Key 目录必须是普通目录".to_string()); + if !crate::prepare_game_creator_private_path_for_read( + directory, + true, + "本机陶泥儿开发者 Key 目录", + )? { + return Ok(None); } - #[cfg(windows)] - secure_windows_game_creator_path_for_current_user(directory, true, false)?; let mut candidates = fs::read_dir(directory) .map_err(|error| format!("读取本机陶泥儿开发者 Key 目录失败:{error}"))? .filter_map(Result::ok) @@ -219,35 +227,15 @@ fn ensure_plain_private_external_editor_directory( path: &Path, label: &str, ) -> Result { - match fs::symlink_metadata(path) { - Ok(metadata) => { - if metadata.file_type().is_symlink() || !metadata.is_dir() { - return Err(format!("本机陶泥儿开发者凭据{label}必须是普通目录")); - } - Ok(false) - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - let created = match fs::create_dir(path) { - Ok(()) => true, - Err(create_error) if create_error.kind() == std::io::ErrorKind::AlreadyExists => { - false - } - Err(create_error) => { - return Err(format!( - "创建本机陶泥儿开发者凭据{label}失败:{create_error}" - )); - } - }; - let metadata = fs::symlink_metadata(path).map_err(|metadata_error| { - format!("读取本机陶泥儿开发者凭据{label}失败:{metadata_error}") - })?; - if metadata.file_type().is_symlink() || !metadata.is_dir() { - return Err(format!("本机陶泥儿开发者凭据{label}必须是普通目录")); - } - Ok(created) - } - Err(error) => Err(format!("读取本机陶泥儿开发者凭据{label}失败:{error}")), + let label = format!("本机陶泥儿开发者凭据{label}"); + let created = crate::ensure_game_creator_private_directory_tree(path, &label)?; + #[cfg(windows)] + if !created { + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, true, true, + )?; } + Ok(created) } /// Prepares the exact private directory before a one-time remote developer key @@ -264,15 +252,11 @@ fn prepare_private_external_editor_api_credentials_parent_dir_at( .parent() .ok_or_else(|| "本机陶泥儿开发者凭据配置缺少上级目录".to_string())?; ensure_plain_private_external_editor_directory(container, "上级目录")?; - let parent_created = ensure_plain_private_external_editor_directory(parent, "目录")?; + ensure_plain_private_external_editor_directory(parent, "目录")?; #[cfg(windows)] - if parent_created { - initialize_windows_game_creator_directory_owner_for_current_user(parent)?; - } else { - secure_windows_game_creator_path_for_current_user(parent, true, true)?; - } + secure_windows_game_creator_path_for_current_user_with_auto_elevation(parent, true, true)?; #[cfg(unix)] - if parent_created { + { use std::os::unix::fs::PermissionsExt; fs::set_permissions(parent, fs::Permissions::from_mode(0o700)) .map_err(|error| format!("收紧本机陶泥儿开发者凭据目录权限失败:{error}"))?; @@ -301,8 +285,19 @@ fn write_private_external_editor_api_credentials_at( if parent_metadata.file_type().is_symlink() || !parent_metadata.is_dir() { return Err("本机陶泥儿开发者 Key 目录必须是普通目录".to_string()); } - if path.exists() { - return Err("本机陶泥儿开发者 Key 已存在,拒绝覆盖".to_string()); + match fs::symlink_metadata(path) { + Ok(metadata) => { + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err( + "本机陶泥儿开发者 Key 目标必须是普通文件,不能是链接或其他对象".to_string(), + ); + } + return Err("本机陶泥儿开发者 Key 已存在,拒绝覆盖".to_string()); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(format!("读取本机陶泥儿开发者 Key 目标失败:{error}")); + } } let body = serde_json::to_string_pretty(&PrivateExternalEditorApiKeyFile { api_key: credentials.api_key.clone(), @@ -325,9 +320,19 @@ fn write_private_external_editor_api_credentials_at( use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options .open(&temporary) .map_err(|error| format!("创建本机陶泥儿开发者 Key 临时文件失败:{error}"))?; + crate::harden_new_game_creator_private_path(&temporary, false, "本机陶泥儿开发者 Key 临时文件") + .map_err(|error| { + let _ = fs::remove_file(&temporary); + format!("初始化本机陶泥儿开发者 Key 临时文件安全权限失败:{error}") + })?; let write_result = file .write_all(format!("{body}\n").as_bytes()) .and_then(|_| file.sync_all()); @@ -336,8 +341,6 @@ fn write_private_external_editor_api_credentials_at( let _ = fs::remove_file(&temporary); return Err(format!("写入本机陶泥儿开发者 Key 临时文件失败:{error}")); } - #[cfg(windows)] - initialize_windows_game_creator_file_owner_for_current_user(&temporary)?; match fs::hard_link(&temporary, path) { Ok(()) => { let _ = fs::remove_file(&temporary); @@ -353,7 +356,14 @@ fn write_private_external_editor_api_credentials_at( } } #[cfg(windows)] - secure_windows_game_creator_path_for_current_user(path, false, true)?; + if let Err(error) = + secure_windows_game_creator_path_for_current_user_with_auto_elevation(path, false, true) + { + let _ = fs::remove_file(path); + return Err(format!( + "复核本机陶泥儿开发者 Key 文件安全权限失败:{error}" + )); + } Ok(()) } @@ -474,11 +484,10 @@ pub(crate) fn upload_local_asset_at( let relative_path = format!("assets/uploads/{asset_id}-{safe_name}"); let absolute_path = root.join(&relative_path); if let Some(parent) = absolute_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建上传目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "上传目录")?; + prepare_game_creator_private_path_for_read(parent, true, "上传目录")?; } - fs::write(&absolute_path, bytes) - .map_err(|error| format!("写入上传文件失败:{}: {error}", absolute_path.display()))?; + crate::write_game_creator_private_file(&absolute_path, bytes, "上传文件")?; register_local_asset_entry( root, @@ -578,13 +587,11 @@ pub(crate) fn import_canvas_export_at( if !export_path.is_absolute() { return Err("画板导出 ZIP 路径必须是绝对路径".to_string()); } + crate::prepare_game_creator_user_selected_path_for_read(export_path, false, "画板导出 ZIP")?; let metadata = fs::symlink_metadata(export_path) .map_err(|error| format!("读取画板导出 ZIP 失败:{}: {error}", export_path.display()))?; - if metadata.file_type().is_symlink() { - return Err("画板导出 ZIP 不能是符号链接".to_string()); - } - if !metadata.is_file() { - return Err("画板导出路径必须是 ZIP 文件".to_string()); + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err("画板导出路径必须是普通 ZIP 文件".to_string()); } init_local_game_project_at(root, "local-project-draft", "未命名游戏原型")?; @@ -765,12 +772,10 @@ pub(crate) async fn sync_canvas_project_assets_at( ); let absolute_path = root.join(&local_path); if let Some(parent) = absolute_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建画板同步目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "画板同步目录")?; + prepare_game_creator_private_path_for_read(parent, true, "画板同步目录")?; } - fs::write(&absolute_path, &download.bytes).map_err(|error| { - format!("写入画板同步资产失败:{}: {error}", absolute_path.display()) - })?; + crate::write_game_creator_private_file(&absolute_path, &download.bytes, "画板同步资产")?; assets.push(register_local_asset_entry( root, &local_path, @@ -1523,13 +1528,18 @@ pub(crate) fn extract_canvas_export_zip_files( let local_relative_path = format!("{import_relative_root}/{normalized_relative}"); let target_path = resolve_local_project_path(root, &local_relative_path)?; if let Some(parent) = target_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建画板导入目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "画板导入目录")?; + prepare_game_creator_private_path_for_read(parent, true, "画板导入目录")?; } - let mut output = File::create(&target_path) - .map_err(|error| format!("写入画板导入文件失败:{}: {error}", target_path.display()))?; - std::io::copy(&mut entry, &mut output) + let entry_size = entry.size(); + let mut bytes = Vec::with_capacity(entry_size.min(MAX_CANVAS_EXPORT_BYTES as u64) as usize); + std::io::Read::take(&mut entry, entry_size + 1) + .read_to_end(&mut bytes) .map_err(|error| format!("解压画板导出文件失败:{}: {error}", target_path.display()))?; + if bytes.len() as u64 != entry_size { + return Err("画板导出 ZIP 条目读取长度不一致".to_string()); + } + crate::write_game_creator_private_file(&target_path, &bytes, "画板导入文件")?; copied_files.push(normalized_relative); } if copied_files.is_empty() { @@ -1807,11 +1817,16 @@ mod tests { { let root = tempfile::tempdir().expect("temp dir"); let directory = root.path().join("config").join("genarrative"); - let first_path = directory.join("external-editor-api-0000000000000001.json"); let first = ExternalEditorApiCredentials { api_base_url: "https://dev.genarrative.world".to_string(), api_key: "tnr_sk_headless_fixture_1".to_string(), }; + let first_path = directory.join( + private_external_editor_api_key_path_for_base_url(&first.api_base_url) + .expect("first credential path") + .file_name() + .expect("first credential filename"), + ); write_private_external_editor_api_credentials_at(&first_path, &first) .expect("write first private credential"); let recovered = unique_private_external_editor_api_credentials_at(&directory) @@ -1820,11 +1835,16 @@ mod tests { assert_eq!(recovered.api_base_url, first.api_base_url); assert_eq!(recovered.api_key, first.api_key); - let second_path = directory.join("external-editor-api-0000000000000002.json"); let second = ExternalEditorApiCredentials { api_base_url: "https://www.genarrative.world".to_string(), api_key: "tnr_sk_headless_fixture_2".to_string(), }; + let second_path = directory.join( + private_external_editor_api_key_path_for_base_url(&second.api_base_url) + .expect("second credential path") + .file_name() + .expect("second credential filename"), + ); write_private_external_editor_api_credentials_at(&second_path, &second) .expect("write second private credential"); let error = match unique_private_external_editor_api_credentials_at(&directory) { @@ -1856,11 +1876,17 @@ mod tests { #[test] fn newly_created_private_external_editor_credentials_directory_is_owned_by_token_user() { let root = tempfile::tempdir().expect("temp dir"); + let credential_file_name = + private_external_editor_api_key_path_for_base_url("https://dev.genarrative.world") + .expect("credential path") + .file_name() + .expect("credential filename") + .to_owned(); let path = root .path() .join("config") .join("genarrative") - .join("external-editor-api-test.json"); + .join(credential_file_name); prepare_private_external_editor_api_credentials_parent_dir_at(&path) .expect("prepare private credential directory"); @@ -1889,7 +1915,13 @@ mod tests { "fixture must reproduce the inherited ACL rejection" ); - let path = parent.join("external-editor-api-test.json"); + let credential_file_name = + private_external_editor_api_key_path_for_base_url("https://dev.genarrative.world") + .expect("credential path") + .file_name() + .expect("credential filename") + .to_owned(); + let path = parent.join(credential_file_name); prepare_private_external_editor_api_credentials_parent_dir_at(&path) .expect("current-user directory should be tightened locally before remote creation"); secure_windows_game_creator_path_for_current_user(&parent, true, false) diff --git a/apps/ai-game-creator-shell/src-tauri/src/browser/evidence.rs b/apps/ai-game-creator-shell/src-tauri/src/browser/evidence.rs index 080606981..2413530d0 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/browser/evidence.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/browser/evidence.rs @@ -1,4 +1,3 @@ -use std::fs; use std::io::Write; use std::path::{Component, Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -46,27 +45,20 @@ pub(super) fn validate_evidence_path(path: &Path) -> Result<(), String> { pub(super) fn prepare_evidence_root(path: &Path) -> Result<(), String> { validate_evidence_path(path)?; - if let Ok(metadata) = fs::symlink_metadata(path) { - if metadata.file_type().is_symlink() || !metadata.is_dir() { - return Err("evidenceRoot 必须是真实目录且不能是符号链接".to_string()); - } - } else { - fs::create_dir_all(path) - .map_err(|error| format!("创建浏览器证据目录失败:{}: {error}", path.display()))?; - } - let metadata = fs::symlink_metadata(path) - .map_err(|error| format!("读取浏览器证据目录失败:{}: {error}", path.display()))?; - if metadata.file_type().is_symlink() || !metadata.is_dir() { - return Err("evidenceRoot 必须是真实目录且不能是符号链接".to_string()); - } + crate::ensure_game_creator_private_directory_tree(path, "浏览器证据目录")?; + crate::prepare_game_creator_private_path_for_read(path, true, "浏览器证据目录")?; Ok(()) } pub(super) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> { let parent = path .parent() .ok_or_else(|| format!("证据文件缺少父目录:{}", path.display()))?; + crate::ensure_game_creator_private_directory_tree(parent, "浏览器证据目录")?; + crate::prepare_game_creator_private_path_for_read(parent, true, "浏览器证据目录")?; + crate::prepare_game_creator_private_path_for_read(path, false, "浏览器证据文件")?; let mut temporary = NamedTempFile::new_in(parent).map_err(|error| format!("创建证据临时文件失败:{error}"))?; + crate::harden_new_game_creator_private_path(temporary.path(), false, "浏览器证据临时文件")?; temporary .write_all(bytes) .map_err(|error| format!("写入证据临时文件失败:{error}"))?; @@ -77,6 +69,7 @@ pub(super) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> { temporary .persist(path) .map_err(|error| format!("保存证据文件失败:{}: {}", path.display(), error.error))?; + crate::prepare_game_creator_private_path_for_read(path, false, "浏览器证据文件")?; Ok(()) } diff --git a/apps/ai-game-creator-shell/src-tauri/src/cli.rs b/apps/ai-game-creator-shell/src-tauri/src/cli.rs index 662437973..cdb713d1e 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/cli.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/cli.rs @@ -4,6 +4,12 @@ const PREVIEW_SERVE_USAGE: &str = "用法:--preview-serve <本地项目绝对 #[derive(Debug, Eq, PartialEq)] pub(crate) enum CliCommand { + RepairPrivateAcl { + path: PathBuf, + target_user_sid: String, + authorization_nonce: String, + scope: String, + }, LlmStatus, PreviewServe { project_path: PathBuf, @@ -220,7 +226,10 @@ impl CliCommand { | Self::PlanGddDecide { project_path, .. } | Self::PreviewServe { project_path } | Self::AgentRun { project_path, .. } => Some((project_path, false)), - Self::LlmStatus | Self::RunnerStatus | Self::RunnerShutdownIfIdle => None, + Self::RepairPrivateAcl { .. } + | Self::LlmStatus + | Self::RunnerStatus + | Self::RunnerShutdownIfIdle => None, } } } @@ -312,7 +321,11 @@ pub(crate) fn game_creator_llm_status_lines(status: &GameCreatorLlmConfigStatus) let mut lines = vec![ format!("agent.mode={}", status.agent_mode), format!("llm.configured={}", status.configured), - format!("llm.apiKeyPresent={}", status.api_key_present), + format!( + "llm.accountCredentialState={}", + status.account_credential_state + ), + format!("llm.officialRouteLocked={}", status.official_route_locked), format!( "llm.baseUrl={}", status.base_url.as_deref().unwrap_or_default() @@ -341,8 +354,12 @@ pub(crate) fn game_creator_llm_status_lines(status: &GameCreatorLlmConfigStatus) agent.agent_id, agent.configured )); lines.push(format!( - "llm.agent.{}.apiKeyPresent={}", - agent.agent_id, agent.api_key_present + "llm.agent.{}.accountCredentialState={}", + agent.agent_id, agent.account_credential_state + )); + lines.push(format!( + "llm.agent.{}.officialRouteLocked={}", + agent.agent_id, agent.official_route_locked )); lines.push(format!( "llm.agent.{}.baseUrl={}", @@ -512,6 +529,33 @@ fn parse_cli_agent_goal_revision(value: &str, usage: &str) -> Result Result, String> { + if args.first().map(String::as_str) == Some("--repair-private-acl") { + if args.len() != 8 + || args[1].trim().is_empty() + || args[2] != "--target-user-sid" + || args[3].trim().is_empty() + || args[4] != "--authorization" + || args[5].trim().is_empty() + || args[6] != "--scope" + || !matches!(args[7].as_str(), "managed" | "user-selected") + { + return Err("用法:--repair-private-acl --target-user-sid --authorization <一次性授权票据> --scope ".to_string()); + } + let path = PathBuf::from(&args[1]); + if !path.is_absolute() { + return Err("AGC 私有 ACL 修复路径必须是绝对路径".to_string()); + } + #[cfg(not(windows))] + { + return Err("AGC 私有 ACL 修复仅支持 Windows".to_string()); + } + return Ok(Some(CliCommand::RepairPrivateAcl { + path, + target_user_sid: args[3].trim().to_string(), + authorization_nonce: args[5].trim().to_string(), + scope: args[7].trim().to_string(), + })); + } if args.first().map(String::as_str) == Some("--preview-serve") { if args.len() != 2 || args[1].trim().is_empty() { return Err(PREVIEW_SERVE_USAGE.to_string()); @@ -997,6 +1041,32 @@ fn serialize_agent_runtime_cli_payload(payload: &T) -> Resu pub(crate) fn run_cli_command(command: CliCommand) -> Result<(), String> { match command { + CliCommand::RepairPrivateAcl { + path, + target_user_sid, + authorization_nonce, + scope, + } => { + #[cfg(windows)] + { + let scope = parse_windows_acl_repair_scope(&scope)?; + consume_windows_acl_repair_authorization( + &path, + &target_user_sid, + &authorization_nonce, + scope, + )?; + repair_game_creator_private_acl_for_user_sid(&path, &target_user_sid) + } + #[cfg(not(windows))] + { + let _ = path; + let _ = target_user_sid; + let _ = authorization_nonce; + let _ = scope; + Err("AGC 私有 ACL 修复仅支持 Windows".to_string()) + } + } CliCommand::LlmStatus => { let status = check_game_creator_llm_config_from_config(); for line in game_creator_llm_status_lines(&status) { @@ -1677,6 +1747,23 @@ mod tests { assert_eq!(parsed["runtimes"][0]["state"]["status"], "running"); } + #[test] + fn repair_private_acl_requires_one_time_authorization() { + let error = parse_cli_command(&[ + "--repair-private-acl".to_string(), + if cfg!(windows) { + r"C:\Users\test\AppData\Local\Genarrative" + } else { + "/tmp/genarrative" + } + .to_string(), + "--target-user-sid".to_string(), + "S-1-5-21-test".to_string(), + ]) + .expect_err("ACL repair must not be callable without its one-time authorization"); + assert!(error.contains("--authorization"), "{error}"); + } + #[test] fn parses_preview_serve_without_runner_or_config() { let project_path = std::env::current_dir().expect("current directory"); diff --git a/apps/ai-game-creator-shell/src-tauri/src/command_exec.rs b/apps/ai-game-creator-shell/src-tauri/src/command_exec.rs index db05d7596..50a66217f 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/command_exec.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/command_exec.rs @@ -1124,15 +1124,18 @@ pub(crate) fn prepare_project_command_launch_spec( .map_err(|error| ProjectCommandError::new(ProjectCommandErrorStage::Preflight, error))?; let isolated_cache = resolve_local_project_path(root, ".agent/runtime/command-env/cache") .map_err(|error| ProjectCommandError::new(ProjectCommandErrorStage::Preflight, error))?; - fs::create_dir_all(&isolated_home) - .and_then(|()| fs::create_dir_all(&isolated_tmp)) - .and_then(|()| fs::create_dir_all(&isolated_cache)) - .map_err(|error| { - ProjectCommandError::new( - ProjectCommandErrorStage::Preflight, - format!("创建 command.exec 隔离目录失败:{error}"), - ) + for (path, label) in [ + (&isolated_home, "command.exec HOME 隔离目录"), + (&isolated_tmp, "command.exec 临时隔离目录"), + (&isolated_cache, "command.exec 缓存隔离目录"), + ] { + crate::ensure_game_creator_private_directory_tree(path, label).map_err(|error| { + ProjectCommandError::new(ProjectCommandErrorStage::Preflight, error) })?; + crate::prepare_game_creator_private_path_for_read(path, true, label).map_err(|error| { + ProjectCommandError::new(ProjectCommandErrorStage::Preflight, error) + })?; + } let mut environment = vec![ (OsString::from("CI"), OsString::from("1")), @@ -2065,13 +2068,13 @@ where let log_path = resolve_local_project_path(root, ".agent/logs/command.log") .map_err(|error| ProjectCommandError::new(ProjectCommandErrorStage::AuditLog, error))?; if let Some(parent) = log_path.parent() { - fs::create_dir_all(parent).map_err(|error| { - ProjectCommandError::new( - ProjectCommandErrorStage::AuditLog, - format!("创建 command.exec 日志目录失败:{error}"), - ) - })?; + crate::ensure_game_creator_private_directory_tree(parent, "command.exec 日志目录") + .map_err(|error| ProjectCommandError::new(ProjectCommandErrorStage::AuditLog, error))?; + crate::prepare_game_creator_private_path_for_read(parent, true, "command.exec 日志目录") + .map_err(|error| ProjectCommandError::new(ProjectCommandErrorStage::AuditLog, error))?; } + crate::prepare_game_creator_private_path_for_read(&log_path, false, "command.exec 命令日志") + .map_err(|error| ProjectCommandError::new(ProjectCommandErrorStage::AuditLog, error))?; let argument_bytes = serde_json::to_vec(&spec.arguments).unwrap_or_default(); let log_entry = format!( "{updated_at} command.exec program={} argsSha256={:x} argsCount={} cwd={} {status} exitCode={} timedOut={} durationMs={} sourceChanged={} verificationEligible={} sandboxBackend={} sandboxMode={} networkAccess={} sandboxProfileVersion={}\n{}\n", @@ -2093,17 +2096,17 @@ where launch_metadata.sandbox_profile_version, process.output, ); - fs::OpenOptions::new() - .create(true) - .append(true) - .open(&log_path) - .and_then(|mut file| file.write_all(log_entry.as_bytes())) - .map_err(|error| { - ProjectCommandError::new( - ProjectCommandErrorStage::AuditLog, - format!("command.exec 执行后写入命令日志失败,需要人工核对:{error}"), - ) - })?; + crate::append_game_creator_private_file( + &log_path, + log_entry.as_bytes(), + "command.exec 命令日志", + ) + .map_err(|error| { + ProjectCommandError::new( + ProjectCommandErrorStage::AuditLog, + format!("command.exec 执行后写入命令日志失败,需要人工核对:{error}"), + ) + })?; record_command_run( root, GameCreationAppCommandRunState { diff --git a/apps/ai-game-creator-shell/src-tauri/src/command_output.rs b/apps/ai-game-creator-shell/src-tauri/src/command_output.rs index 568c1d8f3..30ecac174 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/command_output.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/command_output.rs @@ -145,12 +145,8 @@ pub(crate) fn write_command_output_transcript_at( } let path = resolve_local_project_path(root, &transcript.output_ref)?; if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建 command.exec 输出 sidecar 目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, "command.exec 输出 sidecar 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "command.exec 输出 sidecar 目录")?; } let path = resolve_local_project_path(root, &transcript.output_ref)?; match fs::symlink_metadata(&path) { @@ -166,10 +162,13 @@ pub(crate) fn write_command_output_transcript_at( } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => { - return Err(format!( - "读取 command.exec 输出 sidecar 元数据失败:{}: {error}", - path.display() - )); + prepare_game_creator_private_path_for_read(&path, false, "command.exec 输出 sidecar") + .map_err(|repair_error| { + format!( + "读取 command.exec 输出 sidecar 元数据失败:{}: {error};自动提权修复未完成:{repair_error}", + path.display() + ) + })?; } } @@ -202,6 +201,13 @@ pub(crate) fn write_command_output_transcript_at( )); } }; + if let Err(error) = + harden_new_game_creator_private_path(&path, false, "command.exec 输出 sidecar") + { + drop(file); + let _ = fs::remove_file(&path); + return Err(error); + } file.write_all(&content).map_err(|error| { format!( "写入 command.exec 输出 sidecar 失败:{}: {error}", @@ -317,8 +323,9 @@ pub(crate) fn read_command_output_page_at( } fn read_command_output_transcript_file(path: &Path) -> Result { + prepare_game_creator_private_path_for_read(path, false, "command.exec 输出 sidecar")?; let (mut file, metadata) = - open_project_snapshot_regular_file(path, "command.exec 输出 sidecar")?; + open_project_private_regular_file(path, "command.exec 输出 sidecar")?; if metadata.len() > COMMAND_OUTPUT_TRANSCRIPT_MAX_BYTES as u64 { return Err(format!( "command.exec 输出 sidecar 超过 {} 字节上限", diff --git a/apps/ai-game-creator-shell/src-tauri/src/commands.rs b/apps/ai-game-creator-shell/src-tauri/src/commands.rs index 73221b283..5c564e9ca 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/commands.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/commands.rs @@ -165,8 +165,14 @@ fn validate_local_asset_import_requirements( } let mut total_size = 0u64; for source in source_paths { - let metadata = - fs::symlink_metadata(source.trim()).map_err(|_| "读取本地文件失败".to_string())?; + let path = Path::new(source.trim()); + // Run the explicit user-selection ACL preparation before any size/type + // preflight. On Windows, metadata traversal can itself fail with + // ERROR_ACCESS_DENIED; doing this only in the later import worker would + // leave the early validation path unable to reach the one-shot UAC + // repair entry. + crate::prepare_game_creator_user_selected_path_for_read(path, false, "本地导入文件")?; + let metadata = fs::symlink_metadata(path).map_err(|_| "读取本地文件失败".to_string())?; if metadata.file_type().is_symlink() || !metadata.is_file() { return Err("只能导入普通文件".to_string()); } @@ -282,12 +288,8 @@ pub(crate) fn create_automatic_local_game_project_at( if projects_root.as_os_str().is_empty() || !projects_root.is_absolute() { return Err("自动工作区根目录必须是绝对路径".to_string()); } - fs::create_dir_all(projects_root).map_err(|error| { - format!( - "创建自动工作区根目录失败:{}: {error}", - projects_root.display() - ) - })?; + ensure_game_creator_private_directory_tree(projects_root, "自动工作区根目录")?; + prepare_game_creator_private_path_for_read(projects_root, true, "自动工作区根目录")?; let metadata = fs::symlink_metadata(projects_root).map_err(|error| { format!( "读取自动工作区根目录失败:{}: {error}", @@ -306,6 +308,11 @@ pub(crate) fn create_automatic_local_game_project_at( match fs::create_dir(&project_root) { Ok(()) => { let result = (|| { + prepare_game_creator_private_path_for_read( + &project_root, + true, + "自动项目目录", + )?; enforce_project_permission_policy(&project_root, "project.create")?; let _lock = acquire_project_write_lock(&project_root, "project.create")?; init_local_game_project_at( @@ -377,6 +384,7 @@ pub(crate) fn is_local_project_directory_non_empty(project_path: String) -> Resu if project_path_has_control_chars(root) { return Err("项目目录不能包含控制字符".to_string()); } + crate::prepare_game_creator_project_root_for_read(root, true, "项目目录")?; if !root.exists() { return Ok(false); } @@ -405,6 +413,7 @@ pub(crate) fn inspect_local_project_directory( if project_path_has_control_chars(root) { return Err("项目目录不能包含控制字符".to_string()); } + crate::prepare_game_creator_project_root_for_read(root, true, "项目目录")?; let recent_run_trace = recent_game_creator_run_trace(root); let godot_project_root = discover_local_godot_project_root(root)?; Ok(LocalProjectDirectoryStatus { @@ -500,9 +509,14 @@ pub(crate) async fn pick_local_project_directory( else { return Ok(None); }; - path.into_path() - .map(|path| Some(path.to_string_lossy().into_owned())) - .map_err(|error| format!("读取项目目录失败:{error}")) + let path = path + .into_path() + .map_err(|error| format!("读取项目目录失败:{error}"))?; + // The native picker is the explicit user-selection boundary. Prepare the + // selected root before returning it so inspect/create/open never races the + // first ACL read. + crate::prepare_game_creator_project_root_for_read(&path, true, "用户选择项目目录")?; + Ok(Some(path.to_string_lossy().into_owned())) } #[tauri::command] @@ -521,9 +535,11 @@ pub(crate) async fn pick_local_file(app: tauri::AppHandle) -> Result Result<(), String> { + shutdown_game_creator_codex_app_servers()?; clear_external_agent_runner_platform_session(generation)?; clear_platform_session(generation); Ok(()) @@ -1901,14 +1919,30 @@ pub(crate) fn create_ui_design_resource( let relative_path = format!("ui/{resource_name}.json"); let absolute_path = resolve_local_project_path(root, &relative_path)?; if let Some(parent) = absolute_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建 UI 资源目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "UI 资源目录")?; + prepare_game_creator_private_path_for_read(parent, true, "UI 资源目录")?; } - if absolute_path.exists() { + if prepare_game_creator_private_path_for_read(&absolute_path, false, "UI 资源")? { return Err("UI 设计资源路径已存在,拒绝覆盖".to_string()); } - fs::write(&absolute_path, "") + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options + .open(&absolute_path) .map_err(|error| format!("创建 UI 资源失败:{}: {error}", absolute_path.display()))?; + if let Err(error) = harden_new_game_creator_private_path(&absolute_path, false, "UI 资源") { + drop(file); + let _ = fs::remove_file(&absolute_path); + return Err(error); + } + file.sync_all() + .map_err(|error| format!("同步 UI 资源失败:{}: {error}", absolute_path.display()))?; + drop(file); let asset = match register_local_asset_at( root, &relative_path, @@ -2123,6 +2157,7 @@ pub(crate) fn import_ui_editor_local_files( let mut total_size = 0u64; for source in source_paths { let path = Path::new(source.trim()); + crate::prepare_game_creator_user_selected_path_for_read(path, false, "本地图片")?; let metadata = fs::symlink_metadata(path).map_err(|e| format!("读取本地图片失败:{e}"))?; if metadata.file_type().is_symlink() || !metadata.is_file() { return Err("只能导入普通图片文件".to_string()); @@ -2203,6 +2238,7 @@ fn read_registered_ui_editor_font( return Err("项目资产不是受支持的字体候选".to_string()); } let target = resolve_local_project_path(root, &asset.local_path)?; + prepare_game_creator_private_path_for_read(&target, false, "项目字体")?; let metadata = fs::symlink_metadata(&target).map_err(|_| "读取项目字体失败".to_string())?; if metadata.file_type().is_symlink() || !metadata.is_file() { return Err("项目字体必须是普通文件".to_string()); @@ -2279,6 +2315,7 @@ pub(crate) fn import_ui_editor_local_fonts( let mut input_hashes = std::collections::BTreeSet::new(); for source in source_paths { let path = Path::new(source.trim()); + crate::prepare_game_creator_user_selected_path_for_read(path, false, "本地字体")?; let metadata = fs::symlink_metadata(path).map_err(|_| "读取本地字体失败".to_string())?; if metadata.file_type().is_symlink() || !metadata.is_file() { return Err("只能导入普通字体文件".to_string()); @@ -2337,7 +2374,8 @@ pub(crate) fn import_ui_editor_local_fonts( if !new_inputs.is_empty() { let font_root = root.join("assets/fonts"); - fs::create_dir_all(&font_root).map_err(|_| "创建项目字体目录失败".to_string())?; + ensure_game_creator_private_directory_tree(&font_root, "项目字体目录")?; + prepare_game_creator_private_path_for_read(&font_root, true, "项目字体目录")?; } // 字体批次同样是增量提交合同:已经复制并登记的字体在后续失败时保留。 let mut result = Vec::with_capacity(inputs.len()); @@ -2358,7 +2396,28 @@ pub(crate) fn import_ui_editor_local_fonts( validated.metadata.format.extension() ); let target = resolve_local_project_path(root, &relative_path)?; - fs::write(&target, &bytes).map_err(|_| "写入项目字体失败".to_string())?; + if prepare_game_creator_private_path_for_read(&target, false, "项目字体")? { + return Err(format!("项目字体目标已存在但未登记:{}", target.display())); + } + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options + .open(&target) + .map_err(|error| format!("写入项目字体失败:{}: {error}", target.display()))?; + if let Err(error) = harden_new_game_creator_private_path(&target, false, "项目字体") { + drop(file); + let _ = fs::remove_file(&target); + return Err(error); + } + file.write_all(&bytes) + .and_then(|_| file.sync_all()) + .map_err(|error| format!("写入项目字体失败:{}: {error}", target.display()))?; + drop(file); let registered = register_local_asset_entry( root, &relative_path, @@ -3380,6 +3439,7 @@ pub(crate) fn import_local_project_image_assets_for_agent( reject_sensitive_project_file_read(&normalized)?; reject_agent_local_image_source_path(&normalized)?; let source = resolve_local_project_path(root, &normalized)?; + prepare_game_creator_private_path_for_read(&source, false, "本地图片")?; let metadata = fs::symlink_metadata(&source).map_err(|_| format!("本地图片不存在:{normalized}"))?; if metadata.file_type().is_symlink() || !metadata.is_file() { @@ -3430,16 +3490,37 @@ pub(crate) fn import_local_project_image_assets_for_agent( }); continue; } - if target.exists() && source_path != local_path { + if target.exists() { + prepare_game_creator_private_path_for_read(&target, false, "目标图片")?; let existing_bytes = fs::read(&target).map_err(|_| "读取目标图片失败".to_string())?; if existing_bytes != bytes { return Err(format!("本地图片目标已存在且内容不同:{local_path}")); } } else { if let Some(parent) = target.parent() { - fs::create_dir_all(parent).map_err(|_| "创建本地图片导入目录失败".to_string())?; + ensure_game_creator_private_directory_tree(parent, "本地图片导入目录")?; + prepare_game_creator_private_path_for_read(parent, true, "本地图片导入目录")?; } - fs::write(&target, &bytes).map_err(|_| "写入本地图片失败".to_string())?; + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options + .open(&target) + .map_err(|error| format!("写入本地图片失败:{}: {error}", target.display()))?; + if let Err(error) = harden_new_game_creator_private_path(&target, false, "目标图片") + { + drop(file); + let _ = fs::remove_file(&target); + return Err(error); + } + file.write_all(&bytes) + .and_then(|_| file.sync_all()) + .map_err(|error| format!("写入本地图片失败:{}: {error}", target.display()))?; + drop(file); } let registered = register_local_asset_entry( root, @@ -3588,12 +3669,33 @@ pub(crate) async fn import_account_editor_assets_for_agent( continue; } if target.exists() { + prepare_game_creator_private_path_for_read(&target, false, "账户图片目标")?; return Err(format!("账户图片目标已存在但尚未登记:{local_path}")); } if let Some(parent) = target.parent() { - fs::create_dir_all(parent).map_err(|_| "创建账户图片导入目录失败".to_string())?; + ensure_game_creator_private_directory_tree(parent, "账户图片导入目录")?; + prepare_game_creator_private_path_for_read(parent, true, "账户图片导入目录")?; } - fs::write(&target, &bytes).map_err(|_| "写入账户图片失败".to_string())?; + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options + .open(&target) + .map_err(|error| format!("写入账户图片失败:{}: {error}", target.display()))?; + if let Err(error) = harden_new_game_creator_private_path(&target, false, "账户图片目标") + { + drop(file); + let _ = fs::remove_file(&target); + return Err(error); + } + file.write_all(&bytes) + .and_then(|_| file.sync_all()) + .map_err(|error| format!("写入账户图片失败:{}: {error}", target.display()))?; + drop(file); let (source_kind, canvas_project_id, generation_route) = match record.origin { AgentEditorAssetOrigin::AccountLibrary => ( GameCreationAppAssetSourceKind::Canvas, @@ -3695,9 +3797,31 @@ pub(crate) async fn import_ui_editor_remote_assets( for (asset, asset_id, media_type, local_path, bytes) in downloads { let target = resolve_local_project_path(root, &local_path)?; if let Some(parent) = target.parent() { - fs::create_dir_all(parent).map_err(|e| format!("创建导入目录失败:{e}"))?; + ensure_game_creator_private_directory_tree(parent, "平台素材导入目录")?; + prepare_game_creator_private_path_for_read(parent, true, "平台素材导入目录")?; } - fs::write(&target, &bytes).map_err(|e| format!("写入平台素材失败:{e}"))?; + if prepare_game_creator_private_path_for_read(&target, false, "平台素材")? { + return Err(format!("平台素材目标已存在但尚未登记:{local_path}")); + } + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options + .open(&target) + .map_err(|error| format!("写入平台素材失败:{e}", e = error))?; + if let Err(error) = harden_new_game_creator_private_path(&target, false, "平台素材") { + drop(file); + let _ = fs::remove_file(&target); + return Err(error); + } + file.write_all(&bytes) + .and_then(|_| file.sync_all()) + .map_err(|error| format!("写入平台素材失败:{error}"))?; + drop(file); let registered = register_local_asset_entry( root, &local_path, diff --git a/apps/ai-game-creator-shell/src-tauri/src/config.rs b/apps/ai-game-creator-shell/src-tauri/src/config.rs index 89d87e38b..c5160b1c6 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/config.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/config.rs @@ -1,5 +1,8 @@ use super::*; +pub(crate) const OFFICIAL_AGC_LLM_BASE_URL: &str = "https://router.genarrative.world/v1"; +pub(crate) const OFFICIAL_AGC_LLM_MODEL: &str = "gpt-5.6-sol"; + pub(crate) const GAME_CREATOR_LLM_AGENT_REASONING_EFFORT_DEFAULTS: [(&str, &str); 21] = [ (GAME_CREATOR_PROJECT_SUPERVISOR_AGENT_ID, "high"), ("planner", "high"), @@ -53,6 +56,9 @@ fn build_game_creator_platform_llm_config( llm: &GameCreatorLlmConfig, config_path: &str, ) -> Result { + if game_creator_official_llm_route_locked() { + return build_game_creator_official_platform_llm_config(llm); + } let api_kind = validate_game_creator_llm_web_search_config(llm, config_path)?; let api_key = trim_config_string(&llm.api_key).ok_or_else(|| llm_api_key_config_error(config_path))?; @@ -76,6 +82,33 @@ fn build_game_creator_platform_llm_config( .map_err(|error| format!("LLM 配置无效:{error}")) } +/// Normal AGC builds never receive a Router key. Direct Rust LLM helpers +/// (for example the UI editor/resource editor paths) therefore use the same +/// authenticated API-server proxy as the Codex app-server bridge. The +/// platform access token remains in this process only; it is never serialized +/// into the AGC config or passed to child processes. +fn build_game_creator_official_platform_llm_config( + llm: &GameCreatorLlmConfig, +) -> Result { + let session = current_platform_session() + .ok_or_else(|| "authentication-required: 请先登录陶泥儿账号".to_string())?; + let api_base_url = session.api_base_url.trim_end_matches('/'); + if api_base_url.is_empty() { + return Err("登录态缺少 API Server 地址".to_string()); + } + let proxy_base_url = format!("{api_base_url}/api/llm"); + LlmConfig::new( + LlmProvider::OpenAiCompatible, + proxy_base_url, + session.access_token, + OFFICIAL_AGC_LLM_MODEL.to_string(), + llm.request_timeout_ms, + llm.max_retries, + llm.retry_backoff_ms, + ) + .map_err(|error| format!("官方 AGC LLM 代理配置无效:{error}")) +} + pub(crate) fn game_creator_supports_anthropic_strict_tools( api_kind: LlmApiKind, base_url: &str, @@ -208,7 +241,8 @@ pub(crate) fn check_game_creator_llm_config_from_config() -> GameCreatorLlmConfi return GameCreatorLlmConfigStatus { agent_mode: default_game_creator_agent_mode(), configured: false, - api_key_present: false, + account_credential_state: "unavailable".to_string(), + official_route_locked: game_creator_official_llm_route_locked(), base_url: None, model: None, api_kind: DEFAULT_GAME_CREATOR_LLM_API_KIND.to_string(), @@ -304,8 +338,28 @@ fn check_game_creator_codex_config( ); let mut status = check_game_creator_llm_config_values(&app_config.llm, "llm"); status.agent_mode = app_config.agent_mode.clone(); - status.configured = cli_error.is_none() && global_route_error.is_none(); - status.error = cli_error.clone().or(global_route_error); + if game_creator_official_llm_route_locked() { + let account_ready = current_platform_session().is_some(); + status.account_credential_state = if account_ready { + "ready".to_string() + } else { + "login_required".to_string() + }; + status.official_route_locked = true; + // The status endpoint is safe metadata only. Never echo a legacy + // user-supplied URL/model that was present before the official route + // migration; expose the immutable route instead. + status.base_url = Some(OFFICIAL_AGC_LLM_BASE_URL.to_string()); + status.model = Some(OFFICIAL_AGC_LLM_MODEL.to_string()); + status.api_kind = DEFAULT_GAME_CREATOR_LLM_API_KIND.to_string(); + status.configured = cli_error.is_none() && global_route_error.is_none() && account_ready; + status.error = cli_error.clone().or(global_route_error).or_else(|| { + (!account_ready).then(|| "authentication-required: 请先登录陶泥儿账号".to_string()) + }); + } else { + status.configured = cli_error.is_none() && global_route_error.is_none(); + status.error = cli_error.clone().or(global_route_error); + } status.agents = game_creator_llm_agent_status_definitions() .iter() .map(|definition| { @@ -323,6 +377,15 @@ fn check_game_creator_codex_config( ); agent.configured = cli_error.is_none() && route_error.is_none(); agent.error = cli_error.clone().or(route_error); + if game_creator_official_llm_route_locked() { + agent.account_credential_state = status.account_credential_state.clone(); + agent.official_route_locked = true; + agent.base_url = Some(OFFICIAL_AGC_LLM_BASE_URL.to_string()); + agent.model = Some(OFFICIAL_AGC_LLM_MODEL.to_string()); + agent.api_kind = DEFAULT_GAME_CREATOR_LLM_API_KIND.to_string(); + agent.configured = status.configured; + agent.error = status.error.clone(); + } agent }) .collect(); @@ -396,9 +459,6 @@ pub(crate) fn check_game_creator_llm_config_values( let api_key = trim_config_string(&config.api_key); let base_url = trim_config_string(&config.base_url); let model = trim_config_string(&config.model); - let api_key_present = api_key - .as_ref() - .is_some_and(|value| !value.trim().is_empty()); let api_kind = validate_game_creator_llm_web_search_config(config, config_path); let error = api_kind.as_ref().err().cloned().or_else(|| { match (api_key.as_deref(), base_url.as_deref(), model.as_deref()) { @@ -429,7 +489,13 @@ pub(crate) fn check_game_creator_llm_config_values( GameCreatorLlmConfigStatus { agent_mode: GAME_CREATOR_AGENT_MODE_PROVIDER.to_string(), configured: error.is_none(), - api_key_present, + account_credential_state: if error.is_none() { + "not_required" + } else { + "unavailable" + } + .to_string(), + official_route_locked: game_creator_official_llm_route_locked(), base_url, model, api_kind: api_kind @@ -475,7 +541,8 @@ pub(crate) fn check_game_creator_agent_llm_config_values( agent_id: agent_id.to_string(), label: label.to_string(), configured: status.configured, - api_key_present: status.api_key_present, + account_credential_state: status.account_credential_state.clone(), + official_route_locked: status.official_route_locked, base_url: status.base_url, model: status.model, api_kind: status.api_kind, @@ -638,6 +705,1025 @@ fn validate_game_creator_runtime_config_dir_metadata( Ok(()) } +/// Checks every already-existing path component without following links. +/// `canonicalize` alone is insufficient here because it resolves a junction +/// before the caller gets a chance to apply the owner/DACL policy. +pub(crate) fn validate_game_creator_private_path_ancestors( + path: &Path, + label: &str, +) -> Result<(), String> { + if !path.is_absolute() { + return Err(format!("{label}必须是绝对路径")); + } + for ancestor in path.ancestors().collect::>().into_iter().rev() { + match fs::symlink_metadata(ancestor) { + Ok(metadata) => { + if metadata.file_type().is_symlink() { + return Err(format!( + "{label} 路径不能包含符号链接:{}", + ancestor.display() + )); + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(format!( + "{label} 路径不能包含 Windows reparse point:{}", + ancestor.display() + )); + } + } + if ancestor != path && !metadata.is_dir() { + return Err(format!( + "{label} 父路径必须是普通目录:{}", + ancestor.display() + )); + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(format!( + "读取 {label} 路径元数据失败:{}: {error}", + ancestor.display() + )); + } + } + } + Ok(()) +} + +/// Automatic ACL repair for managed paths is limited to objects AGC owns. A +/// separate, explicit user-selected scope below covers native picker/project +/// root results, including projects stored outside the current profile. +fn game_creator_private_path_allows_auto_elevation(path: &Path) -> bool { + if !path.is_absolute() + || path + .components() + .any(|component| matches!(component, std::path::Component::ParentDir)) + { + return false; + } + + let starts_with_path = |root: &Path| path == root || path.starts_with(root); + if game_creator_runtime_config_dir() + .as_deref() + .is_some_and(starts_with_path) + { + return true; + } + + if let Some(home) = std::env::var_os("USERPROFILE") + .or_else(|| std::env::var_os("HOME")) + .map(PathBuf::from) + .filter(|candidate| candidate.is_absolute()) + { + let credentials_root = home.join(".config").join("genarrative"); + if starts_with_path(&credentials_root) { + return true; + } + + // The Tauri release uses this stable per-user AppData directory. The + // elevated helper runs in a fresh process, so the in-memory runtime + // config-dir override is unavailable there; recognize the packaged + // path from the user's profile as well. + let packaged_app_data = home + .join("AppData") + .join("Local") + .join("world.genarrative.ai-game-creator"); + if starts_with_path(&packaged_app_data) { + return true; + } + } + + for environment_name in ["LOCALAPPDATA", "APPDATA"] { + if let Some(root) = std::env::var_os(environment_name) + .map(PathBuf::from) + .filter(|candidate| candidate.is_absolute()) + { + if starts_with_path(&root.join("world.genarrative.ai-game-creator")) { + return true; + } + } + } + + // A bare `.agent` component is not enough to authorize ownership repair: + // an arbitrary user-selected path can contain a directory with that name. + // An existing AGC marker establishes the managed project root, after + // which every regular descendant (for example `game/index.html`) is + // covered by the same repair boundary. New projects use the explicit + // project-root preparation entry below until their marker is written. + // Nested or unrelated `.agent` directories remain outside the boundary. + let agent_components = path + .components() + .filter_map(|component| match component { + std::path::Component::Normal(name) + if name.to_string_lossy().eq_ignore_ascii_case(".agent") => + { + Some(name.to_os_string()) + } + _ => None, + }) + .collect::>(); + if agent_components.len() > 1 { + return false; + } + + for project_root in path.ancestors() { + let root_metadata = match fs::symlink_metadata(project_root) { + Ok(metadata) => metadata, + Err(_) => continue, + }; + if root_metadata.file_type().is_symlink() || !root_metadata.is_dir() { + continue; + } + let agent_directory = project_root.join(".agent"); + let agent_metadata = match fs::symlink_metadata(&agent_directory) { + Ok(metadata) => metadata, + Err(_) => continue, + }; + let manifest_path = agent_directory.join("manifest.json"); + let manifest_metadata = match fs::symlink_metadata(&manifest_path) { + Ok(metadata) => metadata, + Err(_) => continue, + }; + if agent_metadata.file_type().is_symlink() + || !agent_metadata.is_dir() + || manifest_metadata.file_type().is_symlink() + || !manifest_metadata.is_file() + { + continue; + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if root_metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 + || agent_metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 + || manifest_metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 + { + continue; + } + } + + if let Some(agent_name) = agent_components.first() { + let Some(actual_agent_directory) = path.ancestors().find(|candidate| { + candidate + .file_name() + .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case(".agent")) + }) else { + continue; + }; + if actual_agent_directory != &agent_directory + || actual_agent_directory + .file_name() + .map(|name| name != agent_name) + .unwrap_or(true) + { + continue; + } + } + return true; + } + false +} + +/// A file-picker/project-root result is an explicit native user action. Once +/// the caller has crossed that boundary, a regular object may be repaired by +/// the one-shot UAC helper even when it lives outside the current profile +/// (projects are commonly stored on another drive). The normal +/// reparse/regular-object/ancestor-type checks still run before this predicate +/// is consulted, so links, junctions and non-regular objects never become +/// elevation targets. +#[cfg(windows)] +fn game_creator_user_selected_path_allows_auto_elevation(path: &Path) -> bool { + if !path.is_absolute() + || path + .components() + .any(|component| matches!(component, std::path::Component::ParentDir)) + { + return false; + } + // Never treat a drive/UNC root as a user file. This also prevents an + // unreadable ancestor walk from turning a picker selection into ownership + // repair of the entire volume root. A native picker can technically + // return Windows/Program Files paths, but taking ownership there would + // damage the operating system rather than repair an AGC user file. + if path.as_os_str().is_empty() || path.file_name().is_none() { + return false; + } + let normalized = path + .to_string_lossy() + .replace('/', "\\") + .trim_end_matches('\\') + .to_ascii_lowercase(); + for variable in [ + "WINDIR", + "PROGRAMFILES", + "PROGRAMFILES(X86)", + "PROGRAMDATA", + "COMMONPROGRAMFILES", + "COMMONPROGRAMFILES(X86)", + ] { + let Some(root) = std::env::var_os(variable).map(PathBuf::from) else { + continue; + }; + let root = root + .to_string_lossy() + .replace('/', "\\") + .trim_end_matches('\\') + .to_ascii_lowercase(); + if normalized == root || normalized.starts_with(&(root + "\\")) { + return false; + } + } + true +} + +#[cfg(windows)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum WindowsAclRepairScope { + Managed, + UserSelected, +} + +#[cfg(windows)] +impl WindowsAclRepairScope { + fn wire_name(self) -> &'static str { + match self { + Self::Managed => "managed", + Self::UserSelected => "user-selected", + } + } + + fn allows_path(self, path: &Path) -> bool { + match self { + Self::Managed => game_creator_private_path_allows_auto_elevation(path), + Self::UserSelected => game_creator_user_selected_path_allows_auto_elevation(path), + } + } +} + +#[cfg(windows)] +pub(crate) fn parse_windows_acl_repair_scope(value: &str) -> Result { + match value.trim() { + "managed" => Ok(WindowsAclRepairScope::Managed), + "user-selected" => Ok(WindowsAclRepairScope::UserSelected), + _ => Err("AGC ACL 修复 scope 无效".to_string()), + } +} + +/// Prepares a caller-selected AGC project root. The root itself has no +/// `.agent/manifest.json` yet during first initialization, so it cannot use +/// the marker-based auto-elevation predicate above. This explicit entry is +/// only called by project initialization and the Runner, where the path has +/// already been accepted as the workspace root; descendants remain subject +/// to the marker-based managed-root check. +pub(crate) fn prepare_game_creator_project_root_for_read( + path: &Path, + is_directory: bool, + label: &str, +) -> Result { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(error) => { + let detail = format!("读取 {label} 元数据失败:{}: {error}", path.display()); + #[cfg(windows)] + { + // A selected project root may be unreadable before the leaf + // metadata can be inspected. Keep the same explicit + // user-selected scope and one-shot UAC path used after the + // metadata check, while rejecting all paths outside the + // current profile. + let scope = if game_creator_user_selected_path_allows_auto_elevation(path) { + WindowsAclRepairScope::UserSelected + } else { + WindowsAclRepairScope::Managed + }; + if scope.allows_path(path) && windows_acl_error_may_need_elevation(&detail) { + return secure_windows_game_creator_path_for_current_user_with_auto_elevation_scoped( + path, + is_directory, + true, + scope, + ) + .map(|_| true) + .map_err(|repair_error| { + format!("{detail};自动提权修复未完成:{repair_error}") + }); + } + } + return Err(detail); + } + }; + if metadata.file_type().is_symlink() + || (is_directory && !metadata.is_dir()) + || (!is_directory && !metadata.is_file()) + { + return Err(format!( + "{label} 必须是普通{},不能是链接或其他对象:{}", + if is_directory { "目录" } else { "文件" }, + path.display() + )); + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(format!( + "{label} 不能是 Windows reparse point:{}", + path.display() + )); + } + // A project root is explicitly selected by the user before the AGC + // marker exists, so the managed-path predicate cannot identify it yet. + // Use the explicit user-selected scope for the root; this allows a + // project stored on another drive to be repaired while retaining the + // strict reparse/type checks above. + let scope = if game_creator_user_selected_path_allows_auto_elevation(path) { + WindowsAclRepairScope::UserSelected + } else { + WindowsAclRepairScope::Managed + }; + secure_windows_game_creator_path_for_current_user_with_auto_elevation_scoped( + path, + is_directory, + true, + scope, + )?; + } + #[cfg(not(windows))] + { + validate_game_creator_private_path_ancestors(path, label)?; + } + Ok(true) +} + +#[cfg(windows)] +fn validate_game_creator_private_path_ancestors_with_auto_elevation( + path: &Path, + label: &str, +) -> Result<(), String> { + validate_game_creator_private_path_ancestors_with_auto_elevation_scoped( + path, + label, + WindowsAclRepairScope::Managed, + ) +} + +#[cfg(windows)] +fn validate_game_creator_private_path_ancestors_with_auto_elevation_scoped( + path: &Path, + label: &str, + scope: WindowsAclRepairScope, +) -> Result<(), String> { + #[cfg(test)] + { + return validate_game_creator_private_path_ancestors(path, label); + } + #[cfg(not(test))] + { + let target_user_sid = current_windows_token_user_sid_string()?; + let mut attempted_targets = Vec::::new(); + loop { + match validate_game_creator_private_path_ancestors(path, label) { + Ok(()) => return Ok(()), + Err(error) + if scope.allows_path(path) && windows_acl_error_may_need_elevation(&error) => + { + let repair_target = windows_acl_repair_target(path, scope); + if attempted_targets + .iter() + .any(|target| target == &repair_target) + { + return Err(format!( + "{error};自动提权修复重复命中同一目标,拒绝继续重试:{}", + repair_target.display() + )); + } + attempted_targets.push(repair_target); + attempt_elevated_windows_acl_repair(path, &target_user_sid, scope).map_err( + |repair_error| format!("{error};自动提权修复未完成:{repair_error}"), + )?; + } + Err(error) => return Err(error), + } + } + } +} + +/// Creates a private directory tree one component at a time. `create_dir_all` +/// can follow a junction that appears between components, so every existing +/// and newly-created component is checked before the next one is touched. +pub(crate) fn ensure_game_creator_private_directory_tree( + path: &Path, + label: &str, +) -> Result { + #[cfg(windows)] + validate_game_creator_private_path_ancestors_with_auto_elevation(path, label)?; + #[cfg(not(windows))] + validate_game_creator_private_path_ancestors(path, label)?; + let mut missing = Vec::new(); + let mut current = path.to_path_buf(); + loop { + match fs::symlink_metadata(¤t) { + Ok(metadata) => { + if metadata.file_type().is_symlink() { + return Err(format!("{label} 不能包含符号链接:{}", current.display())); + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(format!( + "{label} 不能包含 Windows reparse point:{}", + current.display() + )); + } + } + if !metadata.is_dir() { + return Err(format!( + "{label} 父路径必须是普通目录:{}", + current.display() + )); + } + break; + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + missing.push(current.clone()); + current = current + .parent() + .ok_or_else(|| { + format!("{label} 没有可用于创建的现存父目录:{}", path.display()) + })? + .to_path_buf(); + } + Err(error) => { + return Err(format!( + "读取 {label} 元数据失败:{}: {error}", + current.display() + )); + } + } + } + + let created_target = missing.first().is_some_and(|created| created == path); + for directory in missing.into_iter().rev() { + let create_result = fs::create_dir(&directory); + match create_result { + Ok(()) => { + #[cfg(windows)] + if game_creator_private_path_allows_auto_elevation(&directory) { + secure_windows_game_creator_path_for_current_user_with_auto_elevation( + &directory, true, true, + )?; + } else { + secure_windows_game_creator_path_for_current_user_with_owner_policy( + &directory, true, true, true, + )?; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).map_err( + |error| format!("收紧 {label} 权限失败:{}: {error}", directory.display()), + )?; + } + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + // Another process won the create race. This object was not + // created by the current invocation, so it must go through + // the full existing-object owner/DACL gate before we touch + // any descendant. A type-only metadata check here would allow + // an attacker-created directory to become trusted. + prepare_game_creator_private_path_for_read(&directory, true, label)?; + } + #[cfg(windows)] + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::WouldBlock + ) || matches!(error.raw_os_error(), Some(5)) => + { + let parent = directory.parent().ok_or_else(|| { + format!("创建 {label} 失败:{}: {error}", directory.display()) + })?; + if game_creator_private_path_allows_auto_elevation(parent) { + secure_windows_game_creator_path_for_current_user_with_auto_elevation( + parent, true, true, + )?; + } else { + secure_windows_game_creator_path_for_current_user_with_owner_policy( + parent, true, true, true, + )?; + } + fs::create_dir(&directory).map_err(|retry_error| { + format!("创建 {label} 失败:{}: {retry_error}", directory.display()) + })?; + if game_creator_private_path_allows_auto_elevation(&directory) { + secure_windows_game_creator_path_for_current_user_with_auto_elevation( + &directory, true, true, + )?; + } else { + secure_windows_game_creator_path_for_current_user_with_owner_policy( + &directory, true, true, true, + )?; + } + } + Err(error) => { + return Err(format!( + "创建 {label} 失败:{}: {error}", + directory.display() + )); + } + } + let metadata = fs::symlink_metadata(&directory) + .map_err(|error| format!("复核 {label} 失败:{}: {error}", directory.display()))?; + if metadata.file_type().is_symlink() || !metadata.is_dir() { + return Err(format!("{label} 必须是普通目录:{}", directory.display())); + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(format!( + "{label} 不能是 Windows reparse point:{}", + directory.display() + )); + } + } + } + Ok(created_target) +} + +/// Hardens a directory or file that this invocation has just created. This +/// intentionally does not adopt an existing object: callers that discover an +/// existing path must go through `prepare_game_creator_private_path_for_read`, +/// which performs the strict owner/reparse/DACL checks and the controlled UAC +/// repair flow. Keeping the two paths separate prevents a race from turning +/// an attacker-owned object into an AGC-managed credential or sidecar file. +pub(crate) fn harden_new_game_creator_private_path( + path: &Path, + is_directory: bool, + label: &str, +) -> Result<(), String> { + if !path.is_absolute() { + return Err(format!("{label}必须是绝对路径")); + } + let metadata = fs::symlink_metadata(path) + .map_err(|error| format!("读取新建 {label} 元数据失败:{}: {error}", path.display()))?; + if metadata.file_type().is_symlink() + || (is_directory && !metadata.is_dir()) + || (!is_directory && !metadata.is_file()) + { + return Err(format!( + "新建 {label} 必须是普通{},不能是链接或其他对象:{}", + if is_directory { "目录" } else { "文件" }, + path.display() + )); + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(format!( + "新建 {label} 不能是 Windows reparse point:{}", + path.display() + )); + } + // A newly-created object normally inherits the creator's security + // descriptor. AGC-owned roots may request the one-shot UAC repair; + // a user-selected path is still hardened strictly after creation so + // a race cannot turn an attacker-owned object into a credential file. + if game_creator_private_path_allows_auto_elevation(path) { + secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, + is_directory, + true, + )?; + } else { + secure_windows_game_creator_path_for_current_user_with_owner_policy( + path, + is_directory, + true, + true, + )?; + } + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions( + path, + fs::Permissions::from_mode(if is_directory { 0o700 } else { 0o600 }), + ) + .map_err(|error| format!("收紧新建 {label} 权限失败:{}: {error}", path.display()))?; + } + Ok(()) +} + +/// Writes a regular AGC-managed file only after its parent and any existing +/// target have passed the private-path policy. The post-write check also +/// hardens a newly-created file, so inherited Windows ACLs cannot remain on a +/// file that was created by this process. +pub(crate) fn write_game_creator_private_file( + path: &Path, + bytes: &[u8], + label: &str, +) -> Result<(), String> { + if !path.is_absolute() { + return Err(format!("{label}必须是绝对路径")); + } + let parent = path.parent().ok_or_else(|| format!("{label}缺少父目录"))?; + ensure_game_creator_private_directory_tree(parent, label)?; + prepare_game_creator_private_path_for_read(parent, true, label)?; + let existed = prepare_game_creator_private_path_for_read(path, false, label)?; + + // Never write directly through the checked pathname. A pathname can be + // replaced after the preflight by another process (or by a junction/link + // attack). Create and harden a sibling temporary inode first, then link + // it into place without replacement. Existing targets are moved to a + // unique backup only after a second strict check; if installation fails, + // the original target is restored. + let file_name = path + .file_name() + .and_then(|value| value.to_str()) + .ok_or_else(|| format!("{label}文件名无效"))?; + let temporary = (0..8) + .map(|attempt| { + path.with_file_name(format!( + ".{file_name}.tmp-{}-{}-{attempt}", + std::process::id(), + uuid::Uuid::new_v4().simple() + )) + }) + .find(|candidate| { + matches!( + fs::symlink_metadata(candidate), + Err(error) if error.kind() == std::io::ErrorKind::NotFound + ) + }) + .ok_or_else(|| format!("创建 {label} 临时文件路径失败:目录中存在冲突残留"))?; + + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW).mode(0o600); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options.open(&temporary).map_err(|error| { + format!( + "创建 {label} 临时文件失败:{}: {error}", + temporary.display() + ) + })?; + if let Err(error) = harden_new_game_creator_private_path(&temporary, false, label) { + drop(file); + let _ = fs::remove_file(&temporary); + return Err(error); + } + let write_result = std::io::Write::write_all(&mut file, bytes).and_then(|_| file.sync_all()); + drop(file); + if let Err(error) = write_result { + let _ = fs::remove_file(&temporary); + return Err(format!( + "写入 {label} 临时文件失败:{}: {error}", + temporary.display() + )); + } + let backup = path.with_file_name(format!( + ".{file_name}.previous-{}-{}", + std::process::id(), + uuid::Uuid::new_v4().simple() + )); + if existed { + // Re-check immediately before moving the old target. Links and + // reparse points remain fail-closed; only a regular managed file may + // enter the recoverable replacement path. + if let Err(error) = prepare_game_creator_private_path_for_read(path, false, label) { + let _ = fs::remove_file(&temporary); + return Err(error); + } + if fs::symlink_metadata(&backup).is_ok() { + let _ = fs::remove_file(&temporary); + return Err(format!("{label}替换备份路径已存在,已拒绝覆盖")); + } + if let Err(error) = fs::rename(path, &backup) { + let _ = fs::remove_file(&temporary); + return Err(format!("准备替换 {label} 失败:{error}")); + } + } + + let install_result = fs::hard_link(&temporary, path).and_then(|_| fs::remove_file(&temporary)); + if let Err(error) = install_result { + let _ = fs::remove_file(&temporary); + if existed { + let _ = fs::rename(&backup, path); + } + return Err(format!("原子安装 {label} 失败:{error}")); + } + if let Err(error) = prepare_game_creator_private_path_for_read(path, false, label) { + if existed { + let _ = fs::remove_file(path); + let _ = fs::rename(&backup, path); + } else { + let _ = fs::remove_file(path); + } + return Err(format!("复核 {label} 失败:{error}")); + } + if existed { + fs::remove_file(&backup) + .map_err(|error| format!("回收 {label} 旧文件备份失败:{error}"))?; + } + Ok(()) +} + +/// Appends to a regular AGC-managed file while applying the same ACL policy +/// as replacement writes. This is used for human-readable logs and memory +/// journals whose append semantics are part of their existing contract. +pub(crate) fn append_game_creator_private_file( + path: &Path, + bytes: &[u8], + label: &str, +) -> Result<(), String> { + if !path.is_absolute() { + return Err(format!("{label}必须是绝对路径")); + } + let parent = path.parent().ok_or_else(|| format!("{label}缺少父目录"))?; + ensure_game_creator_private_directory_tree(parent, label)?; + prepare_game_creator_private_path_for_read(parent, true, label)?; + let existed = prepare_game_creator_private_path_for_read(path, false, label)?; + if existed { + let metadata = fs::symlink_metadata(path) + .map_err(|error| format!("读取 {label} 元数据失败:{}: {error}", path.display()))?; + if !metadata.is_file() { + return Err(format!("{label} 必须是普通文件")); + } + } + let mut options = fs::OpenOptions::new(); + options.write(true).append(true).read(true); + if !existed { + options.create_new(true); + } + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW).mode(0o600); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + const FILE_SHARE_READ: u32 = 0x0000_0001; + const FILE_SHARE_WRITE: u32 = 0x0000_0002; + const FILE_SHARE_DELETE: u32 = 0x0000_0004; + options + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE); + } + let mut file = options + .open(path) + .map_err(|error| format!("写入 {label} 失败:{}: {error}", path.display()))?; + let opened_metadata = file.metadata().map_err(|error| { + format!( + "读取 {label} 文件句柄元数据失败:{}: {error}", + path.display() + ) + })?; + if !opened_metadata.is_file() { + drop(file); + return Err(format!("{label} 必须是普通文件")); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if opened_metadata.nlink() != 1 { + drop(file); + return Err(format!("{label} 不能是硬链接")); + } + let path_metadata = fs::symlink_metadata(path) + .map_err(|error| format!("复核 {label} 路径失败:{}: {error}", path.display()))?; + if path_metadata.file_type().is_symlink() + || path_metadata.dev() != opened_metadata.dev() + || path_metadata.ino() != opened_metadata.ino() + { + drop(file); + return Err(format!("{label} 路径在安全打开期间发生替换")); + } + } + #[cfg(windows)] + crate::runner::validate_windows_regular_file_handle(&file, label)?; + if !existed { + if let Err(error) = harden_new_game_creator_private_path(path, false, label) { + drop(file); + let _ = fs::remove_file(path); + return Err(error); + } + } + use std::io::Write as _; + file.write_all(bytes) + .and_then(|_| file.sync_data()) + .map_err(|error| format!("写入 {label} 失败:{}: {error}", path.display()))?; + if existed { + prepare_game_creator_private_path_for_read(path, false, label)?; + } + Ok(()) +} + +/// Checks a private file/directory before the caller opens it. Windows ACL +/// failures must be handled before `OpenOptions::open`: an inherited DACL can +/// otherwise make the open fail before the strict verifier gets a chance to +/// request UAC repair. Missing leaves are returned as `false`; existing +/// objects are fully validated and, on Windows, repaired/re-validated through +/// the normal auto-elevation path. +pub(crate) fn prepare_game_creator_private_path_for_read( + path: &Path, + is_directory: bool, + label: &str, +) -> Result { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(error) => { + let detail = format!("读取 {label} 元数据失败:{}: {error}", path.display()); + #[cfg(windows)] + { + let result = if game_creator_private_path_allows_auto_elevation(path) { + secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, + is_directory, + true, + ) + } else { + secure_windows_game_creator_path_for_current_user(path, is_directory, true) + }; + return result.map(|_| true).map_err(|repair_error| { + if game_creator_private_path_allows_auto_elevation(path) { + format!("{detail};自动提权修复未完成:{repair_error}") + } else { + format!("{detail};严格私有权限校验未通过:{repair_error}") + } + }); + } + #[cfg(not(windows))] + return Err(detail); + } + }; + if metadata.file_type().is_symlink() + || (is_directory && !metadata.is_dir()) + || (!is_directory && !metadata.is_file()) + { + return Err(format!( + "{label} 必须是普通{},不能是链接或其他对象:{}", + if is_directory { "目录" } else { "文件" }, + path.display() + )); + } + // Metadata on the leaf can be readable while traversal of an ancestor is + // blocked by a foreign owner or inherited ACL. Give the managed object a + // single explicit repair opportunity before surfacing a permission error; + // links/reparse points have already been rejected above and therefore stay + // fail-closed. + #[cfg(windows)] + validate_game_creator_private_path_ancestors_with_auto_elevation(path, label)?; + #[cfg(not(windows))] + validate_game_creator_private_path_ancestors(path, label)?; + #[cfg(windows)] + if game_creator_private_path_allows_auto_elevation(path) { + secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, + is_directory, + true, + )?; + } else { + // User-selected external files are never silently adopted. Keep the + // strict owner/DACL check, but do not escalate an arbitrary path. + secure_windows_game_creator_path_for_current_user(path, is_directory, true)?; + } + Ok(true) +} + +/// Prepares a path returned by an explicit native file picker. On Windows, +/// owner/DACL failures on a regular selected object receive the same one-shot +/// UAC repair as AGC-managed files, including projects stored outside the +/// current profile. Reparse points, links, non-regular objects and ancestor +/// type conflicts are rejected before any repair attempt. +pub(crate) fn prepare_game_creator_user_selected_path_for_read( + path: &Path, + is_directory: bool, + label: &str, +) -> Result { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(error) => { + let detail = format!("读取 {label} 元数据失败:{}: {error}", path.display()); + #[cfg(windows)] + { + // Explicit native file-picker/project-root selections are + // bounded UAC targets even when the normal token cannot + // traverse far enough to read leaf metadata. The helper still + // re-validates owner, type and reparse state before changing + // anything. + if game_creator_user_selected_path_allows_auto_elevation(path) + && windows_acl_error_may_need_elevation(&detail) + { + return secure_windows_game_creator_path_for_current_user_with_auto_elevation_scoped( + path, + is_directory, + true, + WindowsAclRepairScope::UserSelected, + ) + .map(|_| true) + .map_err(|repair_error| { + format!("{detail};自动提权修复未完成:{repair_error}") + }); + } + } + return Err(detail); + } + }; + if metadata.file_type().is_symlink() + || (is_directory && !metadata.is_dir()) + || (!is_directory && !metadata.is_file()) + { + return Err(format!( + "{label} 必须是普通{},不能是链接或其他对象:{}", + if is_directory { "目录" } else { "文件" }, + path.display() + )); + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(format!( + "{label} 不能是 Windows reparse point:{}", + path.display() + )); + } + if game_creator_user_selected_path_allows_auto_elevation(path) { + validate_game_creator_private_path_ancestors_with_auto_elevation_scoped( + path, + label, + WindowsAclRepairScope::UserSelected, + )?; + secure_windows_game_creator_path_for_current_user_with_auto_elevation_scoped( + path, + is_directory, + true, + WindowsAclRepairScope::UserSelected, + )?; + } else { + validate_game_creator_private_path_ancestors(path, label)?; + secure_windows_game_creator_path_for_current_user(path, is_directory, true)?; + } + } + #[cfg(not(windows))] + { + validate_game_creator_private_path_ancestors(path, label)?; + } + Ok(true) +} + +/// Reads an AGC-managed private text file through a validated regular-file +/// handle. The pathname is used only for preflight/open identity checks; bytes +/// are read from the handle so a later rename cannot redirect the read. +pub(crate) fn read_game_creator_private_file_to_string( + path: &Path, + label: &str, + max_bytes: u64, +) -> Result { + let (mut file, metadata) = open_project_private_regular_file(path, label)?; + if metadata.len() > max_bytes { + return Err(format!("{label}过大,已拒绝读取:{}", path.display())); + } + let mut content = String::with_capacity(metadata.len() as usize); + file.read_to_string(&mut content) + .map_err(|error| format!("读取{label}失败:{}: {error}", path.display()))?; + let final_metadata = file + .metadata() + .map_err(|error| format!("复核{label}失败:{}: {error}", path.display()))?; + if final_metadata.len() != metadata.len() { + return Err(format!("{label}读取期间文件发生漂移:{}", path.display())); + } + Ok(content) +} + fn resolve_game_creator_runtime_config_dir( path: &Path, create_and_tighten: bool, @@ -645,18 +1731,23 @@ fn resolve_game_creator_runtime_config_dir( if !path.is_absolute() { return Err("客户端 AppData 配置目录必须是绝对路径".to_string()); } + #[cfg(windows)] + validate_game_creator_private_path_ancestors_with_auto_elevation( + path, + "客户端 AppData 配置目录", + )?; + #[cfg(not(windows))] + validate_game_creator_private_path_ancestors(path, "客户端 AppData 配置目录")?; let mut created = false; if create_and_tighten { match fs::symlink_metadata(path) { Ok(_) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => { if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|create_error| { - format!( - "创建客户端 AppData 配置父目录失败:{}: {create_error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree( + parent, + "客户端 AppData 配置父目录", + )?; } match fs::create_dir(path) { Ok(()) => created = true, @@ -691,8 +1782,31 @@ fn resolve_game_creator_runtime_config_dir( { Ok(()) => {} #[cfg(windows)] + Err(error) if !cfg!(test) && windows_acl_error_may_need_elevation(&error) => { + // Any existing private AppData directory that cannot be safely + // read is repaired through the one-shot elevated helper. This + // covers inherited ACLs and foreign owners while the earlier + // entry/reparse checks remain fail-closed. + let target_user_sid = current_windows_token_user_sid_string() + .map_err(|sid_error| format!("{error};读取当前用户 SID 失败:{sid_error}"))?; + attempt_elevated_windows_acl_repair( + path, + &target_user_sid, + WindowsAclRepairScope::Managed, + ) + .map_err(|repair_error| format!("{error};自动提权修复未完成:{repair_error}"))?; + validate_game_creator_runtime_config_dir_metadata(path, true, false)?; + return fs::canonicalize(path).map_err(|canonicalize_error| { + format!( + "ACL 修复后解析客户端 AppData 配置目录失败:{}: {canonicalize_error}", + path.display() + ) + }); + } + #[cfg(windows)] Err(error) - if create_and_tighten + if cfg!(test) + && create_and_tighten && !created && error.starts_with("Windows 安全对象不属于当前用户:") => { @@ -820,14 +1934,102 @@ pub(crate) fn secure_windows_game_creator_path_for_current_user( is_directory: bool, tighten: bool, ) -> Result<(), String> { - secure_windows_game_creator_path_for_current_user_with_owner_policy( + secure_windows_game_creator_path_for_user_sid_with_owner_policy( path, is_directory, tighten, false, + None, ) } +/// Strictly validates a Windows private object and, when its owner/DACL cannot +/// be used by the current account, performs one explicit UAC repair before +/// validating again. Reparse points and non-regular objects remain +/// fail-closed; a repaired regular object is reassigned to the current token +/// user and receives a private non-inherited DACL. +#[cfg(windows)] +pub(crate) fn secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path: &Path, + is_directory: bool, + tighten: bool, +) -> Result<(), String> { + secure_windows_game_creator_path_for_current_user_with_auto_elevation_scoped( + path, + is_directory, + tighten, + WindowsAclRepairScope::Managed, + ) +} + +/// Same strict verifier as the managed-path entry, but with an explicit scope +/// selected by the caller. This is used by file-picker imports only; the +/// scope is included in the one-shot UAC ticket and checked again by the +/// elevated child process. +#[cfg(windows)] +fn secure_windows_game_creator_path_for_current_user_with_auto_elevation_scoped( + path: &Path, + is_directory: bool, + tighten: bool, + scope: WindowsAclRepairScope, +) -> Result<(), String> { + #[cfg(test)] + { + // Unit tests must not trigger an interactive UAC prompt. The strict + // verifier remains directly testable. For an owner-correct object + // whose only defect is an inherited DACL, emulate the formal prepare + // entry's local tightening in-process; foreign-owner fixtures still + // fail closed because they cannot be reassigned without elevation. + return match secure_windows_game_creator_path_for_current_user(path, is_directory, tighten) + { + Ok(()) => Ok(()), + Err(error) + if scope.allows_path(path) + && windows_acl_error_may_need_elevation(&error) + && !error.contains("安全对象不属于当前用户") => + { + secure_windows_game_creator_path_for_current_user_with_owner_policy( + path, + is_directory, + true, + false, + ) + } + Err(error) => Err(error), + }; + } + #[cfg(not(test))] + { + let target_user_sid = current_windows_token_user_sid_string()?; + let mut attempted_targets = Vec::::new(); + loop { + match secure_windows_game_creator_path_for_current_user(path, is_directory, tighten) { + Ok(()) => return Ok(()), + Err(error) if windows_acl_error_may_need_elevation(&error) => { + if !scope.allows_path(path) { + return Err(error); + } + let repair_target = windows_acl_repair_target(path, scope); + if attempted_targets + .iter() + .any(|target| target == &repair_target) + { + return Err(format!( + "{error};自动提权修复重复命中同一目标,拒绝继续重试:{}", + repair_target.display() + )); + } + attempted_targets.push(repair_target); + attempt_elevated_windows_acl_repair(path, &target_user_sid, scope).map_err( + |repair_error| format!("{error};自动提权修复未完成:{repair_error}"), + )?; + } + Err(error) => return Err(error), + } + } + } +} + #[cfg(windows)] pub(crate) fn initialize_windows_game_creator_file_owner_for_current_user( path: &Path, @@ -845,6 +2047,447 @@ pub(crate) fn initialize_windows_game_creator_directory_owner_for_current_user( secure_windows_game_creator_path_for_current_user_with_owner_policy(path, true, true, true) } +/// Repairs an AGC-managed private object after an explicit UAC elevation. +/// Foreign-owned regular files/directories are deliberately reassigned to the +/// current token user here. The caller has already rejected links/reparse +/// points, and the final strict verification below is mandatory. +#[cfg(windows)] +pub(crate) fn repair_game_creator_private_acl_for_current_user(path: &Path) -> Result<(), String> { + let target_user_sid = current_windows_token_user_sid_string()?; + repair_game_creator_private_acl_for_user_sid(path, &target_user_sid) +} + +#[cfg(windows)] +fn current_windows_token_user_sid_string() -> Result { + use std::ffi::c_void; + + type Handle = *mut c_void; + type Sid = *mut c_void; + + #[repr(C)] + struct SidAndAttributes { + sid: Sid, + attributes: u32, + } + + #[repr(C)] + struct TokenUser { + user: SidAndAttributes, + } + + #[link(name = "advapi32")] + unsafe extern "system" { + fn OpenProcessToken(process: Handle, access: u32, token: *mut Handle) -> i32; + fn GetTokenInformation( + token: Handle, + information_class: u32, + information: *mut c_void, + information_length: u32, + return_length: *mut u32, + ) -> i32; + fn ConvertSidToStringSidW(sid: Sid, string_sid: *mut *mut u16) -> i32; + } + + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetCurrentProcess() -> Handle; + fn CloseHandle(handle: Handle) -> i32; + fn LocalFree(memory: *mut c_void) -> *mut c_void; + } + + const TOKEN_QUERY: u32 = 0x0000_0008; + const TOKEN_USER_CLASS: u32 = 1; + + let mut token = std::ptr::null_mut(); + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 + || token.is_null() + { + return Err(format!( + "读取 Windows 当前用户 token 失败:{}", + std::io::Error::last_os_error() + )); + } + let result = (|| { + let mut required = 0_u32; + unsafe { + GetTokenInformation( + token, + TOKEN_USER_CLASS, + std::ptr::null_mut(), + 0, + &mut required, + ); + } + if required == 0 { + return Err("读取 Windows 当前用户 SID 长度失败".to_string()); + } + let word_size = std::mem::size_of::(); + let mut token_buffer = vec![0_usize; (required as usize).div_ceil(word_size)]; + if unsafe { + GetTokenInformation( + token, + TOKEN_USER_CLASS, + token_buffer.as_mut_ptr().cast(), + required, + &mut required, + ) + } == 0 + { + return Err(format!( + "读取 Windows 当前用户 SID 失败:{}", + std::io::Error::last_os_error() + )); + } + let sid = unsafe { (*(token_buffer.as_ptr().cast::())).user.sid }; + if sid.is_null() { + return Err("Windows 当前用户 SID 无效".to_string()); + } + let mut string_sid = std::ptr::null_mut(); + if unsafe { ConvertSidToStringSidW(sid, &mut string_sid) } == 0 || string_sid.is_null() { + return Err(format!( + "转换 Windows 当前用户 SID 失败:{}", + std::io::Error::last_os_error() + )); + } + let mut length = 0_usize; + while unsafe { *string_sid.add(length) } != 0 { + length = length.saturating_add(1); + if length > 256 { + unsafe { LocalFree(string_sid.cast()) }; + return Err("Windows 当前用户 SID 长度无效".to_string()); + } + } + let value = String::from_utf16(unsafe { std::slice::from_raw_parts(string_sid, length) }) + .map_err(|_| "Windows 当前用户 SID 编码无效".to_string()); + unsafe { LocalFree(string_sid.cast()) }; + value + })(); + unsafe { CloseHandle(token) }; + result +} + +/// The elevated helper may run under administrator credentials that differ +/// from the original desktop user's token. Keep ownership and the private +/// DACL bound to the original TokenUser SID passed by the caller. +#[cfg(windows)] +pub(crate) fn repair_game_creator_private_acl_for_user_sid( + path: &Path, + target_user_sid: &str, +) -> Result<(), String> { + let metadata = fs::symlink_metadata(path) + .map_err(|error| format!("读取待修复私有对象失败:{}: {error}", path.display()))?; + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 + || metadata.file_type().is_symlink() + { + return Err("待修复私有对象不能是 Windows reparse point 或链接".to_string()); + } + if !metadata.is_dir() && !metadata.is_file() { + return Err("待修复私有对象必须是普通文件或目录".to_string()); + } + secure_windows_game_creator_path_for_user_sid_with_owner_policy( + path, + metadata.is_dir(), + true, + true, + Some(target_user_sid), + ) +} + +#[cfg(windows)] +pub(crate) fn windows_acl_error_may_need_elevation(error: &str) -> bool { + (error.contains("DACL") + || error.contains("权限") + || error.contains("error 5") + || error.contains("安全对象不属于当前用户") + || error.contains("启用 Windows") + || error.contains("特权") + || error.contains("1300")) + && !error.contains("链接") + && !error.contains("reparse") +} + +#[cfg(windows)] +fn windows_acl_repair_target(path: &Path, scope: WindowsAclRepairScope) -> PathBuf { + // A user-selected object is the only trusted identity in that scope. Do + // not widen it to an unreadable parent (which could be another user's + // profile or a protected system directory); the helper will validate the + // selected regular object itself and fail closed if traversal remains + // impossible. Managed paths have an established AGC root and may repair + // the first blocked ancestor so inherited ACLs can be fixed in one pass. + if matches!(scope, WindowsAclRepairScope::UserSelected) { + return path.to_path_buf(); + } + // Walk from the filesystem root towards the leaf. If traversal is denied + // on an ancestor, repairing the leaf cannot help because the elevated + // helper will hit the same ancestor before it can inspect the leaf. + for ancestor in path.ancestors().collect::>().into_iter().rev() { + match fs::symlink_metadata(ancestor) { + Ok(_) => {} + Err(error) + if error.kind() == std::io::ErrorKind::PermissionDenied + || error.raw_os_error() == Some(5) => + { + return ancestor.to_path_buf(); + } + Err(_) => {} + } + } + path.to_path_buf() +} + +#[cfg(windows)] +const WINDOWS_ACL_REPAIR_AUTHORIZATION_MAX_BYTES: u64 = 4 * 1024; + +#[cfg(windows)] +struct WindowsAclRepairAuthorizationCleanup { + path: PathBuf, + armed: bool, +} + +#[cfg(windows)] +impl WindowsAclRepairAuthorizationCleanup { + fn new(path: PathBuf) -> Self { + Self { path, armed: true } + } + + fn disarm(&mut self) { + self.armed = false; + } +} + +#[cfg(windows)] +impl Drop for WindowsAclRepairAuthorizationCleanup { + fn drop(&mut self) { + if self.armed { + let _ = fs::remove_file(&self.path); + } + } +} + +#[cfg(windows)] +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct WindowsAclRepairAuthorization { + path: String, + target_user_sid: String, + scope: String, + issued_at: u64, +} + +#[cfg(windows)] +fn windows_acl_repair_authorization_path(nonce: &str) -> Result { + let nonce = nonce.trim(); + if nonce.len() != 32 || !nonce.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err("AGC ACL 修复授权票据无效".to_string()); + } + let temporary_directory = std::env::temp_dir(); + if !temporary_directory.is_absolute() { + return Err("AGC ACL 修复临时目录必须是绝对路径".to_string()); + } + Ok(temporary_directory.join(format!(".genarrative-acl-repair-{nonce}.json"))) +} + +#[cfg(windows)] +fn create_windows_acl_repair_authorization( + path: &Path, + target_user_sid: &str, + scope: WindowsAclRepairScope, +) -> Result { + let nonce = uuid::Uuid::new_v4().simple().to_string(); + let authorization_path = windows_acl_repair_authorization_path(&nonce)?; + let payload = serde_json::to_vec(&WindowsAclRepairAuthorization { + path: path.to_string_lossy().into_owned(), + target_user_sid: target_user_sid.to_string(), + scope: scope.wire_name().to_string(), + issued_at: unix_timestamp(), + }) + .map_err(|error| format!("创建 AGC ACL 修复授权票据失败:{error}"))?; + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options.open(&authorization_path).map_err(|error| { + format!( + "创建 AGC ACL 修复授权票据文件失败:{}: {error}", + authorization_path.display() + ) + })?; + // The ticket is created in the per-user TEMP directory while the normal + // process is not elevated. Do not call the auto-elevation wrapper here: + // that wrapper itself creates a ticket and would recurse indefinitely when + // TEMP inherits a broad DACL. The strict owner-policy path can still + // tighten an owner-correct inherited ACL and rejects a foreign TEMP owner. + if let Err(error) = secure_windows_game_creator_path_for_current_user_with_owner_policy( + &authorization_path, + false, + true, + true, + ) { + drop(file); + let _ = fs::remove_file(&authorization_path); + return Err(format!("初始化 AGC ACL 修复授权票据安全权限失败:{error}")); + } + if let Err(error) = file.write_all(&payload).and_then(|_| file.sync_all()) { + drop(file); + let _ = fs::remove_file(&authorization_path); + return Err(format!("写入 AGC ACL 修复授权票据失败:{error}")); + } + drop(file); + Ok(nonce) +} + +#[cfg(windows)] +pub(crate) fn consume_windows_acl_repair_authorization( + path: &Path, + target_user_sid: &str, + nonce: &str, + scope: WindowsAclRepairScope, +) -> Result<(), String> { + if !scope.allows_path(path) { + return Err(format!( + "AGC ACL 修复目标不在当前用户允许的 {} 范围内:{}", + scope.wire_name(), + path.display() + )); + } + let authorization_path = windows_acl_repair_authorization_path(nonce)?; + let mut cleanup = WindowsAclRepairAuthorizationCleanup::new(authorization_path.clone()); + + // Open the ticket first with no sharing. The old path-metadata-first + // sequence left a replacement window between owner/DACL validation and + // the actual read. The exclusive handle pins the object while the + // descriptor is checked below and while its bytes are consumed. + use std::os::windows::fs::MetadataExt; + use std::os::windows::fs::OpenOptionsExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + use std::io::Read as _; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + let mut file = fs::OpenOptions::new() + .read(true) + .share_mode(0) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(&authorization_path) + .map_err(|error| format!("读取 AGC ACL 修复授权票据内容失败:{error}"))?; + crate::runner::validate_windows_regular_file_handle(&file, "AGC ACL 修复授权票据")?; + let opened_metadata = file + .metadata() + .map_err(|error| format!("读取 AGC ACL 修复授权票据句柄元数据失败:{error}"))?; + if opened_metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 + || !opened_metadata.is_file() + { + return Err("AGC ACL 修复授权票据必须是普通文件".to_string()); + } + if opened_metadata.len() > WINDOWS_ACL_REPAIR_AUTHORIZATION_MAX_BYTES { + return Err("AGC ACL 修复授权票据过大".to_string()); + } + // The elevated helper runs under an administrator token, so validate the + // ticket against the original desktop user's SID rather than the helper's + // current SID. This also rejects a ticket placed in TEMP by another user. + // This check deliberately happens after the exclusive open so the path + // descriptor cannot be swapped while it is being authorized. + secure_windows_game_creator_path_for_user_sid_with_owner_policy( + &authorization_path, + false, + true, + false, + Some(target_user_sid), + )?; + + let mut content = String::new(); + file.read_to_string(&mut content) + .map_err(|error| format!("读取 AGC ACL 修复授权票据内容失败:{error}"))?; + let final_metadata = file + .metadata() + .map_err(|error| format!("复核 AGC ACL 修复授权票据句柄元数据失败:{error}"))?; + if final_metadata.len() != opened_metadata.len() { + return Err("AGC ACL 修复授权票据读取期间发生漂移".to_string()); + } + let authorization = serde_json::from_str::(&content) + .map_err(|error| format!("AGC ACL 修复授权票据格式无效:{error}"))?; + if unix_timestamp().saturating_sub(authorization.issued_at) > 300 { + return Err("AGC ACL 修复授权票据已过期".to_string()); + } + if authorization.path != path.to_string_lossy() + || authorization.target_user_sid != target_user_sid + || authorization.scope != scope.wire_name() + { + return Err("AGC ACL 修复授权票据与目标不匹配".to_string()); + } + + // share_mode(0) intentionally keeps the ticket pinned during validation; + // release the handle before consuming the one-shot file. The cleanup + // guard retries removal on every failure path, while a successful removal + // disarms it to avoid a second delete attempt during unwinding. + drop(file); + fs::remove_file(&authorization_path) + .map_err(|error| format!("删除 AGC ACL 修复授权票据失败:{error}"))?; + cleanup.disarm(); + Ok(()) +} + +/// Starts a one-shot elevated copy of the current executable. The elevated +/// process performs only the allow-listed ACL repair command and exits with a +/// truthful status; UAC cancellation is never treated as success. +#[cfg(windows)] +fn attempt_elevated_windows_acl_repair( + path: &Path, + target_user_sid: &str, + scope: WindowsAclRepairScope, +) -> Result<(), String> { + if !scope.allows_path(path) { + return Err(format!( + "AGC ACL 提权目标不在当前用户允许的 {} 范围内:{}", + scope.wire_name(), + path.display() + )); + } + let executable = + std::env::current_exe().map_err(|error| format!("定位 AGC ACL 修复程序失败:{error}"))?; + if !executable.is_file() { + return Err("AGC ACL 修复程序不存在".to_string()); + } + let repair_path = windows_acl_repair_target(path, scope); + let nonce = create_windows_acl_repair_authorization(&repair_path, target_user_sid, scope)?; + let escaped_executable = executable.to_string_lossy().replace('\'', "''"); + let escaped_path = repair_path.to_string_lossy().replace('\'', "''"); + let escaped_target_user_sid = target_user_sid.replace('\'', "''"); + let escaped_nonce = nonce.replace('\'', "''"); + let script = format!( + "$ErrorActionPreference = 'Stop'; try {{ $p = Start-Process -Verb RunAs -Wait -PassThru -FilePath '{escaped_executable}' -ArgumentList @('--repair-private-acl','{escaped_path}','--target-user-sid','{escaped_target_user_sid}','--authorization','{escaped_nonce}','--scope','{}'); if ($null -eq $p) {{ exit 1223 }}; exit $p.ExitCode }} catch {{ exit 1223 }}", + scope.wire_name() + ); + use std::os::windows::process::CommandExt; + let status = std::process::Command::new("powershell.exe") + .args([ + "-NoProfile", + "-NonInteractive", + "-WindowStyle", + "Hidden", + "-Command", + script.as_str(), + ]) + .creation_flags(0x0800_0000) + .status() + .map_err(|error| format!("启动 AGC ACL 提权修复失败:{error}")); + let _ = windows_acl_repair_authorization_path(&nonce).and_then(|authorization_path| { + fs::remove_file(authorization_path).map_err(|error| error.to_string()) + }); + let status = status?; + if status.success() { + Ok(()) + } else { + Err(format!( + "AGC ACL 提权修复未成功(exit code {:?})", + status.code() + )) + } +} + #[cfg(windows)] pub(crate) fn windows_private_dacl_security_information( initialize_owner: bool, @@ -861,11 +2504,26 @@ pub(crate) fn windows_private_dacl_security_information( } else { 0 } - | if initialize_owner && !owner_matches { - OWNER_SECURITY_INFORMATION - } else { - 0 - } +} + +#[cfg(windows)] +fn windows_security_object_path(path: &Path) -> std::ffi::OsString { + use std::ffi::OsString; + + let raw = path.as_os_str().to_string_lossy(); + // GetNamedSecurityInfoW/SetNamedSecurityInfoW report ERROR_INVALID_NAME + // for ordinary absolute paths at the MAX_PATH boundary. Extended-length + // paths are accepted by these APIs and preserve the exact object identity. + // Do not add the prefix twice, and translate UNC paths to the documented + // \\?\UNC\server\share form. + if raw.starts_with("\\\\?\\") || raw.encode_utf16().count() < 260 { + return path.as_os_str().to_os_string(); + } + if let Some(unc) = raw.strip_prefix("\\\\") { + OsString::from(format!("\\\\?\\UNC\\{unc}")) + } else { + OsString::from(format!("\\\\?\\{raw}")) + } } #[cfg(windows)] @@ -874,10 +2532,57 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( is_directory: bool, tighten: bool, initialize_owner: bool, +) -> Result<(), String> { + secure_windows_game_creator_path_for_user_sid_with_owner_policy( + path, + is_directory, + tighten, + initialize_owner, + None, + ) +} + +#[cfg(windows)] +fn secure_windows_game_creator_path_for_user_sid_with_owner_policy( + path: &Path, + is_directory: bool, + tighten: bool, + initialize_owner: bool, + target_user_sid: Option<&str>, ) -> Result<(), String> { use std::ffi::c_void; use std::os::windows::ffi::OsStrExt; + let metadata = fs::symlink_metadata(path).map_err(|error| { + format!( + "读取 Windows 私有对象元数据失败:{}: {error}", + path.display() + ) + })?; + if metadata.file_type().is_symlink() { + return Err(format!( + "Windows 私有对象不能是符号链接:{}", + path.display() + )); + } + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(format!( + "Windows 私有对象不能是 reparse point:{}", + path.display() + )); + } + } + if (is_directory && !metadata.is_dir()) || (!is_directory && !metadata.is_file()) { + return Err(format!( + "Windows 私有对象类型不符合预期:{}", + path.display() + )); + } + validate_game_creator_private_path_ancestors(path, "Windows 私有对象")?; + type Handle = *mut c_void; type Sid = *mut c_void; @@ -932,6 +2637,24 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( sid_start: u32, } + #[repr(C)] + struct Luid { + low_part: u32, + high_part: i32, + } + + #[repr(C)] + struct LuidAndAttributes { + luid: Luid, + attributes: u32, + } + + #[repr(C)] + struct TokenPrivileges { + privilege_count: u32, + privileges: [LuidAndAttributes; 1], + } + #[link(name = "advapi32")] unsafe extern "system" { fn GetNamedSecurityInfoW( @@ -960,6 +2683,16 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( new_acl: *mut *mut c_void, ) -> u32; fn OpenProcessToken(process: Handle, access: u32, token: *mut Handle) -> i32; + fn LookupPrivilegeValueW(system_name: *const u16, name: *const u16, luid: *mut Luid) + -> i32; + fn AdjustTokenPrivileges( + token: Handle, + disable_all_privileges: i32, + new_state: *mut TokenPrivileges, + buffer_length: u32, + previous_state: *mut TokenPrivileges, + return_length: *mut u32, + ) -> i32; fn GetTokenInformation( token: Handle, information_class: u32, @@ -967,8 +2700,10 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( information_length: u32, return_length: *mut u32, ) -> i32; + fn ConvertStringSidToSidW(string_sid: *const u16, sid: *mut Sid) -> i32; fn EqualSid(first: Sid, second: Sid) -> i32; fn IsValidSid(sid: Sid) -> i32; + fn GetLengthSid(sid: Sid) -> u32; fn IsValidAcl(acl: *mut c_void) -> i32; fn GetAce(acl: *mut c_void, index: u32, ace: *mut *mut c_void) -> i32; fn GetSecurityDescriptorControl( @@ -983,6 +2718,7 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( fn GetCurrentProcess() -> Handle; fn CloseHandle(handle: Handle) -> i32; fn LocalFree(memory: *mut c_void) -> *mut c_void; + fn GetLastError() -> u32; } const SE_FILE_OBJECT: u32 = 1; @@ -990,7 +2726,10 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( const DACL_SECURITY_INFORMATION: u32 = 0x0000_0004; const SE_DACL_PROTECTED: u16 = 0x1000; const TOKEN_QUERY: u32 = 0x0000_0008; + const TOKEN_ADJUST_PRIVILEGES: u32 = 0x0000_0020; const TOKEN_USER_CLASS: u32 = 1; + const SE_PRIVILEGE_ENABLED: u32 = 0x0000_0002; + const ERROR_NOT_ALL_ASSIGNED: u32 = 1300; const SET_ACCESS: i32 = 2; const TRUSTEE_IS_SID: i32 = 0; const TRUSTEE_IS_USER: i32 = 1; @@ -1001,7 +2740,13 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( let mut token = std::ptr::null_mut(); // SAFETY: GetCurrentProcess returns a valid pseudo handle and token is a valid output pointer. - if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 + if unsafe { + OpenProcessToken( + GetCurrentProcess(), + TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, + &mut token, + ) + } == 0 || token.is_null() { return Err(format!( @@ -1010,6 +2755,7 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( )); } + let mut requested_user_sid = std::ptr::null_mut(); let result = (|| { let mut required = 0_u32; // SAFETY: the null query buffer is the documented size-probe call. @@ -1048,8 +2794,34 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( if current_user_sid.is_null() || unsafe { IsValidSid(current_user_sid) } == 0 { return Err("Windows 当前用户 SID 无效".to_string()); } + let target_user_sid = if let Some(target_user_sid) = target_user_sid { + let target_user_sid = target_user_sid.trim(); + if target_user_sid.is_empty() { + return Err("Windows ACL 修复目标 TokenUser SID 不能为空".to_string()); + } + let mut wide_target_user_sid = target_user_sid + .encode_utf16() + .chain(std::iter::once(0)) + .collect::>(); + if unsafe { + ConvertStringSidToSidW(wide_target_user_sid.as_mut_ptr(), &mut requested_user_sid) + } == 0 + || requested_user_sid.is_null() + || unsafe { IsValidSid(requested_user_sid) } == 0 + { + return Err("Windows ACL 修复目标 TokenUser SID 无效".to_string()); + } + requested_user_sid + } else { + current_user_sid + }; - let mut wide_path = path + // Security APIs otherwise reject a perfectly valid private sidecar at + // the MAX_PATH boundary with ERROR_INVALID_NAME. Use the extended + // length spelling only when needed; short paths retain the ordinary + // Win32 form for compatibility with older Windows builds. + let security_path = windows_security_object_path(path); + let mut wide_path = security_path .as_os_str() .encode_wide() .chain(std::iter::once(0)) @@ -1079,7 +2851,7 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( )); } let owner_matches = unsafe { IsValidSid(initial_owner) } != 0 - && unsafe { EqualSid(initial_owner, current_user_sid) } != 0; + && unsafe { EqualSid(initial_owner, target_user_sid) } != 0; unsafe { LocalFree(initial_descriptor) }; if !owner_matches { if !(initialize_owner && tighten) { @@ -1088,6 +2860,58 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( path.display() )); } + + // Assigning ownership to the current token user requires the + // take-ownership/restore privileges on an elevated process. + // Enabling them is attempted only for this allow-listed repair; + // a normal process will fail and the caller will request UAC + // elevation instead of weakening the verifier. + for privilege_name in ["SeTakeOwnershipPrivilege", "SeRestorePrivilege"] { + let mut privilege_name_wide = privilege_name + .encode_utf16() + .chain(std::iter::once(0)) + .collect::>(); + let mut luid = Luid { + low_part: 0, + high_part: 0, + }; + if unsafe { + LookupPrivilegeValueW( + std::ptr::null(), + privilege_name_wide.as_mut_ptr(), + &mut luid, + ) + } == 0 + { + return Err(format!( + "启用 Windows {privilege_name} 失败:{}", + std::io::Error::last_os_error() + )); + } + let mut privileges = TokenPrivileges { + privilege_count: 1, + privileges: [LuidAndAttributes { + luid, + attributes: SE_PRIVILEGE_ENABLED, + }], + }; + let adjust_status = unsafe { + AdjustTokenPrivileges( + token, + 0, + &mut privileges, + std::mem::size_of::() as u32, + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + let adjust_error = unsafe { GetLastError() }; + if adjust_status == 0 || adjust_error == ERROR_NOT_ALL_ASSIGNED { + return Err(format!( + "启用 Windows {privilege_name} 失败:error {adjust_error}" + )); + } + } } if tighten { let mut entry = ExplicitAccessW { @@ -1103,7 +2927,7 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( multiple_trustee_operation: 0, trustee_form: TRUSTEE_IS_SID, trustee_type: TRUSTEE_IS_USER, - name: current_user_sid.cast(), + name: target_user_sid.cast(), }, }; let mut private_dacl = std::ptr::null_mut(); @@ -1124,7 +2948,7 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( SE_FILE_OBJECT, windows_private_dacl_security_information(initialize_owner, owner_matches), if should_initialize_owner { - current_user_sid + target_user_sid } else { std::ptr::null_mut() }, @@ -1171,8 +2995,7 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( } let validation = (|| { - if unsafe { IsValidSid(owner) } == 0 - || unsafe { EqualSid(owner, current_user_sid) } == 0 + if unsafe { IsValidSid(owner) } == 0 || unsafe { EqualSid(owner, target_user_sid) } == 0 { return Err(format!( "Windows 安全对象不属于当前用户:{}", @@ -1229,18 +3052,23 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( } else { 0 }; - if allowed.header.ace_flags & (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE) - != required_inheritance - { + if allowed.header.ace_flags != required_inheritance { return Err(format!("Windows DACL 继承边界无效:{}", path.display())); } let ace_sid = std::ptr::addr_of!(allowed.sid_start) .cast_mut() .cast::(); - if unsafe { IsValidSid(ace_sid) } == 0 - || unsafe { EqualSid(ace_sid, current_user_sid) } == 0 + let sid_length = unsafe { GetLengthSid(ace_sid) } as usize; + let sid_offset = std::mem::size_of::() + std::mem::size_of::(); + if sid_length == 0 + || sid_offset.saturating_add(sid_length) > usize::from(header.ace_size) + || unsafe { IsValidSid(ace_sid) } == 0 + || unsafe { EqualSid(ace_sid, target_user_sid) } == 0 { - return Err(format!("Windows DACL 含非当前用户 ACE:{}", path.display())); + return Err(format!( + "Windows DACL 当前用户 ACE 身份无效:{}", + path.display() + )); } Ok(()) })(); @@ -1250,6 +3078,10 @@ fn secure_windows_game_creator_path_for_current_user_with_owner_policy( })(); // SAFETY: token was opened successfully above. + if !requested_user_sid.is_null() { + // SAFETY: ConvertStringSidToSidW allocates this SID with LocalAlloc. + unsafe { LocalFree(requested_user_sid.cast()) }; + } unsafe { CloseHandle(token) }; result } @@ -1263,16 +3095,96 @@ pub(crate) fn configure_game_creator_runtime_config_dir( let config_dir = prepare_game_creator_runtime_config_dir(&requested_config_dir) .map_err(std::io::Error::other)?; let config_path = config_dir.join(GAME_CREATOR_CONFIG_FILE_NAME); - if !config_path.exists() { + let config_exists = + validate_game_creator_config_file_entry(&config_path).map_err(std::io::Error::other)?; + if !config_exists { write_game_creator_config_atomically(&config_path, DEFAULT_GAME_CREATOR_APP_CONFIG_JSON) .map_err(std::io::Error::other)?; - } else { - migrate_legacy_game_creator_agent_mode(&config_path).map_err(std::io::Error::other)?; + } + // Both the normal config and the optional local override are persisted + // inputs. A release build must scrub legacy provider credentials from + // either file before the next read can observe them again. + for path in [ + config_path, + config_dir.join(GAME_CREATOR_LOCAL_CONFIG_FILE_NAME), + ] { + migrate_legacy_game_creator_agent_mode(&path).map_err(std::io::Error::other)?; + migrate_locked_game_creator_llm_config(&path).map_err(std::io::Error::other)?; } set_game_creator_runtime_config_dir(config_dir); Ok(()) } +/// Validates a persisted AGC config file without following links. Existing +/// regular files are tightened through the same Windows owner/DACL gate used +/// by credential files before any read is allowed. +fn validate_game_creator_config_file_entry(path: &Path) -> Result { + #[cfg(windows)] + validate_game_creator_private_path_ancestors_with_auto_elevation(path, "客户端配置文件")?; + #[cfg(not(windows))] + validate_game_creator_private_path_ancestors(path, "客户端配置文件")?; + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(error) => { + return Err(format!( + "读取客户端配置文件元数据失败:{}: {error}", + path.display() + )); + } + }; + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err("客户端配置文件必须是普通文件,不能是链接或其他对象".to_string()); + } + #[cfg(windows)] + secure_windows_game_creator_path_for_current_user_with_auto_elevation(path, false, true)?; + Ok(true) +} + +fn migrate_locked_game_creator_llm_config(path: &Path) -> Result<(), String> { + if !game_creator_official_llm_route_locked() || !validate_game_creator_config_file_entry(path)? + { + return Ok(()); + } + let content = read_game_creator_private_file_to_string(path, "客户端配置", 256 * 1024)?; + let mut config = serde_json::from_str::(&content) + .map_err(|error| format!("解析客户端配置失败:{}: {error}", path.display()))?; + let changed = scrub_locked_game_creator_config_file(&mut config); + if changed { + let content = serde_json::to_string_pretty(&config) + .map_err(|error| format!("序列化客户端配置失败:{error}"))?; + write_game_creator_config_atomically(path, &format!("{content}\n"))?; + } + Ok(()) +} + +/// Applies the release migration to a parsed config file. This helper is +/// deliberately independent of build-mode detection so regression tests can +/// prove that every sensitive legacy field is removed without enabling a +/// production-only route lock in the test binary. +pub(crate) fn scrub_locked_game_creator_config_file(config: &mut GameCreatorAppConfigFile) -> bool { + let mut changed = config.agent_mode.as_deref() + != Some(GAME_CREATOR_AGENT_MODE_CODEX_APP_SERVER) + || config.agent_llm.is_some(); + config.agent_mode = Some(GAME_CREATOR_AGENT_MODE_CODEX_APP_SERVER.to_string()); + config.agent_llm = None; + if let Some(llm) = config.llm.as_mut() { + changed |= llm.api_key.is_some() + || llm.base_url.is_some() + || llm.model.is_some() + || llm.api_kind.is_some(); + llm.api_key = None; + llm.base_url = None; + llm.model = None; + llm.api_kind = None; + } + if config.editor_api.is_some() { + changed = true; + config.editor_api = None; + } + changed +} + pub(crate) fn legacy_game_creator_agent_mode( config: &GameCreatorAppConfigFile, ) -> Option<&'static str> { @@ -1300,8 +3212,10 @@ pub(crate) fn legacy_game_creator_agent_mode( } fn migrate_legacy_game_creator_agent_mode(path: &Path) -> Result<(), String> { - let content = fs::read_to_string(path) - .map_err(|error| format!("读取客户端配置失败:{}: {error}", path.display()))?; + if !validate_game_creator_config_file_entry(path)? { + return Ok(()); + } + let content = read_game_creator_private_file_to_string(path, "客户端配置", 256 * 1024)?; let mut config = serde_json::from_str::(&content) .map_err(|error| format!("解析客户端配置失败:{}: {error}", path.display()))?; let Some(agent_mode) = legacy_game_creator_agent_mode(&config) else { @@ -1335,9 +3249,29 @@ pub(crate) fn load_game_creator_app_config() -> Result bool { + !cfg!(debug_assertions) && !cfg!(test) && editor_api_mode() == EditorApiMode::PlatformAccount +} + +pub(crate) fn lock_game_creator_app_config_to_official_route(config: &mut GameCreatorAppConfig) { + if !game_creator_official_llm_route_locked() { + return; + } + config.agent_mode = GAME_CREATOR_AGENT_MODE_CODEX_APP_SERVER.to_string(); + config.llm.api_key.clear(); + config.llm.base_url = OFFICIAL_AGC_LLM_BASE_URL.to_string(); + config.llm.model = OFFICIAL_AGC_LLM_MODEL.to_string(); + config.llm.api_kind = DEFAULT_GAME_CREATOR_LLM_API_KIND.to_string(); + config.agent_llm.clear(); + config.editor_api.api_key.clear(); +} + pub(crate) fn game_creator_app_config_view( mut config: GameCreatorAppConfig, ) -> Result { @@ -1353,8 +3287,15 @@ pub(crate) fn game_creator_app_config_view( pub(crate) fn serialize_game_creator_app_config_for_renderer_write( config: &GameCreatorAppConfig, ) -> Result { - let mut value = - serde_json::to_value(config).map_err(|error| format!("序列化客户端配置失败:{error}"))?; + // Keep the serialization boundary defensive. Even if a future caller + // bypasses `write_game_creator_app_config`'s normalizer, a PlatformAccount + // release can never persist or echo legacy provider credentials. + let mut safe_config = config.clone(); + if game_creator_official_llm_route_locked() { + lock_game_creator_app_config_to_official_route(&mut safe_config); + } + let mut value = serde_json::to_value(&safe_config) + .map_err(|error| format!("序列化客户端配置失败:{error}"))?; if editor_api_mode() == EditorApiMode::PlatformAccount { value .as_object_mut() @@ -1435,15 +3376,15 @@ pub(crate) fn merge_game_creator_config_file( path: &Path, ) -> Result<(), String> { let backup_path = game_creator_config_backup_path(path); - let read_path = if path.is_file() { + let path_exists = validate_game_creator_config_file_entry(path)?; + let read_path = if path_exists { path - } else if backup_path.is_file() { + } else if validate_game_creator_config_file_entry(&backup_path)? { backup_path.as_path() } else { return Ok(()); }; - let content = fs::read_to_string(read_path) - .map_err(|error| format!("读取客户端配置失败:{}: {error}", read_path.display()))?; + let content = read_game_creator_private_file_to_string(read_path, "客户端配置", 256 * 1024)?; let file_config = serde_json::from_str::(&content) .map_err(|error| format!("解析客户端配置失败:{}: {error}", read_path.display()))?; if let Some(agent_mode) = file_config.agent_mode { @@ -1486,11 +3427,19 @@ pub(crate) fn write_game_creator_config_atomically( path: &Path, content: &str, ) -> Result<(), String> { + #[cfg(windows)] + validate_game_creator_private_path_ancestors_with_auto_elevation(path, "客户端配置文件")?; + #[cfg(not(windows))] + validate_game_creator_private_path_ancestors(path, "客户端配置文件")?; let parent = path .parent() .ok_or_else(|| "客户端配置缺少父目录".to_string())?; - fs::create_dir_all(parent) + ensure_game_creator_private_directory_tree(parent, "客户端配置目录") .map_err(|error| format!("创建客户端配置目录失败:{}: {error}", parent.display()))?; + // Never replace a symlink or another non-regular object. A regular + // existing config is repaired/tightened before it can be moved to the + // recoverable backup below. + let _initial_path_exists = validate_game_creator_config_file_entry(path)?; let temp_path = path.with_file_name(format!( ".{}.tmp.{}.{}", path.file_name() @@ -1509,12 +3458,24 @@ pub(crate) fn write_game_creator_config_atomically( use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options.open(&temp_path).map_err(|error| { format!( "创建客户端配置临时文件失败:{}: {error}", temp_path.display() ) })?; + if let Err(error) = + harden_new_game_creator_private_path(&temp_path, false, "客户端配置临时文件") + { + drop(file); + let _ = fs::remove_file(&temp_path); + return Err(error); + } let write_result = file .write_all(content.as_bytes()) .and_then(|_| file.sync_all()); @@ -1527,44 +3488,55 @@ pub(crate) fn write_game_creator_config_atomically( )); } + let backup_path = game_creator_config_backup_path(path); + // Re-check the destination immediately before changing either directory + // entry. A newly appeared regular target is moved aside; a link, + // reparse point, foreign object, or unsafe ACL is rejected by the same + // private-path policy used for reads. + let had_previous = validate_game_creator_config_file_entry(path)?; + if validate_game_creator_config_file_entry(&backup_path)? { + fs::remove_file(&backup_path).map_err(|error| { + let _ = fs::remove_file(&temp_path); + format!( + "清理旧客户端配置备份失败:{}: {error}", + backup_path.display() + ) + })?; + } + if had_previous { + if let Err(error) = fs::rename(path, &backup_path) { + let _ = fs::remove_file(&temp_path); + return Err(format!( + "准备替换客户端配置失败:{} -> {}: {error}", + path.display(), + backup_path.display() + )); + } + } match fs::rename(&temp_path, path) { Ok(()) => { - let _ = fs::remove_file(game_creator_config_backup_path(path)); + let _ = fs::remove_file(&backup_path); + #[cfg(windows)] + secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, false, true, + )?; Ok(()) } - Err(replace_error) => { - let backup_path = game_creator_config_backup_path(path); - if path.exists() { - let _ = fs::remove_file(&backup_path); - fs::rename(path, &backup_path).map_err(|error| { - let _ = fs::remove_file(&temp_path); - format!( - "准备替换客户端配置失败:{} -> {}: {error}", - path.display(), - backup_path.display() - ) - })?; - } - match fs::rename(&temp_path, path) { - Ok(()) => { - let _ = fs::remove_file(&backup_path); - Ok(()) - } - Err(error) => { - let restore_error = if backup_path.exists() { - fs::rename(&backup_path, path).err() - } else { - None - }; - let _ = fs::remove_file(&temp_path); - let restore_detail = restore_error - .map(|error| format!(";恢复旧配置失败:{error}")) - .unwrap_or_default(); - Err(format!( - "替换客户端配置失败:{replace_error};重试失败:{error}{restore_detail}" - )) - } - } + Err(error) => { + let restore_error = if had_previous { + fs::rename(&backup_path, path).err() + } else { + None + }; + let _ = fs::remove_file(&temp_path); + let restore_detail = restore_error + .map(|error| format!(";恢复旧配置失败:{error}")) + .unwrap_or_default(); + Err(format!( + "替换客户端配置失败:{} -> {}: {error}{restore_detail}", + temp_path.display(), + path.display() + )) } } } @@ -1705,6 +3677,9 @@ pub(crate) fn trim_config_string(value: &str) -> Option { pub(crate) fn normalize_game_creator_app_config( mut config: GameCreatorAppConfig, ) -> Result { + if game_creator_official_llm_route_locked() { + lock_game_creator_app_config_to_official_route(&mut config); + } config.agent_mode = normalize_game_creator_agent_mode(&config.agent_mode)?; config.llm.api_key = config.llm.api_key.trim().to_string(); config.llm.base_url = @@ -1894,3 +3869,225 @@ mod anthropic_strict_capability_tests { } } } + +#[cfg(test)] +mod private_file_write_tests { + use super::*; + + #[test] + fn private_file_write_installs_via_hardened_sibling_and_replaces_regular_target() { + let root = tempfile::tempdir().expect("create private file fixture"); + let parent = root.path().join("private"); + let path = parent.join("state.json"); + + write_game_creator_private_file(&path, b"first\n", "测试私有文件") + .expect("install first private file"); + assert_eq!( + fs::read(&path).expect("read first private file"), + b"first\n" + ); + + write_game_creator_private_file(&path, b"second\n", "测试私有文件") + .expect("replace private file"); + assert_eq!( + fs::read(&path).expect("read replaced private file"), + b"second\n" + ); + + let leftovers = fs::read_dir(&parent) + .expect("read private file directory") + .filter_map(Result::ok) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .filter(|name| name.contains(".tmp-") || name.contains(".previous-")) + .collect::>(); + assert!( + leftovers.is_empty(), + "temporary/backup residue: {leftovers:?}" + ); + + #[cfg(unix)] + { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let metadata = fs::symlink_metadata(&path).expect("metadata"); + assert_eq!(metadata.mode() & 0o777, 0o600); + } + } + + #[test] + fn private_file_append_creates_and_reuses_hardened_target() { + let root = tempfile::tempdir().expect("create append fixture"); + let path = root.path().join("private").join("journal.log"); + + append_game_creator_private_file(&path, b"first\n", "测试追加文件") + .expect("append first record"); + append_game_creator_private_file(&path, b"second\n", "测试追加文件") + .expect("append second record"); + assert_eq!( + fs::read(&path).expect("read append file"), + b"first\nsecond\n" + ); + + #[cfg(unix)] + { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let metadata = fs::symlink_metadata(&path).expect("append metadata"); + assert_eq!(metadata.nlink(), 1); + assert_eq!(metadata.mode() & 0o777, 0o600); + } + } +} + +#[cfg(test)] +mod private_path_elevation_policy_tests { + use super::*; + + #[test] + fn automatic_elevation_covers_all_regular_project_descendants() { + let root = tempfile::tempdir().expect("create path policy fixture"); + let external_file = root.path().join("game").join("index.html"); + let nested_project_file = root.path().join("assets").join("sprites").join("hero.png"); + let managed_agent_file = root + .path() + .join(".agent") + .join("runtime") + .join("state.json"); + fs::create_dir_all(managed_agent_file.parent().expect("agent parent")) + .expect("create managed agent fixture"); + fs::write(root.path().join(".agent/manifest.json"), b"{}").expect("create marker"); + let traversal_path = root + .path() + .join(".agent") + .join("..") + .join("Windows") + .join("System32"); + + assert!(game_creator_private_path_allows_auto_elevation( + &external_file + )); + assert!(game_creator_private_path_allows_auto_elevation( + &nested_project_file + )); + assert!(game_creator_private_path_allows_auto_elevation( + &managed_agent_file + )); + assert!(!game_creator_private_path_allows_auto_elevation( + &traversal_path + )); + } + + #[test] + fn project_marker_does_not_authorize_unrelated_or_nested_agent_paths() { + let root = tempfile::tempdir().expect("create path policy fixture"); + fs::create_dir_all(root.path().join(".agent")).expect("create agent directory"); + fs::write(root.path().join(".agent/manifest.json"), b"{}").expect("create marker"); + + let unrelated = tempfile::tempdir().expect("create unrelated fixture"); + let unrelated_file = unrelated.path().join("game/index.html"); + let nested_agent = root.path().join("game").join(".agent").join("state.json"); + + assert!(!game_creator_private_path_allows_auto_elevation( + &unrelated_file + )); + assert!(!game_creator_private_path_allows_auto_elevation( + &nested_agent + )); + } + + #[cfg(windows)] + #[test] + fn explicit_user_selection_allows_repair_on_user_selected_non_system_path() { + let profile = std::env::var_os("USERPROFILE") + .or_else(|| std::env::var_os("HOME")) + .map(PathBuf::from) + .expect("current user profile"); + let windir = std::env::var_os("WINDIR") + .map(PathBuf::from) + .expect("WINDIR"); + let program_files = std::env::var_os("ProgramFiles") + .map(PathBuf::from) + .expect("ProgramFiles"); + let system_drive = std::env::var_os("SystemDrive") + .map(PathBuf::from) + .expect("SystemDrive"); + let selected = profile.join("Documents").join("fixture.png"); + let external_drive = PathBuf::from(r"D:\Genarrative\fixture.png"); + let system_path = windir.join("System32").join("fixture.png"); + let program_files_path = program_files.join("Genarrative").join("fixture.png"); + let drive_root = PathBuf::from(format!( + "{}\\", + system_drive.to_string_lossy().trim_end_matches(['\\', '/']) + )); + let unc_root = PathBuf::from(r"\\server\share\"); + let traversal_path = PathBuf::from(r"C:\Users\test\..\Windows\fixture.png"); + + assert!(game_creator_user_selected_path_allows_auto_elevation( + &selected + )); + assert!(game_creator_user_selected_path_allows_auto_elevation( + &external_drive + )); + assert!(!game_creator_user_selected_path_allows_auto_elevation( + &system_path + )); + assert!(!game_creator_user_selected_path_allows_auto_elevation( + &program_files_path + )); + assert!(!game_creator_user_selected_path_allows_auto_elevation( + &drive_root + )); + assert!(!game_creator_user_selected_path_allows_auto_elevation( + &unc_root + )); + assert!(!game_creator_user_selected_path_allows_auto_elevation( + &traversal_path + )); + } + + #[test] + fn arbitrary_agent_directory_without_project_marker_cannot_trigger_elevation() { + let root = tempfile::tempdir().expect("create unverified agent fixture"); + let path = root + .path() + .join(".agent") + .join("runtime") + .join("state.json"); + fs::create_dir_all(path.parent().expect("agent parent")).expect("create agent fixture"); + assert!(!game_creator_private_path_allows_auto_elevation(&path)); + } + + #[test] + fn nested_agent_components_cannot_trigger_elevation() { + let root = tempfile::tempdir().expect("create nested agent fixture"); + let path = root + .path() + .join(".agent") + .join("nested") + .join(".agent") + .join("state.json"); + fs::create_dir_all(path.parent().expect("nested agent parent")) + .expect("create nested agent"); + fs::write(root.path().join(".agent/manifest.json"), b"{}").expect("create marker"); + assert!(!game_creator_private_path_allows_auto_elevation(&path)); + } + + #[cfg(windows)] + #[test] + fn explicit_project_root_entry_can_tighten_owner_correct_inherited_acl() { + let root = tempfile::tempdir().expect("create project root fixture"); + assert!(prepare_game_creator_project_root_for_read(root.path(), true, "项目根").is_ok()); + } + + #[cfg(windows)] + #[test] + fn owner_flag_is_requested_only_when_owner_initialization_is_needed() { + const OWNER_SECURITY_INFORMATION: u32 = 0x0000_0001; + assert_eq!( + windows_private_dacl_security_information(true, false) & OWNER_SECURITY_INFORMATION, + OWNER_SECURITY_INFORMATION + ); + assert_eq!( + windows_private_dacl_security_information(true, true) & OWNER_SECURITY_INFORMATION, + 0 + ); + } +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/debug/debug_drafts.rs b/apps/ai-game-creator-shell/src-tauri/src/debug/debug_drafts.rs index 65a9b9c69..7f2a0d927 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/debug/debug_drafts.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/debug/debug_drafts.rs @@ -5,7 +5,6 @@ //! 不会往仓库写任何文件。 use crate::unix_millis; -use std::fs; use std::path::PathBuf; // 找到仓库根(包含 apps/ai-game-creator-shell/src-tauri/Cargo.toml 的目录), @@ -46,12 +45,15 @@ pub(crate) fn persist_snapshot(raw_content: &str) { .join("apps") .join("ai-game-creator-shell") .join(".llm-drafts"); - if let Err(error) = fs::create_dir_all(&dir) { + if let Err(error) = crate::ensure_game_creator_private_directory_tree(&dir, "LLM 调试快照目录") + { eprintln!("llm.draft.snapshot.dir.failed: {}: {error}", dir.display()); return; } let path = dir.join(format!("draft-{}.txt", unix_millis())); - if let Err(error) = fs::write(&path, raw_content) { + if let Err(error) = + crate::write_game_creator_private_file(&path, raw_content.as_bytes(), "LLM 调试快照") + { eprintln!( "llm.draft.snapshot.write.failed: {}: {error}", path.display() @@ -60,7 +62,8 @@ pub(crate) fn persist_snapshot(raw_content: &str) { } // 同步更新 latest.txt,方便直接打开最近一次草案。 let latest = dir.join("latest.txt"); - let _ = fs::write(&latest, raw_content); + let _ = + crate::write_game_creator_private_file(&latest, raw_content.as_bytes(), "LLM 最新调试快照"); eprintln!("llm.draft.snapshot.saved: {}", path.display()); } @@ -75,7 +78,9 @@ pub(crate) fn persist_error_input(system_prompt: &str, user_prompt: &str, error: .join("apps") .join("ai-game-creator-shell") .join(".llm-drafts"); - if let Err(io_error) = fs::create_dir_all(&dir) { + if let Err(io_error) = + crate::ensure_game_creator_private_directory_tree(&dir, "LLM 错误输入快照目录") + { eprintln!( "llm.draft.error-input.dir.failed: {}: {io_error}", dir.display() @@ -86,7 +91,9 @@ pub(crate) fn persist_error_input(system_prompt: &str, user_prompt: &str, error: "# LLM 生成失败输入快照\n\n## 错误\n{error}\n\n## System Prompt\n{system_prompt}\n\n## User Prompt(含用户需求/短长期记忆/spec/agenda/组 brief/findings)\n{user_prompt}\n", ); let path = dir.join(format!("error-input-{}.txt", unix_millis())); - if let Err(io_error) = fs::write(&path, &body) { + if let Err(io_error) = + crate::write_game_creator_private_file(&path, body.as_bytes(), "LLM 错误输入快照") + { eprintln!( "llm.draft.error-input.write.failed: {}: {io_error}", path.display() @@ -95,6 +102,7 @@ pub(crate) fn persist_error_input(system_prompt: &str, user_prompt: &str, error: } // 同步更新 latest-error-input.txt,方便直接打开最近一次失败输入。 let latest = dir.join("latest-error-input.txt"); - let _ = fs::write(&latest, &body); + let _ = + crate::write_game_creator_private_file(&latest, body.as_bytes(), "LLM 最新错误输入快照"); eprintln!("llm.draft.error-input.saved: {}", path.display()); } diff --git a/apps/ai-game-creator-shell/src-tauri/src/image_inspect.rs b/apps/ai-game-creator-shell/src-tauri/src/image_inspect.rs index 1d23c81c0..149f6221e 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/image_inspect.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/image_inspect.rs @@ -1,6 +1,6 @@ use crate::project::{ - normalize_relative_path, open_project_snapshot_regular_file, - reject_sensitive_project_file_read, resolve_local_project_path, + normalize_relative_path, open_project_private_regular_file, reject_sensitive_project_file_read, + resolve_local_project_path, }; use crate::resource_preview_scheduler::ProjectResourcePreviewScopeCancellation; use base64::Engine as _; @@ -282,7 +282,7 @@ fn read_agent_runtime_inspection_image_with_cancellation( cancellation: &ProjectResourcePreviewScopeCancellation, ) -> Result { cancellation.check()?; - let (mut file, initial_metadata) = open_project_snapshot_regular_file(path, "视觉检查图片")?; + let (mut file, initial_metadata) = open_project_private_regular_file(path, "视觉检查图片")?; cancellation.check()?; if initial_metadata.len() == 0 { return Err(format!("image.inspect 图片不能为空:{relative_path}")); @@ -334,7 +334,7 @@ fn read_agent_runtime_inspection_image_with_cancellation( } cancellation.check()?; - let (reopened, reopened_metadata) = open_project_snapshot_regular_file(path, "视觉检查图片")?; + let (reopened, reopened_metadata) = open_project_private_regular_file(path, "视觉检查图片")?; if !same_open_file_identity(&file, &initial_metadata, &reopened, &reopened_metadata)? { return Err(format!( "image.inspect 图片路径读取期间发生替换:{relative_path}" diff --git a/apps/ai-game-creator-shell/src-tauri/src/main.rs b/apps/ai-game-creator-shell/src-tauri/src/main.rs index ad1499c0b..018e3241a 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/main.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/main.rs @@ -764,7 +764,8 @@ struct GameCreatorDirectTurnUpdateEvent { struct GameCreatorLlmConfigStatus { agent_mode: String, configured: bool, - api_key_present: bool, + account_credential_state: String, + official_route_locked: bool, base_url: Option, model: Option, api_kind: String, @@ -788,7 +789,8 @@ struct GameCreatorAgentLlmConfigStatus { agent_id: String, label: String, configured: bool, - api_key_present: bool, + account_credential_state: String, + official_route_locked: bool, base_url: Option, model: Option, api_kind: String, @@ -1580,7 +1582,10 @@ fn append_bounded_diagnostic_line_with_limit( .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; + ensure_game_creator_private_directory_tree(parent, "诊断日志目录") + .map_err(std::io::Error::other)?; + prepare_game_creator_private_path_for_read(parent, true, "诊断日志目录") + .map_err(std::io::Error::other)?; } let mut file = open_secure_diagnostic_log(path)?; if file.metadata()?.len() >= max_bytes { @@ -1627,6 +1632,8 @@ fn open_secure_diagnostic_log(path: &Path) -> std::io::Result { Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error), } + let existed = prepare_game_creator_private_path_for_read(path, false, "诊断日志") + .map_err(std::io::Error::other)?; let mut options = OpenOptions::new(); options.read(true).write(true).create(true); #[cfg(unix)] @@ -1641,6 +1648,10 @@ fn open_secure_diagnostic_log(path: &Path) -> std::io::Result { options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); } let file = options.open(path)?; + if !existed { + harden_new_game_creator_private_path(path, false, "诊断日志") + .map_err(std::io::Error::other)?; + } let metadata = file.metadata()?; if !metadata.is_file() { return Err(std::io::Error::new( @@ -1661,6 +1672,8 @@ fn open_secure_diagnostic_log(path: &Path) -> std::io::Result { #[cfg(windows)] crate::runner::validate_windows_regular_file_handle(&file, "diagnostic log") .map_err(std::io::Error::other)?; + prepare_game_creator_private_path_for_read(path, false, "诊断日志") + .map_err(std::io::Error::other)?; Ok(file) } diff --git a/apps/ai-game-creator-shell/src-tauri/src/platform_session.rs b/apps/ai-game-creator-shell/src-tauri/src/platform_session.rs index daf5cd59f..0e24b3b53 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/platform_session.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/platform_session.rs @@ -1,5 +1,5 @@ -use sha2::{Digest, Sha256}; use serde::Deserialize; +use sha2::{Digest, Sha256}; use std::fs::{self, OpenOptions}; use std::io::Read; use std::path::{Path, PathBuf}; @@ -8,10 +8,8 @@ use std::sync::{Mutex, OnceLock}; /// Debug-only fixture hook used by the deterministic AGC E2E. The hook takes /// a path, rather than credentials on argv, so a child Runner can inherit the /// test identity without putting the bearer token in process listings. -pub(crate) const PLATFORM_SESSION_FIXTURE_ENV: &str = - "GENARRATIVE_AGC_PLATFORM_SESSION_FIXTURE"; -const PLATFORM_SESSION_FIXTURE_SCHEMA_VERSION: &str = - "genarrative-agc-platform-session-fixture.v1"; +pub(crate) const PLATFORM_SESSION_FIXTURE_ENV: &str = "GENARRATIVE_AGC_PLATFORM_SESSION_FIXTURE"; +const PLATFORM_SESSION_FIXTURE_SCHEMA_VERSION: &str = "genarrative-agc-platform-session-fixture.v1"; const PLATFORM_SESSION_FIXTURE_MAX_BYTES: u64 = 16 * 1024; #[derive(Clone, Debug, Eq, PartialEq)] @@ -144,8 +142,8 @@ fn validate_fixture_path(config_dir: &Path, fixture_path: &Path) -> Result Result, String> { - let before = fs::symlink_metadata(path) - .map_err(|_| "平台登录态 fixture 文件不可读取".to_string())?; + let before = + fs::symlink_metadata(path).map_err(|_| "平台登录态 fixture 文件不可读取".to_string())?; if metadata_is_link_or_reparse(&before) || !before.is_file() { return Err("平台登录态 fixture 必须是普通文件".to_string()); } @@ -169,7 +167,8 @@ fn read_fixture_file(path: &Path) -> Result, String> { if metadata_is_link_or_reparse(&opened) || !opened.is_file() || opened.len() > before.len() { return Err("平台登录态 fixture 文件身份校验失败".to_string()); } - let mut bytes = Vec::with_capacity(opened.len().min(PLATFORM_SESSION_FIXTURE_MAX_BYTES) as usize); + let mut bytes = + Vec::with_capacity(opened.len().min(PLATFORM_SESSION_FIXTURE_MAX_BYTES) as usize); file.take(PLATFORM_SESSION_FIXTURE_MAX_BYTES + 1) .read_to_end(&mut bytes) .map_err(|_| "读取平台登录态 fixture 失败".to_string())?; @@ -188,10 +187,18 @@ fn parse_platform_session_fixture(bytes: &[u8]) -> Result Result Result Result, String> { if create { - fs::create_dir_all(root) - .map_err(|error| format!("创建 Agent DB 项目目录失败:{}: {error}", root.display()))?; + ensure_game_creator_private_directory_tree(root, "Agent DB 项目目录")?; + } + if !prepare_game_creator_private_path_for_read(root, true, "Agent DB 项目目录")? { + return Ok(None); + } + let agent_path = root.join(".agent"); + if create { + ensure_game_creator_private_directory_tree(&agent_path, "项目 .agent 目录")?; + } + if !prepare_game_creator_private_path_for_read(&agent_path, true, "项目 .agent 目录")? { + return Ok(None); } let root_directory = match open_windows_agent_db_root(root, create) { Ok(file) => file, @@ -875,6 +884,21 @@ fn open_agent_db_storage( create: bool, ) -> Result, String> { verify_agent_db_directory_current(&directory)?; + let path = directory.path.join("agent.db"); + let existed = match fs::symlink_metadata(&path) { + Ok(_) => true, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, + Err(_) => { + // Do not let an ACL-denied existing Agent DB fall through to + // NtCreateFile, which would otherwise be reported as a generic + // open failure without trying the approved repair path. + prepare_game_creator_private_path_for_read(&path, false, "Agent 本地索引")?; + true + } + }; + if existed { + prepare_game_creator_private_path_for_read(&path, false, "Agent 本地索引")?; + } let file = { let mut opened = None; for attempt in 0..100 { @@ -924,10 +948,16 @@ fn open_agent_db_storage( return Err("Agent 本地索引必须是普通文件".to_string()); } validate_windows_regular_file_handle(&file, "Agent 本地索引")?; + if existed { + secure_windows_game_creator_path_for_current_user_with_auto_elevation(&path, false, true)?; + } else { + initialize_windows_game_creator_file_owner_for_current_user(&path)?; + secure_windows_game_creator_path_for_current_user_with_auto_elevation(&path, false, false)?; + } verify_agent_db_directory_current(&directory)?; Ok(Some(AgentDbStorage { file, - path: directory.path.join("agent.db"), + path, root_path: directory.root_path, root_directory: directory.root_directory, agent_directory: directory.agent_directory, @@ -4369,13 +4399,10 @@ fn project_append_os_lock_path(path: &Path) -> Result { fn acquire_project_append_os_lock(path: &Path, error_label: &str) -> Result { if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!( - "创建{error_label}跨进程锁目录失败:{}: {error}", - parent.display() - ) - })?; + ensure_game_creator_private_directory_tree(parent, error_label)?; + prepare_game_creator_private_path_for_read(parent, true, error_label)?; } + prepare_game_creator_private_path_for_read(path, false, error_label)?; for attempt in 0..100 { if let Some(file) = try_open_project_append_os_lock(path, error_label)? { return Ok(file); @@ -4391,12 +4418,54 @@ fn acquire_project_append_os_lock(path: &Path, error_label: &str) -> Result Result, String> { use std::os::fd::AsRawFd; - let file = fs::OpenOptions::new() - .create(true) - .read(true) - .write(true) + let existed = prepare_game_creator_private_path_for_read(path, false, error_label)?; + let mut options = fs::OpenOptions::new(); + options.create(true).read(true).write(true); + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW).mode(0o600); + let file = options .open(path) .map_err(|error| format!("打开{error_label}跨进程锁失败:{}: {error}", path.display()))?; + let metadata = file.metadata().map_err(|error| { + format!( + "读取{error_label}跨进程锁元数据失败:{}: {error}", + path.display() + ) + })?; + if !metadata.is_file() { + return Err(format!( + "{error_label}跨进程锁必须是普通文件:{}", + path.display() + )); + } + if !existed { + harden_new_game_creator_private_path(path, false, error_label)?; + } + let path_metadata = fs::symlink_metadata(path).map_err(|error| { + format!( + "复核{error_label}跨进程锁路径失败:{}: {error}", + path.display() + ) + })?; + if path_metadata.file_type().is_symlink() { + return Err(format!( + "{error_label}跨进程锁不能是符号链接:{}", + path.display() + )); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if path_metadata.nlink() != 1 + || path_metadata.dev() != metadata.dev() + || path_metadata.ino() != metadata.ino() + { + return Err(format!( + "{error_label}跨进程锁路径在打开期间发生替换:{}", + path.display() + )); + } + } let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; if result == 0 { return Ok(Some(file)); @@ -4416,14 +4485,29 @@ fn try_open_project_append_os_lock(path: &Path, error_label: &str) -> Result Result, String> { use std::os::windows::fs::OpenOptionsExt; - match fs::OpenOptions::new() - .create(true) - .read(true) - .write(true) - .share_mode(0) - .open(path) - { - Ok(file) => Ok(Some(file)), + let existed = prepare_game_creator_private_path_for_read(path, false, error_label)?; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + match { + let mut options = fs::OpenOptions::new(); + options + .create(true) + .read(true) + .write(true) + .share_mode(0) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); + options.open(path) + } { + Ok(file) => { + crate::runner::validate_windows_regular_file_handle(&file, error_label)?; + if !existed { + harden_new_game_creator_private_path(path, false, error_label)?; + } + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, false, true, + )?; + crate::runner::validate_windows_regular_file_handle(&file, error_label)?; + Ok(Some(file)) + } Err(error) if matches!( error.kind(), @@ -4453,22 +4537,72 @@ pub(super) fn append_jsonl_line_unlocked( error_label: &str, ) -> Result<(), String> { if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建{error_label}目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, error_label)?; + prepare_game_creator_private_path_for_read(parent, true, error_label)?; } - let mut file = fs::OpenOptions::new() - .create(true) - .read(true) - .write(true) + let existed = prepare_game_creator_private_path_for_read(path, false, error_label)?; + let mut options = fs::OpenOptions::new(); + options.create(true).read(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW).mode(0o600); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + const FILE_SHARE_READ: u32 = 0x0000_0001; + const FILE_SHARE_WRITE: u32 = 0x0000_0002; + const FILE_SHARE_DELETE: u32 = 0x0000_0004; + options + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE); + } + let mut file = options .open(path) .map_err(|error| format!("打开{error_label}失败:{}: {error}", path.display()))?; + let opened_metadata = file.metadata().map_err(|error| { + format!( + "读取{error_label}文件句柄元数据失败:{}: {error}", + path.display() + ) + })?; + if !opened_metadata.is_file() { + return Err(format!("{error_label}必须是普通文件:{}", path.display())); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if opened_metadata.nlink() != 1 { + return Err(format!("{error_label}不能是硬链接:{}", path.display())); + } + let path_metadata = fs::symlink_metadata(path) + .map_err(|error| format!("复核{error_label}路径失败:{}: {error}", path.display()))?; + if path_metadata.file_type().is_symlink() + || path_metadata.dev() != opened_metadata.dev() + || path_metadata.ino() != opened_metadata.ino() + { + return Err(format!( + "{error_label}路径在安全打开期间发生替换:{}", + path.display() + )); + } + } + #[cfg(windows)] + crate::runner::validate_windows_regular_file_handle(&file, error_label)?; + if !existed { + harden_new_game_creator_private_path(path, false, error_label)?; + } repair_truncated_jsonl_tail_unlocked(&mut file, path, error_label)?; let framed = format!("{line}\n"); file.seek(SeekFrom::End(0)) .and_then(|_| file.write_all(framed.as_bytes())) .and_then(|_| file.flush()) .and_then(|_| file.sync_data()) - .map_err(|error| format!("写入{error_label}失败:{}: {error}", path.display())) + .map_err(|error| format!("写入{error_label}失败:{}: {error}", path.display()))?; + prepare_game_creator_private_path_for_read(path, false, error_label)?; + Ok(()) } const AGENT_DB_FINALIZATION_SLOT_PREPARED: u8 = 0; diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/asset_canvas.rs b/apps/ai-game-creator-shell/src-tauri/src/project/asset_canvas.rs index 99c961d92..6af0fb201 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/asset_canvas.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/asset_canvas.rs @@ -772,7 +772,7 @@ fn read_asset_canvas_bytes( )) } } - let (file, metadata) = open_project_snapshot_regular_file(&path, label)?; + let (file, metadata) = open_project_private_regular_file(&path, label)?; if metadata.len() > max_bytes as u64 { return Err(format!("{label} 超过 {max_bytes} 字节上限")); } @@ -890,10 +890,12 @@ fn write_asset_canvas_raw_sidecar( } let mut path = resolve_local_project_path(root, relative_path)?; let parent = path.parent().ok_or_else(|| format!("{label} 缺少父目录"))?; - fs::create_dir_all(parent).map_err(|error| format!("创建 {label} 目录失败:{error}"))?; + crate::ensure_game_creator_private_directory_tree(parent, label)?; + crate::prepare_game_creator_private_path_for_read(parent, true, label)?; path = resolve_local_project_path(root, relative_path)?; + crate::prepare_game_creator_private_path_for_read(&path, false, label)?; if fs::symlink_metadata(&path).is_ok() { - open_project_snapshot_regular_file(&path, label)?; + open_project_private_regular_file(&path, label)?; } let file_name = path .file_name() @@ -912,9 +914,19 @@ fn write_asset_canvas_raw_sidecar( use std::os::unix::fs::OpenOptionsExt; options.custom_flags(libc::O_NOFOLLOW).mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options .open(&temp_path) .map_err(|error| format!("创建 {label} 临时文件失败:{error}"))?; + if let Err(error) = crate::harden_new_game_creator_private_path(&temp_path, false, label) { + drop(file); + let _ = fs::remove_file(&temp_path); + return Err(error); + } file.write_all(bytes) .and_then(|_| file.sync_data()) .map_err(|error| { @@ -944,6 +956,7 @@ fn write_asset_canvas_raw_sidecar( .map_err(|error| format!("清理 {label} 恢复副本失败:{error}"))?; } } + crate::prepare_game_creator_private_path_for_read(&path, false, label)?; #[cfg(unix)] File::open(path.parent().ok_or_else(|| format!("{label} 缺少父目录"))?) .and_then(|directory| directory.sync_all()) @@ -1139,7 +1152,10 @@ fn try_acquire_asset_canvas_draft_lock( let parent = path .parent() .ok_or_else(|| "素材画布锁缺少父目录".to_string())?; - fs::create_dir_all(parent).map_err(|_| "创建素材画布锁目录失败".to_string())?; + crate::ensure_game_creator_private_directory_tree(parent, "素材画布锁目录")?; + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + parent, true, true, + )?; let open_lock = |create_new| { let mut options = fs::OpenOptions::new(); options @@ -1161,6 +1177,18 @@ fn try_acquire_asset_canvas_draft_lock( } Err(_) => return Err("获取素材画布系统文件锁失败".to_string()), }, + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + // Permission denial is an ACL defect, not lock contention. Repair + // the existing managed lock once, then retry the non-creating + // open; sharing violations continue to return the normal busy + // result below. + crate::prepare_game_creator_private_path_for_read(&path, false, "素材画布锁")?; + match open_lock(false) { + Ok(file) => (file, false), + Err(error) if windows_file_lock_is_contended(&error) => return Ok(None), + Err(_) => return Err("获取素材画布系统文件锁失败".to_string()), + } + } Err(error) if windows_file_lock_is_contended(&error) => return Ok(None), Err(_) => return Err("获取素材画布系统文件锁失败".to_string()), }; @@ -1168,7 +1196,9 @@ fn try_acquire_asset_canvas_draft_lock( if created { crate::initialize_windows_game_creator_file_owner_for_current_user(&path)?; } else { - crate::secure_windows_game_creator_path_for_current_user(&path, false, true)?; + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + &path, false, true, + )?; } Ok(Some(AssetCanvasDraftLock { _file: file })) } @@ -1210,7 +1240,7 @@ fn open_and_validate_image_file( expected_media_type: &str, expected_sha256: Option<&str>, ) -> Result<(Vec, u32, u32), String> { - let (mut file, metadata) = open_project_snapshot_regular_file(path, "素材图片")?; + let (mut file, metadata) = open_project_private_regular_file(path, "素材图片")?; if metadata.len() == 0 || metadata.len() > ASSET_CANVAS_MAX_MEDIA_BYTES as u64 { return Err("素材图片大小超限".to_string()); } @@ -1610,7 +1640,9 @@ fn rollback_new_asset_canvas_files(paths: &[PathBuf], label: &str) -> Result<(), fn install_new_asset_canvas_file(path: &Path, bytes: &[u8], label: &str) -> Result<(), String> { let parent = path.parent().ok_or_else(|| format!("{label} 缺少父目录"))?; - fs::create_dir_all(parent).map_err(|_| format!("创建 {label} 目录失败"))?; + crate::ensure_game_creator_private_directory_tree(parent, label)?; + crate::prepare_game_creator_private_path_for_read(parent, true, label)?; + crate::prepare_game_creator_private_path_for_read(path, false, label)?; if fs::symlink_metadata(path).is_ok() { return Err(format!("{label} 目标已存在")); } @@ -1622,9 +1654,19 @@ fn install_new_asset_canvas_file(path: &Path, bytes: &[u8], label: &str) -> Resu use std::os::unix::fs::OpenOptionsExt; options.mode(0o600).custom_flags(libc::O_NOFOLLOW); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options .open(&temp_path) .map_err(|_| format!("创建 {label} 临时文件失败"))?; + if let Err(error) = crate::harden_new_game_creator_private_path(&temp_path, false, label) { + drop(file); + let _ = fs::remove_file(&temp_path); + return Err(error); + } if let Err(error) = file.write_all(bytes).and_then(|_| file.sync_all()) { let _ = fs::remove_file(&temp_path); return Err(format!("写入 {label} 临时文件失败:{error}")); @@ -1640,7 +1682,7 @@ fn install_new_asset_canvas_file(path: &Path, bytes: &[u8], label: &str) -> Resu let completion = (|| -> Result<(), String> { fs::remove_file(&temp_path).map_err(|error| format!("完成 {label} 安装失败:{error}"))?; - let (_, metadata) = open_project_snapshot_regular_file(path, label)?; + let (_, metadata) = open_project_private_regular_file(path, label)?; if metadata.len() != bytes.len() as u64 { return Err(format!("{label} 安装后大小不一致")); } @@ -1675,7 +1717,7 @@ fn asset_canvas_draft_media_bytes(root: &Path, draft_id: &str) -> Result ASSET_CANVAS_MAX_LAYERS * 2 { return Err("素材画布媒体条目数量超限".to_string()); } - let (_, metadata) = open_project_snapshot_regular_file(&entry.path(), "素材画布媒体")?; + let (_, metadata) = open_project_private_regular_file(&entry.path(), "素材画布媒体")?; total = total .checked_add(metadata.len()) .ok_or_else(|| "素材画布媒体总量溢出".to_string())?; @@ -2911,7 +2953,7 @@ fn find_ledger_by_idempotency_key( return Err("素材画布 commit ledger 数量超限".to_string()); } let path = entry.path(); - let (_, metadata) = open_project_snapshot_regular_file(&path, "素材画布 commit ledger")?; + let (_, metadata) = open_project_private_regular_file(&path, "素材画布 commit ledger")?; if metadata.len() > ASSET_CANVAS_MAX_LEDGER_BYTES as u64 { return Err("素材画布 commit ledger 超限".to_string()); } @@ -3045,7 +3087,9 @@ fn replace_asset_canvas_runtime_entry( label: &str, ) -> Result<(), String> { let parent = path.parent().ok_or_else(|| format!("{label} 缺少父目录"))?; - fs::create_dir_all(parent).map_err(|_| format!("创建 {label} 目录失败"))?; + crate::ensure_game_creator_private_directory_tree(parent, label)?; + crate::prepare_game_creator_private_path_for_read(parent, true, label)?; + crate::prepare_game_creator_private_path_for_read(path, false, label)?; if let Ok(metadata) = fs::symlink_metadata(path) { if metadata.file_type().is_symlink() || !metadata.is_file() { return Err(format!("{label} 必须是普通文件")); @@ -3059,9 +3103,19 @@ fn replace_asset_canvas_runtime_entry( use std::os::unix::fs::OpenOptionsExt; options.mode(0o600).custom_flags(libc::O_NOFOLLOW); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options .open(&temp_path) .map_err(|_| format!("创建 {label} 临时文件失败"))?; + if let Err(error) = crate::harden_new_game_creator_private_path(&temp_path, false, label) { + drop(file); + let _ = fs::remove_file(&temp_path); + return Err(error); + } if let Err(error) = file.write_all(bytes).and_then(|_| file.sync_all()) { let _ = fs::remove_file(&temp_path); return Err(format!("写入 {label} 临时文件失败:{error}")); @@ -3071,7 +3125,7 @@ fn replace_asset_canvas_runtime_entry( let _ = fs::remove_file(&temp_path); format!("安装 {label} 失败:{error}") })?; - let (_, metadata) = open_project_snapshot_regular_file(path, label)?; + let (_, metadata) = open_project_private_regular_file(path, label)?; if metadata.len() != bytes.len() as u64 { return Err(format!("{label} 安装后大小不一致")); } @@ -4029,7 +4083,7 @@ fn read_asset_canvas_snapshot( root, &asset_canvas_transaction_relative_path(commit_id, file_name), )?; - let (mut file, metadata) = open_project_snapshot_regular_file(&path, "素材画布事务快照")?; + let (mut file, metadata) = open_project_private_regular_file(&path, "素材画布事务快照")?; if metadata.len() > ASSET_CANVAS_MAX_LEDGER_BYTES as u64 { return Err("素材画布事务快照超限".to_string()); } diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/checkpoint.rs b/apps/ai-game-creator-shell/src-tauri/src/project/checkpoint.rs index 66b6b142b..bbdd78bf2 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/checkpoint.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/checkpoint.rs @@ -22,10 +22,10 @@ pub(crate) fn create_local_project_checkpoint_at( &checkpoint_file_relative_path(&checkpoint_id, &normalized_path), )?; if let Some(parent) = target.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!("创建 checkpoint 目录失败:{}: {error}", parent.display()) - })?; + ensure_game_creator_private_directory_tree(parent, "checkpoint 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "checkpoint 目录")?; } + prepare_game_creator_private_path_for_read(&target, false, "checkpoint 文件")?; fs::copy(&source, &target).map_err(|error| { format!( "写入 checkpoint 文件失败:{} -> {}: {error}", @@ -33,6 +33,7 @@ pub(crate) fn create_local_project_checkpoint_at( target.display() ) })?; + prepare_game_creator_private_path_for_read(&target, false, "checkpoint 文件")?; } let total_bytes = files.iter().map(|file| file.size).sum::(); let manifest = serde_json::json!({ @@ -42,20 +43,21 @@ pub(crate) fn create_local_project_checkpoint_at( }); let manifest_path = resolve_local_project_path(root, &checkpoint_manifest_relative_path(&checkpoint_id))?; - fs::write( + if let Some(parent) = manifest_path.parent() { + ensure_game_creator_private_directory_tree(parent, "checkpoint manifest 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "checkpoint manifest 目录")?; + } + prepare_game_creator_private_path_for_read(&manifest_path, false, "checkpoint manifest")?; + crate::write_game_creator_private_file( &manifest_path, format!( "{}\n", serde_json::to_string_pretty(&manifest) .map_err(|error| format!("序列化 checkpoint 失败:{error}"))? - ), - ) - .map_err(|error| { - format!( - "写入 checkpoint manifest 失败:{}: {error}", - manifest_path.display() ) - })?; + .as_bytes(), + "checkpoint manifest", + )?; append_agent_db_record( root, serde_json::json!({ @@ -147,13 +149,68 @@ pub(crate) fn open_project_snapshot_regular_file( } #[cfg(windows)] validate_windows_regular_file_handle(&file, label)?; + // The pathname was checked before opening, but another process can replace + // it between those two operations. Compare the opened handle identity to + // the current directory entry before any caller reads bytes; subsequent + // reads use the already-open handle and therefore are not pathname-based. + let path_metadata = fs::symlink_metadata(path) + .map_err(|error| format!("复核{label}路径失败:{}: {error}", path.display()))?; + if path_metadata.file_type().is_symlink() || !path_metadata.is_file() { + return Err(format!( + "{label}路径在安全打开期间发生替换:{}", + path.display() + )); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if path_metadata.dev() != metadata.dev() || path_metadata.ino() != metadata.ino() { + return Err(format!( + "{label}路径在安全打开期间发生替换:{}", + path.display() + )); + } + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + let mut identity_options = fs::OpenOptions::new(); + identity_options + .read(true) + .custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + let identity_file = identity_options + .open(path) + .map_err(|error| format!("复核{label}路径失败:{}: {error}", path.display()))?; + validate_windows_regular_file_handle(&identity_file, label)?; + if crate::runner::windows_regular_file_handle_identity(&identity_file, label)? + != crate::runner::windows_regular_file_handle_identity(&file, label)? + { + return Err(format!( + "{label}路径在安全打开期间发生替换:{}", + path.display() + )); + } + } Ok((file, metadata)) } +/// Opens an AGC-managed project file after the private-path owner/DACL gate +/// has had a chance to repair an inherited or foreign ACL. Callers that read +/// arbitrary user-selected files must keep using +/// `open_project_snapshot_regular_file` so importing an external file never +/// silently changes its owner. +pub(crate) fn open_project_private_regular_file( + path: &Path, + label: &str, +) -> Result<(File, fs::Metadata), String> { + prepare_game_creator_private_path_for_read(path, false, label)?; + open_project_snapshot_regular_file(path, label) +} + fn read_local_project_content_diff_source( path: &Path, ) -> Result { - let (mut file, metadata) = open_project_snapshot_regular_file(path, "内容 diff 文件")?; + let (mut file, metadata) = open_project_private_regular_file(path, "内容 diff 文件")?; let mut hasher = Sha256::new(); let mut bytes = (metadata.len() <= PROJECT_CONTENT_DIFF_MAX_FILE_BYTES) .then(|| Vec::with_capacity(metadata.len() as usize)); @@ -518,10 +575,12 @@ pub(crate) fn restore_local_project_checkpoint_at( let restored_count = restore_plan.len(); for (source, target) in restore_plan { + prepare_game_creator_private_path_for_read(&source, false, "checkpoint 源文件")?; if let Some(parent) = target.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建恢复目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "恢复目录")?; + prepare_game_creator_private_path_for_read(parent, true, "恢复目录")?; } + prepare_game_creator_private_path_for_read(&target, false, "恢复目标文件")?; fs::copy(&source, &target).map_err(|error| { format!( "恢复 checkpoint 文件失败:{} -> {}: {error}", @@ -529,6 +588,7 @@ pub(crate) fn restore_local_project_checkpoint_at( target.display() ) })?; + prepare_game_creator_private_path_for_read(&target, false, "恢复目标文件")?; } let deleted_count = delete_plan.len(); for target in delete_plan { diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/conversation.rs b/apps/ai-game-creator-shell/src-tauri/src/project/conversation.rs index 12eb9f5d0..0b35bc267 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/conversation.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/conversation.rs @@ -68,6 +68,9 @@ fn file_modified_timestamp(path: &Path) -> u64 { } fn count_conversation_messages(path: &Path) -> Result { + if !prepare_game_creator_private_path_for_read(path, false, "对话记录")? { + return Ok(0); + } match File::open(path) { Ok(file) => { let mut count = 0_u64; @@ -118,6 +121,7 @@ fn read_agent_conversation_session_catalog_unlocked( validate_project_root(root)?; let agent_id = normalize_conversation_agent_id(agent_id)?; let catalog_path = agent_conversation_session_catalog_path(root, &agent_id); + prepare_game_creator_private_path_for_read(&catalog_path, false, "Agent Session 目录")?; let mut catalog = match fs::read_to_string(&catalog_path) { Ok(content) => serde_json::from_str::(&content) .map_err(|error| { @@ -305,37 +309,16 @@ fn write_agent_conversation_session_catalog_unlocked( ) -> Result<(), String> { let path = agent_conversation_session_catalog_path(root, &catalog.agent_id); if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| { - format!("创建 Agent Session 目录失败:{}: {error}", parent.display()) - })?; + ensure_game_creator_private_directory_tree(parent, "Agent Session 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "Agent Session 目录")?; } let content = serde_json::to_string_pretty(catalog) .map_err(|error| format!("序列化 Agent Session 目录失败:{error}"))?; - let temp_path = path.with_file_name(format!( - ".{}.tmp.{}.{}", - path.file_name() - .and_then(|value| value.to_str()) - .unwrap_or("sessions.json"), - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_nanos() - )); - fs::write(&temp_path, format!("{content}\n")).map_err(|error| { - format!( - "写入 Agent Session 临时目录失败:{}: {error}", - temp_path.display() - ) - })?; - fs::rename(&temp_path, &path).map_err(|error| { - let _ = fs::remove_file(&temp_path); - format!( - "替换 Agent Session 目录失败:{} -> {}: {error}", - temp_path.display(), - path.display() - ) - }) + write_game_creator_private_file( + &path, + format!("{content}\n").as_bytes(), + "Agent Session 目录", + ) } pub(crate) fn ensure_agent_conversation_session_at( @@ -419,6 +402,7 @@ pub(crate) fn ensure_agent_session_has_no_live_tasks( let task_path = root .join(".agent/runtime/tasks") .join(format!("{agent_id}.jsonl")); + prepare_game_creator_private_path_for_read(&task_path, false, "Agent Runtime 任务")?; match File::open(&task_path) { Ok(file) => { for line in BufReader::new(file).lines() { @@ -497,6 +481,7 @@ pub(crate) fn ensure_agent_session_has_no_live_tasks( if path.extension().and_then(|value| value.to_str()) != Some("jsonl") { continue; } + prepare_game_creator_private_path_for_read(&path, false, "Agent Runtime 任务")?; let mut delegated_latest_by_run = BTreeMap::::new(); let file = File::open(&path) .map_err(|error| format!("读取 Agent Runtime 任务失败:{}: {error}", path.display()))?; @@ -558,19 +543,25 @@ pub(crate) fn create_game_creator_agent_session_at( let conversation_path = conversation_file_path_for_resolved_session(root, &agent_id, &session_id); if let Some(parent) = conversation_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建对话目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "对话目录")?; + prepare_game_creator_private_path_for_read(parent, true, "对话目录")?; } - fs::OpenOptions::new() - .create_new(true) - .write(true) - .open(&conversation_path) - .map_err(|error| { - format!( - "创建 Agent Session 对话失败:{}: {error}", - conversation_path.display() - ) - })?; + prepare_game_creator_private_path_for_read(&conversation_path, false, "对话记录")?; + let mut options = fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let file = options.open(&conversation_path).map_err(|error| { + format!( + "创建 Agent Session 对话失败:{}: {error}", + conversation_path.display() + ) + })?; + harden_new_game_creator_private_path(&conversation_path, false, "对话记录")?; + drop(file); catalog.sessions.push(AgentConversationSessionRecord { session_id: session_id.clone(), title, @@ -665,20 +656,28 @@ where let conversation_path = conversation_file_path_for_resolved_session(root, &agent_id, &session_id); if let Some(parent) = conversation_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建对话目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "对话目录")?; + prepare_game_creator_private_path_for_read(parent, true, "对话目录")?; } + prepare_game_creator_private_path_for_read( + &conversation_path, + false, + "Agent Session 分叉对话", + )?; let write_result = (|| -> Result<(), String> { - let mut file = fs::OpenOptions::new() - .create_new(true) - .write(true) - .open(&conversation_path) - .map_err(|error| { - format!( - "创建 Agent Session 分叉对话失败:{}: {error}", - conversation_path.display() - ) - })?; + let mut options = fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options.open(&conversation_path).map_err(|error| { + format!( + "创建 Agent Session 分叉对话失败:{}: {error}", + conversation_path.display() + ) + })?; for record in &records { serde_json::to_writer(&mut file, record) .map_err(|error| format!("序列化 Agent Session 分叉消息失败:{error}"))?; @@ -700,6 +699,11 @@ where let _ = fs::remove_file(&conversation_path); return Err(error); } + prepare_game_creator_private_path_for_read( + &conversation_path, + false, + "Agent Session 分叉对话", + )?; let now = unix_timestamp(); let requested_title = title.trim(); @@ -938,6 +942,7 @@ fn read_persisted_local_conversation_records_unlocked( path: &Path, ) -> Result, String> { let mut records = Vec::new(); + prepare_game_creator_private_path_for_read(path, false, "对话记录")?; match File::open(path) { Ok(file) => { for line in BufReader::new(file).lines() { @@ -1431,23 +1436,22 @@ pub(crate) fn append_markdown_entry( error_label: &str, ) -> Result<(), String> { if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("{error_label}:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, error_label)?; + prepare_game_creator_private_path_for_read(parent, true, error_label)?; } + prepare_game_creator_private_path_for_read(path, false, error_label)?; let needs_header = fs::metadata(path) .map(|metadata| metadata.len() == 0) .unwrap_or(true); - let mut file = fs::OpenOptions::new() - .create(true) - .append(true) - .open(path) - .map_err(|error| format!("{error_label}:{}: {error}", path.display()))?; - if needs_header { - file.write_all(header.as_bytes()) - .map_err(|error| format!("{error_label}:{}: {error}", path.display()))?; - } - file.write_all(entry.as_bytes()) - .map_err(|error| format!("{error_label}:{}: {error}", path.display())) + let bytes = if needs_header { + let mut bytes = Vec::with_capacity(header.len() + entry.len()); + bytes.extend_from_slice(header.as_bytes()); + bytes.extend_from_slice(entry.as_bytes()); + bytes + } else { + entry.as_bytes().to_vec() + }; + append_game_creator_private_file(path, &bytes, error_label) } pub(crate) fn append_local_permission_log_at( @@ -1474,16 +1478,12 @@ pub(crate) fn append_local_permission_log_at( let log_path = root.join(".agent/logs/command.log"); if let Some(parent) = log_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建命令日志目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "命令日志目录")?; + prepare_game_creator_private_path_for_read(parent, true, "命令日志目录")?; } + prepare_game_creator_private_path_for_read(&log_path, false, "命令日志")?; let line = format!("{} {event} {command_id}\n", unix_timestamp()); - fs::OpenOptions::new() - .create(true) - .append(true) - .open(&log_path) - .and_then(|mut file| file.write_all(line.as_bytes())) - .map_err(|error| format!("写入命令日志失败:{}: {error}", log_path.display())) + append_game_creator_private_file(&log_path, line.as_bytes(), "命令日志") } #[cfg(test)] diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/export.rs b/apps/ai-game-creator-shell/src-tauri/src/project/export.rs index 0b1238987..4beed6bc5 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/export.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/export.rs @@ -13,6 +13,7 @@ pub(crate) fn export_local_project_package_at( if !game_index_metadata.is_file() { return Err("导出试玩包前需要先生成 game/index.html".to_string()); } + prepare_game_creator_private_path_for_read(&game_index_path, false, "游戏入口")?; let game_index = fs::read_to_string(&game_index_path) .map_err(|error| format!("读取游戏入口失败:{}: {error}", game_index_path.display()))?; if game_index.trim().is_empty() { @@ -51,12 +52,22 @@ pub(crate) fn export_local_project_package_at( let package_relative_path = next_project_export_package_relative_path(root)?; let package_path = resolve_local_project_path(root, &package_relative_path)?; if let Some(parent) = package_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建导出目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "导出目录")?; + prepare_game_creator_private_path_for_read(parent, true, "导出目录")?; } + prepare_game_creator_private_path_for_read(&package_path, false, "试玩包")?; - let file = File::create(&package_path) + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let file = options + .open(&package_path) .map_err(|error| format!("创建试玩包失败:{}: {error}", package_path.display()))?; + harden_new_game_creator_private_path(&package_path, false, "试玩包")?; let mut writer = zip::ZipWriter::new(file); let options = zip::write::SimpleFileOptions::default() .compression_method(zip::CompressionMethod::Deflated); @@ -64,6 +75,7 @@ pub(crate) fn export_local_project_package_at( writer .start_file(relative_path, options) .map_err(|error| format!("写入试玩包条目失败:{relative_path}: {error}"))?; + prepare_game_creator_private_path_for_read(absolute_path, false, "导出文件")?; let bytes = fs::read(absolute_path) .map_err(|error| format!("读取导出文件失败:{}: {error}", absolute_path.display()))?; writer @@ -73,13 +85,10 @@ pub(crate) fn export_local_project_package_at( writer .finish() .map_err(|error| format!("完成试玩包失败:{}: {error}", package_path.display()))?; + prepare_game_creator_private_path_for_read(&package_path, false, "试玩包")?; let updated_at = unix_timestamp(); let log_path = root.join(".agent/logs/command.log"); - if let Some(parent) = log_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建命令日志目录失败:{}: {error}", parent.display()))?; - } let output = format!( "导出试玩包:{},{} 个文件,{}B", package_relative_path, @@ -87,12 +96,7 @@ pub(crate) fn export_local_project_package_at( total_bytes ); let line = format!("{updated_at} project.export_package: {output}\n"); - fs::OpenOptions::new() - .create(true) - .append(true) - .open(&log_path) - .and_then(|mut file| file.write_all(line.as_bytes())) - .map_err(|error| format!("写入命令日志失败:{}: {error}", log_path.display()))?; + append_game_creator_private_file(&log_path, line.as_bytes(), "命令日志")?; record_command_run( root, GameCreationAppCommandRunState { diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/external_editor_bindings.rs b/apps/ai-game-creator-shell/src-tauri/src/project/external_editor_bindings.rs index 391bb6c10..943fc4237 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/external_editor_bindings.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/external_editor_bindings.rs @@ -1111,6 +1111,12 @@ fn validate_bounded_identity(value: &str, label: &str, max_chars: usize) -> Resu fn external_editor_binding_looks_like_absolute_path(value: &str) -> bool { let bytes = value.as_bytes(); Path::new(value).is_absolute() + // A leading slash is rooted on both Unix and Windows, even though + // `Path::is_absolute` is platform-specific and treats `/tmp` as + // drive-relative on Windows. Binding identities are opaque IDs, not + // filesystem paths, so reject both rooted spellings explicitly. + || value.starts_with('/') + || value.starts_with('\\') || value.starts_with("\\\\") || value.starts_with("~/") || value.starts_with("~\\") diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/filesystem.rs b/apps/ai-game-creator-shell/src-tauri/src/project/filesystem.rs index c7f8f38e1..443a08eb3 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/filesystem.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/filesystem.rs @@ -1,7 +1,7 @@ use super::*; #[cfg(windows)] -pub(super) const PROJECT_FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; +pub(crate) const PROJECT_FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; static PROJECT_WRITE_LOCK_NONCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -135,6 +135,7 @@ fn project_write_lock_can_be_reclaimed(path: &Path) -> bool { return false; }; if metadata.file_type().is_symlink() + || windows_metadata_is_reparse_point(&metadata) || !metadata.is_file() || metadata.len() > PROJECT_WRITE_LOCK_MAX_BYTES { @@ -196,12 +197,13 @@ pub(crate) fn acquire_project_write_lock( validate_project_root(root)?; let mut path = resolve_project_write_lock_path(root)?; if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建项目锁目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "项目锁目录")?; + prepare_game_creator_private_path_for_read(parent, true, "项目锁目录")?; } // Re-check the parent after creation so skipping metadata only for the final // create_new target cannot weaken the normal ancestor link/reparse checks. path = resolve_project_write_lock_path(root)?; + prepare_game_creator_private_path_for_read(&path, false, "项目写锁")?; let payload = serde_json::json!({ "commandId": command_id, "pid": std::process::id(), @@ -212,16 +214,26 @@ pub(crate) fn acquire_project_write_lock( .map_err(|error| format!("生成项目写锁失败:{error}"))?; let mut retried_after_reclaim = false; loop { - match fs::OpenOptions::new() - .create_new(true) - .write(true) - .open(&path) + let mut options = fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(windows)] { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + match options.open(&path) { Ok(mut file) => { + if let Err(error) = harden_new_game_creator_private_path(&path, false, "项目写锁") + { + drop(file); + let _ = fs::remove_file(&path); + return Err(error); + } if let Err(error) = file.write_all(content.as_bytes()) { let _ = fs::remove_file(&path); return Err(format!("写入项目写锁失败:{}: {error}", path.display())); } + prepare_game_creator_private_path_for_read(&path, false, "项目写锁")?; return Ok(ProjectWriteLock { path, content: content.clone(), @@ -347,6 +359,7 @@ pub(crate) fn read_local_project_file_at( if !metadata.is_file() { return Err("只能读取文件".to_string()); } + prepare_game_creator_private_path_for_read(&path, false, "项目文件")?; let content = fs::read_to_string(&path) .map_err(|error| format!("读取项目文件失败:{}: {error}", path.display()))?; @@ -483,12 +496,7 @@ pub(crate) fn write_local_project_file_at( if path.exists() && !path.is_file() { return Err("只能写入文件".to_string()); } - if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建项目目录失败:{}: {error}", parent.display()))?; - } - fs::write(&path, content) - .map_err(|error| format!("写入项目文件失败:{}: {error}", path.display()))?; + crate::write_game_creator_private_file(&path, content.as_bytes(), "项目文件")?; Ok(LocalProjectFileMutationResult { path: normalized_path, @@ -516,6 +524,7 @@ pub(crate) fn delete_local_project_file_at( if !path.is_file() { return Err("只能删除文件".to_string()); } + prepare_game_creator_private_path_for_read(&path, false, "项目文件")?; fs::remove_file(&path) .map_err(|error| format!("删除项目文件失败:{}: {error}", path.display()))?; @@ -537,24 +546,17 @@ pub(crate) fn build_local_project_index_at(root: &Path) -> Result { - return Err("项目文件路径不能包含符号链接".to_string()); + Ok(metadata) + if metadata.file_type().is_symlink() + || windows_metadata_is_reparse_point(&metadata) => + { + return Err("项目文件路径不能包含符号链接或 Windows reparse point".to_string()); } Ok(_) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => { @@ -808,10 +813,18 @@ pub(crate) fn validate_project_root(root: &Path) -> Result<(), String> { if project_path_has_control_chars(root) { return Err("项目目录不能包含控制字符".to_string()); } + // Every project operation enters through this validator. On Windows the + // root may be a historical directory whose owner is still the elevated + // installer account or whose DACL is inherited. Reuse the formal prepare + // entry here so all downstream reads/writes get the same one-shot UAC + // repair and post-repair verification, instead of failing later at the + // first individual sidecar read. + #[cfg(windows)] + crate::prepare_game_creator_project_root_for_read(root, true, "项目目录")?; match fs::symlink_metadata(root) { Ok(metadata) => { - if metadata.file_type().is_symlink() { - return Err("项目目录不能是符号链接".to_string()); + if metadata.file_type().is_symlink() || windows_metadata_is_reparse_point(&metadata) { + return Err("项目目录不能是符号链接或 Windows reparse point".to_string()); } } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} @@ -822,6 +835,20 @@ pub(crate) fn validate_project_root(root: &Path) -> Result<(), String> { Ok(()) } +fn windows_metadata_is_reparse_point(metadata: &fs::Metadata) -> bool { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + return metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0; + } + #[cfg(not(windows))] + { + let _ = metadata; + false + } +} + pub(crate) fn project_path_has_control_chars(root: &Path) -> bool { root.to_string_lossy().chars().any(char::is_control) } diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/manifest.rs b/apps/ai-game-creator-shell/src-tauri/src/project/manifest.rs index 5168849e5..3f44c3185 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/manifest.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/manifest.rs @@ -253,6 +253,8 @@ fn try_open_manifest_write_lock_file(path: &Path) -> Result, String .lock() .map_err(|_| "manifest 锁安全打开门禁已损坏".to_string())?; let lock_path = manifest_lock_path(path); + let existed = + crate::prepare_game_creator_private_path_for_read(&lock_path, false, "manifest 锁")?; let mut options = fs::OpenOptions::new(); options .create(true) @@ -277,6 +279,9 @@ fn try_open_manifest_write_lock_file(path: &Path) -> Result, String lock_path.display() )); } + if !existed { + crate::harden_new_game_creator_private_path(&lock_path, false, "manifest 锁")?; + } file.set_permissions(fs::Permissions::from_mode(0o600)) .map_err(|error| format!("收紧 manifest 锁权限失败:{}: {error}", lock_path.display()))?; let path_metadata = fs::symlink_metadata(&lock_path) @@ -340,6 +345,18 @@ fn try_open_manifest_write_lock_file(path: &Path) -> Result, String )); } } + let existed = match fs::symlink_metadata(&lock_path) { + Ok(_) => true, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, + Err(_) => { + // An inherited/foreign ACL can hide an existing lock from the + // normal token. Prepare it through the formal elevation gate so + // the subsequent exclusive open does not misclassify access + // denial as a stale lock or a generic failure. + crate::prepare_game_creator_private_path_for_read(&lock_path, false, "manifest 锁")?; + true + } + }; match fs::OpenOptions::new() .create(true) .read(true) @@ -350,12 +367,21 @@ fn try_open_manifest_write_lock_file(path: &Path) -> Result, String { Ok(file) => { validate_windows_regular_file_handle(&file, "manifest 锁")?; - // 提升权限运行时,Windows 可能用 TokenOwner=Administrators 创建新文件。 - // 独占句柄与普通文件检查通过后,将这个固定锁文件收归当前 TokenUser, - // 再复核句柄并按既有规则验证 owner/DACL;不放宽旧文件的安全门禁。 - crate::initialize_windows_game_creator_file_owner_for_current_user(&lock_path)?; - validate_windows_regular_file_handle(&file, "manifest 锁")?; - crate::secure_windows_game_creator_path_for_current_user(&lock_path, false, false)?; + if existed { + // Existing files may have a foreign owner or inherited DACL; + // let the strict verifier request one-shot UAC repair. + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + &lock_path, false, true, + )?; + } else { + // Only this invocation's newly created lock may initialize its + // owner. It is still revalidated after initialization. + crate::initialize_windows_game_creator_file_owner_for_current_user(&lock_path)?; + validate_windows_regular_file_handle(&file, "manifest 锁")?; + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + &lock_path, false, false, + )?; + } Ok(Some(file)) } Err(error) @@ -402,19 +428,20 @@ pub(crate) fn init_local_game_project_at( return Err("项目名称不能为空".to_string()); } + prepare_game_creator_project_root_for_read(root, true, "本地项目目录")?; for relative in ["game", "assets", "memory", "memory/agents", "exports"] { - fs::create_dir_all(root.join(relative)).map_err(|error| { - format!( - "创建本地项目目录失败:{}: {error}", - root.join(relative).display() - ) - })?; + let path = root.join(relative); + ensure_game_creator_private_directory_tree(&path, "本地项目目录")?; + prepare_game_creator_private_path_for_read(&path, true, "本地项目目录")?; } let index_path = root.join("game/index.html"); - if !index_path.exists() { - fs::write(&index_path, DEFAULT_GAME_INDEX_HTML) - .map_err(|error| format!("写入默认游戏入口失败:{}: {error}", index_path.display()))?; + if !prepare_game_creator_private_path_for_read(&index_path, false, "默认游戏入口")? { + crate::write_game_creator_private_file( + &index_path, + DEFAULT_GAME_INDEX_HTML.as_bytes(), + "默认游戏入口", + )?; } let agent_db_path = root.join(".agent/agent.db"); @@ -430,12 +457,9 @@ pub(crate) fn init_local_game_project_at( } for relative in [".agent/logs", ".agent/runtime"] { - fs::create_dir_all(root.join(relative)).map_err(|error| { - format!( - "创建本地项目目录失败:{}: {error}", - root.join(relative).display() - ) - })?; + let path = root.join(relative); + ensure_game_creator_private_directory_tree(&path, "本地项目目录")?; + prepare_game_creator_private_path_for_read(&path, true, "本地项目目录")?; } let manifest_path = root.join(".agent/manifest.json"); @@ -466,8 +490,15 @@ pub(crate) fn import_local_godot_project_at( if project_path_has_control_chars(root) { return Err("项目目录不能包含控制字符".to_string()); } - if !root.is_dir() { - return Err("Godot 工作区目录不存在或不是文件夹".to_string()); + // The user explicitly selected this workspace as a project root. Route it + // through the project-root ACL entry so an owner-correct inherited DACL (or + // a foreign owner that requires UAC) is repaired before discovery; once the + // AGC marker is written, descendants use the stricter managed-root policy. + prepare_game_creator_project_root_for_read(root, true, "Godot 工作区目录")?; + let root_metadata = fs::symlink_metadata(root) + .map_err(|error| format!("读取 Godot 工作区目录失败:{}: {error}", root.display()))?; + if root_metadata.file_type().is_symlink() || !root_metadata.is_dir() { + return Err("Godot 工作区目录不存在或不是普通文件夹".to_string()); } let godot_project_root = discover_local_godot_project_root(root)?.ok_or_else(|| { "所选工作区未在根目录或一层子目录发现有效的普通文件 project.godot".to_string() @@ -508,12 +539,9 @@ pub(crate) fn import_local_godot_project_at( } for relative in [".agent/logs", ".agent/runtime"] { - fs::create_dir_all(root.join(relative)).map_err(|error| { - format!( - "创建 Godot 项目 Agent 目录失败:{}: {error}", - root.join(relative).display() - ) - })?; + let path = root.join(relative); + ensure_game_creator_private_directory_tree(&path, "Godot 项目 Agent 目录")?; + prepare_game_creator_private_path_for_read(&path, true, "Godot 项目 Agent 目录")?; } let mut manifest = new_game_creation_app_manifest(project_id, name); @@ -1162,8 +1190,8 @@ pub(crate) fn mutate_manifest_at( } let manifest_path = root.join(".agent/manifest.json"); if let Some(parent) = manifest_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建 manifest 目录失败:{}: {error}", parent.display()))?; + ensure_game_creator_private_directory_tree(parent, "manifest 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "manifest 目录")?; } let _write_lock = acquire_manifest_write_lock(&manifest_path)?; let (_, mut manifest) = read_or_create_manifest(root)?; @@ -1182,10 +1210,16 @@ fn manifest_backup_path(path: &Path) -> PathBuf { } pub(crate) fn manifest_storage_exists(path: &Path) -> Result { + let _ = prepare_game_creator_private_path_for_read(path, false, "manifest")?; match fs::symlink_metadata(path) { Ok(_) => Ok(true), Err(error) if error.kind() == std::io::ErrorKind::NotFound => { let backup_path = manifest_backup_path(path); + let _ = prepare_game_creator_private_path_for_read( + &backup_path, + false, + "manifest 恢复副本", + )?; match fs::symlink_metadata(&backup_path) { Ok(_) => Ok(true), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), @@ -1219,9 +1253,15 @@ fn remove_manifest_backup(path: &Path) -> Result<(), String> { pub(crate) fn read_manifest(path: &Path) -> Result { let backup_path = manifest_backup_path(path); + let _ = prepare_game_creator_private_path_for_read(path, false, "manifest")?; let (source_path, metadata, is_backup) = match fs::symlink_metadata(path) { Ok(metadata) => (path, metadata, false), Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let _ = prepare_game_creator_private_path_for_read( + &backup_path, + false, + "manifest 恢复副本", + )?; match fs::symlink_metadata(&backup_path) { Ok(metadata) => (backup_path.as_path(), metadata, true), Err(backup_error) if backup_error.kind() == std::io::ErrorKind::NotFound => { @@ -1255,6 +1295,8 @@ pub(crate) fn read_manifest(path: &Path) -> Result Res .unwrap_or_default() .as_nanos() )); - fs::write(&temp_path, format!("{payload}\n")).map_err(|error| { - format!( - "写入 manifest 临时文件失败:{}: {error}", - temp_path.display() - ) - })?; + crate::write_game_creator_private_file( + &temp_path, + format!("{payload}\n").as_bytes(), + "manifest 临时文件", + )?; install_manifest_temp_with(path, &temp_path, |from, to| fs::rename(from, to))?; + prepare_game_creator_private_path_for_read(path, false, "manifest")?; let installed = read_manifest(path)?; if installed != *manifest { return Err("manifest 安装后回读与待写入内容不一致".to_string()); diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/memory.rs b/apps/ai-game-creator-shell/src-tauri/src/project/memory.rs index a8551c0f2..c18ff0b8c 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/memory.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/memory.rs @@ -5,6 +5,15 @@ pub(crate) fn read_local_game_memory_at( scope: &str, ) -> Result { let (scope, path) = memory_file_path(root, scope)?; + let prepared = prepare_game_creator_private_path_for_read(&path, false, "游戏记忆")?; + if !prepared { + return Ok(LocalGameMemoryResult { + scope: scope.to_string(), + path: path.to_string_lossy().into_owned(), + content: String::new(), + exists: false, + }); + } match fs::read_to_string(&path) { Ok(content) => Ok(LocalGameMemoryResult { scope: scope.to_string(), @@ -28,6 +37,15 @@ pub(crate) fn read_local_agent_memory_at( ) -> Result { let relative_path = agent_role_memory_relative_path_for_task(task_id)?; let path = resolve_local_project_path(root, &relative_path)?; + let prepared = prepare_game_creator_private_path_for_read(&path, false, "Agent 记忆")?; + if !prepared { + return Ok(LocalAgentMemoryResult { + task_id: task_id.to_string(), + path: path.to_string_lossy().into_owned(), + content: String::new(), + exists: false, + }); + } match fs::read_to_string(&path) { Ok(content) => Ok(LocalAgentMemoryResult { task_id: task_id.to_string(), @@ -52,12 +70,7 @@ pub(crate) fn write_local_agent_memory_at( ) -> Result { let relative_path = agent_role_memory_relative_path_for_task(task_id)?; let path = resolve_local_project_path(root, &relative_path)?; - if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建 Agent 记忆目录失败:{}: {error}", parent.display()))?; - } - fs::write(&path, content) - .map_err(|error| format!("写入 Agent 记忆失败:{}: {error}", path.display()))?; + crate::write_game_creator_private_file(&path, content.as_bytes(), "Agent 记忆")?; Ok(LocalAgentMemoryResult { task_id: task_id.to_string(), path: path.to_string_lossy().into_owned(), @@ -72,12 +85,7 @@ pub(crate) fn write_local_game_memory_at( content: &str, ) -> Result { let (scope, path) = memory_file_path(root, scope)?; - if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建记忆目录失败:{}: {error}", parent.display()))?; - } - fs::write(&path, content) - .map_err(|error| format!("写入记忆失败:{}: {error}", path.display()))?; + crate::write_game_creator_private_file(&path, content.as_bytes(), "游戏记忆")?; Ok(LocalGameMemoryResult { scope: scope.to_string(), path: path.to_string_lossy().into_owned(), diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs b/apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs index d9cefa8e4..bb8296f32 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs @@ -1016,7 +1016,7 @@ fn read_stable_resource_edit_file( reject_sensitive_project_file_read(&normalized)?; let absolute = resolve_local_project_path(root, &normalized)?; validate_agent_runtime_inspection_ancestors(root, &absolute)?; - let (mut file, initial_metadata) = open_project_snapshot_regular_file(&absolute, label)?; + let (mut file, initial_metadata) = open_project_private_regular_file(&absolute, label)?; if initial_metadata.len() > max_bytes as u64 { return Err(format!("{label}不能超过 {} MiB", max_bytes / 1024 / 1024)); } @@ -1527,9 +1527,10 @@ fn write_resource_edit_staging( ) -> Result<(), String> { let path = resolve_local_project_path(root, &resource_edit_staging_path(operation_id))?; if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建资源编辑 staging 目录失败:{error}"))?; + ensure_game_creator_private_directory_tree(parent, "资源编辑 staging 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "资源编辑 staging 目录")?; } + prepare_game_creator_private_path_for_read(&path, false, "资源编辑 staging")?; match fs::symlink_metadata(&path) { Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => { return Err("资源编辑 staging 必须是普通文件".to_string()); @@ -1553,16 +1554,30 @@ fn write_resource_edit_staging( options.custom_flags(libc::O_NOFOLLOW); options.mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options .open(&path) .map_err(|error| format!("创建资源编辑 staging 失败:{error}"))?; + if let Err(error) = harden_new_game_creator_private_path(&path, false, "资源编辑 staging") { + drop(file); + let _ = fs::remove_file(&path); + return Err(error); + } file.write_all(bytes) .and_then(|_| file.sync_data()) - .map_err(|error| format!("写入资源编辑 staging 失败:{error}")) + .map_err(|error| { + let _ = fs::remove_file(&path); + format!("写入资源编辑 staging 失败:{error}") + }) } fn read_resource_edit_staging(root: &Path, operation_id: &str) -> Result, String> { let path = resolve_local_project_path(root, &resource_edit_staging_path(operation_id))?; + prepare_game_creator_private_path_for_read(&path, false, "资源编辑 staging")?; let metadata = fs::symlink_metadata(&path) .map_err(|error| format!("读取资源编辑 staging 失败:{error}"))?; if metadata.file_type().is_symlink() || !metadata.is_file() { @@ -1576,6 +1591,10 @@ fn read_optional_resource_edit_staging( operation_id: &str, ) -> Result>, String> { let path = resolve_local_project_path(root, &resource_edit_staging_path(operation_id))?; + let prepared = prepare_game_creator_private_path_for_read(&path, false, "资源编辑 staging")?; + if !prepared { + return Ok(None); + } match fs::symlink_metadata(&path) { Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => { Err("资源编辑 staging 必须是普通文件".to_string()) @@ -2322,10 +2341,7 @@ fn resource_edit_remote_request( }, }); } - Ok(( - "/api/editor/character-animations/generations", - body, - )) + Ok(("/api/editor/character-animations/generations", body)) } LocalProjectResourceEditKind::Video => { let mut body = serde_json::json!({ @@ -2372,10 +2388,7 @@ fn resource_edit_remote_request( "placeholder": external_canvas_placeholder("1:1"), }); } - Ok(( - "/api/editor/audios/sound-effects/generations", - body, - )) + Ok(("/api/editor/audios/sound-effects/generations", body)) } LocalProjectResourceEditKind::BackgroundMusic => { let mut body = serde_json::json!({ @@ -2392,10 +2405,7 @@ fn resource_edit_remote_request( "placeholder": external_canvas_placeholder("1:1"), }); } - Ok(( - "/api/editor/audios/background-music/generations", - body, - )) + Ok(("/api/editor/audios/background-music/generations", body)) } _ => Err("当前资源类型不是远端媒体派生".to_string()), } @@ -3861,8 +3871,10 @@ fn install_resource_edit_final_media( ) -> Result<(), String> { let absolute_path = resolve_local_project_path(root, relative_path)?; if let Some(parent) = absolute_path.parent() { - fs::create_dir_all(parent).map_err(|error| format!("创建派生资源目录失败:{error}"))?; + ensure_game_creator_private_directory_tree(parent, "派生资源目录")?; + prepare_game_creator_private_path_for_read(parent, true, "派生资源目录")?; } + prepare_game_creator_private_path_for_read(&absolute_path, false, "派生资源")?; let mut options = fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] @@ -3871,12 +3883,26 @@ fn install_resource_edit_final_media( options.custom_flags(libc::O_NOFOLLOW); options.mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options .open(&absolute_path) .map_err(|error| format!("创建派生资源失败:{error}"))?; + if let Err(error) = harden_new_game_creator_private_path(&absolute_path, false, "派生资源") + { + drop(file); + let _ = fs::remove_file(&absolute_path); + return Err(error); + } file.write_all(bytes) .and_then(|_| file.sync_data()) - .map_err(|error| format!("写入派生资源失败:{error}")) + .map_err(|error| { + let _ = fs::remove_file(&absolute_path); + format!("写入派生资源失败:{error}") + }) } fn commit_resource_edit_asset_internal( @@ -8273,10 +8299,7 @@ mod tests { Some(&canvas_context), ) .expect("build create video request"); - assert_eq!( - create_video_endpoint, - "/api/editor/videos/generations" - ); + assert_eq!(create_video_endpoint, "/api/editor/videos/generations"); assert!(create_video_body.get("referenceVideoSrcs").is_none()); assert_eq!( create_video_body["projectId"], @@ -8521,9 +8544,7 @@ mod tests { "assetObjectId": "source-video-object" }}}), ); - } else if request_line - .starts_with("POST /api/editor/videos/generations ") - { + } else if request_line.starts_with("POST /api/editor/videos/generations ") { assert!(request_lower .contains("authorization: bearer resource-editor-external-key")); assert!(request_lower.contains("idempotency-key:")); diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/resource_layout.rs b/apps/ai-game-creator-shell/src-tauri/src/project/resource_layout.rs index 8c87f9403..9723484f8 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/resource_layout.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/resource_layout.rs @@ -259,7 +259,9 @@ fn try_open_resource_layout_write_lock_file(root: &Path) -> Result, Ok(file) => { validate_windows_regular_file_handle(&file, "资源布局锁")?; if existed { - crate::secure_windows_game_creator_path_for_current_user(&path, false, true)?; + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + &path, false, true, + )?; } else { crate::initialize_windows_game_creator_file_owner_for_current_user(&path)?; } @@ -379,7 +381,7 @@ fn validate_existing_resource_layout_storage( let path = resolve_local_project_path(root, relative_path)?; match fs::symlink_metadata(&path) { Ok(_) => { - let (_, metadata) = open_project_snapshot_regular_file(&path, "资源布局 sidecar")?; + let (_, metadata) = open_project_private_regular_file(&path, "资源布局 sidecar")?; if metadata.len() > RESOURCE_LAYOUT_MAX_BYTES as u64 { return Err(format!( "资源布局 sidecar 超过 {RESOURCE_LAYOUT_MAX_BYTES} 字节上限" @@ -398,7 +400,7 @@ fn validate_existing_resource_layout_storage( match fs::symlink_metadata(&backup_path) { Ok(_) => { let (_, metadata) = - open_project_snapshot_regular_file(&backup_path, "资源布局恢复副本")?; + open_project_private_regular_file(&backup_path, "资源布局恢复副本")?; if metadata.len() > RESOURCE_LAYOUT_MAX_BYTES as u64 { return Err(format!( "资源布局恢复副本超过 {RESOURCE_LAYOUT_MAX_BYTES} 字节上限" diff --git a/apps/ai-game-creator-shell/src-tauri/src/project/verification.rs b/apps/ai-game-creator-shell/src-tauri/src/project/verification.rs index f30dd9710..acc780b40 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/verification.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/verification.rs @@ -15,6 +15,7 @@ pub(crate) fn run_limited_local_command_at( } let game_index_path = root.join("game/index.html"); + prepare_game_creator_private_path_for_read(&game_index_path, false, "游戏入口")?; let html = fs::read_to_string(&game_index_path) .map_err(|error| format!("读取游戏入口失败:{}: {error}", game_index_path.display()))?; if !html.contains("(&content) @@ -736,14 +721,13 @@ pub(crate) fn write_project_permission_policy_at( validate_project_root(root)?; let policy = normalize_project_permission_policy(policy)?; let path = root.join(PROJECT_PERMISSION_POLICY_PATH); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建项目权限策略目录失败:{}: {error}", parent.display()))?; - } let content = serde_json::to_string_pretty(&policy) .map_err(|error| format!("序列化项目权限策略失败:{error}"))?; - fs::write(&path, format!("{content}\n")) - .map_err(|error| format!("写入项目权限策略失败:{}: {error}", path.display()))?; + crate::write_game_creator_private_file( + &path, + format!("{content}\n").as_bytes(), + "项目权限策略", + )?; append_agent_db_record( root, serde_json::json!({ diff --git a/apps/ai-game-creator-shell/src-tauri/src/resource_inspect.rs b/apps/ai-game-creator-shell/src-tauri/src/resource_inspect.rs index 690c95b45..a311d04c9 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/resource_inspect.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/resource_inspect.rs @@ -2,8 +2,8 @@ use crate::image_inspect::{ same_open_file_identity, same_open_file_snapshot, validate_agent_runtime_inspection_ancestors, }; use crate::project::{ - normalize_relative_path, open_project_snapshot_regular_file, - reject_sensitive_project_file_read, resolve_local_project_path, + normalize_relative_path, open_project_private_regular_file, reject_sensitive_project_file_read, + resolve_local_project_path, }; use crate::resource_preview_scheduler::ProjectResourcePreviewScopeCancellation; use base64::Engine as _; @@ -354,7 +354,7 @@ fn read_stable_project_resource( let absolute = resolve_local_project_path(root, normalized)?; validate_agent_runtime_inspection_ancestors(root, &absolute)?; cancellation.check()?; - let (mut file, initial_metadata) = open_project_snapshot_regular_file(&absolute, label)?; + let (mut file, initial_metadata) = open_project_private_regular_file(&absolute, label)?; cancellation.check()?; if initial_metadata.len() > max_bytes { return Err(format!("{label}不能超过 {} MiB", max_bytes / 1024 / 1024)); @@ -392,7 +392,7 @@ fn read_stable_project_resource( return Err(format!("{label}读取期间发生漂移:{normalized}")); } cancellation.check()?; - let (reopened, reopened_metadata) = open_project_snapshot_regular_file(&absolute, label)?; + let (reopened, reopened_metadata) = open_project_private_regular_file(&absolute, label)?; if !same_open_file_identity(&file, &initial_metadata, &reopened, &reopened_metadata)? { return Err(format!("{label}路径读取期间发生替换:{normalized}")); } diff --git a/apps/ai-game-creator-shell/src-tauri/src/runner.rs b/apps/ai-game-creator-shell/src-tauri/src/runner.rs index be22c4d96..5767b0900 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/runner.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/runner.rs @@ -21,12 +21,14 @@ pub(crate) use client::{ shutdown_external_agent_runner_if_idle, steer_external_agent_runner, wake_external_agent_runner_pending, wake_external_agent_runner_pending_for_run, }; -#[cfg(windows)] -pub(crate) use endpoint::validate_windows_regular_file_handle; pub(crate) use endpoint::{ acquire_external_agent_runner_gui_owner_lock, external_agent_runner_enabled, external_agent_runner_is_server_process, }; +#[cfg(windows)] +pub(crate) use endpoint::{ + validate_windows_regular_file_handle, windows_regular_file_handle_identity, +}; #[allow(unused_imports)] pub(crate) use protocol::{ExternalAgentRunnerStatus, EXTERNAL_AGENT_RUNNER_PROTOCOL_VERSION}; pub(crate) use server::{ diff --git a/apps/ai-game-creator-shell/src-tauri/src/runner/endpoint.rs b/apps/ai-game-creator-shell/src-tauri/src/runner/endpoint.rs index bfbd56241..79a687e43 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/runner/endpoint.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/runner/endpoint.rs @@ -378,12 +378,16 @@ pub(super) fn private_create_new_file(path: &Path) -> io::Result { let secured = (|| { validate_windows_regular_file_handle(&file, "新建私有临时文件") .map_err(io::Error::other)?; - crate::initialize_windows_game_creator_file_owner_for_current_user(path) - .map_err(io::Error::other)?; + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, false, true, + ) + .map_err(io::Error::other)?; validate_windows_regular_file_handle(&file, "新建私有临时文件") .map_err(io::Error::other)?; - crate::secure_windows_game_creator_path_for_current_user(path, false, false) - .map_err(io::Error::other) + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, false, false, + ) + .map_err(io::Error::other) })(); if let Err(error) = secured { drop(file); @@ -399,6 +403,59 @@ pub(super) fn private_create_new_file(path: &Path) -> io::Result { } } +#[cfg(windows)] +pub(crate) fn windows_regular_file_handle_identity( + file: &File, + label: &str, +) -> Result<(u32, u64), String> { + use std::ffi::c_void; + use std::os::windows::io::AsRawHandle; + + #[repr(C)] + struct FileTime { + low_date_time: u32, + high_date_time: u32, + } + + #[repr(C)] + struct ByHandleFileInformation { + file_attributes: u32, + creation_time: FileTime, + last_access_time: FileTime, + last_write_time: FileTime, + volume_serial_number: u32, + file_size_high: u32, + file_size_low: u32, + number_of_links: u32, + file_index_high: u32, + file_index_low: u32, + } + + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetFileInformationByHandle( + file: *mut c_void, + information: *mut ByHandleFileInformation, + ) -> i32; + } + + const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; + // SAFETY: the structure is plain data initialized by GetFileInformationByHandle. + let mut information = unsafe { std::mem::zeroed::() }; + // SAFETY: file owns a live kernel handle and information is a valid output pointer. + if unsafe { GetFileInformationByHandle(file.as_raw_handle().cast(), &mut information) } == 0 { + return Err(format!( + "读取 {label} Windows 文件句柄信息失败:{}", + io::Error::last_os_error() + )); + } + Ok(( + information.volume_serial_number, + (u64::from(information.file_index_high) << 32) | u64::from(information.file_index_low), + )) +} + #[cfg(windows)] pub(crate) fn validate_windows_regular_file_handle(file: &File, label: &str) -> Result<(), String> { use std::ffi::c_void; @@ -600,7 +657,9 @@ pub(super) fn write_external_agent_runner_endpoint_atomic( } #[cfg(windows)] - crate::secure_windows_game_creator_path_for_current_user(path, false, true)?; + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, false, true, + )?; Ok(()) } @@ -630,6 +689,14 @@ pub(super) fn open_external_agent_runner_endpoint_file(path: &Path) -> Result EXTERNAL_AGENT_RUNNER_MAX_ENDPOINT_BYTES { @@ -853,6 +922,12 @@ pub(super) fn try_open_external_agent_runner_lock( )); } + // Repair an existing lock before opening it. Otherwise an inherited + // DACL can make the first OpenOptions call fail before the UAC path gets + // a chance to run. Missing lock files are created below and hardened + // through the same gate after the handle is acquired. + crate::prepare_game_creator_private_path_for_read(path, false, label)?; + match OpenOptions::new() .create(true) .read(true) @@ -879,9 +954,10 @@ pub(super) fn try_open_external_agent_runner_lock( // lock path is known to be a stale, single-link, non-reparse regular file inside // the current TokenUser's private AppData. Repairing its owner is therefore safe // and is required when Windows creates it with TokenOwner=Administrators. - crate::initialize_windows_game_creator_file_owner_for_current_user(path)?; + crate::secure_windows_game_creator_path_for_current_user_with_auto_elevation( + path, false, true, + )?; validate_windows_regular_file_handle(&file, label)?; - crate::secure_windows_game_creator_path_for_current_user(path, false, false)?; Ok(Some(file)) } Err(error) if windows_external_agent_runner_lock_is_busy_error(&error) => Ok(None), diff --git a/apps/ai-game-creator-shell/src-tauri/src/runner/project_owner.rs b/apps/ai-game-creator-shell/src-tauri/src/runner/project_owner.rs index 6092dcf2e..6b07936dd 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/runner/project_owner.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/runner/project_owner.rs @@ -334,6 +334,11 @@ pub(super) fn open_windows_project_owner_root(root: &Path) -> Result 2); let planner = status @@ -917,7 +1016,6 @@ fn llm_config_check_reports_per_agent_status_without_leaking_keys() { .find(|agent| agent.agent_id == "planner") .expect("planner status"); assert!(planner.configured); - assert!(planner.api_key_present); assert_eq!(planner.model.as_deref(), Some("planner-model")); assert_eq!(planner.api_kind, "anthropic"); assert!(!planner.web_search_enabled); @@ -1008,7 +1106,8 @@ fn llm_status_cli_lines_include_agent_errors_without_leaking_keys() { let status = GameCreatorLlmConfigStatus { agent_mode: GAME_CREATOR_AGENT_MODE_PROVIDER.to_string(), configured: false, - api_key_present: false, + account_credential_state: "not_required".to_string(), + official_route_locked: false, base_url: Some("https://global.example.test/v1".to_string()), model: Some("global-model".to_string()), api_kind: "openai_responses".to_string(), @@ -1027,7 +1126,8 @@ fn llm_status_cli_lines_include_agent_errors_without_leaking_keys() { agent_id: "generator".to_string(), label: "Generator".to_string(), configured: false, - api_key_present: false, + account_credential_state: "not_required".to_string(), + official_route_locked: false, base_url: Some("https://generator.example.test/v1".to_string()), model: Some("generator-model".to_string()), api_kind: "openai_chat".to_string(), @@ -1580,6 +1680,29 @@ fn windows_private_dacl_does_not_reassert_an_owner_that_already_matches() { ); } +#[cfg(windows)] +#[test] +fn windows_acl_repair_classifies_foreign_owner_and_permission_failures_for_elevation() { + assert!(windows_acl_error_may_need_elevation( + "Windows 安全对象不属于当前用户:C:\\Users\\test\\AppData" + )); + assert!(windows_acl_error_may_need_elevation( + "Windows DACL 必须禁止继承并仅限当前用户:C:\\Users\\test\\AppData" + )); + assert!(windows_acl_error_may_need_elevation( + "读取 Windows owner 失败:error 5" + )); + assert!(windows_acl_error_may_need_elevation( + "启用 Windows SeTakeOwnershipPrivilege 失败:error 1300" + )); + assert!(!windows_acl_error_may_need_elevation( + "客户端 AppData 配置目录不能是 Windows reparse point" + )); + assert!(!windows_acl_error_may_need_elevation( + "待修复私有对象不能是 Windows reparse point 或链接" + )); +} + #[cfg(windows)] #[test] fn windows_appdata_validation_does_not_follow_directory_links() { diff --git a/apps/ai-game-creator-shell/src-tauri/src/ui_editor/persistence.rs b/apps/ai-game-creator-shell/src-tauri/src/ui_editor/persistence.rs index 9557d24b2..a20a04b26 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/ui_editor/persistence.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/ui_editor/persistence.rs @@ -10,7 +10,7 @@ use crate::*; use nalgebra::Vector2; use serde::{Deserialize, Serialize}; use std::collections::HashSet; -use std::fs::{self, File}; +use std::fs; use std::io::{Read, Write}; use std::path::Path; use std::time::{SystemTime, UNIX_EPOCH}; @@ -312,7 +312,7 @@ fn read_valid_ui_design_document_path( } fn read_ui_design_document_path(path: &Path) -> Result { - let (mut file, metadata) = open_project_snapshot_regular_file(path, "UI 设计 State")?; + let (mut file, metadata) = open_project_private_regular_file(path, "UI 设计 State")?; if metadata.len() > UI_DESIGN_STATE_MAX_BYTES as u64 { return Err(format!( "UI 设计 State 超过 {UI_DESIGN_STATE_MAX_BYTES} 字节上限" @@ -386,9 +386,11 @@ fn write_ui_design_raw_file(path: &Path, label: &str, bytes: &[u8]) -> Result<() return Err(format!("{label} 超过 {UI_DESIGN_STATE_MAX_BYTES} 字节上限")); } let parent = path.parent().ok_or_else(|| format!("{label} 缺少父目录"))?; - fs::create_dir_all(parent).map_err(|error| format!("创建 {label} 目录失败:{error}"))?; + ensure_game_creator_private_directory_tree(parent, label)?; + prepare_game_creator_private_path_for_read(parent, true, label)?; + prepare_game_creator_private_path_for_read(path, false, label)?; if fs::symlink_metadata(path).is_ok() { - open_project_snapshot_regular_file(path, label)?; + open_project_private_regular_file(path, label)?; } let name = path @@ -408,12 +410,22 @@ fn write_ui_design_raw_file(path: &Path, label: &str, bytes: &[u8]) -> Result<() use std::os::unix::fs::OpenOptionsExt; options.custom_flags(libc::O_NOFOLLOW).mode(0o600); } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } let mut file = options.open(&temp_path).map_err(|error| { format!( "创建 {label} 临时文件失败:{}: {error}", temp_path.display() ) })?; + if let Err(error) = harden_new_game_creator_private_path(&temp_path, false, label) { + drop(file); + let _ = fs::remove_file(&temp_path); + return Err(error); + } file.write_all(bytes) .and_then(|_| file.sync_data()) .map_err(|error| { @@ -424,7 +436,6 @@ fn write_ui_design_raw_file(path: &Path, label: &str, bytes: &[u8]) -> Result<() ) })?; drop(file); - match fs::rename(&temp_path, path) { // `.previous` is prepared by write_ui_design_document before this call; // preserve it on the normal atomic-rename path for startup recovery. @@ -456,8 +467,9 @@ fn write_ui_design_raw_file(path: &Path, label: &str, bytes: &[u8]) -> Result<() remove_agent_runtime_json_sidecar_backup(&replacement_path, label)?; } } + prepare_game_creator_private_path_for_read(path, false, label)?; #[cfg(unix)] - File::open(parent) + std::fs::File::open(parent) .and_then(|directory| directory.sync_all()) .map_err(|error| format!("同步 {label} 目录失败:{}: {error}", parent.display()))?; Ok(()) diff --git a/apps/ai-game-creator-shell/src-tauri/src/ui_editor/resource_bridge.rs b/apps/ai-game-creator-shell/src-tauri/src/ui_editor/resource_bridge.rs index 0200500d5..db271aee7 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/ui_editor/resource_bridge.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/ui_editor/resource_bridge.rs @@ -1,10 +1,11 @@ use crate::ui_editor::persistence::initialize_ui_design_state_with_source_image_at; use crate::{ acquire_project_write_lock, advance_agent_runtime_project_revision_locked, - enforce_project_permission_policy, read_existing_manifest_for_project, - read_game_creator_agent_runtime_project_revision, register_local_asset_at, - resolve_local_project_path, write_manifest, GameCreationAppAssetManifestEntry, - GameCreationAppAssetSource, GameCreationAppAssetSourceKind, GameCreationAppManifest, + enforce_project_permission_policy, prepare_game_creator_private_path_for_read, + read_existing_manifest_for_project, read_game_creator_agent_runtime_project_revision, + register_local_asset_at, resolve_local_project_path, write_manifest, + GameCreationAppAssetManifestEntry, GameCreationAppAssetSource, GameCreationAppAssetSourceKind, + GameCreationAppManifest, }; use image::GenericImageView; use serde::{Deserialize, Serialize}; @@ -81,6 +82,7 @@ pub(crate) fn ensure_ui_design_resource_for_prototype( .unwrap_or(prototype_asset_id) .to_string(); let source_absolute_path = resolve_local_project_path(root, &source_path)?; + prepare_game_creator_private_path_for_read(&source_absolute_path, false, "UI 原型图片")?; let dimensions = image::open(&source_absolute_path) .map_err(|error| format!("读取 UI 原型图片失败:{error}"))? .dimensions(); @@ -108,12 +110,7 @@ pub(crate) fn ensure_ui_design_resource_for_prototype( let (resource_name, relative_path) = next_ui_design_path(root, &manifest)?; let absolute_path = resolve_local_project_path(root, &relative_path)?; - if let Some(parent) = absolute_path.parent() { - fs::create_dir_all(parent) - .map_err(|error| format!("创建 UI 资源目录失败:{}: {error}", parent.display()))?; - } - fs::write(&absolute_path, "") - .map_err(|error| format!("创建 UI 资源失败:{}: {error}", absolute_path.display()))?; + crate::write_game_creator_private_file(&absolute_path, b"", "UI 资源")?; let asset = match register_local_asset_at( root, diff --git a/apps/ai-game-creator-shell/src-tauri/src/ui_editor/workflow.rs b/apps/ai-game-creator-shell/src-tauri/src/ui_editor/workflow.rs index 829782148..9d1e68871 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/ui_editor/workflow.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/ui_editor/workflow.rs @@ -396,6 +396,7 @@ fn discover_ui_pages(root: &Path) -> Result, Strin let mut declarations = Vec::<(UiWorkflowPageDeclaration, String)>::new(); let registry_path = resolve_local_project_path(root, UI_WORKFLOW_PAGE_REGISTRY_PATH)?; if registry_path.exists() { + prepare_game_creator_private_path_for_read(®istry_path, false, "UI 页面注册表")?; let metadata = fs::symlink_metadata(®istry_path) .map_err(|error| format!("读取 UI 页面注册表失败:{error}"))?; if metadata.file_type().is_symlink() || !metadata.is_file() { @@ -425,6 +426,7 @@ fn discover_ui_pages(root: &Path) -> Result, Strin if !path.exists() { continue; } + prepare_game_creator_private_path_for_read(&path, false, "UI 页面声明文件")?; let metadata = fs::symlink_metadata(&path) .map_err(|error| format!("读取 UI 页面声明文件失败:{relative}: {error}"))?; if metadata.file_type().is_symlink() { @@ -732,19 +734,37 @@ fn ensure_page_ui_resource( } else { let relative_path = workflow_relative_path(source, &page.page_id); let absolute_path = resolve_local_project_path(root, &relative_path)?; - if absolute_path.exists() { + if prepare_game_creator_private_path_for_read(&absolute_path, false, "UI workflow 资源")? + { return Err(format!( "UI workflow 资源路径已存在但未登记:{relative_path}" )); } - fs::create_dir_all( - absolute_path - .parent() - .ok_or_else(|| "UI workflow 路径缺少父目录".to_string())?, - ) - .map_err(|error| format!("创建 UI workflow 目录失败:{error}"))?; - fs::write(&absolute_path, b"") + let parent = absolute_path + .parent() + .ok_or_else(|| "UI workflow 路径缺少父目录".to_string())?; + ensure_game_creator_private_directory_tree(parent, "UI workflow 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "UI workflow 目录")?; + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut file = options + .open(&absolute_path) .map_err(|error| format!("创建 UI workflow 资源失败:{error}"))?; + if let Err(error) = + harden_new_game_creator_private_path(&absolute_path, false, "UI workflow 资源") + { + drop(file); + let _ = fs::remove_file(&absolute_path); + return Err(error); + } + file.sync_all() + .map_err(|error| format!("同步 UI workflow 资源失败:{error}"))?; + drop(file); let registered = register_local_asset_at( root, &relative_path, @@ -1349,6 +1369,7 @@ fn validate_application_marker( return Err("applicationPath 必须位于 game/".to_string()); } let path = resolve_local_project_path(root, &normalized)?; + prepare_game_creator_private_path_for_read(&path, false, "applicationPath")?; let metadata = fs::symlink_metadata(&path) .map_err(|error| format!("读取 applicationPath 失败:{error}"))?; if metadata.file_type().is_symlink() || !metadata.is_file() || metadata.len() == 0 { @@ -1383,6 +1404,7 @@ fn apply_application_marker( return Err("applicationPath 必须位于 game/".to_string()); } let path = resolve_local_project_path(root, &normalized)?; + prepare_game_creator_private_path_for_read(&path, false, "applicationPath")?; let metadata = fs::symlink_metadata(&path) .map_err(|error| format!("读取 applicationPath 失败:{error}"))?; if metadata.file_type().is_symlink() || !metadata.is_file() || metadata.len() == 0 { @@ -1405,7 +1427,7 @@ fn apply_application_marker( return Ok(()); } let next = format!("{content}\n{marker_comment}\n"); - fs::write(&path, next.as_bytes()) + crate::write_game_creator_private_file(&path, next.as_bytes(), "applicationPath") .map_err(|error| format!("应用 UI 页面 {} 到游戏失败:{error}", page_id))?; advance_agent_runtime_project_revision_locked(root) .map(|_| ()) @@ -1423,11 +1445,11 @@ fn write_final_receipt( let digest = Sha256::digest(source_asset_id.as_bytes()); let relative = format!(".agent/ui-workflows/{}.json", &format!("{digest:x}")[..24]); let path = resolve_local_project_path(root, &relative)?; - fs::create_dir_all( - path.parent() - .ok_or_else(|| "UI workflow receipt 缺少父目录".to_string())?, - ) - .map_err(|error| format!("创建 UI workflow receipt 目录失败:{error}"))?; + let parent = path + .parent() + .ok_or_else(|| "UI workflow receipt 缺少父目录".to_string())?; + ensure_game_creator_private_directory_tree(parent, "UI workflow receipt 目录")?; + prepare_game_creator_private_path_for_read(parent, true, "UI workflow receipt 目录")?; let receipt = UiWorkflowReceipt { schema_version: UI_WORKFLOW_RECEIPT_SCHEMA_VERSION.to_string(), project_id: project_id.to_string(), @@ -1438,10 +1460,34 @@ fn write_final_receipt( let bytes = serde_json::to_vec_pretty(&receipt) .map_err(|error| format!("序列化 UI workflow receipt 失败:{error}"))?; let temporary = path.with_extension("json.tmp"); - fs::write(&temporary, &bytes) + let mut temporary_options = fs::OpenOptions::new(); + temporary_options.write(true).create_new(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + temporary_options.custom_flags(crate::PROJECT_FILE_FLAG_OPEN_REPARSE_POINT); + } + let mut temporary_file = temporary_options + .open(&temporary) + .map_err(|error| format!("创建 UI workflow receipt 临时文件失败:{error}"))?; + if let Err(error) = + harden_new_game_creator_private_path(&temporary, false, "UI workflow receipt 临时文件") + { + drop(temporary_file); + let _ = fs::remove_file(&temporary); + return Err(error); + } + temporary_file + .write_all(&bytes) + .and_then(|_| temporary_file.sync_all()) .map_err(|error| format!("写入 UI workflow receipt 临时文件失败:{error}"))?; - fs::rename(&temporary, &path) - .map_err(|error| format!("安装 UI workflow receipt 失败:{error}"))?; + drop(temporary_file); + prepare_game_creator_private_path_for_read(&path, false, "UI workflow receipt")?; + fs::rename(&temporary, &path).map_err(|error| { + let _ = fs::remove_file(&temporary); + format!("安装 UI workflow receipt 失败:{error}") + })?; + prepare_game_creator_private_path_for_read(&path, false, "UI workflow receipt")?; let installed = fs::read(&path).map_err(|error| format!("回读 UI workflow receipt 失败:{error}"))?; if installed != bytes { diff --git a/apps/ai-game-creator-shell/src/App.tsx b/apps/ai-game-creator-shell/src/App.tsx index e265d1e82..debc671a1 100644 --- a/apps/ai-game-creator-shell/src/App.tsx +++ b/apps/ai-game-creator-shell/src/App.tsx @@ -5254,8 +5254,8 @@ export function App({ ? `LLM 已配置:${formatLlmRouteEndpoint(status)}。` : `LLM 未就绪:${status.error ?? '配置不完整'}。${ status.reasoningEffort ? `推理 ${status.reasoningEffort},` : '' - }联网检索 ${status.webSearchEnabled ? '开启' : '关闭'},API Key:${ - status.apiKeyPresent ? '已读取' : '未读取' + }联网检索 ${status.webSearchEnabled ? '开启' : '关闭'},账号凭据:${ + status.accountCredentialState ?? '未检查' }。`; setMessages((current) => [ ...current, @@ -11036,6 +11036,7 @@ export function App({ {runtimeConfigOpen ? ( setRuntimeConfigOpen(false)} onLog={(entry) => setCommandLog((current) => [...current, entry])} /> diff --git a/apps/ai-game-creator-shell/src/app/types.ts b/apps/ai-game-creator-shell/src/app/types.ts index 23474fb71..8525ca603 100644 --- a/apps/ai-game-creator-shell/src/app/types.ts +++ b/apps/ai-game-creator-shell/src/app/types.ts @@ -618,7 +618,8 @@ export type GameCreatorLlmReasoningEffort = export interface GameCreatorLlmConfigStatus { agentMode: GameCreatorAgentMode; configured: boolean; - apiKeyPresent: boolean; + accountCredentialState?: string; + officialRouteLocked?: boolean; baseUrl: string | null; model: string | null; apiKind: string; @@ -637,7 +638,8 @@ export interface GameCreatorAgentLlmConfigStatus { agentId: string; label: string; configured: boolean; - apiKeyPresent: boolean; + accountCredentialState?: string; + officialRouteLocked?: boolean; baseUrl: string | null; model: string | null; apiKind: string; diff --git a/apps/ai-game-creator-shell/src/features/app-shell/useDeveloperAgentPanel.ts b/apps/ai-game-creator-shell/src/features/app-shell/useDeveloperAgentPanel.ts index ef39f1443..77ac80c1e 100644 --- a/apps/ai-game-creator-shell/src/features/app-shell/useDeveloperAgentPanel.ts +++ b/apps/ai-game-creator-shell/src/features/app-shell/useDeveloperAgentPanel.ts @@ -617,11 +617,11 @@ export function useDeveloperAgentPanel(launcherView: LauncherView) { agentStatus.reasoningEffort ? `,推理 ${agentStatus.reasoningEffort}` : '' - },联网检索 ${agentStatus.webSearchEnabled ? '开启' : '关闭'},API Key ${ - agentStatus.apiKeyPresent ? '已读取' : '未读取' + },联网检索 ${agentStatus.webSearchEnabled ? '开启' : '关闭'},账号凭据 ${ + agentStatus.accountCredentialState ?? '未检查' }` : `当前 Agent LLM 未就绪:${ - agentStatus.error ?? '缺少 API Key 或模型配置' + agentStatus.error ?? '账号凭据或模型配置不可用' }${ agentStatus.reasoningEffort ? `(推理 ${agentStatus.reasoningEffort})` diff --git a/apps/ai-game-creator-shell/src/features/project-summary/agentPresentation.ts b/apps/ai-game-creator-shell/src/features/project-summary/agentPresentation.ts index 126acff67..58347fb5f 100644 --- a/apps/ai-game-creator-shell/src/features/project-summary/agentPresentation.ts +++ b/apps/ai-game-creator-shell/src/features/project-summary/agentPresentation.ts @@ -785,7 +785,7 @@ export function formatLlmAgentStatusLine( ...(agent.reasoningEffort ? [`推理 ${agent.reasoningEffort}`] : []), `流式 ${agent.stream ? '开启' : '关闭'}`, `联网检索 ${agent.webSearchEnabled ? '开启' : '关闭'}`, - `API Key ${agent.apiKeyPresent ? '已读取' : '未读取'}`, + `账号凭据 ${agent.accountCredentialState ?? '未检查'}`, ]; if (!agent.configured && agent.error) { parts.push(`错误:${agent.error}`); @@ -803,7 +803,7 @@ export function formatLlmRouteEndpoint( | 'reasoningEffort' | 'stream' | 'webSearchEnabled' - | 'apiKeyPresent' + | 'accountCredentialState' >, ) { if (isCodexAgentMode(status.agentMode)) { @@ -815,7 +815,7 @@ export function formatLlmRouteEndpoint( status.reasoningEffort ? `,推理 ${status.reasoningEffort}` : '' },流式 ${status.stream ? '开启' : '关闭'},联网检索 ${ status.webSearchEnabled ? '开启' : '关闭' - },API Key ${status.apiKeyPresent ? '已读取' : '未读取'}`; + },账号凭据 ${status.accountCredentialState ?? '未检查'}`; } export function isSameResolvedLlmRouteAsGlobal( @@ -932,7 +932,7 @@ export function formatAgentCardLlmStatus( : []), `流式${agentStatus.stream ? '开' : '关'}`, `联网检索${agentStatus.webSearchEnabled ? '开' : '关'}`, - `Key${agentStatus.apiKeyPresent ? '已读' : '未读'}`, + `账号凭据${agentStatus.accountCredentialState ?? '未检查'}`, ]), ].join(' · '); } @@ -1008,7 +1008,7 @@ export function formatAgentDialogLlmStatus( : []), `流式 ${agentStatus.stream ? '开启' : '关闭'}`, `联网检索 ${agentStatus.webSearchEnabled ? '开启' : '关闭'}`, - `API Key ${agentStatus.apiKeyPresent ? '已读取' : '未读取'}`, + `账号凭据 ${agentStatus.accountCredentialState ?? '未检查'}`, ]; if (!agentStatus.configured && agentStatus.error) { parts.push(`错误:${agentStatus.error}`); diff --git a/apps/ai-game-creator-shell/src/features/runtime-config/RuntimeConfigDialog.tsx b/apps/ai-game-creator-shell/src/features/runtime-config/RuntimeConfigDialog.tsx index 386c6d2cf..e37e7bd4d 100644 --- a/apps/ai-game-creator-shell/src/features/runtime-config/RuntimeConfigDialog.tsx +++ b/apps/ai-game-creator-shell/src/features/runtime-config/RuntimeConfigDialog.tsx @@ -13,7 +13,6 @@ import { } from 'lucide-react'; import { type FormEvent, useEffect, useRef, useState } from 'react'; -import { createGameCreationAppSeedTasks } from '../../../../../packages/shared/src/contracts/gameCreationApp'; import BRAND_ICON from '../../../../../packages/shared/src/icons/taonier-product-ip.png'; import { APP_NAME, APP_VERSION } from '../../app/appMetadata'; import { @@ -23,46 +22,18 @@ import { } from '../../app/dialogs'; import { resolveTauriInvoke } from '../../app/tauri'; import { - type GameCreatorAgentLlmConfig, type GameCreatorAppConfig, type GameCreatorAppConfigView, - type GameCreatorLlmApiKind, - type GameCreatorLlmConfig, + type GameCreatorLlmConfigStatus, type GameCreatorLlmReasoningEffort, gameCreatorLlmReasoningEfforts, - type RuntimeAgentLlmProviderPresetId, - type RuntimeLlmProviderPresetId, } from '../../app/types'; -const runtimeAgentReasoningEffortDefaults = { - 'project-supervisor': 'high', - planner: 'high', - orchestrator: 'medium', - generator: 'high', - evaluator: 'high', - 'design-director': 'medium', - 'design-foundation': 'high', - 'balance-director': 'medium', - 'balance-seed': 'medium', - 'art-director': 'high', - 'art-asset-plan': 'high', - 'art-polish': 'medium', - 'audio-director': 'low', - 'audio-asset-plan': 'medium', - 'code-director': 'medium', - 'code-prototype': 'high', - 'quality-review': 'high', - 'preview-readiness': 'low', - 'preview-playtest': 'low', - 'publish-strategy': 'low', - 'publish-package': 'medium', -} as const satisfies Record; - const defaultRuntimeConfigDraft: GameCreatorAppConfig = { agentMode: 'codex_app_server', llm: { apiKey: '', - baseUrl: 'https://dev.genarrative.world/gpt/v1', + baseUrl: 'https://router.genarrative.world/v1', model: 'gpt-5.6-sol', apiKind: 'openai_responses', reasoningEffort: 'max', @@ -82,6 +53,42 @@ const defaultRuntimeConfigDraft: GameCreatorAppConfig = { }, }; +const OFFICIAL_LLM_BASE_URL = 'https://router.genarrative.world/v1'; +const OFFICIAL_LLM_MODEL = 'gpt-5.6-sol'; + +function formatAccountCredentialState( + status: GameCreatorLlmConfigStatus | null, +) { + switch (status?.accountCredentialState) { + case 'ready': + return { label: '账号 Key 已就绪', tone: 'success' as const }; + case 'login_required': + return { label: '请先登录陶泥儿账号', tone: 'warning' as const }; + case 'permission_required': + case 'forbidden': + return { + label: '账号 Key 权限不足,请重新登录', + tone: 'warning' as const, + }; + case 'acl_repair_required': + return { label: '本机凭据权限需要修复', tone: 'warning' as const }; + case 'unavailable': + return { + label: '账号 Key 暂不可用,请稍后重试', + tone: 'warning' as const, + }; + case 'not_required': + return { + label: '当前发行版不需要本地账号 Key', + tone: 'neutral' as const, + }; + default: + return status?.configured + ? { label: '账号权限已就绪', tone: 'success' as const } + : { label: '尚未检查账号权限', tone: 'neutral' as const }; + } +} + type RuntimeSettingsSection = | 'general' | 'agents' @@ -132,91 +139,6 @@ const runtimeSettingsSections = [ icon: typeof Settings2; }>; -const runtimeCoreAgentLlmRows = [ - { id: 'planner', label: 'Planner' }, - { id: 'orchestrator', label: 'Orchestrator' }, - { id: 'generator', label: 'Generator' }, - { id: 'evaluator', label: 'Evaluator' }, -] as const; - -const runtimeAgentLlmRows = [ - { id: 'project-supervisor', label: '项目总控 Agent' }, - ...runtimeCoreAgentLlmRows, - ...createGameCreationAppSeedTasks().map((task) => ({ - id: task.id, - label: `${task.title} (${task.group}/${task.role})`, - })), -] satisfies Array<{ id: string; label: string }>; - -const runtimeLlmProviderPresets: Array<{ - id: RuntimeLlmProviderPresetId; - label: string; - baseUrl: string; - model: string; - apiKind: GameCreatorLlmApiKind; -}> = [ - { - id: 'openai', - label: 'OpenAI', - baseUrl: 'https://api.openai.com/v1', - model: 'gpt-4.1', - apiKind: 'openai_responses', - }, - { - id: 'deepseek', - label: 'DeepSeek', - baseUrl: 'https://api.deepseek.com', - model: 'deepseek-chat', - apiKind: 'openai_chat', - }, - { - id: 'anthropic', - label: 'Anthropic', - baseUrl: 'https://api.anthropic.com', - model: 'claude-3-5-sonnet-latest', - apiKind: 'anthropic', - }, - { - id: 'ark', - label: '火山 Ark', - baseUrl: 'https://ark.cn-beijing.volces.com/api/v3', - model: 'doubao-seed-1-6', - apiKind: 'openai_chat', - }, -]; - -function findRuntimeLlmProviderPreset( - config: Pick, -) { - return runtimeLlmProviderPresets.find( - (preset) => - preset.baseUrl === config.baseUrl && - preset.model === config.model && - preset.apiKind === config.apiKind, - ); -} - -function resolveRuntimeLlmProviderPresetId( - config: Pick, -): RuntimeLlmProviderPresetId { - return findRuntimeLlmProviderPreset(config)?.id ?? 'custom'; -} - -function resolveRuntimeAgentLlmProviderPresetId( - config: GameCreatorAgentLlmConfig, -): RuntimeAgentLlmProviderPresetId { - if (!config.baseUrl && !config.model && !config.apiKind) { - return 'inherit'; - } - return ( - findRuntimeLlmProviderPreset({ - baseUrl: config.baseUrl ?? '', - model: config.model ?? '', - apiKind: config.apiKind ?? defaultRuntimeConfigDraft.llm.apiKind, - })?.id ?? 'custom' - ); -} - function clampRuntimeConfigNumber(value: number, minimum: number) { const numericValue = Number(value); return Number.isFinite(numericValue) && numericValue >= minimum @@ -230,102 +152,24 @@ function isGameCreatorLlmReasoningEffort( return gameCreatorLlmReasoningEfforts.some((effort) => effort === value); } -function normalizeRuntimeAgentLlmConfig( - config: GameCreatorAgentLlmConfig | undefined, -): GameCreatorAgentLlmConfig { - if (!config) { - return {}; - } - const normalized: GameCreatorAgentLlmConfig = {}; - if (typeof config.apiKey === 'string' && config.apiKey.trim()) { - normalized.apiKey = config.apiKey; - } - if (typeof config.baseUrl === 'string' && config.baseUrl.trim()) { - normalized.baseUrl = config.baseUrl; - } - if (typeof config.model === 'string' && config.model.trim()) { - normalized.model = config.model; - } - if ( - config.apiKind && - ['openai_responses', 'openai_chat', 'anthropic'].includes(config.apiKind) - ) { - normalized.apiKind = config.apiKind; - } - if (isGameCreatorLlmReasoningEffort(config.reasoningEffort)) { - normalized.reasoningEffort = config.reasoningEffort; - } - if (typeof config.stream === 'boolean') { - normalized.stream = config.stream; - } - if (typeof config.webSearchEnabled === 'boolean') { - normalized.webSearchEnabled = config.webSearchEnabled; - } - if (typeof config.contextWindowTokens === 'number') { - normalized.contextWindowTokens = clampRuntimeConfigNumber( - config.contextWindowTokens, - 1, - ); - } - if (typeof config.autoCompactTokenLimit === 'number') { - normalized.autoCompactTokenLimit = clampRuntimeConfigNumber( - config.autoCompactTokenLimit, - 1, - ); - } - if (typeof config.toolOutputTokenLimit === 'number') { - normalized.toolOutputTokenLimit = clampRuntimeConfigNumber( - config.toolOutputTokenLimit, - 1, - ); - } - if (typeof config.requestTimeoutMs === 'number') { - normalized.requestTimeoutMs = clampRuntimeConfigNumber( - config.requestTimeoutMs, - 1000, - ); - } - if (typeof config.maxRetries === 'number') { - normalized.maxRetries = clampRuntimeConfigNumber(config.maxRetries, 0); - } - if (typeof config.retryBackoffMs === 'number') { - normalized.retryBackoffMs = clampRuntimeConfigNumber( - config.retryBackoffMs, - 1, - ); - } - return normalized; -} - function normalizeRuntimeConfigDraft( config: GameCreatorAppConfig, allowAdvancedExternalEditorConfig: boolean, ): GameCreatorAppConfig { - const apiKind: GameCreatorLlmApiKind = [ - 'openai_responses', - 'openai_chat', - 'anthropic', - ].includes(config.llm.apiKind) - ? config.llm.apiKind - : defaultRuntimeConfigDraft.llm.apiKind; const reasoningEffort = isGameCreatorLlmReasoningEffort( config.llm.reasoningEffort, ) ? config.llm.reasoningEffort : defaultRuntimeConfigDraft.llm.reasoningEffort; - const agentLlm: Record = {}; - for (const [agentId, agentConfig] of Object.entries(config.agentLlm ?? {})) { - const normalized = normalizeRuntimeAgentLlmConfig(agentConfig); - if (Object.keys(normalized).length > 0) { - agentLlm[agentId] = normalized; - } - } return { ...config, - agentMode: config.agentMode, + agentMode: 'codex_app_server', llm: { ...config.llm, - apiKind, + apiKey: '', + baseUrl: OFFICIAL_LLM_BASE_URL, + model: OFFICIAL_LLM_MODEL, + apiKind: 'openai_responses', reasoningEffort, webSearchEnabled: typeof config.llm.webSearchEnabled === 'boolean' @@ -356,7 +200,10 @@ function normalizeRuntimeConfigDraft( maxRetries: clampRuntimeConfigNumber(config.llm.maxRetries, 0), retryBackoffMs: clampRuntimeConfigNumber(config.llm.retryBackoffMs, 1), }, - agentLlm, + // Official AGC builds have one account-backed route. Drop every legacy + // per-agent override (including non-sensitive tuning) at the UI boundary + // so it cannot be persisted or accidentally re-exposed as a route. + agentLlm: {}, editorApi: allowAdvancedExternalEditorConfig ? { ...defaultRuntimeConfigDraft.editorApi, ...config.editorApi } : { ...defaultRuntimeConfigDraft.editorApi }, @@ -365,14 +212,25 @@ function normalizeRuntimeConfigDraft( export function RuntimeConfigDialog({ allowAdvancedExternalEditorConfig = false, + llmConfigStatus = null, onClose, onLog, }: { projectPath?: string; allowAdvancedExternalEditorConfig?: boolean; + llmConfigStatus?: GameCreatorLlmConfigStatus | null; onClose: () => void; onLog?: (entry: string) => void; }) { + const allowCustomLlmConfiguration = false; + // The prop is intentionally not sufficient to expose developer credentials: + // only an explicitly opted-in Vite development build may render the legacy + // External Editor fields. Release bundles therefore ignore accidental or + // stale callers that pass the prop. + const advancedExternalEditorConfigEnabled = + allowAdvancedExternalEditorConfig && + import.meta.env.DEV && + import.meta.env.VITE_AGC_ENABLE_ADVANCED_EXTERNAL_EDITOR_CONFIG === '1'; const [runtimeConfigPath, setRuntimeConfigPath] = useState(''); const [runtimeConfigStatus, setRuntimeConfigStatus] = useState('未读取'); const [runtimeConfigToast, setRuntimeConfigToast] = @@ -380,9 +238,10 @@ export function RuntimeConfigDialog({ const [runtimeConfigDraft, setRuntimeConfigDraft] = useState(defaultRuntimeConfigDraft); const [runtimeConfigBusy, setRuntimeConfigBusy] = useState(false); + const [effectiveLlmConfigStatus, setEffectiveLlmConfigStatus] = + useState(llmConfigStatus); const [activeSection, setActiveSection] = useState('general'); - const [expandedAgentIds, setExpandedAgentIds] = useState([]); const runtimeConfigBusyRef = useRef(false); useEscapeToClose(onClose); @@ -399,6 +258,10 @@ export function RuntimeConfigDialog({ }; }, []); + useEffect(() => { + setEffectiveLlmConfigStatus(llmConfigStatus); + }, [llmConfigStatus]); + useEffect(() => { void readRuntimeConfig(); // The dialog reads once on mount; subsequent reads are explicit user actions. @@ -418,81 +281,6 @@ export function RuntimeConfigDialog({ })); } - function updateRuntimeLlmProviderPreset( - presetId: RuntimeLlmProviderPresetId, - ) { - const preset = runtimeLlmProviderPresets.find( - (candidate) => candidate.id === presetId, - ); - if (!preset) { - return; - } - setRuntimeConfigDraft((current) => ({ - ...current, - llm: { - ...current.llm, - baseUrl: preset.baseUrl, - model: preset.model, - apiKind: preset.apiKind, - }, - })); - } - - function updateRuntimeAgentLlmConfig< - K extends keyof GameCreatorAgentLlmConfig, - >(agentId: string, key: K, value: GameCreatorAgentLlmConfig[K]) { - setRuntimeConfigDraft((current) => ({ - ...current, - agentLlm: { - ...(current.agentLlm ?? {}), - [agentId]: { - ...(current.agentLlm?.[agentId] ?? {}), - [key]: value, - }, - }, - })); - } - - function updateRuntimeAgentLlmProviderPreset( - agentId: string, - presetId: RuntimeAgentLlmProviderPresetId, - ) { - if (presetId === 'inherit') { - setRuntimeConfigDraft((current) => { - const nextConfig = { ...(current.agentLlm?.[agentId] ?? {}) }; - delete nextConfig.baseUrl; - delete nextConfig.model; - delete nextConfig.apiKind; - return { - ...current, - agentLlm: { - ...(current.agentLlm ?? {}), - [agentId]: nextConfig, - }, - }; - }); - return; - } - const preset = runtimeLlmProviderPresets.find( - (candidate) => candidate.id === presetId, - ); - if (!preset) { - return; - } - setRuntimeConfigDraft((current) => ({ - ...current, - agentLlm: { - ...(current.agentLlm ?? {}), - [agentId]: { - ...(current.agentLlm?.[agentId] ?? {}), - baseUrl: preset.baseUrl, - model: preset.model, - apiKind: preset.apiKind, - }, - }, - })); - } - async function readRuntimeConfig() { if (runtimeConfigBusyRef.current) { return; @@ -513,10 +301,19 @@ export function RuntimeConfigDialog({ setRuntimeConfigPath(result.path); const config = normalizeRuntimeConfigDraft( result.config, - allowAdvancedExternalEditorConfig, + advancedExternalEditorConfigEnabled, ); setRuntimeConfigDraft(config); setRuntimeConfigStatus(`已读取:${result.path}`); + try { + const status = await invoke( + 'check_game_creator_llm_config', + ); + setEffectiveLlmConfigStatus(status); + } catch { + // Older test fixtures and non-Tauri previews may not expose the + // diagnostic command; the config read itself remains usable. + } onLog?.('runtime_config.read'); } catch (error) { setRuntimeConfigStatus( @@ -548,11 +345,11 @@ export function RuntimeConfigDialog({ { ...runtimeConfigDraft, agentMode: 'codex_app_server', - editorApi: allowAdvancedExternalEditorConfig + editorApi: advancedExternalEditorConfigEnabled ? runtimeConfigDraft.editorApi : defaultRuntimeConfigDraft.editorApi, }, - allowAdvancedExternalEditorConfig, + advancedExternalEditorConfigEnabled, ); const result = await invoke( 'write_game_creator_app_config', @@ -561,10 +358,19 @@ export function RuntimeConfigDialog({ setRuntimeConfigPath(result.path); const savedConfig = normalizeRuntimeConfigDraft( result.config, - allowAdvancedExternalEditorConfig, + advancedExternalEditorConfigEnabled, ); setRuntimeConfigDraft(savedConfig); setRuntimeConfigStatus(`已保存:${result.path}`); + try { + const status = await invoke( + 'check_game_creator_llm_config', + ); + setEffectiveLlmConfigStatus(status); + } catch { + // Keep the last safe status when the optional diagnostic refresh is + // unavailable in a preview or test fixture. + } setRuntimeConfigToast({ tone: 'success', message: '保存成功,新的运行时配置已生效', @@ -700,91 +506,35 @@ export function RuntimeConfigDialog({ 陶泥儿智能创作(固定) 需求将由陶泥儿智能创作服务执行 +
+ 官方 LLM 路由 + router.genarrative.world/v1 · gpt-5.6-sol + + 登录后自动使用账号权限,客户端不保存或展示 LLM API Key。 + +
+ {(() => { + const credential = formatAccountCredentialState( + effectiveLlmConfigStatus, + ); + return ( +
+ 账号权限 + {credential.label} + + {credential.tone === 'success' + ? '由 API Server 按当前登录账号转发到官方 Router。' + : '请返回登录页完成登录或重新登录;普通用户无需填写任何 LLM Key。'} + +
+ ); + })()} {runtimeConfigDraft.agentMode !== 'codex_cli' ? ( <> - - - - - - - - - - - - - - - - - ) : null} - - ); - })} + {activeSection === 'agents' && !allowCustomLlmConfiguration ? ( +
+ Agent 路由 + 所有 Agent 统一使用官方账号路由 + + 普通用户不能为单个 Agent 设置 Provider、Key、Base URL + 或模型。 +
) : null} {activeSection === 'connections' ? ( @@ -1232,7 +706,7 @@ export function RuntimeConfigDialog({

配置图片编辑器使用的外部服务

- {allowAdvancedExternalEditorConfig ? ( + {advancedExternalEditorConfigEnabled ? (