Pārlūkot izejas kodu

修复 macOS 客户端局域网权限身份冲突

Samien 3 stundas atpakaļ
vecāks
revīzija
c951bfbe03

+ 60 - 0
desktop/macos-network-identity.test.mjs

@@ -0,0 +1,60 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import { load } from 'js-yaml'
+import { namespaceMachOUUID } from '../scripts/prepare-desktop-macos.mjs'
+
+function binary(cpu = 0x100000c) {
+  const bytes = Buffer.alloc(96, 0x42)
+  bytes.writeUInt32LE(0xfeedfacf, 0); bytes.writeUInt32LE(cpu, 4)
+  bytes.writeUInt32LE(1, 16); bytes.writeUInt32LE(24, 20)
+  bytes.writeUInt32LE(0x1b, 32); bytes.writeUInt32LE(24, 36)
+  return bytes
+}
+
+test('Electron build UUIDs are separated by app/helper identity without changing other bytes', () => {
+  const original = binary(), before = Buffer.from(original)
+  const client = namespaceMachOUUID(original, 'cn.samien.yaoyao.desktop')
+  const full = namespaceMachOUUID(original, 'cn.samien.yaoyao.desktop.full')
+  const helper = namespaceMachOUUID(original, 'cn.samien.yaoyao.desktop.helper')
+  assert.deepEqual(original, before)
+  assert.deepEqual(client, namespaceMachOUUID(original, 'cn.samien.yaoyao.desktop'))
+  assert.equal(new Set([original, client, full, helper].map(b => b.subarray(40, 56).toString('hex'))).size, 4)
+  assert.deepEqual(client.subarray(0, 40), original.subarray(0, 40))
+  assert.deepEqual(client.subarray(56), original.subarray(56))
+  const nextElectron = binary(); nextElectron[40]++
+  assert.notDeepEqual(client, namespaceMachOUUID(nextElectron, 'cn.samien.yaoyao.desktop'))
+})
+
+test('universal builds rewrite both architecture slices and preserve their boundaries', () => {
+  const bytes = Buffer.alloc(512)
+  bytes.writeUInt32BE(0xcafebabe, 0); bytes.writeUInt32BE(2, 4)
+  bytes.writeUInt32BE(128, 16); bytes.writeUInt32BE(96, 20)
+  bytes.writeUInt32BE(256, 36); bytes.writeUInt32BE(96, 40)
+  binary().copy(bytes, 128); const intel = binary(0x1000007); intel[40]++; intel.copy(bytes, 256)
+  const result = namespaceMachOUUID(bytes, 'test.app')
+  assert.deepEqual(result.subarray(128, 224), namespaceMachOUUID(bytes.subarray(128, 224), 'test.app'))
+  assert.deepEqual(result.subarray(256, 352), namespaceMachOUUID(intel, 'test.app'))
+  assert.deepEqual(result.subarray(0, 128), bytes.subarray(0, 128))
+  bytes.writeUInt32BE(128, 36)
+  assert.throws(() => namespaceMachOUUID(bytes, 'test.app'), /重叠/)
+})
+
+test('malformed executables fail before anything is written', () => {
+  assert.throws(() => namespaceMachOUUID(Buffer.alloc(4), 'test.app'), /Mach-O/)
+  for (const [offset, value] of [[20, 9999], [36, 0], [36, 16], [32, 0x19], [16, 2]]) {
+    const bytes = binary(); bytes.writeUInt32LE(value, offset)
+    assert.throws(() => namespaceMachOUUID(bytes, 'test.app'), /Mach-O/)
+  }
+  assert.throws(() => namespaceMachOUUID(binary(), ''), /应用标识/)
+})
+
+test('both macOS package variants declare LAN access and run identity preparation before signing', () => {
+  const root = new URL('../', import.meta.url)
+  for (const file of ['electron-builder.client.yml', 'electron-builder.yml']) {
+    const config = load(readFileSync(new URL(file, root), 'utf8'))
+    assert.match(config.mac.extendInfo.NSLocalNetworkUsageDescription, /局域网服务器/)
+    const hook = readFileSync(new URL(config.afterPack, root), 'utf8')
+    assert.match(hook, /prepareMacDesktop/)
+  }
+})

+ 2 - 0
electron-builder.client.yml

@@ -1,5 +1,6 @@
 appId: cn.samien.yaoyao.desktop
 productName: 夭夭
+afterPack: scripts/prepare-desktop-macos.mjs
 directories:
   output: desktop-release-client
   app: .desktop-build-client/shell
@@ -34,6 +35,7 @@ mac:
   hardenedRuntime: true
   gatekeeperAssess: false
   extendInfo:
+    NSLocalNetworkUsageDescription: 夭夭需要连接你指定的局域网服务器,以登录账号、同步消息和使用电脑功能。
     NSMicrophoneUsageDescription: 夭夭使用麦克风接收语音消息。
 dmg:
   title: 夭夭 ${version}

+ 1 - 0
electron-builder.yml

@@ -79,6 +79,7 @@ mac:
   hardenedRuntime: true
   gatekeeperAssess: false
   extendInfo:
+    NSLocalNetworkUsageDescription: 夭夭需要连接你指定的局域网服务器,以登录账号、同步消息和使用电脑功能。
     NSMicrophoneUsageDescription: 夭夭使用麦克风接收语音消息。
 dmg:
   title: 夭夭 ${version}

+ 67 - 0
scripts/prepare-desktop-macos.mjs

