diff --git a/.github/workflows/test-action.yml b/.github/workflows/test-action.yml index f9db61e..6ee3a56 100644 --- a/.github/workflows/test-action.yml +++ b/.github/workflows/test-action.yml @@ -19,11 +19,63 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - run: npm ci + - run: npm run build + - name: Setup Hugo - uses: peaceiris/actions-hugo@2752ce1d29631191ea3f27c23495fa06139a5b78 # v3.2.1 + uses: ./ with: hugo-version: ${{ matrix.hugo-version }} extended: ${{ matrix.extended }} - name: Verify Hugo run: hugo version + + dart-sass: + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, ubuntu-24.04-arm, macos-15-intel, macos-15, windows-2025, windows-11-arm] + extended: [false, true] + hugo-version: ['0.160.1'] + exclude: + # Hugo 0.160.1 has no Windows arm64 extended archive. + - os: windows-11-arm + extended: true + include: + - os: ubuntu-24.04 + extended: false + hugo-version: '0.114.0' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: '.nvmrc' + cache: 'npm' + - run: npm ci + - run: npm run build + - name: Setup Hugo and Dart Sass from this PR + uses: ./ + with: + hugo-version: ${{ matrix.hugo-version }} + extended: ${{ matrix.extended }} + dart-sass-version: '1.108.2' + - name: Use the legacy template API on Hugo 0.114.0 + if: matrix.hugo-version == '0.114.0' + run: node -e "const fs = require('fs'); const p = '__tests__/fixtures/dart-sass/layouts/index.html'; fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replace('css.Sass', 'resources.ToCSS'));" + - name: Verify standalone Dart Sass + run: sass --version + - name: Compile SCSS with Hugo and verify CSS + shell: bash + run: | + hugo --source __tests__/fixtures/dart-sass --destination "$RUNNER_TEMP/dart-sass-site" + node -e "const fs = require('fs'); const css = fs.readFileSync(process.env.RUNNER_TEMP + '/dart-sass-site/css/main.css', 'utf8'); if (!/\.dart-sass-fixture\s*\{\s*width: 4px;\s*\}/.test(css)) throw new Error(css);" diff --git a/README.md b/README.md index 9a7750e..39ec374 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ Thanks to this change, we can complete this action in less than a few seconds. - [Getting started](#getting-started) - [⭐️ Create your workflow](#%EF%B8%8F-create-your-workflow) - [Options](#options) + - [⭐️ Install Dart Sass](#%EF%B8%8F-install-dart-sass) - [⭐️ Use Hugo extended](#%EF%B8%8F-use-hugo-extended) - [⭐️ Use the latest version of Hugo](#%EF%B8%8F-use-the-latest-version-of-hugo) - [Tips](#tips) @@ -115,6 +116,42 @@ jobs: ## Options +### ⭐️ Install Dart Sass + +Set `dart-sass-version` to a fixed standalone [Dart Sass](https://github.com/sass/dart-sass) release version: + +```yaml +- uses: peaceiris/actions-hugo@v3 + with: + hugo-version: '0.160.1' + dart-sass-version: '1.108.2' +- run: hugo --minify +``` + +In your Hugo template, select the Dart Sass transpiler: + +```go-html-template +{{ $css := resources.Get "scss/main.scss" | css.Sass (dict "transpiler" "dartsass") }} + +``` + +Requires **Hugo 0.114.0 or later**; on older template APIs, use `resources.ToCSS` +instead of `css.Sass`. Dart Sass works independently of `extended`. The old +`dart-sass-embedded` protocol is not supported. + +Use a fixed `major.minor.patch` version. Omitting `dart-sass-version` or leaving it +empty skips Sass entirely. Linux **glibc**, macOS, and Windows runners on **x64 or arm64** are +supported when the selected release has the matching asset; musl is unsupported. +The `github-token` input defaults to `${{ github.token }}`; read-only permissions suffice. + +Archives must have a valid GitHub API SHA-256 digest and pass verification before +extraction or execution. Missing digests or assets, API errors, and mismatches fail +the action. This checks integrity against the same publisher, not a signature or +an independent immutable checksum pin. + +See [Dart Sass details](docs/dart-sass.md) for version and platform selection, +token overrides, failure modes, and the security trust model. + ### ⭐️ Use Hugo extended Set `extended: true` to use a Hugo extended version. diff --git a/__tests__/fixtures/dart-sass/assets/main.scss b/__tests__/fixtures/dart-sass/assets/main.scss new file mode 100644 index 0000000..ac48805 --- /dev/null +++ b/__tests__/fixtures/dart-sass/assets/main.scss @@ -0,0 +1,5 @@ +@use 'sass:math'; +$width: math.div(12px, 3); +.dart-sass-fixture { + width: $width; +} diff --git a/__tests__/fixtures/dart-sass/hugo.toml b/__tests__/fixtures/dart-sass/hugo.toml new file mode 100644 index 0000000..0a0859e --- /dev/null +++ b/__tests__/fixtures/dart-sass/hugo.toml @@ -0,0 +1,2 @@ +baseURL = 'https://example.org/' +disableKinds = ['taxonomy', 'term', 'RSS', 'sitemap'] diff --git a/__tests__/fixtures/dart-sass/layouts/index.html b/__tests__/fixtures/dart-sass/layouts/index.html new file mode 100644 index 0000000..1d914d8 --- /dev/null +++ b/__tests__/fixtures/dart-sass/layouts/index.html @@ -0,0 +1,2 @@ +{{ $css := resources.Get "main.scss" | css.Sass (dict "transpiler" "dartsass" "targetPath" "css/main.css") }} +Dart Sass integration diff --git a/__tests__/install-dart-sass.test.ts b/__tests__/install-dart-sass.test.ts new file mode 100644 index 0000000..d9d43ba --- /dev/null +++ b/__tests__/install-dart-sass.test.ts @@ -0,0 +1,298 @@ +import * as core from '@actions/core'; +import * as tc from '@actions/tool-cache'; +import * as exec from '@actions/exec'; +import fetch from 'node-fetch'; +import {createHash} from 'crypto'; +import {mkdtemp, writeFile, rm} from 'fs/promises'; +import {tmpdir} from 'os'; +import * as path from 'path'; +import { + getDartSassAssetName, + installDartSass, + verifyDartSassArchive +} from '../src/install-dart-sass'; + +jest.mock('node-fetch'); + +const version = '1.108.2'; +const body = 'test archive bytes'; +const digest = `sha256:${createHash('sha256').update(body).digest('hex')}`; +const mockedFetch = jest.mocked(fetch); +const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!; +const originalArch = Object.getOwnPropertyDescriptor(process, 'arch')!; +let directory: string; +let archive: string; + +beforeEach(async () => { + directory = await mkdtemp(path.join(tmpdir(), 'dart-sass-test-')); + archive = path.join(directory, 'archive'); + await writeFile(archive, body); + jest.spyOn(tc, 'downloadTool').mockResolvedValue(archive); + jest.spyOn(tc, 'extractTar').mockResolvedValue(directory); + jest.spyOn(tc, 'extractZip').mockResolvedValue(directory); + jest.spyOn(core, 'addPath').mockImplementation(() => {}); + jest.spyOn(exec, 'exec').mockResolvedValue(0); + mockedFetch.mockReset(); +}); + +afterEach(async () => { + Object.defineProperty(process, 'platform', originalPlatform); + Object.defineProperty(process, 'arch', originalArch); + jest.restoreAllMocks(); + await rm(directory, {recursive: true, force: true}); +}); + +function metadata(overrides: Record = {}): void { + const name = getDartSassAssetName(version, process.platform, process.arch, '2.39'); + mockedFetch.mockResolvedValue({ + ok: true, + json: async () => ({ + tag_name: version, + assets: [ + { + name, + digest, + browser_download_url: `https://github.com/sass/dart-sass/releases/download/${version}/${name}`, + ...overrides + } + ] + }) + } as Awaited>); +} + +function expectNoInstallation(): void { + expect(tc.extractTar).not.toHaveBeenCalled(); + expect(tc.extractZip).not.toHaveBeenCalled(); + expect(exec.exec).not.toHaveBeenCalled(); + expect(core.addPath).not.toHaveBeenCalled(); +} + +test('empty input makes no network calls or PATH changes', async () => { + await installDartSass('', 'unused-token'); + expect(fetch).not.toHaveBeenCalled(); + expect(tc.downloadTool).not.toHaveBeenCalled(); + expectNoInstallation(); +}); + +test.each([ + 'latest', + '^1.89.1', + '1.89', + 'v1.89.1', + '01.89.1', + '1.89.1-beta.1', + 'https://example.com/sass', + '../1.89.1' +])('rejects non-fixed input %s before network access', async value => { + await expect(installDartSass(value)).rejects.toThrow('fixed version'); + expect(fetch).not.toHaveBeenCalled(); + expectNoInstallation(); +}); + +test.each([ + ['linux', 'x64', 'linux-x64.tar.gz'], + ['linux', 'arm64', 'linux-arm64.tar.gz'], + ['darwin', 'x64', 'macos-x64.tar.gz'], + ['darwin', 'arm64', 'macos-arm64.tar.gz'], + ['win32', 'x64', 'windows-x64.zip'], + ['win32', 'arm64', 'windows-arm64.zip'] +])('maps %s/%s exactly', (platform, arch, suffix) => { + expect(getDartSassAssetName(version, platform, arch, '2.39')).toBe( + `dart-sass-${version}-${suffix}` + ); +}); + +test.each([ + ['freebsd', 'x64'], + ['linux', 'ia32'], + ['darwin', 'arm'], + ['win32', 'riscv64'] +])('rejects unsupported %s/%s', (platform, arch) => { + expect(() => getDartSassAssetName(version, platform, arch, '2.39')).toThrow('Unsupported'); +}); + +test('rejects musl or unknown libc', () => { + expect(() => getDartSassAssetName(version, 'linux', 'x64')).toThrow('glibc'); +}); + +test.each([ + undefined, + null, + '', + 'sha512:' + 'a'.repeat(64), + 'sha256:' + 'a'.repeat(63), + 'sha256:' + 'g'.repeat(64) +])('rejects missing or malformed digest %s before download', async invalid => { + metadata({digest: invalid}); + await expect(installDartSass(version)).rejects.toThrow('no valid GitHub API SHA-256 digest'); + expect(tc.downloadTool).not.toHaveBeenCalled(); + expectNoInstallation(); +}); + +test('rejects checksum mismatch before extraction or execution', async () => { + metadata({digest: 'sha256:' + '0'.repeat(64)}); + await expect(installDartSass(version)).rejects.toThrow('SHA-256 mismatch'); + expectNoInstallation(); +}); + +test('rejects missing archive', async () => { + metadata({name: 'another-platform.tar.gz'}); + await expect(installDartSass(version)).rejects.toThrow('no release asset'); + expect(tc.downloadTool).not.toHaveBeenCalled(); + expectNoInstallation(); +}); + +test('rejects unexpected download URL', async () => { + metadata({browser_download_url: 'https://example.com/archive'}); + await expect(installDartSass(version)).rejects.toThrow('Unexpected download URL'); + expect(tc.downloadTool).not.toHaveBeenCalled(); + expectNoInstallation(); +}); + +test.each([403, 404, 429, 500])('fails closed on API HTTP %s', async status => { + mockedFetch.mockResolvedValue({ok: false, status} as Awaited>); + await expect(installDartSass(version)).rejects.toThrow(`HTTP ${status}`); + expect(tc.downloadTool).not.toHaveBeenCalled(); + expectNoInstallation(); +}); + +test('fails closed on network error', async () => { + mockedFetch.mockRejectedValue(new Error('network failed')); + await expect(installDartSass(version)).rejects.toThrow('Unable to fetch Dart Sass'); + expectNoInstallation(); +}); + +test.each([null, {}, {tag_name: 'other', assets: []}, {tag_name: version, assets: null}])( + 'rejects malformed release metadata %j', + async release => { + mockedFetch.mockResolvedValue({ok: true, json: async () => release} as Awaited< + ReturnType + >); + await expect(installDartSass(version)).rejects.toThrow('Invalid Dart Sass'); + expectNoInstallation(); + } +); + +test('fails closed on invalid JSON', async () => { + mockedFetch.mockResolvedValue({ + ok: true, + status: 200, + json: async (): Promise => { + throw new Error('invalid JSON'); + } + } as Awaited>); + await expect(installDartSass(version)).rejects.toThrow('Invalid Dart Sass'); + expectNoInstallation(); +}); + +test('fails closed on download or read failure', async () => { + metadata(); + jest.mocked(tc.downloadTool).mockRejectedValueOnce(new Error('download failed')); + await expect(installDartSass(version)).rejects.toThrow('download failed'); + jest.mocked(tc.downloadTool).mockResolvedValueOnce(path.join(directory, 'missing')); + await expect(installDartSass(version)).rejects.toThrow('ENOENT'); + expectNoInstallation(); +}); + +test('verifies bytes then preserves the whole standalone directory on PATH', async () => { + metadata(); + await installDartSass(version); + const extract = process.platform === 'win32' ? tc.extractZip : tc.extractTar; + expect(extract).toHaveBeenCalledWith(archive); + expect(core.addPath).toHaveBeenCalledWith(path.join(directory, 'dart-sass')); + expect(exec.exec).not.toHaveBeenCalled(); +}); + +test('accepts uppercase checksum hex but rejects invalid verification input', async () => { + await expect( + verifyDartSassArchive(archive, 'sha256:' + digest.slice(7).toUpperCase()) + ).resolves.toBeUndefined(); + await expect(verifyDartSassArchive(archive, '')).rejects.toThrow('no valid'); +}); + +test.each([ + ['linux', 'x64'], + ['linux', 'arm64'], + ['darwin', 'x64'], + ['darwin', 'arm64'], + ['win32', 'x64'], + ['win32', 'arm64'] +])('installs the verified archive for %s/%s', async (platform, arch) => { + Object.defineProperty(process, 'platform', {value: platform, configurable: true}); + Object.defineProperty(process, 'arch', {value: arch, configurable: true}); + jest + .spyOn(process.report, 'getReport') + .mockReturnValue({header: {glibcVersionRuntime: '2.39'}} as unknown as ReturnType< + typeof process.report.getReport + >); + metadata(); + await installDartSass(version); + const extract = platform === 'win32' ? tc.extractZip : tc.extractTar; + const otherExtract = platform === 'win32' ? tc.extractTar : tc.extractZip; + expect(extract).toHaveBeenCalledWith(archive); + expect(otherExtract).not.toHaveBeenCalled(); + expect(core.addPath).toHaveBeenCalledWith(path.join(directory, 'dart-sass')); +}); + +test('does not add PATH if extraction fails', async () => { + metadata(); + jest.mocked(tc.extractTar).mockRejectedValue(new Error('extraction failed')); + jest.mocked(tc.extractZip).mockRejectedValue(new Error('extraction failed')); + await expect(installDartSass(version)).rejects.toThrow('extraction failed'); + expect(core.addPath).not.toHaveBeenCalled(); +}); + +test('uses the explicit token only for exact-origin metadata and refuses redirects', async () => { + metadata(); + const info = jest.spyOn(core, 'info'); + const debug = jest.spyOn(core, 'debug'); + await installDartSass(version, 'test-token'); + expect(fetch).toHaveBeenCalledWith( + `https://api.github.com/repos/sass/dart-sass/releases/tags/${version}`, + expect.objectContaining({ + headers: expect.objectContaining({Authorization: 'Bearer test-token'}), + redirect: 'error' + }) + ); + expect(jest.mocked(tc.downloadTool).mock.calls[0]).toHaveLength(1); + expect(JSON.stringify(jest.mocked(tc.downloadTool).mock.calls)).not.toContain('test-token'); + expect(JSON.stringify(info.mock.calls)).not.toContain('test-token'); + expect(JSON.stringify(debug.mock.calls)).not.toContain('test-token'); +}); + +test.each(['', 'explicit-token'])( + 'never uses a stale environment token with input %j', + async token => { + const original = process.env.GITHUB_TOKEN; + process.env.GITHUB_TOKEN = 'stale-environment-token'; + try { + metadata(); + await installDartSass(version, token); + const headers = mockedFetch.mock.calls[0][1]?.headers; + expect((headers as Record).Authorization).toBe( + token ? 'Bearer explicit-token' : undefined + ); + expect(JSON.stringify(mockedFetch.mock.calls)).not.toContain('stale-environment-token'); + } finally { + if (original === undefined) delete process.env.GITHUB_TOKEN; + else process.env.GITHUB_TOKEN = original; + } + } +); + +test('does not expose token-bearing transport or parsing errors', async () => { + mockedFetch.mockRejectedValueOnce(new Error('transport error containing secret-token')); + await expect(installDartSass(version, 'secret-token')).rejects.toEqual( + new Error(`Unable to fetch Dart Sass ${version} release metadata.`) + ); + mockedFetch.mockResolvedValueOnce({ + ok: true, + json: async (): Promise => { + throw new Error('parse error containing secret-token'); + } + } as Awaited>); + await expect(installDartSass(version, 'secret-token')).rejects.toEqual( + new Error(`Invalid Dart Sass ${version} release metadata.`) + ); + expectNoInstallation(); +}); diff --git a/__tests__/main.test.ts b/__tests__/main.test.ts index b025538..9effb38 100644 --- a/__tests__/main.test.ts +++ b/__tests__/main.test.ts @@ -1,4 +1,7 @@ import * as main from '../src/main'; +import * as core from '@actions/core'; +import * as sass from '../src/install-dart-sass'; +import {readFileSync} from 'fs'; import * as io from '@actions/io'; import path from 'path'; import {Tool, Action} from '../src/constants'; @@ -85,3 +88,29 @@ describe('showVersion()', () => { await expect(main.showVersion('gitgit', ['--version'])).rejects.toThrow('spawn gitgit ENOENT'); }); }); + +describe('Dart Sass token input plumbing', () => { + afterEach(() => jest.restoreAllMocks()); + + test('declares the runner-resolved GitHub token as the default', () => { + const metadata = readFileSync(path.join(__dirname, '..', 'action.yml'), 'utf8'); + expect(metadata).toMatch(/github-token:[\s\S]*?default: \$\{\{ github.token \}\}/); + }); + + test.each(['runner-resolved-default-token', 'explicit-token', ''])( + 'passes the resolved github-token input %j explicitly to Sass', + async token => { + jest.spyOn(core, 'getInput').mockImplementation(name => { + const inputs: Record = { + 'hugo-version': Tool.TestVersionSpec, + 'dart-sass-version': '1.108.2', + 'github-token': token + }; + return inputs[name] || ''; + }); + const install = jest.spyOn(sass, 'installDartSass').mockResolvedValue(); + await main.run(); + expect(install).toHaveBeenCalledWith('1.108.2', token); + } + ); +}); diff --git a/action.yml b/action.yml index ec49924..854aa40 100644 --- a/action.yml +++ b/action.yml @@ -10,6 +10,14 @@ inputs: description: 'Download (if necessary) and use Hugo extended version. Example: true' required: false default: 'false' + dart-sass-version: + description: 'Optional fixed standalone Dart Sass version (e.g. 1.108.2). Requires a GitHub API SHA-256 digest.' + required: false + default: '' + github-token: + description: 'GitHub token for Dart Sass release metadata. Read-only permissions suffice; set empty for unauthenticated requests.' + required: false + default: ${{ github.token }} runs: using: 'node24' main: 'lib/index.js' diff --git a/docs/dart-sass.md b/docs/dart-sass.md new file mode 100644 index 0000000..5e3d889 --- /dev/null +++ b/docs/dart-sass.md @@ -0,0 +1,91 @@ +# Dart Sass installation details + +See the [README](../README.md) for workflow and Hugo template examples. + +## Inputs and compatibility + +`dart-sass-version` is optional and defaults to an empty string. When omitted or +empty, it causes no Sass network requests, installation, or PATH changes. When +set, it must be a fixed `major.minor.patch` version, such as `1.108.2`. The action +rejects `latest`, ranges, `v` prefixes, prereleases, and arbitrary download URLs. + +The installer uses standalone releases from [sass/dart-sass](https://github.com/sass/dart-sass). +Hugo **0.114.0 or later** is required to use this standalone executable. Select +`"transpiler" "dartsass"` in `css.Sass`, or in `resources.ToCSS` on older Hugo +versions. Installation is independent of the `extended` input. The old +`dart-sass-embedded` executable and protocol are outside this action's support. + +## Platform and archive selection + +The action selects the exact archive for the requested version and the Node +runtime's operating system and architecture: + +| Runner | Architectures | Archive suffix | +| --- | --- | --- | +| Linux with glibc | x64, arm64 | `linux-.tar.gz` | +| macOS | x64, arm64 | `macos-.tar.gz` | +| Windows | x64, arm64 | `windows-.zip` | + +The full asset name is `dart-sass--`. The selected release must +publish that exact asset. There is no fallback to another version, architecture, +or download host. Linux musl (including Alpine), unknown libc, and unsupported +operating systems or architectures are rejected. Linux detection uses Node's +runtime report to confirm glibc. + +After verification, the action extracts the entire standalone `dart-sass` +directory and adds that directory to PATH. Its launcher and sibling `src` runtime +stay together, making `sass` available to subsequent workflow steps. Installing +Sass does not change which Hugo archives a release provides; for example, Hugo +0.160.1 has a Windows arm64 standard archive but no Windows arm64 extended archive. + +## GitHub authentication + +The `github-token` input defaults to `${{ github.token }}`. Read-only permissions +suffice; no additional write permissions are needed. The token authenticates only +the exact release metadata endpoint on `https://api.github.com`, with redirects +disabled. It is never passed to archive downloads or included in installer logs +or errors. + +To use another token, set the input explicitly: + +```yaml +- uses: peaceiris/actions-hugo@v3 + with: + hugo-version: '0.160.1' + dart-sass-version: '1.108.2' + github-token: ${{ secrets.SASS_METADATA_TOKEN }} +``` + +Set `github-token: ''` to make unauthenticated metadata requests instead. This has +lower API rate limits. An explicitly empty input remains empty: the action never +falls back to `GITHUB_TOKEN` or another environment token. When Sass is disabled, +the action does not make a Sass metadata request regardless of the token input. + +## Integrity checks and failures + +The action fetches official release metadata for the requested version, confirms +the tag and matching asset, and requires a digest in the form `sha256:<64 hex digits>`. +It also checks that the download URL matches the expected official release URL. +After downloading, it computes the archive's SHA-256 digest and compares it with +the API digest **before extraction or execution**. + +The action fails closed on: + +- Unsupported platforms, invalid versions, or missing release assets. +- API failures, including authentication errors, rate limits, redirects, and invalid metadata. +- Missing or malformed digests, download/read errors, or checksum mismatches. +- Extraction failures; the Sass directory is not added to PATH if extraction fails. + +There is no manual checksum input or unverified fallback. Older releases often +have no API digest, including 1.89.0 and earlier. Choose a release with +digest-bearing assets, such as 1.108.2. The installer checks the actual metadata; +it does not infer digest or asset availability from the version number alone. + +## Trust model + +The digest and archive come from the same publisher through GitHub. Verification +checks that the downloaded bytes match the publisher's current metadata. It is +not a signature, provenance attestation, or an independent immutable checksum +pin. A fixed version does not independently prevent replacement of a release +asset and its digest. GitHub API availability and the integrity of the publisher's +release metadata remain part of the trust and availability model. diff --git a/src/install-dart-sass.ts b/src/install-dart-sass.ts new file mode 100644 index 0000000..31c0a48 --- /dev/null +++ b/src/install-dart-sass.ts @@ -0,0 +1,120 @@ +import * as core from '@actions/core'; +import * as tc from '@actions/tool-cache'; +import {createHash} from 'crypto'; +import {createReadStream} from 'fs'; +import * as path from 'path'; +import fetch from 'node-fetch'; + +interface ReleaseAsset { + name: string; + digest?: string | null; + browser_download_url: string; +} + +interface Release { + tag_name: string; + assets: ReleaseAsset[]; +} + +export function getDartSassAssetName( + version: string, + platform: string, + arch: string, + glibcVersion?: string +): string { + if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version)) { + throw new Error('dart-sass-version must be a fixed version such as 1.108.2 (without v).'); + } + const platforms: Record = {linux: 'linux', darwin: 'macos', win32: 'windows'}; + const os = platforms[platform]; + if (!os || !['x64', 'arm64'].includes(arch)) { + throw new Error(`Unsupported Dart Sass platform: ${platform}/${arch}.`); + } + if (platform === 'linux' && !glibcVersion) { + throw new Error('Dart Sass requires Linux with glibc; musl and unknown libc are unsupported.'); + } + const extension = platform === 'win32' ? 'zip' : 'tar.gz'; + return `dart-sass-${version}-${os}-${arch}.${extension}`; +} + +export async function verifyDartSassArchive(archive: string, digest: string): Promise { + if (!/^sha256:[a-fA-F0-9]{64}$/.test(digest)) { + throw new Error('Dart Sass release asset has no valid GitHub API SHA-256 digest.'); + } + const hash = createHash('sha256'); + for await (const chunk of createReadStream(archive)) { + hash.update(chunk); + } + if (hash.digest('hex') !== digest.slice(7).toLowerCase()) { + throw new Error('Dart Sass archive SHA-256 mismatch; refusing to extract or execute it.'); + } +} + +export async function installDartSass(version: string, token = ''): Promise { + if (version === '') { + return; + } + + // Node's report identifies the libc actually used by this runner. Do not assume + // Linux means glibc or silently install an incompatible archive on musl. + const header = + process.platform === 'linux' + ? (process.report?.getReport() as {header?: {glibcVersionRuntime?: string}})?.header + : undefined; + const name = getDartSassAssetName( + version, + process.platform, + process.arch, + header?.glibcVersionRuntime + ); + const headers: Record = { + 'User-Agent': 'peaceiris/actions-hugo', + Accept: 'application/vnd.github+json' + }; + if (token) { + headers.Authorization = `Bearer ${token}`; + } + let response; + try { + response = await fetch(`https://api.github.com/repos/sass/dart-sass/releases/tags/${version}`, { + headers, + redirect: 'error' + }); + } catch { + // Do not surface transport errors that may contain request headers. + throw new Error(`Unable to fetch Dart Sass ${version} release metadata.`); + } + if (!response.ok) { + throw new Error( + `Unable to fetch Dart Sass ${version} release metadata: HTTP ${response.status}.` + ); + } + let release: Release | null; + try { + release = (await response.json()) as Release | null; + } catch { + throw new Error(`Invalid Dart Sass ${version} release metadata.`); + } + if (release?.tag_name !== version || !Array.isArray(release.assets)) { + throw new Error(`Invalid Dart Sass ${version} release metadata.`); + } + const asset = release.assets.find(candidate => candidate?.name === name); + if (!asset) { + throw new Error(`Dart Sass ${version} has no release asset for this runner: ${name}.`); + } + if (typeof asset.digest !== 'string' || !/^sha256:[a-fA-F0-9]{64}$/.test(asset.digest)) { + throw new Error(`Dart Sass asset ${name} has no valid GitHub API SHA-256 digest.`); + } + const url = `https://github.com/sass/dart-sass/releases/download/${version}/${name}`; + if (asset.browser_download_url !== url) { + throw new Error(`Unexpected download URL for Dart Sass asset ${name}.`); + } + const archive = await tc.downloadTool(url); + await verifyDartSassArchive(archive, asset.digest); + // Keep the launcher and its sibling src runtime together, including on Windows. + const extracted = name.endsWith('.zip') + ? await tc.extractZip(archive) + : await tc.extractTar(archive); + core.addPath(path.join(extracted, 'dart-sass')); + core.info(`Dart Sass version: ${version}`); +} diff --git a/src/main.ts b/src/main.ts index 2e375e2..8a11175 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3,6 +3,7 @@ import * as exec from '@actions/exec'; import {getLatestVersion} from './get-latest-version'; import {installer} from './installer'; import {Tool} from './constants'; +import {installDartSass} from './install-dart-sass'; export interface ActionResult { exitcode: number; @@ -47,6 +48,7 @@ export async function run(): Promise { core.info(`${Tool.Name} version: ${installVersion}`); await installer(installVersion); + await installDartSass(core.getInput('dart-sass-version'), core.getInput('github-token')); result = await showVersion(Tool.CmdName, [Tool.CmdOptVersion]); return result;