The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): parallelize payload signing and split the timestamp pass
ethernetdeb620c65275
diff --git a/apps/desktop/scripts/after-pack.mjs b/apps/desktop/scripts/after-pack.mjsindex 5b1c7150d81..bd54043363d 100644--- a/apps/desktop/scripts/after-pack.mjs+++ b/apps/desktop/scripts/after-pack.mjs@@ -93,5 +93,5 @@ export default async function afterPack(context) {// per-file by the customSign hook (scripts/batch-sign-binaries.mjs) after// electron-builder's own rcedit + fuses pass. No-op with a loud warning when// the AZURE_SIGN_* environment is absent (unsigned/fork/nightly lanes).- batchSignAppTree(context.appOutDir, exe)+ await batchSignAppTree(context.appOutDir, exe)}diff --git a/apps/desktop/scripts/batch-sign-binaries.mjs b/apps/desktop/scripts/batch-sign-binaries.mjsindex fd644836fa2..0cd8317c3b9 100644--- a/apps/desktop/scripts/batch-sign-binaries.mjs+++ b/apps/desktop/scripts/batch-sign-binaries.mjs@@ -38,12 +38,84 @@// electron-builder cache walk from scripts/stage-msixbundle.mjs; nothing is// hardcoded to C:\Tools.-import { execFileSync } from 'node:child_process'+import { execFile } from 'node:child_process'import fs from 'node:fs'import path from 'node:path'import { isMain } from './utils.mjs'export const CHUNK_SIZE = 100+// How many signtool children may run at once. Azure Trusted Signing and the+// timestamp server are both network round-trips per file, so N concurrent+// children multiply throughput ~Nx. Keep it modest — the timestamp server+// rate-limits aggressive bursters.+export const DEFAULT_CONCURRENCY = 4+// Separate timestamp pass URL. `timestamp.acs.microsoft.com` intermittently+// fails with "Invalid Time Stamp Request Length:-1" (documented widely);+// digicert's RFC3161 endpoint has been reliable in the release pipeline.+const TIMESTAMP_URL = 'http://timestamp.digicert.com'++/**+ * execFile as a promise, so chunks can run concurrently.+ * @returns {Promise<void>} rejects with the child's error on non-zero exit.+ */+function execFileAsync(cmd, args, options) {+ return new Promise((resolve, reject) => {+ execFile(cmd, args, options, (error) => {+ if (error) reject(error)+ else resolve()+ })+ })+}++/**+ * Retry a fallible op (bounded). Used for the timestamp pass, where the+ * external server flakes intermittently — a retried timestamp beats a whole+ * rebuild. Exponential backoff (1s, 2s, ...) between attempts.+ *+ * @param {() => Promise<void>} fn+ * @param {{ attempts?: number, baseDelayMs?: number }} [opts]+ */+export async function withRetry(fn, opts = {}) {+ const attempts = opts.attempts ?? 3+ const baseDelayMs = opts.baseDelayMs ?? 1000+ let lastError+ for (let attempt = 1; attempt <= attempts; attempt += 1) {+ try {+ return await fn()+ } catch (error) {+ lastError = error+ if (attempt < attempts) {+ await new Promise((resolve) => setTimeout(resolve, baseDelayMs * attempt))+ }+ }+ }+ throw lastError+}++/**+ * Run up to `concurrency` async workers over items. Each worker pulls the+ * next item as it frees up, so unevenly-sized work balances itself.+ *+ * @param {T[]} items+ * @param {number} concurrency+ * @param {(item: T, index: number) => Promise<void>} worker+ * @template T+ */+export async function runPool(items, concurrency, worker) {+ let index = 0+ const next = async () => {+ while (index < items.length) {+ const i = index+ index += 1+ await worker(items[i], i)+ }+ }+ const workers = Array.from(+ { length: Math.min(Math.max(1, concurrency), items.length) },+ () => next()+ )+ await Promise.all(workers)+}/*** Recursively collect every .exe/.dll under dir. Symbolic links are skipped@@ -247,35 +319,73 @@ export function resolveDotnetRuntimeDir(env = process.env) {/*** Sign one chunk of binaries with a single signtool invocation (argv array,* never a shell string — the joined list can be long and must not interpolate- * through a shell).+ * through a shell). Azure-only: NO timestamp here (see timestampChunk — the+ * sign pass would otherwise hold each file hostage to the flaky timestamp+ * server, and a timestamp failure would force a full re-sign).** @param {string[]} files- * @param {{ signtool: string, dlib: string, metadataPath: string, exec?: typeof execFileSync, env?: NodeJS.ProcessEnv }} opts+ * @param {{ signtool: string, dlib: string, metadataPath: string, exec?: typeof execFile, execOptions?: import('node:child_process').ExecFileOptions }} opts*/-export function signChunk(files, opts) {- const exec = opts.exec ?? execFileSync- const execOptions = { stdio: 'inherit' }- if (opts.env) execOptions.env = opts.env- exec(opts.signtool, [+export async function signChunk(files, opts) {+ const args = ['sign','/fd', 'SHA256',- '/td', 'SHA256',- '/tr', 'http://timestamp.digicert.com','/dlib', opts.dlib,'/dmdf', opts.metadataPath,...files- ], execOptions)+ ]+ if (opts.exec) {+ await opts.exec(opts.signtool, args, opts.execOptions)+ return+ }+ await execFileAsync(opts.signtool, args, opts.execOptions ?? { stdio: 'inherit' })+}++/**+ * RFC3161-timestamp one chunk of ALREADY-SIGNED files. No /dlib, no /dmdf —+ * this is pure timestamping, so it neither re-auths against Azure nor+ * re-initializes the .NET dlib. The timestamp server is the flaky external+ * dependency, so this pass retries per chunk (a retried timestamp beats a+ * whole re-sign) and runs concurrently like the sign pass.+ *+ * @param {string[]} files+ * @param {{ signtool: string, timestampUrl?: string, exec?: typeof execFile, execOptions?: import('node:child_process').ExecFileOptions, timestampAttempts?: number, timestampRetryDelayMs?: number }} opts+ */+export async function timestampChunk(files, opts) {+ const args = [+ 'timestamp',+ '/tr', opts.timestampUrl ?? TIMESTAMP_URL,+ '/td', 'SHA256',+ ...files+ ]+ const run = async () => {+ if (opts.exec) {+ await opts.exec(opts.signtool, args, opts.execOptions)+ return+ }+ await execFileAsync(opts.signtool, args, opts.execOptions ?? { stdio: 'inherit' })+ }+ await withRetry(run, {+ attempts: opts.timestampAttempts,+ baseDelayMs: opts.timestampRetryDelayMs+ })}/*** Batch-sign every binary under a tree.*+ * Two passes: (1) Azure Authenticode sign — concurrent signtool children,+ * no timestamp; (2) RFC3161 timestamp — concurrent, no Azure/dlib, retried+ * per chunk. Parallelism is the whole speed story: both Azure and the+ * timestamp server are per-file network round-trips, so N concurrent children+ * multiply throughput ~Nx.+ ** @param {string[]} binaries file list from getBinaries- * @param {{ env?: NodeJS.ProcessEnv, exec?: typeof execFileSync, chunkSize?: number, mkdtemp?: typeof fs.mkdtempSync, signtool?: string, dlib?: string }} [opts]- * @returns {{ signed: number, chunks: number, skipped: boolean }}+ * @param {{ env?: NodeJS.ProcessEnv, exec?: typeof execFile, chunkSize?: number, concurrency?: number, mkdtemp?: typeof fs.mkdtempSync, signtool?: string, dlib?: string, timestampUrl?: string, timestampAttempts?: number, timestampRetryDelayMs?: number }} [opts]+ * @returns {Promise<{ signed: number, chunks: number, skipped: boolean }>}* skipped=true when Azure signing is not configured (caller warns).*/-export function batchSignBinaries(binaries, opts = {}) {+export async function batchSignBinaries(binaries, opts = {}) {const env = opts.env ?? process.envif (!azureSigningConfigured(env)) {return { signed: 0, chunks: 0, skipped: true }@@ -306,11 +416,25 @@ export function batchSignBinaries(binaries, opts = {}) {CodeSigningAccountName: env.AZURE_SIGN_ACCOUNT,CertificateProfileName: env.AZURE_SIGN_PROFILE}))+ const concurrency = opts.concurrency ?? DEFAULT_CONCURRENCY+ const batches = chunk(binaries, opts.chunkSize ?? CHUNK_SIZE)+ const execOptions = { stdio: 'inherit', env: signEnv }try {- const batches = chunk(binaries, opts.chunkSize ?? CHUNK_SIZE)- for (const batch of batches) {- signChunk(batch, { signtool, dlib, metadataPath, exec: opts.exec, env: signEnv })- }+ // Pass 1: Azure Authenticode sign — concurrent, no timestamp.+ await runPool(batches, concurrency, (batch) =>+ signChunk(batch, { signtool, dlib, metadataPath, exec: opts.exec, execOptions })+ )+ // Pass 2: RFC3161 timestamp — concurrent, no Azure/dlib, retried.+ await runPool(batches, concurrency, (batch) =>+ timestampChunk(batch, {+ signtool,+ timestampUrl: opts.timestampUrl,+ exec: opts.exec,+ execOptions,+ timestampAttempts: opts.timestampAttempts,+ timestampRetryDelayMs: opts.timestampRetryDelayMs+ })+ )return { signed: binaries.length, chunks: batches.length, skipped: false }} finally {fs.rmSync(tmpDir, { recursive: true, force: true })@@ -324,9 +448,9 @@ export function batchSignBinaries(binaries, opts = {}) {** @param {string} appOutDir* @param {string} productExePath absolute path of the main product exe- * @param {{ env?: NodeJS.ProcessEnv, exec?: typeof execFileSync }} [opts]+ * @param {{ env?: NodeJS.ProcessEnv, exec?: typeof execFile, chunkSize?: number, concurrency?: number, timestampUrl?: string, timestampAttempts?: number, timestampRetryDelayMs?: number }} [opts]*/-export function batchSignAppTree(appOutDir, productExePath, opts = {}) {+export async function batchSignAppTree(appOutDir, productExePath, opts = {}) {const env = opts.env ?? process.envif (!azureSigningConfigured(env)) {console.warn(@@ -340,7 +464,7 @@ export function batchSignAppTree(appOutDir, productExePath, opts = {}) {skip: (file) => (productExe ? path.resolve(file) === productExe : false)})if (binaries.length === 0) return { signed: 0, chunks: 0, skipped: false }- const result = batchSignBinaries(binaries, opts)+ const result = await batchSignBinaries(binaries, opts)console.log(`[batch-sign] signed ${result.signed} payload binaries in ${result.chunks} signtool batch(es)` +` (product exe excluded — signed per-file after rcedit)`@@ -393,13 +517,13 @@ export async function customSign(configuration, packager, deps = {}) {return true}-function main() {+async function main() {const root = process.argv[2]if (!root) {console.error('usage: batch-sign-binaries.mjs <dir>')process.exit(2)}- const result = batchSignAppTree(root, process.env.HERMES_PRODUCT_EXE || path.join(root, 'Hermes.exe'))+ const result = await batchSignAppTree(root, process.env.HERMES_PRODUCT_EXE || path.join(root, 'Hermes.exe'))if (result.skipped) process.exit(0)}diff --git a/apps/desktop/scripts/batch-sign-binaries.test.mjs b/apps/desktop/scripts/batch-sign-binaries.test.mjsindex bdbad622f83..8cf539fbe2f 100644--- a/apps/desktop/scripts/batch-sign-binaries.test.mjs+++ b/apps/desktop/scripts/batch-sign-binaries.test.mjs@@ -165,7 +165,7 @@ test('customSign does not mistake a similarly-named payload exe for the product)})-test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and signs via chunked argv-array invocations when set', () => {+test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and signs via chunked argv-array invocations when set', async () => {const root = tmpTree()fs.mkdirSync(path.join(root, 'tools'), { recursive: true })const exe = path.join(root, 'Hermes.exe')@@ -174,16 +174,17 @@ test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and signfs.writeFileSync(path.join(root, 'tools', 'ffmpeg.dll'), 'x')// Unsigned lane: loud no-op, nothing invoked.- const skipped = batchSignAppTree(root, exe, { env: {} })+ const skipped = await batchSignAppTree(root, exe, { env: {} })assert.deepEqual(skipped, { signed: 0, chunks: 0, skipped: true })- // Signed lane: product exe excluded, chunked execFileSync with argv arrays.+ // Signed lane: product exe excluded, chunked argv arrays. Two passes per+ // chunk: 'sign' (Azure, no timestamp) then 'timestamp' (RFC3161, no dlib).const invocations = []const fakeExec = (tool, args) => {invocations.push({ tool, args })return Buffer.from('')}- const result = batchSignAppTree(root, exe, {+ const result = await batchSignAppTree(root, exe, {env: {AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net',AZURE_SIGN_ACCOUNT: 'codesign2',@@ -196,10 +197,13 @@ test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and sign})assert.deepEqual(result, { signed: 2, chunks: 1, skipped: false })- assert.equal(invocations.length, 1)- assert.equal(invocations[0].tool, 'signtool.exe')- assert.ok(Array.isArray(invocations[0].args), 'argv array, never a shell string')- const args = invocations[0].args+ assert.equal(invocations.length, 2, 'one sign + one timestamp pass for a single chunk')+ const [signInv, tsInv] = invocations+ assert.equal(signInv.tool, 'signtool.exe')+ assert.ok(Array.isArray(signInv.args), 'argv array, never a shell string')+ assert.equal(signInv.args[0], 'sign')+ assert.equal(tsInv.args[0], 'timestamp')+ const args = signInv.argsassert.ok(!args.some(arg => typeof arg === 'string' && arg.includes(' ')))assert.equal(args.includes(exe), false, 'product exe excluded — signed per-file after rcedit')assert.equal(args.includes(path.join(root, 'tools', 'node.exe')), true)@@ -207,10 +211,20 @@ test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and signassert.equal(args[args.indexOf('/dlib') + 1], 'azure.codesigning.dlib.dll')assert.ok(args[args.indexOf('/dmdf') + 1].endsWith('batch-sign.json'))assert.equal(args[args.indexOf('/fd') + 1], 'SHA256')- assert.equal(args[args.indexOf('/td') + 1], 'SHA256')+ // Sign pass carries NO timestamp flags — timestamping is the separate pass.+ assert.equal(args.includes('/tr'), false)+ assert.equal(args.includes('/td'), false)+ // Timestamp pass carries /tr + /td but NO dlib / dmdf.+ const tsArgs = tsInv.args+ assert.equal(tsArgs[tsArgs.indexOf('/tr') + 1], 'http://timestamp.digicert.com')+ assert.equal(tsArgs[tsArgs.indexOf('/td') + 1], 'SHA256')+ assert.equal(tsArgs.includes('/dlib'), false)+ assert.equal(tsArgs.includes('/dmdf'), false)+ assert.ok(tsArgs.includes(path.join(root, 'tools', 'node.exe')), 'timestamp pass covers the same files')+ assert.ok(tsArgs.includes(path.join(root, 'tools', 'ffmpeg.dll')))})-test('batchSignAppTree chunks large trees into ~100-file signtool invocations', () => {+test('batchSignAppTree chunks large trees into ~100-file signtool invocations, sign + timestamp passes', async () => {const root = tmpTree()fs.mkdirSync(path.join(root, 'tools'), { recursive: true })for (let i = 0; i < 250; i += 1) {@@ -218,7 +232,7 @@ test('batchSignAppTree chunks large trees into ~100-file signtool invocations',}const invocations = []- const result = batchSignAppTree(root, path.join(root, 'Hermes.exe'), {+ const result = await batchSignAppTree(root, path.join(root, 'Hermes.exe'), {env: {AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net',AZURE_SIGN_ACCOUNT: 'codesign2',@@ -234,13 +248,85 @@ test('batchSignAppTree chunks large trees into ~100-file signtool invocations',})assert.deepEqual(result, { signed: 250, chunks: 3, skipped: false })- assert.equal(invocations.length, 3)+ // 3 chunks × 2 passes (sign + timestamp).+ assert.equal(invocations.length, 6)+ const signBatches = invocations.filter(a => a[0] === 'sign')+ const tsBatches = invocations.filter(a => a[0] === 'timestamp')+ assert.equal(signBatches.length, 3)+ assert.equal(tsBatches.length, 3)assert.deepEqual(- invocations.map(batch => batch.filter(arg => arg.endsWith('.exe')).length),- [100, 100, 50]+ signBatches.map(batch => batch.filter(arg => arg.endsWith('.exe')).length).sort((a, b) => a - b),+ [50, 100, 100])- const flat = invocations.flat().filter(arg => arg.endsWith('.exe'))+ const flat = signBatches.flat().filter(arg => arg.endsWith('.exe'))assert.equal(new Set(flat).size, 250, 'every binary signed exactly once')+ const tsFlat = tsBatches.flat().filter(arg => arg.endsWith('.exe'))+ assert.equal(new Set(tsFlat).size, 250, 'every binary timestamped exactly once')+ assert.deepEqual(new Set(tsFlat), new Set(flat), 'timestamp pass covers the same files as the sign pass')+})++test('sign chunks run concurrently, capped at the configured concurrency', async () => {+ const root = tmpTree()+ fs.mkdirSync(path.join(root, 'tools'), { recursive: true })+ for (let i = 0; i < 12; i += 1) {+ fs.writeFileSync(path.join(root, 'tools', `bin${i}.exe`), 'x')+ }++ // 12 files at chunk size 1 → 12 chunks, each a sign + timestamp pass. The+ // fake holds its "child" open across an await so the pool's concurrency is+ // actually observable (a sync fake would report max 1 by construction).+ let inFlight = 0+ let maxInFlight = 0+ const fakeExec = async () => {+ inFlight += 1+ maxInFlight = Math.max(maxInFlight, inFlight)+ await new Promise(resolve => setTimeout(resolve, 5))+ inFlight -= 1+ }++ await batchSignAppTree(root, path.join(root, 'Hermes.exe'), {+ env: {+ AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net',+ AZURE_SIGN_ACCOUNT: 'codesign2',+ AZURE_SIGN_PROFILE: 'hermesagent'+ },+ exec: fakeExec,+ mkdtemp: () => root,+ signtool: 'signtool.exe',+ dlib: 'azure.codesigning.dlib.dll',+ chunkSize: 1,+ concurrency: 3+ })++ assert.equal(maxInFlight, 3, 'never more than the configured concurrency in flight')+})++test('timestamp pass retries a flaky server before giving up', async () => {+ const root = tmpTree()+ fs.mkdirSync(path.join(root, 'tools'), { recursive: true })+ fs.writeFileSync(path.join(root, 'tools', 'node.exe'), 'x')++ let calls = 0+ const fakeExec = (tool, args) => {+ if (args[0] === 'sign') return+ calls += 1+ if (calls < 3) throw new Error('Invalid Time Stamp Request Length:-1')+ }++ await batchSignAppTree(root, path.join(root, 'Hermes.exe'), {+ env: {+ AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net',+ AZURE_SIGN_ACCOUNT: 'codesign2',+ AZURE_SIGN_PROFILE: 'hermesagent'+ },+ exec: fakeExec,+ mkdtemp: () => root,+ signtool: 'signtool.exe',+ dlib: 'azure.codesigning.dlib.dll',+ timestampRetryDelayMs: 0+ })++ assert.equal(calls, 3, 'timestamp pass retried until the server succeeded')})// ── toolset resolution: signtool + dlib must be same-arch ───────────────────@@ -301,7 +387,7 @@ test('resolveDotnetRuntimeDir finds the bundled .NET runtime dir', () => {assert.ok(/dotnet-runtime-/.test(path.basename(dotnet)), `unexpected dotnet dir ${dotnet}`)})-test('batchSignBinaries sets DOTNET_ROOT from the bundled runtime for the signtool child', () => {+test('batchSignBinaries sets DOTNET_ROOT from the bundled runtime for the signtool child', async () => {const { cache } = fakeToolsetCache()const root = tmpTree()fs.mkdirSync(path.join(root, 'tools'), { recursive: true })@@ -309,7 +395,7 @@ test('batchSignBinaries sets DOTNET_ROOT from the bundled runtime for the signtoconst exe = path.join(root, 'Hermes.exe')const invocations = []- const result = batchSignAppTree(root, exe, {+ const result = await batchSignAppTree(root, exe, {env: {ELECTRON_BUILDER_CACHE: cache,AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net',@@ -324,13 +410,18 @@ test('batchSignBinaries sets DOTNET_ROOT from the bundled runtime for the signto})assert.equal(result.signed, 1)- assert.equal(invocations.length, 1)- const opts = invocations[0].opts+ assert.equal(invocations.length, 2, 'one sign + one timestamp pass')+ const signInv = invocations.find(inv => inv.args[0] === 'sign')+ const tsInv = invocations.find(inv => inv.args[0] === 'timestamp')+ assert.ok(signInv, 'sign pass present')+ assert.ok(tsInv, 'timestamp pass present')+ const opts = signInv.optsassert.ok(opts && opts.env, 'exec must receive a child env')assert.equal(opts.env.DOTNET_ROOT, path.join(cache, '[email protected]', 'dotnet-runtime-win-x64-8_0_28-ghi'))// The signtool chosen must be the host-arch one, not x86.- assert.match(invocations[0].tool, new RegExp(`[\\\\/]${signingArch()}[\\\\/]signtool\\.exe$`))- // dlib must be same arch.- const dlibArg = invocations[0].args[invocations[0].args.indexOf('/dlib') + 1]+ assert.match(signInv.tool, new RegExp(`[\\\\/]${signingArch()}[\\\\/]signtool\\.exe$`))+ assert.match(tsInv.tool, new RegExp(`[\\\\/]${signingArch()}[\\\\/]signtool\\.exe$`))+ const dlibArg = signInv.args[signInv.args.indexOf('/dlib') + 1]assert.match(dlibArg, new RegExp(`[\\\\/]${signingArch()}[\\\\/]azure\\.codesigning\\.dlib\\.dll$`, 'i'))+ assert.equal(tsInv.args.includes('/dlib'), false, 'timestamp pass has no dlib')})