@@ -0,0 +1,67 @@
+import { createHash } from 'node:crypto'
+import { execFileSync } from 'node:child_process'
+import { readFileSync, readdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+// macOS local-network privacy also looks up the responsible app by Mach-O UUID.
+// Stock Electron binaries share that UUID across otherwise unrelated bundles.
+// Run once on freshly staged executables, BEFORE electron-builder signs them.
+// Namespace each upstream build UUID by bundle ID; leave framework/dSYM UUIDs alone.
+export function namespaceMachOUUID(input, bundleId) {
+  if (!bundleId?.trim()) throw new Error('缺少 macOS 应用标识')
+  const bytes = Buffer.from(input), patches = []
+  function thin(start, size) {
+    const end = start + size
+    if (size < 32 || start < 0 || end > bytes.length || bytes.readUInt32LE(start) !== 0xfeedfacf)
+      throw new Error('不支持或损坏的 Mach-O 64 位可执行文件')
+    const count = bytes.readUInt32LE(start + 16), commandsEnd = start + 32 + bytes.readUInt32LE(start + 20)
+    if (commandsEnd > end) throw new Error('Mach-O 加载命令越界')
+    let offset = start + 32, uuidOffset
+    for (let i = 0; i < count; i++) {
+      if (offset + 8 > commandsEnd) throw new Error('Mach-O 加载命令不完整')
+      const command = bytes.readUInt32LE(offset), length = bytes.readUInt32LE(offset + 4)
+      if (length < 8 || length % 8 || offset + length > commandsEnd) throw new Error('Mach-O 加载命令长度无效')
+      if (command === 0x1b) {
+        if (length !== 24 || uuidOffset !== undefined) throw new Error('Mach-O LC_UUID 不唯一或无效')
+        uuidOffset = offset + 8
+      }
+      offset += length
+    }
+    if (offset !== commandsEnd || uuidOffset === undefined) throw new Error('Mach-O 缺少有效的 LC_UUID')
+    const uuid = createHash('sha256').update('yaoyao-macho-uuid-v1\0').update(bundleId).update('\0')
+      .update(bytes.subarray(uuidOffset, uuidOffset + 16)).digest().subarray(0, 16)
+    uuid[6] = (uuid[6] & 0x0f) | 0x80 // RFC 9562 version 8, application-defined UUID
+    uuid[8] = (uuid[8] & 0x3f) | 0x80
+    patches.push({ offset: uuidOffset, uuid })
+  }
+  if (bytes.length >= 8 && bytes.readUInt32BE(0) === 0xcafebabe) {
+    const count = bytes.readUInt32BE(4), tableEnd = 8 + count * 20, ranges = []
+    if (!count || tableEnd > bytes.length) throw new Error('Mach-O universal 架构表无效')
+    for (let i = 0; i < count; i++) {
+      const entry = 8 + i * 20, start = bytes.readUInt32BE(entry + 8), size = bytes.readUInt32BE(entry + 12)
+      if (start < tableEnd || ranges.some(r => start < r.end && start + size > r.start))
+        throw new Error('Mach-O universal 架构重叠')
+      thin(start, size)
+      ranges.push({ start, end: start + size })
+    }
+  } else thin(0, bytes.length)
+  for (const { offset, uuid } of patches) uuid.copy(bytes, offset)
+  return bytes
+}
+
+export default async function prepareMacDesktop(context) {
+  if (context.electronPlatformName !== 'darwin') return
+  const app = join(context.appOutDir, context.packager.appInfo.productFilename + '.app')
+  const plist = (bundle, key) => execFileSync('/usr/libexec/PlistBuddy', ['-c', `Print :${key}`, join(bundle, 'Contents', 'Info.plist')], { encoding: 'utf8' }).trim()
+  if (!plist(app, 'NSLocalNetworkUsageDescription')) throw new Error('应用缺少局域网权限用途说明')
+  const frameworks = join(app, 'Contents', 'Frameworks')
+  const bundles = [app, ...readdirSync(frameworks, { withFileTypes: true })
+    .filter(entry => entry.isDirectory() && entry.name.endsWith('.app')).map(entry => join(frameworks, entry.name))]
+  for (const bundle of bundles) {
+    const id = plist(bundle, 'CFBundleIdentifier'), name = plist(bundle, 'CFBundleExecutable')
+    if (!name || /[/\\]/.test(name)) throw new Error('应用可执行文件名称无效')
+    const executable = join(bundle, 'Contents', 'MacOS', name)
+    writeFileSync(executable, namespaceMachOUUID(readFileSync(executable), id))
+    console.log(`签名前配置独立的 macOS 网络权限身份:${id}`)
+  }
+}

+ 2 - 0
scripts/verify-desktop-runtime.mjs

@@ -2,6 +2,7 @@ import {execFileSync} from 'node:child_process'
 import {readFileSync} from 'node:fs'
 import {join} from 'node:path'
 import {verifyRuntimePackage} from '../bin/lib/runtime-release.mjs'
+import prepareMacDesktop from './prepare-desktop-macos.mjs'
 
 /** Run before signing: a valid build directory does not prove extraResources
  * retained the Runner's external packages in the actual application. */
@@ -37,6 +38,7 @@ export function verifyDesktopRuntime(runtime,version){
 
 export default async function verifyPackagedDesktop(context){
   if(context.electronPlatformName!=='darwin')return
+  await prepareMacDesktop(context)
   const version=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).dependencies.playwright
   const runtime=join(context.appOutDir,context.packager.appInfo.productFilename+'.app','Contents','Resources','runtime')
   verifyDesktopRuntime(runtime,version)