| 1 | import { createHash } from 'node:crypto'; |
| 2 | import { execFileSync } from 'node:child_process'; |
| 3 | import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'; |
| 4 | import { tmpdir } from 'node:os'; |
| 5 | import { basename, dirname, join, resolve } from 'node:path'; |
| 6 | import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 7 | |
| 8 | const here = dirname(fileURLToPath(import.meta.url)); |
| 9 | const lock = JSON.parse(readFileSync(join(here, 'macos-sshfs-dependencies.json'))); |
| 10 | const sha256 = file => createHash('sha256').update(readFileSync(file)).digest('hex'); |
| 11 | const run = (command, args) => execFileSync(command, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }); |
| 12 | const saveJSON = (file, value) => writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`); |
| 13 | const copy = (source, dest) => { mkdirSync(dirname(dest), { recursive: true }); cpSync(source, dest, { recursive: true, dereference: true }); }; |
| 14 | |
| 15 | function files(root, relative = '') { |
| 16 | return readdirSync(join(root, relative)).sort().flatMap(name => { |
| 17 | const path = relative ? `${relative}/${name}` : name; |
| 18 | return statSync(join(root, path)).isDirectory() ? files(root, path) : [path]; |
| 19 | }); |
| 20 | } |
| 21 | |
| 22 | export function inspectDependency(name, prefix) { |
| 23 | const spec = lock[name]; |
| 24 | const formula = join(prefix, '.brew', `${name}.rb`); |
| 25 | const receipt = JSON.parse(readFileSync(join(prefix, 'INSTALL_RECEIPT.json'))); |
| 26 | const formulaDigest = sha256(formula); |
| 27 | if (![spec.formulaSha256, ...(spec.additionalFormulaSha256 ?? [])].includes(formulaDigest) || receipt.source?.spec !== 'stable' || receipt.source?.versions?.stable !== spec.version) { |
| 28 | throw new Error(`${name}: installed formula/version differs from the reviewed SSHFS dependency lock; actual version=${receipt.source?.versions?.stable}, formulaSHA256=${formulaDigest}. Update the source lock before building.`); |
| 29 | } |
| 30 | |
| 31 | const selected = Object.fromEntries(['homebrew_version', 'compiler', 'arch', 'built_as_bottle', 'poured_from_bottle', 'built_on', 'used_options', 'runtime_dependencies'].map(key => [key, receipt[key]])); |
| 32 | return { spec, formula, receipt: { ...selected, source: { spec: 'stable', version: spec.version, tap: receipt.source.tap, tap_git_head: receipt.source.tap_git_head } } }; |
| 33 | } |
| 34 | |
| 35 | function download(url, expected, dest) { |
| 36 | mkdirSync(dirname(dest), { recursive: true }); |
| 37 | run('curl', ['--fail', '--location', '--silent', '--show-error', '--proto', '=https', '--proto-redir', '=https', '--retry', '2', '--connect-timeout', '20', '--max-time', '240', url, '-o', dest]); |
| 38 | if (sha256(dest) !== expected) throw new Error(`Source checksum mismatch: ${basename(dest)}`); |
| 39 | } |
| 40 | |
| 41 | export function extractLicenses(archive, output, component) { |
| 42 | const selectors = { |
| 43 | sshfs: [/^(COPYING|AUTHORS|LICENSE[^/]*)$/], |
| 44 | glib: [/^COPYING$/, /^LICENSES\//], |
| 45 | gettext: [/^COPYING$/, /^gettext-runtime\/(COPYING|intl\/(COPYING.LIB|AUTHORS))$/], |
| 46 | pcre2: [/^COPYING$/, /^LICENCE(?:\.md)?$/, /^deps\/sljit\/LICENSE$/], |
| 47 | }[component]; |
| 48 | const names = run('tar', ['-tf', archive]).trim().split('\n'); |
| 49 | const selected = names.filter(name => !name.endsWith('/') && selectors.some(match => match.test(name.replace(/^[^/]+\//, '')))); |
| 50 | if (!selected.length) throw new Error(`No license material in ${basename(archive)}`); |
| 51 | const temp = mkdtempSync(join(tmpdir(), 'cage-sshfs-licenses-')); |
| 52 | try { |
| 53 | |
| 54 | |
| 55 | run('tar', ['-xf', archive, '-C', temp, ...selected]); |
| 56 | for (const name of selected) { |
| 57 | const relative = name.replace(/^[^/]+\//, ''); |
| 58 | const dest = join(output, relative); |
| 59 | mkdirSync(dirname(dest), { recursive: true }); |
| 60 | writeFileSync(dest, readFileSync(join(temp, name))); |
| 61 | } |
| 62 | } finally { rmSync(temp, { recursive: true, force: true }); } |
| 63 | } |
| 64 | |
| 65 | export function prepare(sdk, output) { |
| 66 | if (existsSync(output)) throw new Error('Source materials destination already exists.'); |
| 67 | |
| 68 | const installed = Object.fromEntries(['glib', 'gettext', 'pcre2'].map(name => { |
| 69 | const prefix = realpathSync(run('brew', ['--prefix', name]).trim()); |
| 70 | return [name, { prefix, ...inspectDependency(name, prefix) }]; |
| 71 | })); |
| 72 | mkdirSync(output, { recursive: true }); |
| 73 | copy(join(here, 'rebuild-macos-sshfs.sh'), join(output, 'rebuild-macos-sshfs.sh')); |
| 74 | copy(join(here, '../../LICENSE'), join(output, 'cage/LICENSE')); |
| 75 | for (const file of ['sshfs-openwith.patch', 'macos-fuse-media.sh', 'macos-sshfs-dependencies.json']) copy(join(here, file), join(output, 'cage', file)); |
| 76 | copy(join(here, 'macos-sshfs-source-README'), join(output, 'README')); |
| 77 | download(lock.sshfs.url, lock.sshfs.sha256, join(output, 'upstream/sshfs.tar.gz')); |
| 78 | extractLicenses(join(output, 'upstream/sshfs.tar.gz'), join(output, 'licenses/sshfs'), 'sshfs'); |
| 79 | const archives = { glib: 'glib.tar.xz', gettext: 'gettext.tar.gz', pcre2: 'pcre2.tar.bz2' }; |
| 80 | const inputs = { glib: ['lib/libgthread-2.0.a', 'lib/libglib-2.0.a', 'include/glib-2.0', 'lib/glib-2.0/include'], gettext: ['lib/libintl.a', 'include/libintl.h'], pcre2: ['lib/libpcre2-8.a', 'include/pcre2.h', 'include/pcre2posix.h'] }; |
| 81 | for (const [name, { prefix, spec, formula, receipt }] of Object.entries(installed)) { |
| 82 | copy(formula, join(output, 'homebrew', `${name}.rb`)); |
| 83 | saveJSON(join(output, 'homebrew', `${name}-receipt.json`), receipt); |
| 84 | const archive = join(output, 'upstream', archives[name]); |
| 85 | download(spec.url, spec.sha256, archive); |
| 86 | extractLicenses(archive, join(output, 'licenses', name), name); |
| 87 | for (const resource of spec.resources ?? []) download(resource.url, resource.sha256, join(output, 'upstream', `${resource.name}.tar.xz`)); |
| 88 | for (const patch of spec.patches ?? []) download(patch.url, patch.sha256, join(output, 'homebrew', patch.file)); |
| 89 | for (const file of inputs[name]) { |
| 90 | const target = join(output, 'dependencies', name, file); |
| 91 | copy(join(prefix, file), target); |
| 92 | |
| 93 | |
| 94 | for (const path of statSync(target).isDirectory() ? files(target) : ['']) { |
| 95 | if (sha256(join(target, path)) !== sha256(join(prefix, file, path))) throw new Error(`${name}: dependency changed while collecting sources.`); |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | download('https://raw.githubusercontent.com/Homebrew/homebrew-core/68093a0680c21eb19fb034af0d8c5104848315e7/LICENSE.txt', 'f80329e58613ad669c0e73cb132d8060b9b2c55e339c73848068e4d1567f4627', join(output, 'licenses/homebrew/LICENSE.txt')); |
| 100 | const sdkFiles = [...files(join(sdk, 'include')).map(path => `include/${path}`), 'lib/libfuse3.dylib']; |
| 101 | saveJSON(join(output, 'build.json'), { |
| 102 | cageVersion: readFileSync(join(here, '../../VERSION'), 'utf8').trim(), |
| 103 | dependencies: lock, |
| 104 | toolchain: { clang: run('clang', ['--version']).split('\n')[0], sdk: run('xcrun', ['--show-sdk-version']).trim(), deploymentTarget: process.env.MACOSX_DEPLOYMENT_TARGET ?? '14.0' }, |
| 105 | macfuse: { version: '5.5.0', url: 'https://github.com/macfuse/macfuse/releases/download/macfuse-5.5.0/macfuse-5.5.0.dmg', sha256: '92c21ef2db4199bcf5bddc8e6efb57b23ecb9715f74ab38cba2c77ab226d3830', files: sdkFiles.map(path => ({ path, sha256: sha256(join(sdk, path)) })) }, |
| 106 | }); |
| 107 | writeFileSync(join(output, 'NOTICE'), `Cage macOS SSHFS corresponding source and relink materials\n\nSSHFS ${lock.sshfs.version} (${lock.sshfs.commit}): GNU GPL version 2 (see licenses/sshfs/COPYING).\nCage changes: cage/sshfs-openwith.patch (guest-local file-opening metadata).\nStatically linked GLib ${lock.glib.version} and GNU gettext libintl ${lock.gettext.version}: LGPL-2.1-or-later.\nPCRE2 ${lock.pcre2.version}: BSD-3-Clause WITH PCRE2-exception; bundled SLJIT: BSD-2-Clause.\nUpstream copyright and license notices are retained in licenses/ and the complete upstream archives.\nHomebrew recipes are under the BSD 2-Clause license in licenses/homebrew/LICENSE.txt.\nThe source archive includes the exact static libraries and headers used by the build.\nThe external macFUSE runtime is installed separately; its pinned SDK acquisition instructions are in README.\nThe final signed executable hash and every distributed source/relink input hash are in manifest.json.\n`); |
| 108 | } |
| 109 | |
| 110 | export function finish(materials, binary, archive, licenses) { |
| 111 | const build = JSON.parse(readFileSync(join(materials, 'build.json'))); |
| 112 | const manifest = { format: 1, cageVersion: build.cageVersion, executable: { path: 'project/cage-sshfs', sha256: sha256(binary) }, files: files(materials).filter(path => path !== 'manifest.json').map(path => ({ path, sha256: sha256(join(materials, path)) })) }; |
| 113 | saveJSON(join(materials, 'manifest.json'), manifest); |
| 114 | copy(join(materials, 'licenses'), licenses); |
| 115 | copy(join(materials, 'NOTICE'), join(licenses, 'NOTICE')); |
| 116 | copy(join(materials, 'build.json'), join(licenses, 'build.json')); |
| 117 | mkdirSync(dirname(archive), { recursive: true }); |
| 118 | run('tar', ['-czf', archive, '-C', materials, '.']); |
| 119 | verifyArchive(archive, binary, build.cageVersion); |
| 120 | } |
| 121 | |
| 122 | export function verifyArchive(archive, binary, version) { |
| 123 | const temp = mkdtempSync(join(tmpdir(), 'cage-sshfs-source-verify-')); |
| 124 | try { |
| 125 | run('tar', ['-xzf', archive, '-C', temp]); |
| 126 | const manifest = JSON.parse(readFileSync(join(temp, 'manifest.json'))); |
| 127 | if (manifest.format !== 1 || manifest.cageVersion !== version || manifest.executable?.sha256 !== sha256(binary)) throw new Error('macOS guest source does not match this signed executable/version.'); |
| 128 | for (const item of manifest.files) { |
| 129 | if (!item.path.split('/').every(part => part && part !== '.' && part !== '..') || item.path.startsWith('/') || sha256(join(temp, item.path)) !== item.sha256) throw new Error(`macOS guest source integrity check failed: ${item.path}`); |
| 130 | } |
| 131 | } finally { rmSync(temp, { recursive: true, force: true }); } |
| 132 | } |
| 133 | |
| 134 | if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { |
| 135 | const [action, ...args] = process.argv.slice(2); |
| 136 | if (action === 'prepare' && args.length === 2) prepare(...args); |
| 137 | else if (action === 'finish' && args.length === 4) finish(...args); |
| 138 | else if (action === 'verify' && args.length === 3) verifyArchive(...args); |
| 139 | else throw new Error('Usage: collect-macos-sshfs-sources.mjs prepare SDK DIRECTORY | finish DIRECTORY BINARY ARCHIVE LICENSES | verify ARCHIVE BINARY VERSION'); |
| 140 | } |