| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| import { | |
| access, | |
| mkdir, | |
| mkdtemp, | |
| readFile, | |
| readdir, | |
| realpath, | |
| rm, | |
| writeFile, | |
| } from 'node:fs/promises'; | |
| import { tmpdir } from 'node:os'; | |
| import { basename, dirname, join, resolve } from 'node:path'; | |
| import { fileURLToPath, pathToFileURL } from 'node:url'; | |
| import { crc32, inflateSync } from 'node:zlib'; | |
| import { FILESYSTEM_WORKER_PROTOCOL_VERSION } from '../packages/runtime/dist/filesystem-worker/protocol.js'; | |
| import { readProductManifestIdentity } from './product-release-identity.mjs'; | |
| import { assertPackagedUpdateConfiguration } from './desktop-update-contract.mjs'; | |
| import { stapleMacosArtifact } from './staple-macos-artifact.mjs'; | |
| import { | |
| resolveDesktopBuildVersion, | |
| resolveDesktopReleaseTarget, | |
| resolveRuntimeHostSetupPackage, | |
| } from './desktop-nightly.mjs'; | |
| import { | |
| assertMissing, | |
| assertPackagedDependencyClosure, | |
| assertPackagedResources, | |
| isolatedUserEnv, | |
| makePtyProbe, | |
| runCommand, | |
| sha256File, | |
| smokePackagedRenderer, | |
| } from './verify-packaged-app.mjs'; | |
| const repoRoot = dirname(dirname(fileURLToPath(import.meta.url))); | |
| const expectedAppId = 'com.maka.desktop'; | |
| function runCommandFromRepo(command, args, options = {}) { | |
| return runCommand(command, args, { cwd: repoRoot, ...options }); | |
| } | |
| // macOS-only: the worker exists to enforce a sandbox profile, and Windows has no | |
| // implementation of one, so the app there runs file tools in-process instead. | |
| export async function smokePackagedFilesystemWorker( | |
| executable, | |
| worker, | |
| { workingDirectory, run = runCommand } = {}, | |
| ) { | |
| const workspace = await realpath(workingDirectory); | |
| const target = join(workspace, 'filesystem-worker-smoke.txt'); | |
| const content = 'maka-filesystem-worker-ok'; | |
| const operationBoundary = { | |
| filesystem: { | |
| entries: [{ path: target, access: 'write', scope: 'exact' }], | |
| }, | |
| }; | |
| const request = { | |
| version: FILESYSTEM_WORKER_PROTOCOL_VERSION, | |
| requestId: 'release-filesystem-worker-smoke', | |
| operation: { kind: 'write', cwd: workspace, path: target, content }, | |
| operationBoundary, | |
| expectedTarget: { | |
| enforcementPath: target, | |
| access: 'write', | |
| scope: 'exact', | |
| targetType: 'missing', | |
| // Protocol v7 requires the three-state identity; a write to a target | |
| // approved as missing carries 'missing' (#3484 / #3487). | |
| identity: 'missing', | |
| }, | |
| }; | |
| await rm(target, { force: true }); | |
| try { | |
| const result = await run(executable, [worker], { | |
| cwd: workspace, | |
| env: { | |
| ELECTRON_RUN_AS_NODE: '1', | |
| ...isolatedUserEnv(join(workspace, 'worker-home'), { temporaryDirectory: workspace }), | |
| }, | |
| input: `${JSON.stringify(request)}\n`, | |
| }); | |
| const response = JSON.parse(result.stdout); | |
| if ( | |
| response?.ok !== true || | |
| response.result?.kind !== 'write' || | |
| (await readFile(target, 'utf8')) !== content | |
| ) { | |
| throw new Error(`Packaged filesystem worker smoke failed: ${result.stdout.trim()}`); | |
| } | |
| } finally { | |
| await rm(target, { force: true }); | |
| } | |
| } | |
| function assertSingleArchitecture(output, subject, expectedArch) { | |
| const architectures = output.trim().split(/\s+/).filter(Boolean); | |
| // lipo names Intel Mach-O slices x86_64; Node and the release target use x64. | |
| const machoArch = expectedArch === 'x64' ? 'x86_64' : expectedArch; | |
| if (architectures.length !== 1 || architectures[0] !== machoArch) { | |
| throw new Error( | |
| `${subject} must contain only ${expectedArch}, found: ${architectures.join(', ')}`, | |
| ); | |
| } | |
| } | |
| /** | |
| * macOS draws the 16px and 32px faces of an ICNS from the ARGB slots `ic04` | |
| * and `ic05`. PNG data packed into the legacy `icp4`/`icp5`/`icp6` slots is | |
| * not decoded, so it renders as noise — which is what a Finder list row, the | |
| * Dock's Trash, Activity Monitor and the DMG's own volume icon show. Every | |
| * larger size keeps working, so nothing else in this verifier notices. | |
| * | |
| * electron-builder shipped that exact shape from 26.15.2 through 26.15.3 | |
| * (electron-userland/electron-builder#9940). The icon is generated by a | |
| * toolset the builder downloads at build time, so the bundle is the only | |
| * place the result can be seen: assert on it here rather than on a version | |
| * pin that says nothing about what was produced. | |
| */ | |
| const UNRENDERABLE_ICNS_SLOTS = new Map([ | |
| ['icp4', '16x16'], | |
| ['icp5', '32x32'], | |
| ['icp6', '64x64'], | |
| ]); | |
| // Side length of each slot's art. `iconutil` and the builder's toolset both | |
| // write `ic04`/`ic05` as ARGB planes and every larger size as PNG. The toolset | |
| // 26.15.3 pinned also put 512px and 1024px art in `ic13`/`ic14`. | |
| const ARGB_ICNS_SLOTS = new Map([ | |
| ['ic04', 16], | |
| ['ic05', 32], | |
| ]); | |
| const PNG_ICNS_SLOTS = new Map([ | |
| ['ic07', 128], | |
| ['ic08', 256], | |
| ['ic09', 512], | |
| ['ic10', 1024], | |
| ['ic11', 32], | |
| ['ic12', 64], | |
| ['ic13', 256], | |
| ['ic14', 512], | |
| ]); | |
| const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); | |
| function readIcnsSlots(icns) { | |
| if (icns.length < 8 || icns.subarray(0, 4).toString('latin1') !== 'icns') { | |
| throw new Error('Maka icon is not an ICNS archive.'); | |
| } | |
| // A header that disagrees with the file is a truncated or padded archive, | |
| // and its entries cannot be trusted to end where they claim. | |
| const declared = icns.readUInt32BE(4); | |
| if (declared !== icns.length) { | |
| throw new Error(`Maka icon declares ${declared} bytes but holds ${icns.length}.`); | |
| } | |
| const slots = new Map(); | |
| // Every entry declares its own length including the 8-byte header, so a zero | |
| // or truncated length is the difference between a parse error and a loop. | |
| // The entries must account for every byte after the header. | |
| for (let offset = 8; offset < icns.length; ) { | |
| if (offset + 8 > icns.length) { | |
| throw new Error(`Maka icon ends inside an entry header at byte ${offset}.`); | |
| } | |
| const type = icns.subarray(offset, offset + 4).toString('latin1'); | |
| const length = icns.readUInt32BE(offset + 4); | |
| if (length < 8 || offset + length > icns.length) { | |
| throw new Error(`Maka icon entry ${type} declares an unusable length of ${length}.`); | |
| } | |
| slots.set(type, icns.subarray(offset + 8, offset + length)); | |
| offset += length; | |
| } | |
| return slots; | |
| } | |
| /** | |
| * An `ic04`/`ic05` payload is `ARGB` followed by the alpha, red, green and | |
| * blue planes, packed the ICNS way: a control byte below 0x80 copies the next | |
| * `control + 1` bytes, and one from 0x80 up repeats the next byte | |
| * `control - 0x80 + 3` times. macOS unpacks each plane on its own and cuts a | |
| * token off at the plane's end, so a token that runs past its plane shifts | |
| * every plane after it: it can draw the art only if each plane ends exactly | |
| * on a token boundary and four `side` × `side` planes leave no bytes over. | |
| */ | |
| function isDecodableArgb(payload, side) { | |
| if (payload.subarray(0, 4).toString('latin1') !== 'ARGB') return false; | |
| const plane = side * side; | |
| let produced = 0; | |
| for (let offset = 4; offset < payload.length; ) { | |
| const control = payload[offset]; | |
| const literal = control < 0x80; | |
| const count = literal ? control + 1 : control - 0x80 + 3; | |
| const consumed = 1 + (literal ? count : 1); | |
| if (offset + consumed > payload.length) return false; | |
| if (Math.floor(produced / plane) !== Math.floor((produced + count - 1) / plane)) return false; | |
| produced += count; | |
| offset += consumed; | |
| } | |
| return produced === 4 * plane; | |
| } | |
| // Channels per pixel for each PNG color type. | |
| const PNG_CHANNELS = new Map([ | |
| [0, 1], | |
| [2, 3], | |
| [3, 1], | |
| [4, 2], | |
| [6, 4], | |
| ]); | |
| /** | |
| * The size of a PNG slot's art, or undefined unless it decodes: every chunk's | |
| * CRC holds from IHDR through IEND with nothing after it, and the IDAT stream | |
| * inflates to exactly one filter byte (0-4) and one scanline per row of the | |
| * size IHDR declares. | |
| */ | |
| function decodedPngSize(payload) { | |
| let header; | |
| const data = []; | |
| let offset = PNG_SIGNATURE.length; | |
| for (let ended = false; !ended; ) { | |
| if (offset + 12 > payload.length) return undefined; | |
| const length = payload.readUInt32BE(offset); | |
| if (offset + 12 + length > payload.length) return undefined; | |
| const chunk = payload.subarray(offset + 4, offset + 8 + length); | |
| if (crc32(chunk) !== payload.readUInt32BE(offset + 8 + length)) return undefined; | |
| const type = chunk.subarray(0, 4).toString('latin1'); | |
| if (header === undefined && type !== 'IHDR') return undefined; | |
| if (type === 'IHDR') header = chunk.subarray(4); | |
| if (type === 'IDAT') data.push(chunk.subarray(4)); | |
| ended = type === 'IEND'; | |
| offset += 12 + length; | |
| } | |
| if (offset !== payload.length || header.length !== 13) return undefined; | |
| const width = header.readUInt32BE(0); | |
| const height = header.readUInt32BE(4); | |
| const stride = 1 + Math.ceil((width * PNG_CHANNELS.get(header[9]) * header[8]) / 8); | |
| let pixels; | |
| try { | |
| pixels = inflateSync(Buffer.concat(data)); | |
| } catch { | |
| return undefined; | |
| } | |
| if (pixels.length !== height * stride) return undefined; | |
| for (let row = 0; row < pixels.length; row += stride) { | |
| if (pixels[row] > 4) return undefined; | |
| } | |
| return { width, height }; | |
| } | |
| export async function assertRenderableAppIcon(resourcesPath, { readIcon = readFile } = {}) { | |
| const slots = readIcnsSlots(await readIcon(join(resourcesPath, 'icon.icns'))); | |
| const isPng = (payload) => payload?.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE); | |
| const unrenderable = [...UNRENDERABLE_ICNS_SLOTS] | |
| .filter(([type]) => isPng(slots.get(type))) | |
| .map(([type, size]) => `${size} (${type})`); | |
| if (unrenderable.length > 0) { | |
| throw new Error( | |
| `Maka icon stores PNG data in ICNS slots macOS does not render: ${unrenderable.join(', ')}.`, | |
| ); | |
| } | |
| const missing = [...ARGB_ICNS_SLOTS] | |
| .filter(([type]) => !slots.has(type)) | |
| .map(([type, side]) => `${side}x${side} (${type})`); | |
| if (missing.length > 0) { | |
| throw new Error(`Maka icon is missing the sizes macOS draws smallest: ${missing.join(', ')}.`); | |
| } | |
| // Presence alone would accept an empty or truncated payload in exactly the | |
| // sizes this check exists to protect. | |
| const undecodable = [...ARGB_ICNS_SLOTS] | |
| .filter(([type, side]) => !isDecodableArgb(slots.get(type), side)) | |
| .map(([type, side]) => `${side}x${side} (${type})`); | |
| if (undecodable.length > 0) { | |
| throw new Error(`Maka icon has small sizes macOS cannot decode: ${undecodable.join(', ')}.`); | |
| } | |
| const misdrawn = [...PNG_ICNS_SLOTS] | |
| .filter(([type]) => isPng(slots.get(type))) | |
| .flatMap(([type, side]) => { | |
| const size = decodedPngSize(slots.get(type)); | |
| if (!size) return [`${type} does not decode`]; | |
| if (size.width === side && size.height === side) return []; | |
| return [`${type} holds ${size.width}x${size.height} where macOS expects ${side}x${side}`]; | |
| }); | |
| if (misdrawn.length > 0) { | |
| throw new Error(`Maka icon has PNG art macOS cannot draw: ${misdrawn.join('; ')}.`); | |
| } | |
| } | |
| async function readPlistValue(run, infoPlist, key) { | |
| const { stdout } = await run('plutil', ['-extract', key, 'raw', '-o', '-', infoPlist]); | |
| return stdout.trim(); | |
| } | |
| export async function verifyPackagedMacApp( | |
| appPath, | |
| { | |
| run = runCommandFromRepo, | |
| requirePath = access, | |
| forbidPath = assertMissing, | |
| smokeRenderer = smokePackagedRenderer, | |
| smokeFilesystemWorker = smokePackagedFilesystemWorker, | |
| workingDirectory = dirname(appPath), | |
| environment = process.env, | |
| // The architecture the DMG was chosen for, not the one this process happens | |
| // to run as: `process.arch` under Rosetta, or on a runner packaging the | |
| // other slice, would assert the wrong thing about the binary it opened. | |
| expectedArch = process.arch, | |
| // Which channel the packaged client points at is the descriptor's to decide, | |
| // so the caller that resolved the target passes it. Nothing but the release | |
| // verifier can see a nightly descriptor. | |
| channel = 'release', | |
| } = {}, | |
| ) { | |
| const product = await readProductManifestIdentity(); | |
| const contents = join(appPath, 'Contents'); | |
| const resources = join(contents, 'Resources'); | |
| const infoPlist = join(contents, 'Info.plist'); | |
| const appId = await readPlistValue(run, infoPlist, 'CFBundleIdentifier'); | |
| if (appId !== expectedAppId) { | |
| throw new Error(`Expected app id ${expectedAppId}, found ${appId}.`); | |
| } | |
| const version = await readPlistValue(run, infoPlist, 'CFBundleShortVersionString'); | |
| const expectedVersion = resolveDesktopBuildVersion(product.version, environment); | |
| if (version !== expectedVersion) { | |
| throw new Error(`Expected app version ${expectedVersion}, found ${version}.`); | |
| } | |
| const executableName = await readPlistValue(run, infoPlist, 'CFBundleExecutable'); | |
| const executable = join(contents, 'MacOS', executableName); | |
| const filesystemWorker = join(resources, 'workers', 'filesystem-worker.mjs'); | |
| const appAsar = join(resources, 'app.asar'); | |
| await requirePath(executable); | |
| await assertPackagedResources(resources, { requirePath, forbidPath }); | |
| await assertRenderableAppIcon(resources); | |
| await assertPackagedUpdateConfiguration(resources, { channel }); | |
| await assertPackagedDependencyClosure(resources); | |
| const executableArchitectures = await run('lipo', ['-archs', executable]); | |
| assertSingleArchitecture(executableArchitectures.stdout, 'Maka executable', expectedArch); | |
| await run('codesign', ['--verify', '--deep', '--strict', '--verbose=2', appPath]); | |
| await run('spctl', ['--assess', '--type', 'execute', '--verbose=4', appPath]); | |
| await stapleMacosArtifact(appPath, { | |
| validateOnly: true, | |
| run: (command, args, options) => run(command, args, { timeoutMs: options.timeout }), | |
| }); | |
| const ptyProbe = makePtyProbe( | |
| '/bin/echo', | |
| ['maka-node-pty-ok'], | |
| resolveRuntimeHostSetupPackage(product.version, environment), | |
| ); | |
| await run(executable, ['-e', ptyProbe, join(appAsar, 'package.json')], { | |
| env: { | |
| ELECTRON_RUN_AS_NODE: '1', | |
| ...isolatedUserEnv(join(workingDirectory, 'pty-home')), | |
| }, | |
| }); | |
| await smokeFilesystemWorker(executable, filesystemWorker, { workingDirectory, run }); | |
| await smokeRenderer(executable, { workingDirectory }); | |
| } | |
| export async function verifyMacosDmg( | |
| arch, | |
| { | |
| platform = process.platform, | |
| run = runCommandFromRepo, | |
| verifyApp = verifyPackagedMacApp, | |
| environment = process.env, | |
| checksum = sha256File, | |
| } = {}, | |
| ) { | |
| if (platform !== 'darwin') { | |
| throw new Error('DMG verification requires macOS.'); | |
| } | |
| // Named from the descriptor rather than handed in as a path, the way | |
| // `verify:linux` already resolves its own payloads. The workflows used to | |
| // spell this name out in YAML, which put a second authority on the artifact | |
| // name beside the descriptor — and, unlike it, that copy was checked by | |
| // nothing. | |
| const target = await resolveDesktopReleaseTarget(`macos-${arch}`, { environment }); | |
| const dmgPath = resolve(target.payloadPath('.dmg')); | |
| await access(dmgPath); | |
| const temporaryDirectory = await mkdtemp(join(tmpdir(), 'maka-release-verify-')); | |
| const mountpoint = join(temporaryDirectory, 'mounted'); | |
| const copiedApp = join(temporaryDirectory, 'Maka.app'); | |
| await mkdir(mountpoint); | |
| let mounted = false; | |
| try { | |
| await run('hdiutil', ['attach', dmgPath, '-readonly', '-nobrowse', '-mountpoint', mountpoint]); | |
| mounted = true; | |
| const apps = (await readdir(mountpoint)).filter((name) => name.endsWith('.app')); | |
| if (apps.length !== 1) { | |
| throw new Error(`Expected one app in DMG, found ${apps.length}.`); | |
| } | |
| await run('ditto', [join(mountpoint, apps[0]), copiedApp]); | |
| } finally { | |
| if (mounted) { | |
| await run('hdiutil', ['detach', mountpoint]); | |
| } | |
| } | |
| try { | |
| await verifyApp(copiedApp, { | |
| workingDirectory: temporaryDirectory, | |
| expectedArch: arch, | |
| channel: target.nightly ? 'nightly' : 'release', | |
| }); | |
| // Which payloads a formal release publishes a `.sha256` beside is the | |
| // descriptor's to decide, the way `verify:linux` already reads it. | |
| const checksums = []; | |
| for (const path of target.checksumPaths()) { | |
| const sha256 = await checksum(path); | |
| const checksumPath = `${path}.sha256`; | |
| await writeFile(checksumPath, `${sha256} ${basename(path)}\n`, 'utf8'); | |
| checksums.push({ path, checksumPath, sha256 }); | |
| } | |
| return { dmgPath, checksums }; | |
| } finally { | |
| await rm(temporaryDirectory, { recursive: true, force: true }); | |
| } | |
| } | |
| if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { | |
| const result = await verifyMacosDmg(process.argv[2] ?? process.arch); | |
| console.log(`Verified ${result.dmgPath}`); | |
| for (const { path, sha256 } of result.checksums) { | |
| console.log(`SHA-256 ${sha256} ${basename(path)}`); | |
| } | |
| } |