Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/actions/find/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ configuration option.

**Optional** Bool - whether to capture screenshots of scanned pages and include links to them in the issue

#### `timeout_per_url`

**Optional** Maximum time, in seconds, for one URL. Default: `300`. A timeout or failure stops the action without
filing issues or updating cached results.

#### `scans`

**Optional** Stringified JSON array of scans to perform. Core engines and local plugins use string names.
Expand All @@ -56,6 +61,7 @@ will be performed. See [the plugin docs](../../../PLUGINS.md#loading-plugins-fro
Absolute path to a JSON file containing the list of potential accessibility gaps. The action writes this file to a temporary directory and returns the absolute path. For example: `$RUNNER_TEMP/findings-<uuid>.json`.

The file will contain a JSON array of finding objects. For example:

```json
[]
```
4 changes: 4 additions & 0 deletions .github/actions/find/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ inputs:
description: 'Whether to ignore HTTPS errors when scanning URLs with self-signed certificates'
required: false
default: 'false'
timeout_per_url:
description: 'Maximum time in seconds for one URL; defaults to 300'
required: false
default: '300'

outputs:
findings_file:
Expand Down
62 changes: 34 additions & 28 deletions .github/actions/find/src/findForUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,18 @@ export async function findForUrl(
reducedMotion?: ReducedMotionPreference,
colorScheme?: ColorSchemePreference,
ignoreHttpsErrors: boolean = false,
browserEndpoint?: string,
): Promise<Finding[]> {
const {url, excludeSelectors, waitForSelectors} = urlConfig
const browser = await playwright.chromium.launch({
headless: true,
executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined,
})

// Scan processes use the supervisor's browser; direct callers own a new browser.
const browser = browserEndpoint
? await playwright.chromium.connect(browserEndpoint)
: await playwright.chromium.launch({
headless: true,
executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined,
})

const contextOptions = {
...(authContext?.toPlaywrightBrowserContextOptions() ?? {}),
...(reducedMotion ? {reducedMotion} : {}),
Expand All @@ -47,6 +53,7 @@ export async function findForUrl(
),
)

// Keep collected findings in memory until the complete browser lifecycle succeeds.
const findings: Finding[] = []
const addFinding = async (findingData: FindingInput) => {
let screenshotId
Expand All @@ -56,37 +63,36 @@ export async function findForUrl(
findings.push({...findingData, screenshotId, originalUrl: url})
}

try {
const scansContext = getScansContext()

if (scansContext.shouldRunPlugins) {
const plugins = await loadPlugins()
for (const plugin of plugins) {
if (scansContext.scansToPerform.includes(plugin.name)) {
core.info(`Running plugin: ${plugin.name}`)
await invokePlugin({
plugin,
page,
addFinding,
})
} else {
core.info(`Skipping plugin ${plugin.name} because it is not included in the 'scans' input`)
}
const scansContext = getScansContext()

// Run configured plugins before the built-in scanners share the same page.
if (scansContext.shouldRunPlugins) {
const plugins = await loadPlugins()
for (const plugin of plugins) {
if (scansContext.scansToPerform.includes(plugin.name)) {
core.info(`Running plugin: ${plugin.name}`)
await invokePlugin({
plugin,
page,
addFinding,
})
} else {
core.info(`Skipping plugin ${plugin.name} because it is not included in the 'scans' input`)
}
}
}

if (scansContext.shouldPerformAxeScan) {
await runAxeScan({page, addFinding, excludeSelectors})
}
if (scansContext.shouldPerformAxeScan) {
await runAxeScan({page, addFinding, excludeSelectors})
}

if (scansContext.shouldPerformAccesslintScan) {
await runAccesslintScan({page, addFinding})
}
} catch (e) {
core.error(`Error during accessibility scan: ${e}`)
if (scansContext.shouldPerformAccesslintScan) {
await runAccesslintScan({page, addFinding})
}

return findings
} finally {
// Close the context first, then ensure the browser is closed even if context cleanup fails.
try {
await context?.close()
} finally {
Expand Down
24 changes: 9 additions & 15 deletions .github/actions/find/src/generateScreenshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import * as core from '@actions/core'
const SCREENSHOT_DIR = path.join(process.env.GITHUB_WORKSPACE || process.cwd(), '.screenshots')

export const generateScreenshots = async function (page: Page) {
let screenshotId: string | undefined
// Ensure screenshot directory exists
if (!fs.existsSync(SCREENSHOT_DIR)) {
fs.mkdirSync(SCREENSHOT_DIR, {recursive: true})
Expand All @@ -18,22 +17,17 @@ export const generateScreenshots = async function (page: Page) {
core.info(`Using existing screenshot directory ${SCREENSHOT_DIR}`)
}

try {
const screenshotBuffer = await page.screenshot({
fullPage: true,
type: 'png',
})
const screenshotBuffer = await page.screenshot({
fullPage: true,
type: 'png',
})

screenshotId = crypto.randomUUID()
const filename = `${screenshotId}.png`
const filepath = path.join(SCREENSHOT_DIR, filename)
const screenshotId = crypto.randomUUID()
const filename = `${screenshotId}.png`
const filepath = path.join(SCREENSHOT_DIR, filename)

fs.writeFileSync(filepath, screenshotBuffer)
core.info(`Screenshot saved: ${filename}`)
} catch (error) {
core.error(`Failed to capture/save screenshot: ${error}`)
screenshotId = undefined
}
fs.writeFileSync(filepath, screenshotBuffer)
core.info(`Screenshot saved: ${filename}`)

return screenshotId
}
86 changes: 77 additions & 9 deletions .github/actions/find/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,46 @@ import path from 'node:path'
import * as core from '@actions/core'
import {AuthContext} from './AuthContext.js'
import {findForUrl} from './findForUrl.js'
import {runScanInChildProcess, type ScanRequest, type ScanResponse} from './processSupervisor.js'

export default async function () {
core.info("Starting 'find' action")

// Load action inputs before starting any scan process.
const urlConfigs = loadUrlConfigs()
const urls = loadUrls({urlConfigs})
const reducedMotion = loadReducedMotion()
const colorScheme = loadColorScheme()
const ignoreHttpsErrors = loadIgnoreHttpsErrors()
const timeoutPerUrl = loadTimeoutPerUrl()

const actualUrls = urlConfigs || urls || []

const authContextInput: AuthContextInput = JSON.parse(core.getInput('auth_context', {required: false}) || '{}')
const authContext = new AuthContext(authContextInput)
const includeScreenshots = core.getInput('include_screenshots', {required: false}) !== 'false'

// Scan URLs one at a time so only one scan process and browser process group exists.
const findings = []
for (const urlConfig of actualUrls) {
const {url} = urlConfig
core.info(`Preparing to scan ${url}`)
const findingsForUrl = await findForUrl(
urlConfig,
authContext,
includeScreenshots,
reducedMotion,
colorScheme,
ignoreHttpsErrors,
)
let findingsForUrl
try {
findingsForUrl = await runScanInChildProcess(
{
urlConfig,
authContextInput,
includeScreenshots,
reducedMotion,
colorScheme,
ignoreHttpsErrors,
},
timeoutPerUrl,
)
} catch (error) {
throw new Error(`Scan incomplete for ${url}: ${errorMessage(error)}`, {cause: error})
}

if (findingsForUrl.length === 0) {
core.info(`No accessibility gaps were found on ${url}`)
continue
Expand All @@ -39,6 +52,7 @@ export default async function () {
core.info(`Found ${findingsForUrl.length} findings for ${url}`)
}

// Publish output only after the complete URL set has succeeded.
const findingsPath = path.join(process.env.RUNNER_TEMP || '/tmp', `findings-${crypto.randomUUID()}.json`)
fs.writeFileSync(findingsPath, JSON.stringify(findings))
core.setOutput('findings_file', findingsPath)
Expand All @@ -48,6 +62,51 @@ export default async function () {
core.info("Finished 'find' action")
}

if (process.env.ACCESSIBILITY_SCANNER_SCAN_PROCESS === '1') {
process.once('message', request => {
void processScanRequest(request as ScanRequest)
})
}

async function processScanRequest(request: ScanRequest) {
try {
const findings = await findForUrl(
request.urlConfig,
new AuthContext(request.authContextInput),
request.includeScreenshots,
request.reducedMotion,
request.colorScheme,
request.ignoreHttpsErrors,
request.browserEndpoint,
)

await sendScanResponse({type: 'result', findings})
} catch (error) {
process.exitCode = 1
await sendScanResponse({type: 'error', error: errorMessage(error)})
} finally {
process.disconnect?.()
}
}

async function sendScanResponse(response: ScanResponse) {
const send = process.send
if (!send || !process.connected) {
throw new Error('Scan process IPC is unavailable')
}

await new Promise<void>((resolve, reject) => {
send.call(process, response, error => {
if (error) reject(error)
else resolve()
})
})
}

function errorMessage(error: unknown) {
return error instanceof Error ? error.message : String(error)
}

function loadUrlConfigs() {
const urlConfigInput = core.getInput('url_configs', {required: false})
if (!urlConfigInput) return
Expand Down Expand Up @@ -120,3 +179,12 @@ function loadColorScheme() {
function loadIgnoreHttpsErrors() {
return core.getInput('ignore_https_errors', {required: false}).toLowerCase() === 'true'
}

function loadTimeoutPerUrl() {
const input = core.getInput('timeout_per_url', {required: false}) || '300'
const seconds = Number(input)
if (!Number.isSafeInteger(seconds) || seconds <= 0 || seconds > 2_147_483) {
throw new Error("Input 'timeout_per_url' must be a positive whole number less than 2,147,484.")
}
return seconds
}
5 changes: 3 additions & 2 deletions .github/actions/find/src/pluginManager/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,14 @@ export async function loadPlugins() {
await loadCustomPlugins()
await loadNpmPlugins()
}
} catch {
} catch (error) {
plugins.length = 0
core.error(abortError)
throw error
} finally {
pluginsLoaded = true
return plugins
}
return plugins
}

export const abortError = `
Expand Down
Loading
Loading