Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
fix(desktop): initialize shared signing keychain before Remotion packaging
Leggett1858d5ecea8e
diff --git a/apps/desktop/scripts/mac-signing.mjs b/apps/desktop/scripts/mac-signing.mjsindex e76e2593..de277d04 100644--- a/apps/desktop/scripts/mac-signing.mjs+++ b/apps/desktop/scripts/mac-signing.mjs@@ -1,8 +1,100 @@import { spawnSync } from 'node:child_process';+import { randomBytes } from 'node:crypto';+import { existsSync, mkdtempSync, rmSync } from 'node:fs';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';export const DEFAULT_OPENCREATOR_APPLE_TEAM_ID = 'NVRH5R5DJ5';export const DEFAULT_NOTARY_KEYCHAIN_PROFILE = 'clawee-notary';+// Prepare one keychain before standalone component signing and keep it alive+// through Electron Builder. CSC_KEYCHAIN avoids a second certificate import.+export async function withMacSigningKeychain(env, action, options = {}) {+ const existingKeychain = env.APPLE_KEYCHAIN?.trim() || env.CSC_KEYCHAIN?.trim();+ if (existingKeychain) return action(signingEnvironment(env, existingKeychain));+ if (!hasValue(env.CSC_LINK)) return action(env);+ if (!hasValue(env.CSC_KEY_PASSWORD)) {+ throw new Error('Temporary macOS signing requires CSC_KEY_PASSWORD with CSC_LINK');+ }++ const tools = options.keychainTools ?? loadKeychainTools();+ const temporaryFiles = new tools.TmpDir();+ const currentDir = mkdtempSync(join(tmpdir(), 'opencreator-component-signing-'));+ const keychainFile = join(currentDir, 'signing.keychain');+ const keychainPassword = randomBytes(32).toString('hex');+ const security = options.runSecurity ?? (args => runSecurity(args, [+ env.CSC_LINK, env.CSC_KEY_PASSWORD, keychainPassword+ ]));+ const listKeychains = async () => (await security(['list-keychains', '-d', 'user']))+ .split('\n').map(line => line.trim().replace(/^"|"$/g, '')).filter(Boolean);+ let keychainCreated = false;+ let addedKeychains = [];+ try {+ let certificate;+ try { certificate = await tools.importCertificate(env.CSC_LINK, temporaryFiles, currentDir); }+ catch { throw new Error('Unable to prepare the macOS signing certificate from CSC_LINK'); }+ await security(['create-keychain', '-p', keychainPassword, keychainFile]);+ keychainCreated = true;+ await security(['unlock-keychain', '-p', keychainPassword, keychainFile]);+ await security(['set-keychain-settings', '-lut', '21600', keychainFile]);+ const currentKeychains = await listKeychains();+ addedKeychains = [keychainFile, tools.rootCertKeychain].filter(path => path && !currentKeychains.includes(path));+ await security(['list-keychains', '-d', 'user', '-s', ...addedKeychains, ...currentKeychains]);+ await security(['import', certificate, '-k', keychainFile,+ '-T', '/usr/bin/codesign', '-T', '/usr/bin/productbuild', '-P', env.CSC_KEY_PASSWORD]);+ // This password belongs to the keychain, not the imported PKCS#12 file.+ await security(['set-key-partition-list', '-S', 'apple-tool:,apple:', '-s', '-k', keychainPassword, keychainFile]);+ return await action(signingEnvironment(env, keychainFile));+ } finally {+ try {+ if (addedKeychains.length > 0) {+ const currentKeychains = await listKeychains();+ await security(['list-keychains', '-d', 'user', '-s', ...currentKeychains.filter(path => !addedKeychains.includes(path))]);+ }+ } finally {+ try {+ if (keychainCreated || existsSync(keychainFile) || existsSync(`${keychainFile}-db`)) {+ await security(['delete-keychain', keychainFile]);+ }+ }+ finally {+ try { await temporaryFiles.cleanup(); }+ finally { rmSync(currentDir, { recursive: true, force: true }); }+ }+ }+ }+}++function signingEnvironment(env, keychainFile) {+ const result = { ...env, APPLE_KEYCHAIN: keychainFile, CSC_KEYCHAIN: keychainFile };+ delete result.CSC_LINK;+ delete result.CSC_KEY_PASSWORD;+ return result;+}++function runSecurity(args, secrets) {+ const result = spawnSync('/usr/bin/security', args, { encoding: 'utf8', timeout: 60_000 });+ if (result.error || result.status !== 0) {+ let detail = result.stderr?.trim() || result.error?.message || 'No diagnostic output';+ for (const secret of secrets) if (secret) detail = detail.replaceAll(secret, '[redacted]');+ throw new Error(`macOS signing: security ${args[0]} failed (${result.status ?? 'process error'}): ${detail}`);+ }+ return result.stdout;+}++function loadKeychainTools() {+ const require = createRequire(import.meta.url);+ const builderRequire = createRequire(require.resolve('electron-builder'));+ const signingPath = builderRequire.resolve('app-builder-lib/out/codeSign/codesign.js');+ const signingRequire = createRequire(signingPath);+ return {+ ...signingRequire(signingPath),+ TmpDir: signingRequire('builder-util').TmpDir,+ rootCertKeychain: resolve(dirname(signingPath), '../../certs/root_certs.keychain')+ };+}+export function configureMacDirectorySigning(input) {const builderEnv = { ...input.env };diff --git a/apps/desktop/scripts/package-release.mjs b/apps/desktop/scripts/package-release.mjsindex 211d45d8..f30c6353 100644--- a/apps/desktop/scripts/package-release.mjs+++ b/apps/desktop/scripts/package-release.mjs@@ -22,7 +22,8 @@ import { spawnSync } from 'node:child_process';import { fileURLToPath } from 'node:url';import {configureMacDirectorySigning,- configureMacReleaseSigning+ configureMacReleaseSigning,+ withMacSigningKeychain} from './mac-signing.mjs';import { submitAndWaitForNotarization } from './apple-notarization.mjs';import { prepareElectronBuilderCache } from './electron-builder-cache.mjs';@@ -126,198 +127,205 @@ const {appleTeamId: process.env.OPENCREATOR_APPLE_TEAM_ID?? process.env.APPLE_TEAM_ID});-const packageStartedAt = Date.now();-await runStage('构建独立 Remotion 组件与轻量角色资源', process.execPath, [- resolve(scriptDir, 'prepare-stickman-runtime.mjs')-], { cwd: rootDir, env: builderEnv, timeoutMs: 25 * 60_000 });-if (macSigning.mode === 'developer-id' && mode === 'release') {- const componentNotaryArchive = resolve(desktopDir, '.pack', 'remotion-notarization.zip');- try {- await runStage('准备 Remotion 组件公证', 'ditto', ['-c', '-k', '--keepParent', resolve(desktopDir, '.pack', 'stickman-runtime'), componentNotaryArchive], { cwd: rootDir, env: builderEnv });- await submitAndWaitForNotarization(componentNotaryArchive, notarizationArgs);- } finally { rmSync(componentNotaryArchive, { force: true }); }-}-await runStage(- mode === 'dir' ? '生成可运行目录' : '生成桌面安装包',- 'electron-builder',- args,- {- cwd: desktopDir,- env: builderEnv,- timeoutMs: mode === 'dir' ? 20 * 60_000 : 50 * 60_000+const packageWithSigningEnvironment = async builderEnv => {+ const packageStartedAt = Date.now();+ await runStage('构建独立 Remotion 组件与轻量角色资源', process.execPath, [+ resolve(scriptDir, 'prepare-stickman-runtime.mjs')+ ], { cwd: rootDir, env: builderEnv, timeoutMs: 25 * 60_000 });+ if (macSigning.mode === 'developer-id' && mode === 'release') {+ const componentNotaryArchive = resolve(desktopDir, '.pack', 'remotion-notarization.zip');+ try {+ await runStage('准备 Remotion 组件公证', 'ditto', ['-c', '-k', '--keepParent', resolve(desktopDir, '.pack', 'stickman-runtime'), componentNotaryArchive], { cwd: rootDir, env: builderEnv });+ await submitAndWaitForNotarization(componentNotaryArchive, notarizationArgs);+ } finally { rmSync(componentNotaryArchive, { force: true }); }}-);--const packageRoot = findFreshPackageRoot(candidates);-const artifacts = findFreshArtifacts(packageStartedAt, mode, platform);-const remotionComponent = JSON.parse(readFileSync(resolve(desktopDir, '.pack', 'components', 'remotion-component.json'), 'utf8'));-const componentArchive = resolve(desktopDir, '.pack', 'components', remotionComponent.fileName);-if (macSigning.mode === 'developer-id' && mode === 'release') {- await finalizeMacReleaseArtifacts(- artifacts.filter(path => path.endsWith('.dmg')),- notarizationArgs+ await runStage(+ mode === 'dir' ? '生成可运行目录' : '生成桌面安装包',+ 'electron-builder',+ args,+ {+ cwd: desktopDir,+ env: builderEnv,+ timeoutMs: mode === 'dir' ? 20 * 60_000 : 50 * 60_000+ });-}-const webBuild = hashDirectory(resolve(rootDir, 'apps/web/dist'));-const creatorAgentRuntime = hashDirectory(resolve(- desktopDir,- '.pack',- 'daemon',- 'runtime',- 'opencreator-runtime'-));-const codexRuntimeManifest = JSON.parse(readFileSync(- resolve(desktopDir, '.pack', 'codex-runtime', 'manifest.json'),- 'utf8'-));-const creatorRuntimeManifest = JSON.parse(readFileSync(- resolve(desktopDir, '.pack', 'creator-runtime', 'krillinai', 'manifest.json'),- 'utf8'-));-const stickmanRuntimeRoot = resolve(desktopDir, '.pack', 'stickman-runtime');-const stickmanRuntimeManifest = verifyStickmanRuntime(- stickmanRuntimeRoot,- platform,- arch-);-const stickmanRuntime = hashStickmanDirectory(stickmanRuntimeRoot);-const stickmanRuntimeManifestSha256 = hashStickmanFile(- resolve(stickmanRuntimeRoot, 'manifest.json')-);-const creatorSubtitleFontSourceManifest = JSON.parse(readFileSync(- resolve(rootDir, 'assets', 'creator-subtitle-fonts', 'manifest.json'),- 'utf8'-));-const creatorPresetManifest = JSON.parse(readFileSync(- resolve(++ const packageRoot = findFreshPackageRoot(candidates);+ const artifacts = findFreshArtifacts(packageStartedAt, mode, platform);+ const remotionComponent = JSON.parse(readFileSync(resolve(desktopDir, '.pack', 'components', 'remotion-component.json'), 'utf8'));+ const componentArchive = resolve(desktopDir, '.pack', 'components', remotionComponent.fileName);+ if (macSigning.mode === 'developer-id' && mode === 'release') {+ await finalizeMacReleaseArtifacts(+ artifacts.filter(path => path.endsWith('.dmg')),+ notarizationArgs+ );+ }+ const webBuild = hashDirectory(resolve(rootDir, 'apps/web/dist'));+ const creatorAgentRuntime = hashDirectory(resolve(desktopDir,'.pack','daemon','runtime',- 'creator-presets',- 'manifest.json'- ),- 'utf8'-));-const creatorSubtitleFontResources = creatorRuntimeManifest.resources- .filter(resource => (- resource.path.startsWith('fonts/')- || resource.path.startsWith('licenses/fonts/')+ 'opencreator-runtime'));-const creatorSubtitleWebFontResources = creatorSubtitleFontSourceManifest.fonts- .map(font => {- if (- typeof font?.webFile !== 'string'- || typeof font?.webSha256 !== 'string'- || !/^[a-f0-9]{64}$/i.test(font.webSha256)- ) {- throw new Error('Creator subtitle Web font manifest is invalid');- }- const source = resolve(rootDir, 'assets', 'creator-subtitle-fonts', font.webFile);- const built = resolve(rootDir, 'apps', 'web', 'dist', 'fonts', 'opencreator', basename(font.webFile));- if (!existsSync(source) || hashFile(source) !== font.webSha256.toLowerCase()) {- throw new Error(`Creator subtitle Web source font hash mismatch: ${font.webFile}`);- }- if (!existsSync(built) || hashFile(built) !== font.webSha256.toLowerCase()) {- throw new Error(`Creator subtitle Web build font hash mismatch: ${built}`);- }- return {- path: `fonts/opencreator/${basename(font.webFile)}`,- sha256: font.webSha256.toLowerCase()- };- });-const manifest = {- version: 1,- commit: gitOutput(['rev-parse', 'HEAD']) || 'unknown',- dirty: gitOutput(['status', '--porcelain', '--untracked-files=normal']).length > 0,- generatedAt: new Date().toISOString(),- platform,- arch,- mode,- officialBuild,- packageRoot,- packageRootRelative: relative(rootDir, packageRoot),- webBuildHash: webBuild.hash,- webFileCount: webBuild.fileCount,- creatorAgentRuntimeHash: creatorAgentRuntime.hash,- creatorAgentRuntimeFileCount: creatorAgentRuntime.fileCount,- stickmanRuntimeHash: stickmanRuntime.hash,- stickmanRuntimeFileCount: stickmanRuntime.fileCount,- stickmanRuntimeManifestSha256,- remotionVersion: stickmanRuntimeManifest.remotionVersion,- chromiumVersion: stickmanRuntimeManifest.chromiumVersion,- remotionComponent,- creatorPresetCatalogHash: creatorPresetManifest.catalogHash,- creatorPresetAssetSetHash: creatorPresetManifest.assetSetHash,- creatorPresetResourceCount: creatorPresetManifest.files.length,- creatorSubtitleFontSetHash: hashResourceDescriptors(- creatorSubtitleFontResources- ),- creatorSubtitleFontResourceCount: creatorSubtitleFontResources.length,- creatorSubtitleWebFontSetHash: hashResourceDescriptors(- creatorSubtitleWebFontResources- ),- creatorSubtitleWebFontResourceCount: creatorSubtitleWebFontResources.length,- codexRuntimeVersion: codexRuntimeManifest.version,- codexRuntimeCommit: codexRuntimeManifest.commit,- codexRuntimeBinarySha256: codexRuntimeManifest.binary.sha256,- codexAppServerProtocolSha256: codexRuntimeManifest.appServerProtocol.schemaSha256,- krillinCliVersion: creatorRuntimeManifest.cliVersion,- krillinSourceCommit: creatorRuntimeManifest.sourceCommit,- krillinSourceSha256: creatorRuntimeManifest.sourceSha256,- krillinIntegrationPatchSha256: creatorRuntimeManifest.integrationPatchSha256,- ytDlpRuntimeMode: creatorRuntimeManifest.ytDlp?.mode,- ytDlpVersion: creatorRuntimeManifest.ytDlp?.version,- ytDlpPythonVersion: creatorRuntimeManifest.ytDlp?.pythonVersion,- macSigningMode: macSigning.mode,- appleTeamId: macSigning.teamId ?? null,- artifacts: [...artifacts, componentArchive].map(path => ({- path,- relativePath: relative(rootDir, path),- bytes: statSync(path).size,- sha256: hashFile(path)- }))-};-writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);-console.log(`[desktop-package] 构建清单:${manifestPath}`);-console.log(`[desktop-package] 包根目录:${packageRoot}`);-if (process.env.GITHUB_ENV) {- appendFileSync(- process.env.GITHUB_ENV,- `OPENCREATOR_DESKTOP_BUILD_MANIFEST=${manifestPath}\n`- + `OPENCREATOR_DESKTOP_PACKAGE_ROOT=${packageRoot}\n`+ const codexRuntimeManifest = JSON.parse(readFileSync(+ resolve(desktopDir, '.pack', 'codex-runtime', 'manifest.json'),+ 'utf8'+ ));+ const creatorRuntimeManifest = JSON.parse(readFileSync(+ resolve(desktopDir, '.pack', 'creator-runtime', 'krillinai', 'manifest.json'),+ 'utf8'+ ));+ const stickmanRuntimeRoot = resolve(desktopDir, '.pack', 'stickman-runtime');+ const stickmanRuntimeManifest = verifyStickmanRuntime(+ stickmanRuntimeRoot,+ platform,+ arch);-}+ const stickmanRuntime = hashStickmanDirectory(stickmanRuntimeRoot);+ const stickmanRuntimeManifestSha256 = hashStickmanFile(+ resolve(stickmanRuntimeRoot, 'manifest.json')+ );+ const creatorSubtitleFontSourceManifest = JSON.parse(readFileSync(+ resolve(rootDir, 'assets', 'creator-subtitle-fonts', 'manifest.json'),+ 'utf8'+ ));+ const creatorPresetManifest = JSON.parse(readFileSync(+ resolve(+ desktopDir,+ '.pack',+ 'daemon',+ 'runtime',+ 'creator-presets',+ 'manifest.json'+ ),+ 'utf8'+ ));+ const creatorSubtitleFontResources = creatorRuntimeManifest.resources+ .filter(resource => (+ resource.path.startsWith('fonts/')+ || resource.path.startsWith('licenses/fonts/')+ ));+ const creatorSubtitleWebFontResources = creatorSubtitleFontSourceManifest.fonts+ .map(font => {+ if (+ typeof font?.webFile !== 'string'+ || typeof font?.webSha256 !== 'string'+ || !/^[a-f0-9]{64}$/i.test(font.webSha256)+ ) {+ throw new Error('Creator subtitle Web font manifest is invalid');+ }+ const source = resolve(rootDir, 'assets', 'creator-subtitle-fonts', font.webFile);+ const built = resolve(rootDir, 'apps', 'web', 'dist', 'fonts', 'opencreator', basename(font.webFile));+ if (!existsSync(source) || hashFile(source) !== font.webSha256.toLowerCase()) {+ throw new Error(`Creator subtitle Web source font hash mismatch: ${font.webFile}`);+ }+ if (!existsSync(built) || hashFile(built) !== font.webSha256.toLowerCase()) {+ throw new Error(`Creator subtitle Web build font hash mismatch: ${built}`);+ }+ return {+ path: `fonts/opencreator/${basename(font.webFile)}`,+ sha256: font.webSha256.toLowerCase()+ };+ });+ const manifest = {+ version: 1,+ commit: gitOutput(['rev-parse', 'HEAD']) || 'unknown',+ dirty: gitOutput(['status', '--porcelain', '--untracked-files=normal']).length > 0,+ generatedAt: new Date().toISOString(),+ platform,+ arch,+ mode,+ officialBuild,+ packageRoot,+ packageRootRelative: relative(rootDir, packageRoot),+ webBuildHash: webBuild.hash,+ webFileCount: webBuild.fileCount,+ creatorAgentRuntimeHash: creatorAgentRuntime.hash,+ creatorAgentRuntimeFileCount: creatorAgentRuntime.fileCount,+ stickmanRuntimeHash: stickmanRuntime.hash,+ stickmanRuntimeFileCount: stickmanRuntime.fileCount,+ stickmanRuntimeManifestSha256,+ remotionVersion: stickmanRuntimeManifest.remotionVersion,+ chromiumVersion: stickmanRuntimeManifest.chromiumVersion,+ remotionComponent,+ creatorPresetCatalogHash: creatorPresetManifest.catalogHash,+ creatorPresetAssetSetHash: creatorPresetManifest.assetSetHash,+ creatorPresetResourceCount: creatorPresetManifest.files.length,+ creatorSubtitleFontSetHash: hashResourceDescriptors(+ creatorSubtitleFontResources+ ),+ creatorSubtitleFontResourceCount: creatorSubtitleFontResources.length,+ creatorSubtitleWebFontSetHash: hashResourceDescriptors(+ creatorSubtitleWebFontResources+ ),+ creatorSubtitleWebFontResourceCount: creatorSubtitleWebFontResources.length,+ codexRuntimeVersion: codexRuntimeManifest.version,+ codexRuntimeCommit: codexRuntimeManifest.commit,+ codexRuntimeBinarySha256: codexRuntimeManifest.binary.sha256,+ codexAppServerProtocolSha256: codexRuntimeManifest.appServerProtocol.schemaSha256,+ krillinCliVersion: creatorRuntimeManifest.cliVersion,+ krillinSourceCommit: creatorRuntimeManifest.sourceCommit,+ krillinSourceSha256: creatorRuntimeManifest.sourceSha256,+ krillinIntegrationPatchSha256: creatorRuntimeManifest.integrationPatchSha256,+ ytDlpRuntimeMode: creatorRuntimeManifest.ytDlp?.mode,+ ytDlpVersion: creatorRuntimeManifest.ytDlp?.version,+ ytDlpPythonVersion: creatorRuntimeManifest.ytDlp?.pythonVersion,+ macSigningMode: macSigning.mode,+ appleTeamId: macSigning.teamId ?? null,+ artifacts: [...artifacts, componentArchive].map(path => ({+ path,+ relativePath: relative(rootDir, path),+ bytes: statSync(path).size,+ sha256: hashFile(path)+ }))+ };+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);+ console.log(`[desktop-package] 构建清单:${manifestPath}`);+ console.log(`[desktop-package] 包根目录:${packageRoot}`);+ if (process.env.GITHUB_ENV) {+ appendFileSync(+ process.env.GITHUB_ENV,+ `OPENCREATOR_DESKTOP_BUILD_MANIFEST=${manifestPath}\n`+ + `OPENCREATOR_DESKTOP_PACKAGE_ROOT=${packageRoot}\n`+ );+ }-await runStage('验证桌面包', process.execPath, [- resolve(scriptDir, 'verify-package.mjs')-], {- cwd: rootDir,- env: {- ...builderEnv,- OPENCREATOR_DESKTOP_BUILD_MANIFEST: manifestPath,- OPENCREATOR_DESKTOP_PACKAGE_ROOT: packageRoot,- ...(macSigning.mode === 'developer-id'- ? {- OPENCREATOR_REQUIRE_DEVELOPER_ID: '1',- OPENCREATOR_APPLE_TEAM_ID: macSigning.teamId,- ...(mode === 'release'- ? { OPENCREATOR_REQUIRE_NOTARIZED_MAC_APP: '1' }- : {})- }- : {})- },- timeoutMs: 5 * 60_000-});+ await runStage('验证桌面包', process.execPath, [+ resolve(scriptDir, 'verify-package.mjs')+ ], {+ cwd: rootDir,+ env: {+ ...builderEnv,+ OPENCREATOR_DESKTOP_BUILD_MANIFEST: manifestPath,+ OPENCREATOR_DESKTOP_PACKAGE_ROOT: packageRoot,+ ...(macSigning.mode === 'developer-id'+ ? {+ OPENCREATOR_REQUIRE_DEVELOPER_ID: '1',+ OPENCREATOR_APPLE_TEAM_ID: macSigning.teamId,+ ...(mode === 'release'+ ? { OPENCREATOR_REQUIRE_NOTARIZED_MAC_APP: '1' }+ : {})+ }+ : {})+ },+ timeoutMs: 5 * 60_000+ });-if (mode !== 'dir') {- const packageJson = JSON.parse(readFileSync(join(desktopDir, 'package.json'), 'utf8'));- const assetsDir = join(releaseDir, 'publish', `${platform}-${arch}`);- const assets = stageReleaseAssets({ manifest, version: packageJson.version, assetsDir });- console.log(`[desktop-package] 发布附件:${assetsDir} (${assets.length} files)`);- if (process.env.GITHUB_ENV) {- appendFileSync(process.env.GITHUB_ENV, `OPENCREATOR_DESKTOP_RELEASE_ASSETS=${assetsDir}\n`);+ if (mode !== 'dir') {+ const packageJson = JSON.parse(readFileSync(join(desktopDir, 'package.json'), 'utf8'));+ const assetsDir = join(releaseDir, 'publish', `${platform}-${arch}`);+ const assets = stageReleaseAssets({ manifest, version: packageJson.version, assetsDir });+ console.log(`[desktop-package] 发布附件:${assetsDir} (${assets.length} files)`);+ if (process.env.GITHUB_ENV) {+ appendFileSync(process.env.GITHUB_ENV, `OPENCREATOR_DESKTOP_RELEASE_ASSETS=${assetsDir}\n`);+ }}+};+if (macSigning.mode === 'developer-id') {+ await withMacSigningKeychain(builderEnv, packageWithSigningEnvironment);+} else {+ await packageWithSigningEnvironment(builderEnv);}function parseMode(args) {diff --git a/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs b/apps/desktop/scripts/sign-creator-runtime-after-pack.mjsindex 21f75172..7750e35a 100644--- a/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs+++ b/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs@@ -13,7 +13,7 @@ import { join, relative } from 'node:path';import { spawnSync } from 'node:child_process';import { verifyCreatorRuntime } from './creator-runtime-contract.mjs';import { verifyStickmanRuntime } from './stickman-runtime-contract.mjs';-import { findDeveloperIdIdentity } from './mac-signing.mjs';+import { findDeveloperIdIdentity, withMacSigningKeychain } from './mac-signing.mjs';import { prepareMacAppIcon } from './mac-app-icon.mjs';const machOMagicValues = new Set([@@ -34,15 +34,18 @@ export async function afterPack(context) {await signCreatorRuntimeBundle(context);}-export async function signRemotionComponent(runtimeRoot, env = process.env) {+export async function signRemotionComponent(runtimeRoot, env = process.env, options = {}) {if (env.OPENCREATOR_SIGN_CREATOR_RUNTIME !== '1') return;- if (process.platform !== 'darwin') throw new Error('Remotion Developer ID signing requires macOS');- const identity = env.OPENCREATOR_REMOTION_SIGNING_IDENTITY?.trim()- || findSigningIdentity(env.OPENCREATOR_APPLE_TEAM_ID, env.APPLE_KEYCHAIN ?? null);- const binaries = findMachOBinaries(runtimeRoot);- if (binaries.length === 0) throw new Error('Remotion component has no native binaries');- for (const path of binaries) signMachOBinary(path, identity, env.APPLE_KEYCHAIN ?? null);- updateManifestHashes(runtimeRoot, binaries);+ if ((options.platform ?? process.platform) !== 'darwin') throw new Error('Remotion Developer ID signing requires macOS');+ await (options.withKeychain ?? withMacSigningKeychain)(env, async signingEnv => {+ const keychainFile = signingEnv.APPLE_KEYCHAIN ?? null;+ const identity = signingEnv.OPENCREATOR_REMOTION_SIGNING_IDENTITY?.trim()+ || (options.findIdentity ?? findSigningIdentity)(signingEnv.OPENCREATOR_APPLE_TEAM_ID, keychainFile);+ const binaries = (options.findBinaries ?? findMachOBinaries)(runtimeRoot);+ if (binaries.length === 0) throw new Error('Remotion component has no native binaries');+ for (const path of binaries) await (options.signBinary ?? signMachOBinary)(path, identity, keychainFile);+ updateManifestHashes(runtimeRoot, binaries);+ });}export async function signDaemonRuntimeBundle(context, options = {}) {diff --git a/apps/desktop/test/creator-runtime-signing.test.mjs b/apps/desktop/test/creator-runtime-signing.test.mjsindex e2874943..27655b0b 100644--- a/apps/desktop/test/creator-runtime-signing.test.mjs+++ b/apps/desktop/test/creator-runtime-signing.test.mjs@@ -15,6 +15,7 @@ import {signDaemonRuntimeBundle,signCreatorRuntimeBundle,signStickmanRuntimeBundle,+ signRemotionComponent,updateManifestHashes} from '../scripts/sign-creator-runtime-after-pack.mjs';@@ -27,6 +28,22 @@ afterEach(() => {});describe('Creator Runtime Developer ID signing', () => {+ it('signs the independent Remotion component using its prepared keychain and refreshes final hashes', async () => {+ const fixture = createStickmanFixture();+ const findIdentity = vi.fn(() => 'Developer ID Application: Junxi YIN (NVRH5R5DJ5)');+ const signBinary = vi.fn(path => writeFileSync(path, Buffer.concat([+ readFileSync(path), Buffer.from('-component-signature')+ ])));+ const withKeychain = vi.fn(async (env, action) => action({ ...env, APPLE_KEYCHAIN: '/tmp/component-test.keychain' }));+ await signRemotionComponent(fixture.runtimeRoot, {+ ...signingEnv(), OPENCREATOR_SIGN_CREATOR_RUNTIME: '1', CSC_LINK: 'test-p12', CSC_KEY_PASSWORD: 'test-password'+ }, { platform: 'darwin', withKeychain, findIdentity, findBinaries: () => fixture.binaryPaths, signBinary });+ expect(withKeychain).toHaveBeenCalledTimes(1);+ expect(findIdentity).toHaveBeenCalledWith('NVRH5R5DJ5', '/tmp/component-test.keychain');+ expect(signBinary).toHaveBeenCalledWith(fixture.binaryPaths[0], 'Developer ID Application: Junxi YIN (NVRH5R5DJ5)', '/tmp/component-test.keychain');+ expect(() => verifyStickmanRuntime(fixture.runtimeRoot, 'darwin', 'arm64')).not.toThrow();+ });+it('verifies the input, signs binaries and records their final hashes', async () => {const fixture = createFixture();const verifyRuntime = vi.fn(verifyCreatorRuntime);diff --git a/apps/desktop/test/mac-signing.test.mjs b/apps/desktop/test/mac-signing.test.mjsindex ab84c94b..68717e36 100644--- a/apps/desktop/test/mac-signing.test.mjs+++ b/apps/desktop/test/mac-signing.test.mjs@@ -1,10 +1,11 @@-import { readFileSync } from 'node:fs';+import { existsSync, readFileSync } from 'node:fs';import { describe, expect, it, vi } from 'vitest';import {configureMacDirectorySigning,configureMacReleaseSigning,findDeveloperIdIdentity,- resolveNotarizationCredentials+ resolveNotarizationCredentials,+ withMacSigningKeychain} from '../scripts/mac-signing.mjs';const identity =@@ -14,6 +15,105 @@ const identities = () => (+ ' 1 valid identities found\n');+describe('shared macOS signing keychain', () => {+ function fixture(overrides = {}) {+ const cleanup = vi.fn();+ const keychainTools = {+ TmpDir: class { cleanup = cleanup; },+ importCertificate: vi.fn(async () => '/tmp/test-certificate.p12'),+ rootCertKeychain: '/builder/root_certs.keychain',+ ...overrides+ };+ let searchList = ['/existing/login.keychain'];+ const runSecurity = vi.fn(async args => {+ if (args[0] === 'list-keychains') {+ if (args[3] === '-s') searchList = args.slice(4);+ return searchList.map(path => `"${path}"`).join('\n');+ }+ return '';+ });+ return { cleanup, keychainTools, runSecurity };+ }+ const credentials = { CSC_LINK: 'test-p12', CSC_KEY_PASSWORD: 'test-password' };++ it('imports before signing, uses the keychain password for ACLs and reuses the keychain in Electron Builder', async () => {+ const options = fixture();+ let keychain;+ expect(await withMacSigningKeychain(credentials, async env => {+ keychain = env.APPLE_KEYCHAIN;+ expect(env.CSC_KEYCHAIN).toBe(keychain);+ expect(env).not.toHaveProperty('CSC_LINK');+ expect(env).not.toHaveProperty('CSC_KEY_PASSWORD');+ const commands = options.runSecurity.mock.calls.map(([args]) => args);+ const keychainPassword = commands.find(args => args[0] === 'create-keychain')[2];+ expect(keychainPassword).not.toBe(credentials.CSC_KEY_PASSWORD);+ expect(commands).toContainEqual(['set-key-partition-list', '-S', 'apple-tool:,apple:', '-s', '-k', keychainPassword, keychain]);+ expect(commands).toContainEqual(['import', '/tmp/test-certificate.p12', '-k', keychain,+ '-T', '/usr/bin/codesign', '-T', '/usr/bin/productbuild', '-P', credentials.CSC_KEY_PASSWORD]);+ expect(commands.some(args => args[0] === 'delete-keychain')).toBe(false);+ // Preserve unrelated keychains added while the build is in progress.+ await options.runSecurity(['list-keychains', '-d', 'user', '-s', keychain,+ '/builder/root_certs.keychain', '/existing/login.keychain', '/another/build.keychain']);+ return 'signed';+ }, options)).toBe('signed');+ expect(credentials).not.toHaveProperty('APPLE_KEYCHAIN');+ expect(options.runSecurity).toHaveBeenCalledWith(['delete-keychain', keychain]);+ expect(options.runSecurity).toHaveBeenCalledWith(['list-keychains', '-d', 'user', '-s', '/existing/login.keychain', '/another/build.keychain']);+ expect(options.cleanup).toHaveBeenCalledTimes(1);+ expect(existsSync(options.keychainTools.importCertificate.mock.calls[0][2])).toBe(false);+ });++ it.each(['signing', 'import'])('cleans temporary credentials when %s fails', async failure => {+ const options = fixture();+ if (failure === 'import') {+ const original = options.runSecurity;+ options.runSecurity = vi.fn(async args => {+ if (args[0] === 'import') throw new Error('import failed');+ return original(args);+ });+ }+ const action = vi.fn(async () => { throw new Error('signing failed'); });+ await expect(withMacSigningKeychain(credentials, action, options)).rejects.toThrow(`${failure} failed`);+ if (failure === 'import') expect(action).not.toHaveBeenCalled();+ expect(options.runSecurity).toHaveBeenCalledWith(['delete-keychain', expect.stringMatching(/signing\.keychain$/)]);+ expect(options.cleanup).toHaveBeenCalledTimes(1);+ expect(existsSync(options.keychainTools.importCertificate.mock.calls[0][2])).toBe(false);+ });++ it('cleans certificate preparation failures without creating a keychain or exposing certificate contents', async () => {+ const options = fixture({ importCertificate: vi.fn(async () => { throw new Error('secret base64 contents'); }) });+ await expect(withMacSigningKeychain(credentials, vi.fn(), options)).rejects.toThrow('Unable to prepare the macOS signing certificate');+ expect(options.runSecurity).not.toHaveBeenCalled();+ expect(options.cleanup).toHaveBeenCalledTimes(1);+ expect(existsSync(options.keychainTools.importCertificate.mock.calls[0][2])).toBe(false);+ });++ it('preserves ordinary local signing without creating a keychain', async () => {+ const options = fixture();+ const env = {};+ const action = vi.fn();+ await withMacSigningKeychain(env, action, options);+ expect(action).toHaveBeenCalledWith(env);+ expect(options.keychainTools.importCertificate).not.toHaveBeenCalled();+ expect(options.runSecurity).not.toHaveBeenCalled();+ });++ it.each(['APPLE_KEYCHAIN', 'CSC_KEYCHAIN'])('reuses an existing %s without deleting user credentials', async name => {+ const options = fixture();+ const action = vi.fn();+ await withMacSigningKeychain({ ...credentials, [name]: '/existing/release.keychain' }, action, options);+ expect(action).toHaveBeenCalledWith({ APPLE_KEYCHAIN: '/existing/release.keychain', CSC_KEYCHAIN: '/existing/release.keychain' });+ expect(options.keychainTools.importCertificate).not.toHaveBeenCalled();+ expect(options.runSecurity).not.toHaveBeenCalled();+ });++ it('rejects incomplete CI credentials before creating a keychain', async () => {+ const options = fixture();+ await expect(withMacSigningKeychain({ CSC_LINK: 'test-p12' }, vi.fn(), options)).rejects.toThrow('CSC_KEY_PASSWORD');+ expect(options.keychainTools.importCertificate).not.toHaveBeenCalled();+ });+});+describe('macOS directory signing', () => {it('keeps ordinary local packages ad-hoc without accessing a private key', () => {const result = configureMacDirectorySigning({