Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持 RSB 浏览器 Passkey 登录 (#1826)
Dash3499ad433d5a
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 4e8a40b20c..778e4b7f02 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -192,7 +192,7 @@"autoprefixer": "^10.4.20","cross-env": "^7.0.3","drizzle-kit": "^0.31.10",- "electron": "41.2.0",+ "electron": "41.10.3","eslint": "^9.0.0","eslint-config-prettier": "^9.1.0","jsdom": "^29.1.1",diff --git a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt b/apps/desktop/resources/THIRD-PARTY-NOTICES.txtindex 70166341bd..3f88ebf2ed 100644--- a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt+++ b/apps/desktop/resources/THIRD-PARTY-NOTICES.txt@@ -3348,7 +3348,7 @@ Apache LicenseOnly the viewer JavaScript (viewer-static.min.js) is redistributed. Upstream icon sets / stencils / templates carry an additional no-Atlassian-use restriction; none of those assets are redistributed by this product.-------------------------------------------------------------------------------Electron (bundled runtime) 41.2.0+Electron (bundled runtime) 41.10.3License: MITSource: https://github.com/electron/electron------------------------------------------------------------------------------diff --git a/apps/desktop/scripts/ci/lib.mjs b/apps/desktop/scripts/ci/lib.mjsindex 8b289e27d2..f31f965413 100644--- a/apps/desktop/scripts/ci/lib.mjs+++ b/apps/desktop/scripts/ci/lib.mjs@@ -474,10 +474,147 @@ export function runDbValidate() {// ── macOS local signing ────────────────────────────────────────────────────-export function writeMacEntitlements(destPath, { appleEvents = false } = {}) {+const APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/;+const MAC_BUNDLE_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/;++/** 正式签名包的 WebAuthn Touch ID keychain access group。 */+export function macWebAuthnKeychainAccessGroup(teamId, bundleId) {+ const normalizedTeamId = String(teamId ?? '').trim();+ const normalizedBundleId = String(bundleId ?? '').trim();+ if (!APPLE_TEAM_ID_PATTERN.test(normalizedTeamId)) {+ throw new Error(`invalid Apple Team ID for WebAuthn: ${normalizedTeamId || '(empty)'}`);+ }+ if (!MAC_BUNDLE_ID_PATTERN.test(normalizedBundleId) || normalizedBundleId.includes('..')) {+ throw new Error(`invalid macOS bundle id for WebAuthn: ${normalizedBundleId || '(empty)'}`);+ }+ return `${normalizedTeamId}.${normalizedBundleId}.webauthn`;+}++function entitlementValueAllows(values, requestedValue) {+ return values.some((value) => {+ if (typeof value !== 'string') return false;+ if (value === requestedValue) return true;+ return value.endsWith('*') && requestedValue.startsWith(value.slice(0, -1));+ });+}++/** Validate the authorization carried by a decoded Developer ID profile. */+export function assertMacWebAuthnProvisioningProfile(+ profile,+ { teamId, bundleId, keychainAccessGroup, now = new Date() },+) {+ const profileTeams = Array.isArray(profile?.TeamIdentifier) ? profile.TeamIdentifier : [];+ if (!profileTeams.includes(teamId)) {+ throw new Error(`WebAuthn provisioning profile does not authorize Apple Team ID ${teamId}`);+ }+ const expiresAt = new Date(profile?.ExpirationDate ?? Number.NaN);+ if (!Number.isFinite(expiresAt.getTime()) || expiresAt <= now) {+ throw new Error('WebAuthn provisioning profile is expired or has no valid expiration date');+ }+ const entitlements = profile?.Entitlements;+ if (!entitlements || typeof entitlements !== 'object' || Array.isArray(entitlements)) {+ throw new Error('WebAuthn provisioning profile has no entitlement allowlist');+ }+ if (entitlements['com.apple.developer.team-identifier'] !== teamId) {+ throw new Error(`WebAuthn provisioning profile entitlement Team ID does not match ${teamId}`);+ }+ const requestedApplicationId = `${teamId}.${bundleId}`;+ const applicationId =+ entitlements['com.apple.application-identifier'] ?? entitlements['application-identifier'];+ if (!entitlementValueAllows([applicationId], requestedApplicationId)) {+ throw new Error(`WebAuthn provisioning profile does not authorize ${requestedApplicationId}`);+ }+ const keychainAccessGroups = entitlements['keychain-access-groups'];+ if (+ !Array.isArray(keychainAccessGroups) ||+ !entitlementValueAllows(keychainAccessGroups, keychainAccessGroup)+ ) {+ throw new Error(+ `WebAuthn provisioning profile does not authorize keychain group ${keychainAccessGroup}`,+ );+ }+}++/** Decode, validate and embed the profile required by keychain-access-groups. */+export function embedMacWebAuthnProvisioningProfile(+ appPath,+ profilePath,+ expected,+ dependencies = {},+) {+ const spawnCommand = dependencies.spawnCommand ?? spawnSync;+ const decodeResult = spawnCommand('/usr/bin/security', ['cms', '-D', '-i', profilePath], {+ encoding: 'utf8',+ });+ if (decodeResult.error || decodeResult.status !== 0) {+ throw new Error(+ `failed to decode WebAuthn provisioning profile: ${decodeResult.error?.message ?? decodeResult.stderr?.trim() ?? `exit ${decodeResult.status}`}`,+ );+ }+ const decodedProfileDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-webauthn-profile-'));+ const decodedProfilePath = path.join(decodedProfileDir, 'decoded.plist');+ try {+ fs.writeFileSync(decodedProfilePath, decodeResult.stdout);++ const extractProfileField = (field, format) => {+ const result = spawnCommand(+ '/usr/bin/plutil',+ ['-extract', field, format, '-o', '-', '--', decodedProfilePath],+ { encoding: 'utf8' },+ );+ if (result.error || result.status !== 0) {+ throw new Error(+ `failed to inspect WebAuthn provisioning profile: ${field} extraction failed: ${result.error?.message ?? result.stderr?.trim() ?? `exit ${result.status}`}`,+ );+ }+ return result.stdout;+ };++ let profile;+ try {+ profile = {+ TeamIdentifier: JSON.parse(extractProfileField('TeamIdentifier', 'json')),+ ExpirationDate: extractProfileField('ExpirationDate', 'raw').trim(),+ Entitlements: JSON.parse(extractProfileField('Entitlements', 'json')),+ };+ } catch (error) {+ if (error instanceof SyntaxError) {+ throw new Error(+ 'failed to inspect WebAuthn provisioning profile: plist field extraction returned invalid JSON',+ { cause: error },+ );+ }+ throw error;+ }+ assertMacWebAuthnProvisioningProfile(profile, expected);+ } finally {+ fs.rmSync(decodedProfileDir, { recursive: true, force: true });+ }+ const embeddedPath = path.join(appPath, 'Contents', 'embedded.provisionprofile');+ fs.copyFileSync(profilePath, embeddedPath);+ return embeddedPath;+}++function escapeXmlText(value) {+ return value+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll("'", ''');+}++export function writeMacEntitlements(destPath, { appleEvents = false, keychainAccessGroup } = {}) {const appleEventsEntitlement = appleEvents? ` <key>com.apple.security.automation.apple-events</key><true/>+`+ : '';+ const keychainAccessGroupEntitlement = keychainAccessGroup+ ? ` <key>keychain-access-groups</key>+ <array>+ <string>${escapeXmlText(keychainAccessGroup)}</string>+ </array>`: '';const content = `<?xml version="1.0" encoding="UTF-8"?>@@ -492,7 +629,7 @@ export function writeMacEntitlements(destPath, { appleEvents = false } = {}) {<true/><key>com.apple.security.device.audio-input</key><true/>-${appleEventsEntitlement}</dict>+${appleEventsEntitlement}${keychainAccessGroupEntitlement}</dict></plist>`;fs.writeFileSync(destPath, content);}@@ -509,8 +646,38 @@ function readCodesignEntitlements(bundlePath) {return `${result.stdout || ''}${result.stderr || ''}`;}+export function parseCodesignTeamIdentifier(output) {+ return (+ String(output ?? '')+ .match(/^TeamIdentifier=(.+)$/m)?.[1]+ ?.trim() ?? ''+ );+}++function readCodesignTeamIdentifier(bundlePath) {+ const result = spawnSync('/usr/bin/codesign', ['-dv', '--verbose=4', bundlePath], {+ encoding: 'utf8',+ });+ if (result.status !== 0) {+ throw new Error(+ `codesign identity inspection failed for ${bundlePath}: ${result.stderr || result.stdout}`,+ );+ }+ const output = `${result.stdout || ''}\n${result.stderr || ''}`;+ return parseCodesignTeamIdentifier(output);+}+function hasAppleEventsEntitlement(entitlements) {- return /<key>com\.apple\.security\.automation\.apple-events<\/key>\s*<true\s*\/>/.test(entitlements);+ return /<key>com\.apple\.security\.automation\.apple-events<\/key>\s*<true\s*\/>/.test(+ entitlements,+ );+}++function hasKeychainAccessGroup(entitlements, keychainAccessGroup) {+ const escaped = keychainAccessGroup.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ return new RegExp(+ `<key>keychain-access-groups<\\/key>\\s*<array>[\\s\\S]*?<string>${escaped}<\\/string>[\\s\\S]*?<\\/array>`,+ ).test(entitlements);}function readPlistString(infoPlistPath, key) {@@ -525,8 +692,12 @@ function readPlistString(infoPlistPath, key) {return result.stdout.trim();}+export function readMacBundleIdentifier(appPath) {+ return readPlistString(path.join(appPath, 'Contents', 'Info.plist'), 'CFBundleIdentifier');+}+/** Verify the packaged Contacts/JXA privacy contract after signing. */-export function verifyMacContactsPermissions(appPath) {+export function verifyMacContactsPermissions(appPath, { keychainAccessGroup, signingTeamId } = {}) {const infoPlistPath = path.join(appPath, 'Contents', 'Info.plist');const appleEventsUsage = readPlistString(infoPlistPath, 'NSAppleEventsUsageDescription');const contactsUsage = readPlistString(infoPlistPath, 'NSContactsUsageDescription');@@ -539,9 +710,27 @@ export function verifyMacContactsPermissions(appPath) {}}- if (!hasAppleEventsEntitlement(readCodesignEntitlements(appPath))) {+ const mainEntitlements = readCodesignEntitlements(appPath);+ if (!hasAppleEventsEntitlement(mainEntitlements)) {throw new Error('main app is missing com.apple.security.automation.apple-events=true');}+ if (keychainAccessGroup && !hasKeychainAccessGroup(mainEntitlements, keychainAccessGroup)) {+ throw new Error(`main app is missing WebAuthn keychain access group ${keychainAccessGroup}`);+ }+ if (signingTeamId) {+ const actualTeamId = readCodesignTeamIdentifier(appPath);+ if (actualTeamId !== signingTeamId) {+ throw new Error(+ `macOS signature TeamIdentifier mismatch: expected ${signingTeamId}, got ${actualTeamId || '(empty)'}`,+ );+ }+ }+ if (+ keychainAccessGroup &&+ !fs.existsSync(path.join(appPath, 'Contents', 'embedded.provisionprofile'))+ ) {+ throw new Error('main app is missing the WebAuthn provisioning profile');+ }const frameworksDir = path.join(appPath, 'Contents', 'Frameworks');const helperApps = fs.readdirSync(frameworksDir, { withFileTypes: true })@@ -551,8 +740,16 @@ export function verifyMacContactsPermissions(appPath) {if (hasAppleEventsEntitlement(readCodesignEntitlements(helperApp))) {throw new Error(`helper app must not receive Apple Events entitlement: ${helperApp}`);}+ if (+ keychainAccessGroup &&+ hasKeychainAccessGroup(readCodesignEntitlements(helperApp), keychainAccessGroup)+ ) {+ throw new Error(`helper app must not receive WebAuthn keychain access group: ${helperApp}`);+ }}- console.log('==> Verified macOS Contacts usage descriptions and main-only Apple Events entitlement');+ console.log(+ `==> Verified macOS Contacts usage descriptions and main-only Apple Events${keychainAccessGroup ? ' / WebAuthn' : ''} entitlements`,+ );}export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementsPath) {@@ -587,7 +784,13 @@ export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlement* Developer ID 由内向外逐层签名(Electron app 不能依赖 --deep)。* @param {{ signIdentity: string }} identity*/-export function signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEntitlementsPath, identity) {+export function signMacAppWithIdentity(+ appPath,+ helperEntitlementsPath,+ mainEntitlementsPath,+ identity,+ { keychainAccessGroup } = {},+) {console.log(' Removing provenance attributes...');exec(`/usr/bin/xattr -dr com.apple.provenance "${appPath}" 2>/dev/null || true`);@@ -629,7 +832,10 @@ export function signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEnticonsole.log(' Verifying signature...');exec(`/usr/bin/codesign --verify --deep --strict "${appPath}"`);- verifyMacContactsPermissions(appPath);+ verifyMacContactsPermissions(appPath, {+ keychainAccessGroup,+ signingTeamId: identity.teamId,+ });}const NOTARYTOOL_TIMEOUT_MS = 1800000;diff --git a/apps/desktop/scripts/package-desktop.mjs b/apps/desktop/scripts/package-desktop.mjsindex faad729712..019ddbc6a7 100644--- a/apps/desktop/scripts/package-desktop.mjs+++ b/apps/desktop/scripts/package-desktop.mjs@@ -64,6 +64,9 @@ import {ensureLinuxRuntimeAssets,logLinuxPackagingRequirements,writeMacEntitlements,+ macWebAuthnKeychainAccessGroup,+ embedMacWebAuthnProvisioningProfile,+ readMacBundleIdentifier,adhocSignMacApp,resolveAppleIdentity,signMacAppWithIdentity,@@ -141,7 +144,7 @@ function cleanOutDir() {}}-function runForgeMake({ platform, arch, region, version, noSign }) {+function runForgeMake({ platform, arch, region, version, noSign, webAuthnAppleTeamId }) {console.log('==> Building remote bundles...');execSync('node scripts/build-remote-bundles.mjs', { cwd: DESKTOP_ROOT, stdio: 'inherit' });@@ -155,6 +158,9 @@ function runForgeMake({ platform, arch, region, version, noSign }) {CINDY_AUTH_REGION: region,// forge.config.ts 注入 packagerConfig.appVersion;版本无关时为占位 0.0.0。APP_VERSION: version,+ // 只给最终会做 Developer ID 签名的 macOS bundle 烘焙 Team ID。ad-hoc、+ // dev 与其它平台显式置空,避免继承 shell 里的陈旧值后误启 Touch ID。+ CINDY_WEBAUTHN_APPLE_TEAM_ID: webAuthnAppleTeamId ?? '',};// Git Bash(agent 常用 shell)会导出 NoDefaultCurrentDirectoryInExePath=1,// 使 cmd.exe 不再搜索当前目录——node-pty rebuild 时 winpty.gyp 的@@ -325,7 +331,17 @@ async function finishWindows({ artifactDir, baseName, appName, versionless, alloreturn { files, signing: { installerSigned, internalExesSigned: Boolean(winSignCmd) } };}-async function finishDarwin({ artifactDir, baseName, appName, arch, versionless, allowUnsigned, noSign }) {+async function finishDarwin({+ artifactDir,+ baseName,+ appName,+ arch,+ versionless,+ allowUnsigned,+ noSign,+ macSigningIdentity,+ webAuthnProvisioningProfile,+}) {const packagedDir = path.join(DESKTOP_ROOT, 'out', `${appName}-darwin-${arch}`);const appPath = path.join(packagedDir, `${appName}.app`);if (!fs.existsSync(appPath)) {@@ -336,8 +352,6 @@ async function finishDarwin({ artifactDir, baseName, appName, arch, versionless,fs.mkdirSync(RELEASE_DIR, { recursive: true });const helperEntitlementsPath = path.join(RELEASE_DIR, 'build-helper.entitlements');const mainEntitlementsPath = path.join(RELEASE_DIR, 'build-main.entitlements');- writeMacEntitlements(helperEntitlementsPath);- writeMacEntitlements(mainEntitlementsPath, { appleEvents: true });const applePassword = noSign ? undefined : process.env.APPLE_APP_PASSWORD;const wantsRealSigning = !versionless && !noSign;@@ -351,9 +365,27 @@ async function finishDarwin({ artifactDir, baseName, appName, arch, versionless,const files = [];if (wantsRealSigning && applePassword) {- const identity = { ...resolveAppleIdentity(), applePassword };+ const identity = macSigningIdentity ?? { ...resolveAppleIdentity(), applePassword };+ const bundleId = readMacBundleIdentifier(appPath);+ const keychainAccessGroup = webAuthnProvisioningProfile+ ? macWebAuthnKeychainAccessGroup(identity.teamId, bundleId)+ : undefined;+ writeMacEntitlements(helperEntitlementsPath);+ writeMacEntitlements(mainEntitlementsPath, {+ appleEvents: true,+ keychainAccessGroup,+ });+ if (keychainAccessGroup) {+ embedMacWebAuthnProvisioningProfile(appPath, webAuthnProvisioningProfile, {+ teamId: identity.teamId,+ bundleId,+ keychainAccessGroup,+ });+ }console.log('==> Signing (Developer ID)...');- signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEntitlementsPath, identity);+ signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEntitlementsPath, identity, {+ keychainAccessGroup,+ });console.log('==> Notarizing...');notarizeMacApp(appPath, identity);signingMode = 'developer-id+notarized';@@ -373,6 +405,8 @@ async function finishDarwin({ artifactDir, baseName, appName, arch, versionless,files.push(fileEntry('hotfix', hotfixZipPath));} else {// 版本无关(或显式放行)→ ad-hoc 签名,产出 .app 的 zip 供本机/内部试用。+ writeMacEntitlements(helperEntitlementsPath);+ writeMacEntitlements(mainEntitlementsPath, { appleEvents: true });adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementsPath);const appZipPath = path.join(artifactDir, `${baseName}-${arch}.zip`);console.log('==> Creating app ZIP (ad-hoc signed)...');@@ -429,6 +463,30 @@ async function main() {const { version, versionless } = await resolvePackageVersion(versionSpec, () =>fetchCdnBaselineVersion(platform === 'darwin' ? 'darwin-arm64' : `${platform}-${archs[0]}`, region),);+ const applePassword =+ platform === 'darwin' && !versionless && !noSign ? process.env.APPLE_APP_PASSWORD : undefined;+ const macSigningIdentity = applePassword+ ? { ...resolveAppleIdentity(), applePassword }+ : undefined;+ const webAuthnProfileValue =+ macSigningIdentity && process.env.CINDY_MAC_WEBAUTHN_PROVISIONING_PROFILE?.trim();+ const webAuthnProvisioningProfile = webAuthnProfileValue+ ? path.resolve(DESKTOP_ROOT, webAuthnProfileValue)+ : undefined;+ if (+ webAuthnProvisioningProfile &&+ (!fs.existsSync(webAuthnProvisioningProfile) ||+ !fs.statSync(webAuthnProvisioningProfile).isFile())+ ) {+ throw new Error(+ `CINDY_MAC_WEBAUTHN_PROVISIONING_PROFILE is not a file: ${webAuthnProvisioningProfile}`,+ );+ }+ if (macSigningIdentity && !webAuthnProvisioningProfile) {+ console.warn(+ 'WARN: macOS Touch ID WebAuthn is disabled: set CINDY_MAC_WEBAUTHN_PROVISIONING_PROFILE to a Developer ID provisioning profile that authorizes keychain-access-groups.',+ );+ }console.log('='.repeat(60));console.log(`==> Package Cindy desktop`);@@ -484,7 +542,14 @@ async function main() {fs.rmSync(artifactDir, { recursive: true, force: true });cleanOutDir();- runForgeMake({ platform, arch, region, version, noSign });+ runForgeMake({+ platform,+ arch,+ region,+ version,+ noSign,+ webAuthnAppleTeamId: webAuthnProvisioningProfile ? macSigningIdentity?.teamId : undefined,+ });// drizzle 资源校验(平台差异只在 packaged 内路径)。const drizzleOut =@@ -520,6 +585,8 @@ async function main() {versionless,allowUnsigned,noSign,+ macSigningIdentity,+ webAuthnProvisioningProfile,}));const buildInfo = buildBuildInfo({diff --git a/apps/desktop/src/main/__tests__/loginScenarioHarness.test.ts b/apps/desktop/src/main/__tests__/loginScenarioHarness.test.tsindex 404ef17fbb..181d4527bf 100644--- a/apps/desktop/src/main/__tests__/loginScenarioHarness.test.ts+++ b/apps/desktop/src/main/__tests__/loginScenarioHarness.test.ts@@ -50,6 +50,15 @@ describe('authManager 注入点(静态源码断言)', () => {expect(viteMainConfigSource).toContain("find: '@cindy/auth-client/fixtures'");expect(viteMainConfigSource).toContain('loginScenarios.production-stub.ts');});++ it('vite.main.config 保留显式空 Team ID,不让 .env 旧值重新启用 Touch ID', () => {+ expect(viteMainConfigSource).toContain(+ "Object.prototype.hasOwnProperty.call(process.env, key)",+ );+ expect(viteMainConfigSource).toContain(+ "readMainEnvPreservingEmpty('CINDY_WEBAUTHN_APPLE_TEAM_ID').trim()",+ );+ });});describe('guard 行为(production-mode 断言)', () => {diff --git a/apps/desktop/src/main/__tests__/rsb-browser-webauthn.test.ts b/apps/desktop/src/main/__tests__/rsb-browser-webauthn.test.tsnew file mode 100644index 0000000000..6a967e7ebb--- /dev/null+++ b/apps/desktop/src/main/__tests__/rsb-browser-webauthn.test.ts@@ -0,0 +1,453 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++const nativePopupMocks = vi.hoisted(() => ({+ getOwner: vi.fn(() => null),+}));++vi.mock('../rsb-browser-bridge/native-popup-surfaces.js', () => ({+ getRsbNativePopupOwnerWebContents: nativePopupMocks.getOwner,+}));++import { BrowserWindow, webContents } from 'electron';++import { BROWSER_PARTITION } from '../../shared/webviewPartition';+import {+ configureRsbBrowserWebAuthn,+ installRsbWebAuthnAccountSelection,+ resolveWebAuthnKeychainAccessGroup,+ selectRsbWebAuthnAccount,+} from '../rsb-browser-webauthn';+import { RSB_BROWSER_WEBAUTHN_LABELS } from '../rsbBrowserWebAuthnLabels';++const silentLogger = {+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+};++const visibleOwner = {+ isDestroyed: () => false,+ isVisible: () => true,+};+const resolveVisibleOwner = () => visibleOwner;++afterEach(() => {+ vi.restoreAllMocks();+ nativePopupMocks.getOwner.mockReset();+ nativePopupMocks.getOwner.mockReturnValue(null);+});++function createSessionHarness() {+ let listener:+ | ((+ event: unknown,+ details: {+ relyingPartyId: string;+ accounts: Array<{+ credentialId: string;+ displayName?: string;+ name?: string;+ }>;+ frame: { detached: boolean } | null;+ },+ callback: (credentialId?: string | null) => void,+ ) => void)+ | undefined;+ const browserSession = {+ on: vi.fn((event: string, nextListener: typeof listener) => {+ expect(event).toBe('select-webauthn-account');+ listener = nextListener;+ }),+ };+ return {+ browserSession,+ getListener: () => {+ if (!listener) throw new Error('listener not installed');+ return listener;+ },+ };+}++describe('resolveWebAuthnKeychainAccessGroup', () => {+ it('combines the signed Apple team identity with the runtime bundle id', () => {+ expect(resolveWebAuthnKeychainAccessGroup('TEAM123456', 'com.xd.cindy')).toBe(+ 'TEAM123456.com.xd.cindy.webauthn',+ );+ });++ it.each([+ [undefined, 'com.xd.cindy'],+ ['', 'com.xd.cindy'],+ ['too-short', 'com.xd.cindy'],+ ['TEAM123456', ''],+ ['TEAM123456', 'com..xd.cindy'],+ ['TEAM123456', 'com.xd.cindy<bad>'],+ ])('fails closed for an invalid signing identity (%s, %s)', (teamId, appId) => {+ expect(resolveWebAuthnKeychainAccessGroup(teamId, appId)).toBeNull();+ });+});++describe('selectRsbWebAuthnAccount', () => {+ const labels = RSB_BROWSER_WEBAUTHN_LABELS.en;++ it('returns the only discoverable credential without showing a redundant chooser', async () => {+ const showDialog = vi.fn();+ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'example.com',+ accounts: [{ credentialId: 'credential-1', name: '[email protected]' }],+ frame: { detached: false },+ },+ { labels, showDialog, resolveDialogOwner: resolveVisibleOwner },+ ),+ ).resolves.toBe('credential-1');+ expect(showDialog).not.toHaveBeenCalled();+ });++ it('shows every account and returns the selected credential id', async () => {+ const showDialog = vi.fn(async () => ({ response: 1 }));+ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'login.example.com',+ accounts: [+ { credentialId: 'credential-1', displayName: 'Dash', name: '[email protected]' },+ { credentialId: 'credential-2', name: '[email protected]' },+ ],+ frame: { detached: false },+ },+ { labels, showDialog, resolveDialogOwner: resolveVisibleOwner },+ ),+ ).resolves.toBe('credential-2');++ expect(showDialog).toHaveBeenCalledWith(+ visibleOwner,+ expect.objectContaining({+ title: 'Choose a Passkey',+ message: 'Choose a passkey for login.example.com',+ buttons: ['1. Dash ([email protected])', '2. [email protected]', 'Cancel Passkey Sign-In'],+ defaultId: 0,+ cancelId: 2,+ noLink: true,+ }),+ );+ });++ it('cancels when the frame is stale, the user cancels, or navigation wins the dialog race', async () => {+ const detachedFrame = { detached: true };+ const neverShown = vi.fn();+ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'example.com',+ accounts: [{ credentialId: 'credential-1' }, { credentialId: 'credential-2' }],+ frame: detachedFrame,+ },+ { labels, showDialog: neverShown, resolveDialogOwner: resolveVisibleOwner },+ ),+ ).resolves.toBeUndefined();+ expect(neverShown).not.toHaveBeenCalled();++ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'example.com',+ accounts: [{ credentialId: 'credential-1' }, { credentialId: 'credential-2' }],+ frame: { detached: false },+ },+ {+ labels,+ showDialog: async () => ({ response: 2 }),+ resolveDialogOwner: resolveVisibleOwner,+ },+ ),+ ).resolves.toBeUndefined();++ const frame = { detached: false };+ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'example.com',+ accounts: [{ credentialId: 'credential-1' }, { credentialId: 'credential-2' }],+ frame,+ },+ {+ labels,+ showDialog: async () => {+ frame.detached = true;+ return { response: 0 };+ },+ resolveDialogOwner: resolveVisibleOwner,+ },+ ),+ ).resolves.toBeUndefined();+ });++ it('normalizes authenticator-provided labels before placing them on native buttons', async () => {+ const showDialog = vi.fn(async () => ({ response: 2 }));+ await selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'example.com\nspoofed prompt',+ accounts: [+ { credentialId: 'credential-1', displayName: 'Dash\n\u202eAdmin' },+ { credentialId: 'credential-2' },+ ],+ frame: { detached: false },+ },+ { labels, showDialog, resolveDialogOwner: resolveVisibleOwner },+ );++ expect(showDialog).toHaveBeenCalledWith(+ visibleOwner,+ expect.objectContaining({+ message: 'Choose a passkey for example.com spoofed prompt',+ buttons: ['1. Dash Admin', '2. Passkey 2', 'Cancel Passkey Sign-In'],+ }),+ );+ });++ it('fails closed when the request source is not the visible focused RSB surface', async () => {+ const showDialog = vi.fn();+ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'background.example.com',+ accounts: [{ credentialId: 'credential-1' }, { credentialId: 'credential-2' }],+ frame: { detached: false },+ },+ { labels, showDialog, resolveDialogOwner: () => null },+ ),+ ).resolves.toBeUndefined();+ expect(showDialog).not.toHaveBeenCalled();+ });++ it('resolves the BrowserWindow through an ordinary RSB webview host', async () => {+ const source = {+ id: 101,+ hostWebContents: { id: 11 },+ isDestroyed: () => false,+ isFocused: () => true,+ };+ const fromFrame = vi.spyOn(webContents, 'fromFrame').mockReturnValue(source as never);+ const fromWebContents = vi+ .spyOn(BrowserWindow, 'fromWebContents')+ .mockImplementation((candidate) =>+ candidate === source.hostWebContents ? (visibleOwner as never) : null,+ );+ const showDialog = vi.fn(async () => ({ response: 0 }));++ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'example.com',+ accounts: [{ credentialId: 'credential-1' }, { credentialId: 'credential-2' }],+ frame: { detached: false },+ },+ { labels, showDialog },+ ),+ ).resolves.toBe('credential-1');++ expect(fromFrame).toHaveBeenCalledOnce();+ expect(fromWebContents).toHaveBeenCalledWith(source.hostWebContents);+ expect(showDialog).toHaveBeenCalledWith(visibleOwner, expect.anything());+ });++ it('resolves an adopted native popup through the existing popup owner registry', async () => {+ const source = {+ id: 202,+ isDestroyed: () => false,+ isFocused: () => true,+ };+ const hostWebContents = { id: 22 };+ nativePopupMocks.getOwner.mockReturnValue(hostWebContents as never);+ const fromFrame = vi.spyOn(webContents, 'fromFrame').mockReturnValue(source as never);+ const fromWebContents = vi+ .spyOn(BrowserWindow, 'fromWebContents')+ .mockImplementation((candidate) =>+ candidate === hostWebContents ? (visibleOwner as never) : null,+ );+ const showDialog = vi.fn(async () => ({ response: 1 }));++ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'popup.example.com',+ accounts: [{ credentialId: 'credential-1' }, { credentialId: 'credential-2' }],+ frame: { detached: false },+ },+ { labels, showDialog },+ ),+ ).resolves.toBe('credential-2');++ expect(fromFrame).toHaveBeenCalledOnce();+ expect(nativePopupMocks.getOwner).toHaveBeenCalledWith(source.id);+ expect(fromWebContents).toHaveBeenCalledWith(hostWebContents);+ expect(showDialog).toHaveBeenCalledWith(visibleOwner, expect.anything());+ });++ it('fails closed when a native popup has no live owner', async () => {+ const source = {+ id: 303,+ isDestroyed: () => false,+ isFocused: () => true,+ };+ vi.spyOn(webContents, 'fromFrame').mockReturnValue(source as never);+ const showDialog = vi.fn();++ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'orphan.example.com',+ accounts: [{ credentialId: 'credential-1' }, { credentialId: 'credential-2' }],+ frame: { detached: false },+ },+ { labels, showDialog },+ ),+ ).resolves.toBeUndefined();+ expect(nativePopupMocks.getOwner).toHaveBeenCalledWith(source.id);+ expect(showDialog).not.toHaveBeenCalled();+ });++ it('rejects an authenticator response too large for a safe native chooser', async () => {+ const showDialog = vi.fn();+ await expect(+ selectRsbWebAuthnAccount(+ {+ relyingPartyId: 'example.com',+ accounts: Array.from({ length: 21 }, (_, index) => ({+ credentialId: `credential-${index}`,+ })),+ frame: { detached: false },+ },+ { labels, showDialog, resolveDialogOwner: resolveVisibleOwner },+ ),+ ).resolves.toBeUndefined();+ expect(showDialog).not.toHaveBeenCalled();+ });+});++describe('installRsbWebAuthnAccountSelection', () => {+ it('installs once per session and invokes Electron callback exactly once on failure', async () => {+ const harness = createSessionHarness();+ const selectAccount = vi.fn(async () => {+ throw new Error('chooser unavailable');+ });++ expect(+ installRsbWebAuthnAccountSelection(harness.browserSession, {+ selectAccount,+ logger: silentLogger,+ }),+ ).toBe(true);+ expect(+ installRsbWebAuthnAccountSelection(harness.browserSession, {+ selectAccount,+ logger: silentLogger,+ }),+ ).toBe(false);+ expect(harness.browserSession.on).toHaveBeenCalledOnce();++ const callback = vi.fn();+ harness.getListener()(+ {},+ {+ relyingPartyId: 'example.com',+ accounts: [{ credentialId: 'credential-1' }],+ frame: { detached: false },+ },+ callback,+ );+ await vi.waitFor(() => expect(callback).toHaveBeenCalledOnce());+ expect(callback).toHaveBeenCalledWith(undefined);+ });++ it('serializes concurrent chooser requests', async () => {+ const harness = createSessionHarness();+ let finishFirst: (() => void) | undefined;+ const selectAccount = vi+ .fn<() => Promise<string | undefined>>()+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishFirst = () => resolve('credential-1');+ }),+ )+ .mockResolvedValueOnce('credential-2');+ installRsbWebAuthnAccountSelection(harness.browserSession, { selectAccount });++ const firstCallback = vi.fn();+ const secondCallback = vi.fn();+ const details = {+ relyingPartyId: 'example.com',+ accounts: [{ credentialId: 'credential-1' }],+ frame: { detached: false },+ };+ harness.getListener()({}, details, firstCallback);+ harness.getListener()({}, details, secondCallback);++ await vi.waitFor(() => expect(selectAccount).toHaveBeenCalledTimes(1));+ expect(secondCallback).not.toHaveBeenCalled();+ finishFirst?.();+ await vi.waitFor(() => expect(secondCallback).toHaveBeenCalledWith('credential-2'));+ expect(firstCallback).toHaveBeenCalledWith('credential-1');+ });+});++describe('configureRsbBrowserWebAuthn', () => {+ it('installs account selection on Windows without applying macOS configuration', () => {+ const harness = createSessionHarness();+ const configureWebAuthn = vi.fn();+ expect(+ configureRsbBrowserWebAuthn({+ platform: 'win32',+ browserSession: harness.browserSession,+ configureWebAuthn,+ logger: silentLogger,+ }),+ ).toEqual({ accountSelectionInstalled: true, touchIdConfigured: false });+ expect(configureWebAuthn).not.toHaveBeenCalled();+ });++ it('fails closed on unsigned macOS builds but keeps roaming authenticator selection', () => {+ const harness = createSessionHarness();+ const configureWebAuthn = vi.fn();+ expect(+ configureRsbBrowserWebAuthn({+ platform: 'darwin',+ appleTeamId: '',+ appId: 'com.xd.cindy',+ browserSession: harness.browserSession,+ configureWebAuthn,+ logger: silentLogger,+ }),+ ).toEqual({ accountSelectionInstalled: true, touchIdConfigured: false });+ expect(configureWebAuthn).not.toHaveBeenCalled();+ });++ it('configures signed macOS builds with the matching keychain group and localized reason', () => {+ const harness = createSessionHarness();+ const configureWebAuthn = vi.fn();+ expect(+ configureRsbBrowserWebAuthn({+ platform: 'darwin',+ appleTeamId: 'TEAM123456',+ appId: 'com.xd.cindy',+ browserSession: harness.browserSession,+ configureWebAuthn,+ logger: silentLogger,+ }),+ ).toEqual({ accountSelectionInstalled: true, touchIdConfigured: true });+ expect(configureWebAuthn).toHaveBeenCalledWith({+ touchID: {+ keychainAccessGroup: 'TEAM123456.com.xd.cindy.webauthn',+ promptReason: expect.stringContaining('$1'),+ },+ });+ expect(harness.browserSession.on).toHaveBeenCalledWith(+ 'select-webauthn-account',+ expect.any(Function),+ );+ expect(BROWSER_PARTITION).toBe('persist:xdmaker-browser-app');+ });+});diff --git a/apps/desktop/src/main/__tests__/rsbBrowserWebAuthnLabels.test.ts b/apps/desktop/src/main/__tests__/rsbBrowserWebAuthnLabels.test.tsnew file mode 100644index 0000000000..77b7af7a2a--- /dev/null+++ b/apps/desktop/src/main/__tests__/rsbBrowserWebAuthnLabels.test.ts@@ -0,0 +1,10 @@+/** RSB WebAuthn 原生账户选择框四语文案的术语门禁。 */+import { RSB_BROWSER_WEBAUTHN_LABELS } from '../rsbBrowserWebAuthnLabels';++import { describeShadowCatalogGlossary, flattenShadowCatalog } from './shadowCatalogGlossary';++describeShadowCatalogGlossary(+ 'RSB WebAuthn 原生账户选择框符合术语表',+ flattenShadowCatalog(RSB_BROWSER_WEBAUTHN_LABELS, 'desktop:browser.passkey.'),+ 'RSB WebAuthn 原生账户选择框',+);diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex c12dcf3472..069112320e 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -177,6 +177,7 @@ import {setRsbPopupOpenerReportSubscriber,setRsbPopupOpenerResolver,} from './webview-security';+import { configureRsbBrowserWebAuthn } from './rsb-browser-webauthn.js';import {installSelectionContextMenu,setSelectionContextMenuLocale,@@ -5867,6 +5868,10 @@ app.on('ready', async () => {return;}+ // WebAuthn 是 app/session 级能力:在任何 RSB guest 或 popup WebContents 创建+ // 之前装账户选择回调;正式签名的 macOS 包同时启用 Touch ID 平台认证器。+ configureRsbBrowserWebAuthn();+// safeStorage 可观测性(#871):这条链路此前在日志里完全不可见,出问题(用户在// 系统钥匙串弹窗点了拒绝 → 加解密静默降级失败)只能靠弹窗反推。这里只落派生// 身份(条目名 = `<app.name> Safe Storage`),**刻意不调 isEncryptionAvailable()**diff --git a/apps/desktop/src/main/rsb-browser-webauthn.ts b/apps/desktop/src/main/rsb-browser-webauthn.tsnew file mode 100644index 0000000000..0a35f991b4--- /dev/null+++ b/apps/desktop/src/main/rsb-browser-webauthn.ts@@ -0,0 +1,304 @@+/**+ * RSB browser WebAuthn host integration.+ *+ * WebAuthn itself stays inside Chromium and the OS authenticator. Main only+ * enables Electron's macOS Touch ID backend for correctly signed builds and+ * supplies the account chooser Electron requires when an authenticator returns+ * multiple discoverable credentials. Ordinary RSB webviews and adopted popup+ * WebContents share BROWSER_PARTITION, so this single session listener covers+ * both without weakening renderer or webview isolation.+ */+import {+ app,+ BrowserWindow,+ dialog,+ session,+ webContents,+ type ConfigureWebAuthnOptions,+ type MessageBoxOptions,+ type WebAuthnAccount,+ type WebContents,+ type WebFrameMain,+} from 'electron';++import { CURRENT_APP_ID } from '../shared/brandRegion.js';+import { BROWSER_PARTITION } from '../shared/webviewPartition.js';+import { getResolvedMainLocale } from './i18n.js';+import { createLogger, type Logger } from './logger.js';+import {+ RSB_BROWSER_WEBAUTHN_LABELS,+ type RsbBrowserWebAuthnLabels,+} from './rsbBrowserWebAuthnLabels.js';+import { getRsbNativePopupOwnerWebContents } from './rsb-browser-bridge/native-popup-surfaces.js';++const log = createLogger('rsb-webauthn');+const APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/;+const APP_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/;+const MAX_ACCOUNT_LABEL_LENGTH = 96;+const MAX_RELYING_PARTY_ID_LENGTH = 253;+const MAX_CHOOSER_ACCOUNTS = 20;++type WebAuthnSelectionDetails = {+ relyingPartyId: string;+ accounts: WebAuthnAccount[];+ frame: Pick<WebFrameMain, 'detached'> | null;+};++type WebAuthnSelectionCallback = (credentialId?: string | null) => void;+type WebAuthnSelectionListener = (+ event: unknown,+ details: WebAuthnSelectionDetails,+ callback: WebAuthnSelectionCallback,+) => void;++interface WebAuthnSessionLike {+ on(event: 'select-webauthn-account', listener: WebAuthnSelectionListener): unknown;+}++interface AccountDialogResult {+ response: number;+}++type AccountDialogOwner = Pick<BrowserWindow, 'isDestroyed' | 'isVisible'>;+type NativePopupOwnerResolver = (webContentsId: number) => WebContents | null;+type ShowAccountDialog = (+ owner: AccountDialogOwner,+ options: MessageBoxOptions,+) => Promise<AccountDialogResult>;+type ResolveAccountDialogOwner = (+ frame: WebAuthnSelectionDetails['frame'],+) => AccountDialogOwner | null;+type SelectAccount = (details: WebAuthnSelectionDetails) => Promise<string | undefined>;++export interface ConfigureRsbBrowserWebAuthnDependencies {+ platform?: NodeJS.Platform;+ appleTeamId?: string;+ appId?: string;+ browserSession?: WebAuthnSessionLike;+ configureWebAuthn?: (options: ConfigureWebAuthnOptions) => void;+ selectAccount?: SelectAccount;+ logger?: Pick<Logger, 'info' | 'warn' | 'error'>;+}++const configuredSessions = new WeakSet<object>();++/** Build the access group shared by Electron runtime configuration and signing. */+export function resolveWebAuthnKeychainAccessGroup(+ appleTeamId: string | undefined,+ appId: string,+): string | null {+ const teamId = appleTeamId?.trim() ?? '';+ const bundleId = appId.trim();+ if (!APPLE_TEAM_ID_PATTERN.test(teamId)) return null;+ if (!APP_ID_PATTERN.test(bundleId) || bundleId.includes('..')) return null;+ return `${teamId}.${bundleId}.webauthn`;+}++function frameIsDetached(frame: WebAuthnSelectionDetails['frame']): boolean {+ if (!frame) return true;+ try {+ return frame.detached;+ } catch {+ return true;+ }+}++function boundedSingleLine(value: string | undefined, maxLength: number): string {+ return (+ (value ?? '')+ .replace(/\p{Cc}+/gu, ' ')+ // Authenticator account names are untrusted. Strip Unicode formatting and+ // bidi controls so a credential cannot visually reorder the native dialog.+ .replace(/\p{Cf}+/gu, '')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, maxLength)+ );+}++function accountButtonLabel(+ account: WebAuthnAccount,+ index: number,+ labels: RsbBrowserWebAuthnLabels,+): string {+ const displayName = boundedSingleLine(account.displayName, MAX_ACCOUNT_LABEL_LENGTH);+ const name = boundedSingleLine(account.name, MAX_ACCOUNT_LABEL_LENGTH);+ const accountLabel =+ displayName && name && displayName !== name+ ? `${displayName} (${name})`.slice(0, MAX_ACCOUNT_LABEL_LENGTH)+ : displayName || name || labels.unknownAccount.replace('{{index}}', String(index + 1));+ // A stable ordinal prevents an authenticator-controlled label from being+ // confused with the cancel action or another credential.+ return `${index + 1}. ${accountLabel}`;+}++function relyingPartyLabel(value: string): string {+ return boundedSingleLine(value, MAX_RELYING_PARTY_ID_LENGTH);+}++function defaultResolveAccountDialogOwner(+ frame: WebAuthnSelectionDetails['frame'],+ resolveNativePopupOwner: NativePopupOwnerResolver = getRsbNativePopupOwnerWebContents,+): AccountDialogOwner | null {+ if (!frame || frameIsDetached(frame)) return null;+ try {+ const source = webContents.fromFrame(frame as WebFrameMain);+ if (!source || source.isDestroyed() || !source.isFocused()) return null;+ const nativePopupOwner = resolveNativePopupOwner(source.id);+ const owner =+ BrowserWindow.fromWebContents(source) ??+ (source.hostWebContents ? BrowserWindow.fromWebContents(source.hostWebContents) : null) ??+ (nativePopupOwner ? BrowserWindow.fromWebContents(nativePopupOwner) : null);+ if (!owner || owner.isDestroyed() || !owner.isVisible()) return null;+ return owner;+ } catch {+ return null;+ }+}++function defaultShowAccountDialog(+ owner: AccountDialogOwner,+ options: MessageBoxOptions,+): Promise<AccountDialogResult> {+ return dialog.showMessageBox(owner as BrowserWindow, options);+}++/**+ * Ask the user which discoverable credential to use. A stale/detached request+ * is cancelled rather than allowing a selection to cross a navigation boundary.+ */+export async function selectRsbWebAuthnAccount(+ details: WebAuthnSelectionDetails,+ options: {+ labels?: RsbBrowserWebAuthnLabels;+ showDialog?: ShowAccountDialog;+ resolveDialogOwner?: ResolveAccountDialogOwner;+ resolveNativePopupOwner?: NativePopupOwnerResolver;+ } = {},+): Promise<string | undefined> {+ if (+ frameIsDetached(details.frame) ||+ details.accounts.length === 0 ||+ details.accounts.length > MAX_CHOOSER_ACCOUNTS+ )+ return undefined;+ const owner = (+ options.resolveDialogOwner ??+ ((frame) => defaultResolveAccountDialogOwner(frame, options.resolveNativePopupOwner))+ )(details.frame);+ if (!owner) return undefined;+ if (details.accounts.length === 1) return details.accounts[0]?.credentialId || undefined;++ const labels = options.labels ?? RSB_BROWSER_WEBAUTHN_LABELS[getResolvedMainLocale()];+ const buttons = details.accounts.map((account, index) =>+ accountButtonLabel(account, index, labels),+ );+ const cancelId = buttons.length;+ buttons.push(labels.cancel);++ const result = await (options.showDialog ?? defaultShowAccountDialog)(owner, {+ type: 'question',+ title: labels.title,+ message: labels.message.replace(+ '{{relyingPartyId}}',+ relyingPartyLabel(details.relyingPartyId) || labels.unknownRelyingParty,+ ),+ detail: labels.detail,+ buttons,+ defaultId: 0,+ cancelId,+ noLink: true,+ });++ if (frameIsDetached(details.frame)) return undefined;+ if (!Number.isInteger(result.response) || result.response < 0 || result.response >= cancelId) {+ return undefined;+ }+ return details.accounts[result.response]?.credentialId;+}++/** Install Electron's mandatory discoverable-account callback once per session. */+export function installRsbWebAuthnAccountSelection(+ browserSession: WebAuthnSessionLike,+ options: {+ selectAccount?: SelectAccount;+ logger?: Pick<Logger, 'warn'>;+ } = {},+): boolean {+ if (configuredSessions.has(browserSession as object)) return false;+ const selectAccount = options.selectAccount ?? ((details) => selectRsbWebAuthnAccount(details));+ const logger = options.logger ?? log;+ let selectionQueue = Promise.resolve();+ browserSession.on('select-webauthn-account', (_event, details, callback) => {+ const runSelection = async () => {+ let credentialId: string | undefined;+ try {+ credentialId = await selectAccount(details);+ } catch (error) {+ logger.warn('account selection failed; cancelling WebAuthn request', {+ error: error instanceof Error ? error.message : String(error),+ });+ } finally {+ callback(credentialId);+ }+ };+ // Native message boxes are modal but concurrent WebAuthn requests can still+ // arrive from separate RSB guests. Serialize them, then re-check source focus+ // inside selectRsbWebAuthnAccount before presenting each chooser.+ selectionQueue = selectionQueue.then(runSelection, runSelection);+ });+ configuredSessions.add(browserSession as object);+ return true;+}++/** Configure WebAuthn for the persistent RSB browser session after app ready. */+export function configureRsbBrowserWebAuthn(+ dependencies: ConfigureRsbBrowserWebAuthnDependencies = {},+): { accountSelectionInstalled: boolean; touchIdConfigured: boolean } {+ const logger = dependencies.logger ?? log;+ const browserSession =+ dependencies.browserSession ??+ (session.fromPartition(BROWSER_PARTITION) as unknown as WebAuthnSessionLike);+ const accountSelectionInstalled = installRsbWebAuthnAccountSelection(browserSession, {+ selectAccount: dependencies.selectAccount,+ logger,+ });++ if ((dependencies.platform ?? process.platform) !== 'darwin') {+ logger.info('WebAuthn account selection installed', {+ partition: BROWSER_PARTITION,+ touchId: false,+ });+ return { accountSelectionInstalled, touchIdConfigured: false };+ }++ const keychainAccessGroup = resolveWebAuthnKeychainAccessGroup(+ dependencies.appleTeamId ?? process.env.CINDY_WEBAUTHN_APPLE_TEAM_ID,+ dependencies.appId ?? CURRENT_APP_ID,+ );+ if (!keychainAccessGroup) {+ logger.info('Touch ID WebAuthn unavailable in this build: no signed Apple Team identity', {+ partition: BROWSER_PARTITION,+ });+ return { accountSelectionInstalled, touchIdConfigured: false };+ }++ const labels = RSB_BROWSER_WEBAUTHN_LABELS[getResolvedMainLocale()];+ try {+ (dependencies.configureWebAuthn ?? ((options) => app.configureWebAuthn(options)))({+ touchID: {+ keychainAccessGroup,+ promptReason: labels.touchIdPromptReason,+ },+ });+ logger.info('Touch ID WebAuthn configured', {+ partition: BROWSER_PARTITION,+ });+ return { accountSelectionInstalled, touchIdConfigured: true };+ } catch (error) {+ logger.error('failed to configure Touch ID WebAuthn', {+ error: error instanceof Error ? error.message : String(error),+ });+ return { accountSelectionInstalled, touchIdConfigured: false };+ }+}diff --git a/apps/desktop/src/main/rsbBrowserWebAuthnLabels.ts b/apps/desktop/src/main/rsbBrowserWebAuthnLabels.tsnew file mode 100644index 0000000000..c04009d2d1--- /dev/null+++ b/apps/desktop/src/main/rsbBrowserWebAuthnLabels.ts@@ -0,0 +1,62 @@+/**+ * RSB WebAuthn 原生账户选择框的四语文案。+ *+ * 这份 catalog 不走 renderer i18next,单独成模块是为了让主进程测试能够在+ * 不加载 Electron 启动入口的前提下执行术语与标点门禁。+ */+import type { SupportedLocale } from '../shared/locale.js';++export interface RsbBrowserWebAuthnLabels {+ title: string;+ message: string;+ detail: string;+ cancel: string;+ unknownAccount: string;+ unknownRelyingParty: string;+ touchIdPromptReason: string;+}++export const RSB_BROWSER_WEBAUTHN_LABELS: Record<+ SupportedLocale,+ RsbBrowserWebAuthnLabels+> = {+ 'zh-CN': {+ title: '选择通行密钥',+ message: '选择用于 {{relyingPartyId}} 的通行密钥',+ detail: 'Cindy 只会把你的选择交给认证器;通行密钥的私密信息始终留在认证器中。',+ cancel: '取消通行密钥登录',+ unknownAccount: '通行密钥 {{index}}',+ unknownRelyingParty: '此网站',+ touchIdPromptReason: '在 $1 验证你的身份',+ },+ en: {+ title: 'Choose a Passkey',+ message: 'Choose a passkey for {{relyingPartyId}}',+ detail:+ 'Cindy only passes your selection to the authenticator; the passkey secret stays in the authenticator.',+ cancel: 'Cancel Passkey Sign-In',+ unknownAccount: 'Passkey {{index}}',+ unknownRelyingParty: 'this website',+ touchIdPromptReason: 'verify your identity on $1',+ },+ ja: {+ title: 'パスキーを選択',+ message: '{{relyingPartyId}} で使用するパスキーを選択',+ detail:+ 'Cindy は選択内容のみを認証器に渡します。パスキーの秘密情報は常に認証器内に保持されます。',+ cancel: 'パスキーでのサインインをキャンセル',+ unknownAccount: 'パスキー {{index}}',+ unknownRelyingParty: 'このウェブサイト',+ touchIdPromptReason: '$1 で本人確認を行う',+ },+ ko: {+ title: '패스키 선택',+ message: '{{relyingPartyId}}에 사용할 패스키 선택',+ detail:+ 'Cindy는 선택 내용만 인증 장치에 전달하며, 패스키의 비밀 정보는 항상 인증 장치에 남아 있습니다.',+ cancel: '패스키 로그인 취소',+ unknownAccount: '패스키 {{index}}',+ unknownRelyingParty: '이 웹사이트',+ touchIdPromptReason: '$1에서 본인 확인',+ },+};diff --git a/apps/desktop/src/test/vitest/electron-stub.ts b/apps/desktop/src/test/vitest/electron-stub.tsindex 130dcf3e7d..e755ecfc46 100644--- a/apps/desktop/src/test/vitest/electron-stub.ts+++ b/apps/desktop/src/test/vitest/electron-stub.ts@@ -74,6 +74,7 @@ export const app = createEmitter({getName: () => 'XDMaker Test',setName: noop,getVersion: () => '0.0.0-test',+ configureWebAuthn: noop,setAppUserModelId: noop,requestSingleInstanceLock: () => true,releaseSingleInstanceLock: noop,@@ -307,6 +308,7 @@ export const session = {export const webContents = {fromId: () => null,+ fromFrame: () => null,getAllWebContents: () => [],};diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.tsindex befd198ca4..32ed7bfe95 100644--- a/apps/desktop/vite.main.config.ts+++ b/apps/desktop/vite.main.config.ts@@ -23,6 +23,10 @@ export default defineConfig(({ mode }) => {// 非 VITE_* 的 main-only 变量(不暴露到 renderer/preload;编译期注入)const allEnv = loadEnv(mode, process.cwd(), '');const readMainEnv = (key: string): string => allEnv[key] || process.env[key] || '';+ const readMainEnvPreservingEmpty = (key: string): string =>+ Object.prototype.hasOwnProperty.call(process.env, key)+ ? process.env[key] ?? ''+ : allEnv[key] ?? '';return {resolve: {// 仅 fixtures 生产排除条件(v6.17 允许范围):production 构建把@@ -54,6 +58,11 @@ export default defineConfig(({ mode }) => {'process.env.XDT_FILO_GOOGLE_CLIENT_SECRET': JSON.stringify(readMainEnv('XDT_FILO_GOOGLE_CLIENT_SECRET'),),+ // macOS WebAuthn Touch ID 的 Team ID 是公开签名身份,不是凭证。正式打包入口+ // 只在 Developer ID 签名路径注入;ad-hoc/dev 留空,runtime fail closed。+ 'process.env.CINDY_WEBAUTHN_APPLE_TEAM_ID': JSON.stringify(+ readMainEnvPreservingEmpty('CINDY_WEBAUTHN_APPLE_TEAM_ID').trim(),+ ),'process.env.XDT_VOICE_INPUT_DICTIONARY_TEXT_DEBUG': JSON.stringify(readMainEnv('XDT_VOICE_INPUT_DICTIONARY_TEXT_DEBUG'),),diff --git a/docs/legal/notices/THIRD-PARTY-NOTICES.txt b/docs/legal/notices/THIRD-PARTY-NOTICES.txtindex 62c1298af1..0af0c06a2a 100644--- a/docs/legal/notices/THIRD-PARTY-NOTICES.txt+++ b/docs/legal/notices/THIRD-PARTY-NOTICES.txt@@ -3555,7 +3555,7 @@ Apache LicenseOnly the viewer JavaScript (viewer-static.min.js) is redistributed. Upstream icon sets / stencils / templates carry an additional no-Atlassian-use restriction; none of those assets are redistributed by this product.-------------------------------------------------------------------------------Electron (bundled runtime) 41.2.0+Electron (bundled runtime) 41.10.3License: MITSource: https://github.com/electron/electron------------------------------------------------------------------------------diff --git a/docs/legal/notices/desktop-linux.txt b/docs/legal/notices/desktop-linux.txtindex f746e6badd..7b7998999f 100644--- a/docs/legal/notices/desktop-linux.txt+++ b/docs/legal/notices/desktop-linux.txt@@ -286,7 +286,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.-------------------------------------------------------------------------------Electron (bundled runtime) 41.2.0+Electron (bundled runtime) 41.10.3License: MITSource: https://github.com/electron/electron------------------------------------------------------------------------------diff --git a/docs/legal/notices/desktop-macos.txt b/docs/legal/notices/desktop-macos.txtindex 740f3c190e..7ca6b8bdd1 100644--- a/docs/legal/notices/desktop-macos.txt+++ b/docs/legal/notices/desktop-macos.txt@@ -286,7 +286,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.-------------------------------------------------------------------------------Electron (bundled runtime) 41.2.0+Electron (bundled runtime) 41.10.3License: MITSource: https://github.com/electron/electron------------------------------------------------------------------------------diff --git a/docs/legal/notices/desktop-win.txt b/docs/legal/notices/desktop-win.txtindex 01bd81bc5f..c9eddf527a 100644--- a/docs/legal/notices/desktop-win.txt+++ b/docs/legal/notices/desktop-win.txt@@ -286,7 +286,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.-------------------------------------------------------------------------------Electron (bundled runtime) 41.2.0+Electron (bundled runtime) 41.10.3License: MITSource: https://github.com/electron/electron------------------------------------------------------------------------------diff --git a/docs/legal/notices/sbom/desktop-linux.spdx.json b/docs/legal/notices/sbom/desktop-linux.spdx.jsonindex b79463b702..6781b83925 100644--- a/docs/legal/notices/sbom/desktop-linux.spdx.json+++ b/docs/legal/notices/sbom/desktop-linux.spdx.json@@ -3,7 +3,7 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-linux",- "documentNamespace": "https://cindy.app/spdx/desktop-linux/156d44a61ecf03e9226484f8e891de84ed099853480e30fba697a651bf84af24",+ "documentNamespace": "https://cindy.app/spdx/desktop-linux/8151ecd512d84f855fdd8838bf5948fc9b37ad5b84e05bfde10182cf77f14a3b","creationInfo": {"created": "2026-08-02T09:08:05Z","creators": [@@ -43,8 +43,8 @@},{"name": "Electron (bundled runtime)",- "SPDXID": "SPDXRef-Package-e01faf6cc0ab33f1",- "versionInfo": "41.2.0",+ "SPDXID": "SPDXRef-Package-e57785feb130dc56",+ "versionInfo": "41.10.3","downloadLocation": "https://github.com/electron/electron","filesAnalyzed": false,"licenseConcluded": "MIT",@@ -13669,7 +13669,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-e01faf6cc0ab33f1"+ "relatedSpdxElement": "SPDXRef-Package-e57785feb130dc56"},{"spdxElementId": "SPDXRef-DOCUMENT",diff --git a/docs/legal/notices/sbom/desktop-macos.spdx.json b/docs/legal/notices/sbom/desktop-macos.spdx.jsonindex 895c60a362..07f26760e2 100644--- a/docs/legal/notices/sbom/desktop-macos.spdx.json+++ b/docs/legal/notices/sbom/desktop-macos.spdx.json@@ -3,7 +3,7 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-macos",- "documentNamespace": "https://cindy.app/spdx/desktop-macos/1668c13954a47a76830fdbc5ec00a56b0bf2d6ea47c88c057d140572c73fb28b",+ "documentNamespace": "https://cindy.app/spdx/desktop-macos/81c6f1f9a4da87983a716bdb405a4e5adc859e32ef59b98b654af4b0a58a1a54","creationInfo": {"created": "2026-08-02T09:08:05Z","creators": [@@ -53,8 +53,8 @@},{"name": "Electron (bundled runtime)",- "SPDXID": "SPDXRef-Package-e01faf6cc0ab33f1",- "versionInfo": "41.2.0",+ "SPDXID": "SPDXRef-Package-e57785feb130dc56",+ "versionInfo": "41.10.3","downloadLocation": "https://github.com/electron/electron","filesAnalyzed": false,"licenseConcluded": "MIT",@@ -13684,7 +13684,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-e01faf6cc0ab33f1"+ "relatedSpdxElement": "SPDXRef-Package-e57785feb130dc56"},{"spdxElementId": "SPDXRef-DOCUMENT",diff --git a/docs/legal/notices/sbom/desktop-win.spdx.json b/docs/legal/notices/sbom/desktop-win.spdx.jsonindex 0bb70886c9..81e330e6c1 100644--- a/docs/legal/notices/sbom/desktop-win.spdx.json+++ b/docs/legal/notices/sbom/desktop-win.spdx.json@@ -3,7 +3,7 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-win",- "documentNamespace": "https://cindy.app/spdx/desktop-win/13eefb05658bb33ea52ade0679664ceaf1ace05c2f2a30ad4ee7562116a4903c",+ "documentNamespace": "https://cindy.app/spdx/desktop-win/c7127ee2d25b879a6e695800f8557d443f07d3f99c78086df0c6dea7d2a99958","creationInfo": {"created": "2026-08-02T09:08:05Z","creators": [@@ -43,8 +43,8 @@},{"name": "Electron (bundled runtime)",- "SPDXID": "SPDXRef-Package-e01faf6cc0ab33f1",- "versionInfo": "41.2.0",+ "SPDXID": "SPDXRef-Package-e57785feb130dc56",+ "versionInfo": "41.10.3","downloadLocation": "https://github.com/electron/electron","filesAnalyzed": false,"licenseConcluded": "MIT",@@ -18038,7 +18038,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-e01faf6cc0ab33f1"+ "relatedSpdxElement": "SPDXRef-Package-e57785feb130dc56"},{"spdxElementId": "SPDXRef-DOCUMENT",diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex aca4c71030..c4109b3d9f 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -223,6 +223,10 @@ issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mod腾讯授权页可能展示的外部产品名称,客户端仅按原品牌名展示;先登记为 proposed,待产品术语评审后再决定是否固化。+### Passkey++WebAuthn 可发现凭证的用户可见名称,采用 Apple、Google 与 Microsoft 平台常见译法;先登记为 proposed,待产品术语评审后固化。+### Personal WeChat个人微信连接在设置页中的产品名称;先登记为 proposed,待产品术语评审后再决定是否固化。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 315b775570..b4293c4293 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -54,6 +54,17 @@},"note": "远端主机上由 Cindy 管理的 Codex 凭证目录(~/.xdt-server/v1/codex-home/),与用户本机 ~/.codex 相区分。四语统一保留英文原词(home 小写),避免各语言自造「Codex 主目录」等不同说法;syncAuth 与 codexAuthMissing 等远端登录态文案使用。"},+ {+ "id": "passkey",+ "status": "proposed",+ "en": "Passkey",+ "translations": {+ "zh-CN": "通行密钥",+ "ja": "パスキー",+ "ko": "패스키"+ },+ "note": "WebAuthn 可发现凭证的用户可见名称,采用 Apple、Google 与 Microsoft 平台常见译法;先登记为 proposed,待产品术语评审后固化。"+ },{"id": "anthropic-messages","status": "proposed",diff --git a/package.json b/package.jsonindex da373f2a6d..bbce2dd828 100644--- a/package.json+++ b/package.json@@ -16,7 +16,7 @@"url": "https://github.com/makecindy/cindy/issues"},"engines": {- "node": ">=22",+ "node": ">=22.12","pnpm": ">=10.7 <11"},"packageManager": "[email protected]+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5df9301a61..e09ea56532 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -480,8 +480,8 @@ importers:specifier: ^0.31.10version: 0.31.10electron:- specifier: 41.2.0- version: 41.2.0+ specifier: 41.10.3+ version: 41.10.3eslint:specifier: ^9.0.0version: 9.39.5([email protected])@@ -2045,6 +2045,10 @@ packages:resolution: {integrity: sha512-U8j5Hyj2Zt7I5PciJvPJfmEv69Gb/Da9v+k655z3Jj1cuY0UnToEJ61IhXrzlTYqo+jUKC+fgAjDJ6vltJTS0A==}engines: {node: '>= 14.17.5'}+ '@electron-internal/[email protected]':+ resolution: {integrity: sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==}+ engines: {node: '>=22.12.0'}+'@electron/[email protected]':resolution: {integrity: sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==}engines: {node: '>=10.12.0'}@@ -2054,14 +2058,14 @@ packages:resolution: {integrity: sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==}hasBin: true- '@electron/[email protected]':- resolution: {integrity: sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ==}- engines: {node: '>=12'}-'@electron/[email protected]':resolution: {integrity: sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==}engines: {node: '>=14'}+ '@electron/[email protected]':+ resolution: {integrity: sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==}+ engines: {node: '>=22.12.0'}+'@electron/[email protected]':resolution: {integrity: sha512-aL+bFMIkpR0cmmj5Zgy0LMKEpgy43/hw5zadEArgmAMWWlKc5buwFvFT9G/o/YJkvXAJm5q3iuTuLaiaXW39sg==}engines: {node: '>= 10.0.0'}@@ -6125,9 +6129,9 @@ packages:resolution: {integrity: sha512-j9ETcBGJaXxAY/b6UBpR7LZfjdU4BAO+yvr4ifqHEdyuc3UNCy91PDGkWKY5UQ4coHNYfnwFggrqD6QPeFGAlg==}engines: {node: '>=8.0.0'}- resolution: {integrity: sha512-0OKLiymqfV0WK68RBXqAm3Myad2TpI5wwxLCBEUcH5Nugo3YfSk7p1Js/AL9266qTz5xZioUnxt9hG8FFwax0g==}- engines: {node: '>= 12.20.55'}+ resolution: {integrity: sha512-MJuSODPw8siv/I8JjhctW/cS/XNldwI4gLRyyWZx6QkoZJUDgbEvitp7IVOnGrHENTQb6Udo+zMpKhFnhlIhdg==}+ engines: {node: '>= 22.12.0'}hasBin: true@@ -6171,6 +6175,10 @@ packages:resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}engines: {node: '>=6'}+ resolution: {integrity: sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}+resolution: {integrity: sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==}@@ -11540,6 +11548,8 @@ snapshots:dependencies:chrome-trace-event: 1.0.4+ '@electron-internal/[email protected]': {}+'@electron/[email protected]':dependencies:commander: 5.1.0@@ -11552,7 +11562,7 @@ snapshots:fs-extra: 9.1.0minimist: 1.2.8- '@electron/[email protected]':+ '@electron/[email protected]':dependencies:debug: 4.4.3env-paths: 2.2.1@@ -11566,17 +11576,16 @@ snapshots:transitivePeerDependencies:- supports-color- '@electron/[email protected]':+ '@electron/[email protected]':dependencies:debug: 4.4.3- env-paths: 2.2.1- fs-extra: 8.1.0- got: 11.8.6+ env-paths: 3.0.0+ graceful-fs: 4.2.11progress: 2.0.3- semver: 6.3.1+ semver: 7.8.5sumchecker: 3.0.1optionalDependencies:- global-agent: 3.0.0+ undici: 7.28.0transitivePeerDependencies:- supports-color@@ -16133,11 +16142,11 @@ snapshots:- supports-coloroptional: truedependencies:- '@electron/get': 2.0.3+ '@electron-internal/extract-zip': 1.0.5+ '@electron/get': 5.1.0'@types/node': 24.13.3- extract-zip: 2.0.1transitivePeerDependencies:- supports-color@@ -16168,6 +16177,8 @@ snapshots:+ [email protected]: {}+diff --git a/scripts/__tests__/dev-docs-contract.test.mjs b/scripts/__tests__/dev-docs-contract.test.mjsindex f482b2d2dc..1ab7bfd08f 100644--- a/scripts/__tests__/dev-docs-contract.test.mjs+++ b/scripts/__tests__/dev-docs-contract.test.mjs@@ -173,7 +173,7 @@ test("developer documentation links resolve", () => {test("runtime versions and the docs contract are code-owned", () => {const rootPackage = readJson("package.json");- assert.equal(rootPackage.engines.node, ">=22");+ assert.equal(rootPackage.engines.node, ">=22.12");assert.equal(rootPackage.engines.pnpm, ">=10.7 <11");assert.match(rootPackage.packageManager, /^pnpm@10\./);assert.match(rootPackage.scripts["test:runner"], /scripts\/__tests__\/dev-docs-contract\.test\.mjs/);diff --git a/scripts/__tests__/notarize-mac-app.test.mjs b/scripts/__tests__/notarize-mac-app.test.mjsindex 7ed5700668..69bc618694 100644--- a/scripts/__tests__/notarize-mac-app.test.mjs+++ b/scripts/__tests__/notarize-mac-app.test.mjs@@ -1,16 +1,208 @@// macOS 公证编排回归测试。所有命令与文件操作都通过依赖注入模拟,// 不连接 Apple 服务、不读取真实凭证,也不创建打包产物。-import { test } from 'node:test';-import assert from 'node:assert/strict';+import { test } from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";-import { notarizeMacApp } from '../../apps/desktop/scripts/ci/lib.mjs';+import {+ assertMacWebAuthnProvisioningProfile,+ embedMacWebAuthnProvisioningProfile,+ macWebAuthnKeychainAccessGroup,+ notarizeMacApp,+ parseCodesignTeamIdentifier,+ writeMacEntitlements,+} from "../../apps/desktop/scripts/ci/lib.mjs";-const APP_PATH = '/tmp/Cindy.app';+const APP_PATH = "/tmp/Cindy.app";const ZIP_PATH = `${APP_PATH}.zip`;const IDENTITY = Object.freeze({- appleId: '[email protected]',- teamId: 'TEAM123456',- applePassword: 'test-app-password',+ appleId: "[email protected]",+ teamId: "TEAM123456",+ applePassword: "test-app-password",+});++test("macOS WebAuthn access group is derived from the exact signing and bundle identities", () => {+ assert.equal(+ macWebAuthnKeychainAccessGroup("TEAM123456", "com.xd.cindy"),+ "TEAM123456.com.xd.cindy.webauthn",+ );+ assert.throws(+ () => macWebAuthnKeychainAccessGroup("short", "com.xd.cindy"),+ /invalid Apple Team ID/,+ );+ assert.throws(+ () => macWebAuthnKeychainAccessGroup("TEAM123456", "com..xd.cindy"),+ /invalid macOS bundle id/,+ );+});++test("macOS WebAuthn keychain entitlement is main-only", () => {+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), "cindy-webauthn-entitlements-"),+ );+ const helperPath = path.join(tempDir, "helper.plist");+ const mainPath = path.join(tempDir, "main.plist");+ const keychainAccessGroup = macWebAuthnKeychainAccessGroup(+ "TEAM123456",+ "com.xd.cindy",+ );+ try {+ writeMacEntitlements(helperPath);+ writeMacEntitlements(mainPath, { appleEvents: true, keychainAccessGroup });++ const helper = fs.readFileSync(helperPath, "utf8");+ const main = fs.readFileSync(mainPath, "utf8");+ assert.doesNotMatch(helper, /keychain-access-groups/);+ assert.doesNotMatch(helper, /apple-events/);+ assert.match(main, /com\.apple\.security\.automation\.apple-events/);+ assert.match(main, /<key>keychain-access-groups<\/key>/);+ assert.ok(+ main.includes(`<string>${keychainAccessGroup}</string>`),+ "main entitlements should contain the exact WebAuthn keychain group",+ );+ assert.ok(+ !main.includes("<string>TEAM123456.com.xd.other.webauthn</string>"),+ "main entitlements should reject a different WebAuthn keychain group",+ );+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+});++function validWebAuthnProvisioningProfile(overrides = {}) {+ return {+ TeamIdentifier: ["TEAM123456"],+ ExpirationDate: "2099-01-01T00:00:00.000Z",+ Entitlements: {+ "com.apple.developer.team-identifier": "TEAM123456",+ "com.apple.application-identifier": "TEAM123456.com.xd.cindy",+ "keychain-access-groups": ["TEAM123456.com.xd.cindy.webauthn"],+ },+ ...overrides,+ };+}++const WEB_AUTHN_PROFILE_EXPECTED = Object.freeze({+ teamId: "TEAM123456",+ bundleId: "com.xd.cindy",+ keychainAccessGroup: "TEAM123456.com.xd.cindy.webauthn",+});++test("macOS WebAuthn provisioning profile must authorize the signing, app and keychain identities", () => {+ assert.doesNotThrow(() =>+ assertMacWebAuthnProvisioningProfile(+ validWebAuthnProvisioningProfile(),+ WEB_AUTHN_PROFILE_EXPECTED,+ ),+ );+ assert.throws(+ () =>+ assertMacWebAuthnProvisioningProfile(+ validWebAuthnProvisioningProfile({ TeamIdentifier: ["OTHER12345"] }),+ WEB_AUTHN_PROFILE_EXPECTED,+ ),+ /does not authorize Apple Team ID/,+ );+ assert.throws(+ () =>+ assertMacWebAuthnProvisioningProfile(+ validWebAuthnProvisioningProfile({+ Entitlements: {+ ...validWebAuthnProvisioningProfile().Entitlements,+ "keychain-access-groups": ["TEAM123456.com.xd.other.webauthn"],+ },+ }),+ WEB_AUTHN_PROFILE_EXPECTED,+ ),+ /does not authorize keychain group/,+ );+});++test("macOS WebAuthn provisioning profile is validated before it is embedded", () => {+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), "cindy-webauthn-profile-"),+ );+ const appPath = path.join(tempDir, "Cindy.app");+ const profilePath = path.join(tempDir, "source.provisionprofile");+ fs.mkdirSync(path.join(appPath, "Contents"), { recursive: true });+ fs.writeFileSync(profilePath, "signed-profile-bytes");+ const spawnCalls = [];+ try {+ const embeddedPath = embedMacWebAuthnProvisioningProfile(+ appPath,+ profilePath,+ WEB_AUTHN_PROFILE_EXPECTED,+ {+ spawnCommand(command, args, options) {+ spawnCalls.push({ command, args, options });+ if (command === "/usr/bin/security") {+ return {+ status: 0,+ stdout: `<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict>+ <key>ExpirationDate</key><date>2099-01-01T00:00:00Z</date>+ <key>DER-Encoded-Profile</key><data>AAECAwQ=</data>+</dict></plist>`,+ stderr: "",+ };+ }+ assert.equal(command, "/usr/bin/plutil");+ assert.equal(args[0], "-extract");+ assert.equal(args[3], "-o");+ assert.equal(args[4], "-");+ assert.equal(args[5], "--");+ assert.match(+ args[6].replaceAll("\\", "/"),+ /\/cindy-webauthn-profile-[^/]+\/decoded\.plist$/,+ );+ if (args[1] === "TeamIdentifier") {+ assert.equal(args[2], "json");+ return { status: 0, stdout: JSON.stringify(["TEAM123456"]), stderr: "" };+ }+ if (args[1] === "ExpirationDate") {+ assert.equal(args[2], "raw");+ return { status: 0, stdout: "2099-01-01T00:00:00Z\n", stderr: "" };+ }+ assert.equal(args[1], "Entitlements");+ assert.equal(args[2], "json");+ return {+ status: 0,+ stdout: JSON.stringify(validWebAuthnProvisioningProfile().Entitlements),+ stderr: "",+ };+ },+ },+ );+ assert.equal(+ embeddedPath,+ path.join(appPath, "Contents", "embedded.provisionprofile"),+ );+ assert.equal(fs.readFileSync(embeddedPath, "utf8"), "signed-profile-bytes");+ assert.equal(spawnCalls.length, 4);+ assert.deepEqual(spawnCalls.slice(1).map(({ args }) => args.slice(0, 3)), [+ ["-extract", "TeamIdentifier", "json"],+ ["-extract", "ExpirationDate", "raw"],+ ["-extract", "Entitlements", "json"],+ ]);+ assert.ok(spawnCalls.every(({ args }) => !args.includes("-convert")));+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+});++test("codesign TeamIdentifier parser reads the signing authority actually applied", () => {+ assert.equal(+ parseCodesignTeamIdentifier(+ "Identifier=com.xd.cindy\nTeamIdentifier=TEAM123456\n",+ ),+ "TEAM123456",+ );+ assert.equal(+ parseCodesignTeamIdentifier("TeamIdentifier=not set"),+ "not set",+ );});function createHarness(results) {