const fs = require('node:fs'); const image = 'k2patel/floodui'; async function selectRelease({ref = '', requested = ''} = {}, request = fetch) { const automatic = !ref.startsWith('refs/tags/') && (!requested || requested === 'auto'); const get = (url, options = {}) => request(url, { ...options, signal: AbortSignal.timeout(30000), }); let version = ref.startsWith('refs/tags/') ? ref.slice('refs/tags/'.length) : requested; if (automatic) { const response = await get('https://api.github.com/repos/jesec/flood/releases/latest', { headers: {Accept: 'application/vnd.github+json', 'User-Agent': 'docker-flood-client'}, }); if (!response.ok) throw new Error(`GitHub release check failed: HTTP ${response.status}`); const release = await response.json(); if (release.draft || release.prerelease) throw new Error('Expected a stable published release'); version = release.tag_name; } // Also keeps the workflow output and Docker tag safe from upstream metadata. if (typeof version !== 'string' || !/^v\d+\.\d+\.\d+(?:-[a-zA-Z0-9][a-zA-Z0-9.-]*)?$/.test(version)) { throw new Error(`Unsupported Flood release tag: ${JSON.stringify(version)}`); } if (automatic) { const auth = await get(`https://auth.docker.io/token?service=registry.docker.io&scope=repository:${image}:pull`); if (!auth.ok) throw new Error(`Docker Hub token request failed: HTTP ${auth.status}`); const {token} = await auth.json(); if (!token) throw new Error('Docker Hub returned no pull token'); const manifest = await get(`https://registry-1.docker.io/v2/${image}/manifests/${version}`, { method: 'HEAD', headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json', }, }); if (manifest.ok) return {version, shouldBuild: false}; if (manifest.status !== 404) throw new Error(`Docker Hub image check failed: HTTP ${manifest.status}`); } return {version, shouldBuild: true}; } if (require.main === module) { selectRelease({ref: process.env.SOURCE_REF, requested: process.env.FLOOD_VERSION}) .then(({version, shouldBuild}) => { console.log(`${version}: ${shouldBuild ? 'build and publish client image' : 'already published; skipping'}`); if (process.env.GITHUB_OUTPUT) { fs.appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\nshould_build=${shouldBuild}\n`); } }) .catch(error => { console.error(error.message); process.exitCode = 1; }); } module.exports = {selectRelease};