|
| 1 | +import crypto from 'node:crypto'; |
| 2 | +import fs from 'node:fs/promises'; |
| 3 | +import process from 'node:process'; |
| 4 | +import * as url from 'node:url'; |
| 5 | +import core from "@actions/core"; |
| 6 | +import playwright from 'playwright'; |
| 7 | + |
| 8 | +export default async function () { |
| 9 | + core.info("Starting 'auth' action"); |
| 10 | + |
| 11 | + let browser: playwright.Browser | undefined; |
| 12 | + let context: playwright.BrowserContext | undefined; |
| 13 | + let page: playwright.Page | undefined; |
| 14 | + try { |
| 15 | + // Get inputs |
| 16 | + const loginUrl = core.getInput('login_url', { required: true }); |
| 17 | + const username = core.getInput('username', { required: true }); |
| 18 | + const password = core.getInput('password', { required: true }); |
| 19 | + core.setSecret(password); |
| 20 | + |
| 21 | + // Create a temporary directory for authenticated session state |
| 22 | + const actionDirectory = `${url.fileURLToPath(new URL(import.meta.url))}/..`; |
| 23 | + const sessionStateDirectory = `${process.env.RUNNER_TEMP ?? actionDirectory}/.auth/${crypto.randomUUID()}`; |
| 24 | + await fs.mkdir(sessionStateDirectory, { recursive: true }); |
| 25 | + const sessionStatePath = `${sessionStateDirectory}/sessionState.json`; |
| 26 | + |
| 27 | + // Launch a headless browser |
| 28 | + browser = await playwright.chromium.launch({ headless: true, executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined }); |
| 29 | + context = await browser.newContext(); |
| 30 | + page = await context.newPage(); |
| 31 | + |
| 32 | + // Log in |
| 33 | + core.info("Navigating to login page"); |
| 34 | + await page.goto(loginUrl); |
| 35 | + core.info('Filling username'); |
| 36 | + await page.getByLabel(/username/i).fill(username); |
| 37 | + core.info('Filling password'); |
| 38 | + await page.getByLabel(/password/i).fill(password); |
| 39 | + core.info('Logging in'); |
| 40 | + await page.getByLabel(/password/i) |
| 41 | + .locator('xpath=ancestor::form') |
| 42 | + .evaluate((form) => (form as HTMLFormElement).submit()); |
| 43 | + |
| 44 | + // Write authenticated session state to a file and output its path |
| 45 | + await context.storageState({ path: sessionStatePath }); |
| 46 | + core.setOutput("session_state_path", sessionStatePath); |
| 47 | + core.info(`Wrote authenticated session state to ${sessionStatePath}`); |
| 48 | + } catch (error) { |
| 49 | + if (page) { |
| 50 | + core.info(`Errored at page URL: ${page.url()}`); |
| 51 | + } |
| 52 | + core.setFailed(`${error}`); |
| 53 | + process.exit(1); |
| 54 | + } finally { |
| 55 | + // Clean up |
| 56 | + await context?.close(); |
| 57 | + await browser?.close(); |
| 58 | + } |
| 59 | + |
| 60 | + core.info("Finished 'auth' action"); |
| 61 | +} |
0 commit comments