From 3082589ebacab02897203a2de04431beac0b6f9b Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:02:46 -0800 Subject: [PATCH] Move Changesets versioning and tagging to Azure Pipelines --- .github/workflows/publish-packages.yml | 64 -- build/azure-pipelines/changesets.mjs | 178 +++++ build/azure-pipelines/changesets.yml | 48 ++ .../steps/create-github-app-token.yml | 624 ++++++++++++++++++ 4 files changed, 850 insertions(+), 64 deletions(-) delete mode 100644 .github/workflows/publish-packages.yml create mode 100644 build/azure-pipelines/changesets.mjs create mode 100644 build/azure-pipelines/changesets.yml create mode 100644 build/azure-pipelines/steps/create-github-app-token.yml diff --git a/.github/workflows/publish-packages.yml b/.github/workflows/publish-packages.yml deleted file mode 100644 index 54afcc17aa45..000000000000 --- a/.github/workflows/publish-packages.yml +++ /dev/null @@ -1,64 +0,0 @@ -name: Publish packages - -on: - push: - branches: [v2] - workflow_dispatch: - -permissions: - contents: read - id-token: write - -concurrency: ${{ github.workflow }}-${{ github.ref }} - -jobs: - build: - runs-on: ubuntu-latest - environment: - name: azure - deployment: false - if: github.repository == 'microsoft/TypeScript-Website' - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - filter: blob:none - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: "24.x" - - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - - - run: pnpm install - - - uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 - with: - client-id: ${{ vars.AZURE_CLIENT_ID }} - tenant-id: ${{ vars.AZURE_TENANT_ID }} - subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} - - - name: Create GitHub App token - id: app-token - uses: microsoft/create-github-app-token-via-key-vault@5ba0d436e9c3cac52feff4d1f2f66f9698ce4a2d # v1 - with: - client-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID }} - key-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID }} - owner: microsoft - repositories: TypeScript-Website - permission-contents: write - permission-pull-requests: write - - name: Configure git for GitHub App token - shell: bash - env: - GITHUB_APP_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - set -euo pipefail - basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GITHUB_APP_TOKEN).toString("base64"))')" - echo "::add-mask::$basic_auth" - git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" - - uses: changesets/action@ae32849d5ba541f9ae29e40e22a623bc13562f51 # v2.1.2 - with: - github-token: ${{ steps.app-token.outputs.token }} - # Packages are published to npm by build/azure-pipelines/release.yml. - publish-script: pnpm changeset git-tag diff --git a/build/azure-pipelines/changesets.mjs b/build/azure-pipelines/changesets.mjs new file mode 100644 index 000000000000..276e5ba61e2c --- /dev/null +++ b/build/azure-pipelines/changesets.mjs @@ -0,0 +1,178 @@ +// Opens or updates the "Version Packages" PR while changesets are pending. +// Once that PR is merged, tags the new versions and creates GitHub releases. + +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const pipelinePath = "build/azure-pipelines/changesets.yml"; +const maxBodyLength = 60000; + +function requiredEnv(name) { + const value = process.env[name]; + if (!value) throw new Error(`${name} is required.`); + return value; +} + +const repository = requiredEnv("GITHUB_REPOSITORY"); +const token = requiredEnv("GH_TOKEN"); +const botName = "typescript-automation[bot]"; +const botEmail = "290192711+typescript-automation[bot]@users.noreply.github.com"; +const env = { + ...process.env, + GITHUB_TOKEN: token, + GIT_AUTHOR_NAME: botName, + GIT_AUTHOR_EMAIL: botEmail, + GIT_COMMITTER_NAME: botName, + GIT_COMMITTER_EMAIL: botEmail, +}; + +function run(command, args, input, extraEnv) { + console.log(`> ${command} ${args.join(" ")}`); + return execFileSync(command, args, { env: { ...env, ...extraEnv }, input, encoding: "utf8", stdio: ["pipe", "pipe", "inherit"], maxBuffer: 64 * 1024 * 1024 }); +} + +function changesetOutput(args) { + const outputPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "changesets-")), "output"); + process.stdout.write(run("pnpm", ["changeset", ...args], undefined, { CHANGESETS_OUTPUT: outputPath })); + return fs.existsSync(outputPath) ? fs.readFileSync(outputPath, "utf8") : ""; +} + +function githubApi(apiPath, method = "GET", body) { + const args = ["api", "--method", method, `repos/${repository}/${apiPath}`]; + if (body) args.push("--input", "-"); + return JSON.parse(run("gh", args, body && JSON.stringify(body))); +} + +const basicAuth = Buffer.from(`x-access-token:${token}`).toString("base64"); +console.log(`##vso[task.setsecret]${basicAuth}`); +function push(args) { + run("git", ["push", `https://github.com/${repository}.git`, ...args], undefined, { + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader", + GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basicAuth}`, + }); +} + +// Returns the CHANGELOG.md section for a version, the same section +// changesets/action uses for version PR bodies and release notes. +function getChangelogEntry(packageDir, version) { + const changelogPath = path.join(packageDir, "CHANGELOG.md"); + if (!fs.existsSync(changelogPath)) return ""; + + let fence; + let depth; + const content = []; + for (const line of fs.readFileSync(changelogPath, "utf8").split(/\r?\n/)) { + const fenceMatch = /^ {0,3}(`{3,}|~{3,})/.exec(line); + if (fence) { + if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) fence = undefined; + } + else if (fenceMatch) { + fence = fenceMatch[1]; + } + else { + const heading = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/.exec(line); + if (heading) { + if (depth === undefined) { + if ((heading[2] ?? "").trim() === version) depth = heading[1].length; + continue; + } + if (heading[1].length <= depth) break; + } + } + if (depth !== undefined) content.push(line); + } + return content.join("\n").trim(); +} + +function getPackageDirs() { + const packages = JSON.parse(run("pnpm", ["list", "--recursive", "--depth", "-1", "--json"])); + return new Map(packages.map(pkg => [pkg.name, pkg.path])); +} + +function tagReleases() { + const tags = changesetOutput(["git-tag"]).split("\n").filter(Boolean).map(line => JSON.parse(line)); + if (tags.length === 0) return; + + push(tags.map(({ tag }) => `refs/tags/${tag}`)); + const packageDirs = getPackageDirs(); + for (const { tag, packageName } of tags) { + const version = tag.slice(packageName.length + 1); + const release = githubApi("releases", "POST", { + tag_name: tag, + name: tag, + body: getChangelogEntry(packageDirs.get(packageName), version), + prerelease: version.includes("-"), + }); + console.log(`Created ${release.html_url}`); + } +} + +function createBody(baseBranch, releases, preState, includeEntries) { + const lines = [ + `This PR was opened by the Changesets pipeline (\`${pipelinePath}\`). When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to ${baseBranch}, this PR will be updated.`, + "", + ]; + if (preState?.mode === "pre") { + lines.push( + `> [!IMPORTANT]`, + `> \`${baseBranch}\` is in **pre mode**, so this branch contains prereleases. To exit pre mode, run \`changeset pre exit\` on \`${baseBranch}\`.`, + "", + ); + } + lines.push("# Releases", ""); + if (!includeEntries) { + lines.push("> The changelog information of each package has been omitted from this message, as the content exceeds the size limit.", ""); + } + for (const { name, newVersion, entry } of releases) { + lines.push(`## ${name}@${newVersion}`, ""); + if (includeEntries && entry) lines.push(entry, ""); + } + return lines.join("\n"); +} + +function versionPackages(baseBranch, plan) { + const versionBranch = `changeset-release/${baseBranch}`; + const title = plan.preState?.mode === "pre" ? `Version Packages (${plan.preState.tag})` : "Version Packages"; + + run("git", ["switch", "--force-create", versionBranch]); + process.stdout.write(run("pnpm", ["changeset", "version"])); + run("git", ["add", "--all"]); + run("git", ["-c", "core.hooksPath=/dev/null", "commit", "--message", title]); + push(["--force", `HEAD:refs/heads/${versionBranch}`]); + + const bumpOrder = ["major", "minor", "patch"]; + const packageDirs = getPackageDirs(); + const releases = plan.releases + .filter(release => release.type !== "none") + .sort((a, b) => bumpOrder.indexOf(a.type) - bumpOrder.indexOf(b.type)) + .map(release => ({ ...release, entry: getChangelogEntry(packageDirs.get(release.name), release.newVersion) })); + + let body = createBody(baseBranch, releases, plan.preState, true); + if (body.length > maxBodyLength) body = createBody(baseBranch, releases, plan.preState, false); + + const [owner] = repository.split("/"); + const query = new URLSearchParams({ state: "open", base: baseBranch, head: `${owner}:${versionBranch}` }); + const [existing] = githubApi(`pulls?${query}`); + const pr = existing + ? githubApi(`pulls/${existing.number}`, "PATCH", { title, body }) + : githubApi("pulls", "POST", { base: baseBranch, head: versionBranch, title, body }); + console.log(`${existing ? "Updated" : "Created"} ${pr.html_url}`); +} + +const { baseBranch } = JSON.parse(fs.readFileSync(".changeset/config.json", "utf8")); +// `changeset status` compares the working tree against a local base branch. +run("git", ["switch", "--force-create", baseBranch]); +const plan = JSON.parse(changesetOutput(["status"])); + +if (plan.changesets.length === 0) { + tagReleases(); +} +else if (plan.changesets.every(changeset => changeset.releases.length === 0)) { + console.log("All pending changesets are empty; not creating a version PR."); +} +else { + versionPackages(baseBranch, plan); +} diff --git a/build/azure-pipelines/changesets.yml b/build/azure-pipelines/changesets.yml new file mode 100644 index 000000000000..dc5c4900159c --- /dev/null +++ b/build/azure-pipelines/changesets.yml @@ -0,0 +1,48 @@ +trigger: + batch: true + branches: + include: + - v2 +pr: none + +variables: + - name: TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID + value: Iv23li4GolzJSEp1mzHI + - name: TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID + value: https://jststeam-passwords.vault.azure.net/keys/typescript-automation + +jobs: + - ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/v2') }}: + - job: Changesets + displayName: Version or tag packages + pool: + vmImage: ubuntu-latest + steps: + # The changelog generator reads the commit that added each changeset. + - checkout: self + fetchDepth: 0 + fetchFilter: blob:none + fetchTags: false + + - task: UseNode@1 + displayName: Use Node 24.x + inputs: + version: 24.x + + - bash: | + set -euo pipefail + npm install --global "$(jq -r '.packageManager' package.json)" + pnpm install --frozen-lockfile + displayName: Install dependencies + + - template: /build/azure-pipelines/steps/create-github-app-token.yml@self + parameters: + azureSubscription: typescript-automation-signing + repositories: TypeScript-Website + permissions: contents:write,pull_requests:write + insertSteps: + - bash: node build/azure-pipelines/changesets.mjs + displayName: Version or tag packages + env: + GH_TOKEN: $(GH_TOKEN) + GITHUB_REPOSITORY: microsoft/TypeScript-Website diff --git a/build/azure-pipelines/steps/create-github-app-token.yml b/build/azure-pipelines/steps/create-github-app-token.yml new file mode 100644 index 000000000000..8b5d4ffe8367 --- /dev/null +++ b/build/azure-pipelines/steps/create-github-app-token.yml @@ -0,0 +1,624 @@ +# Step template for creating a GitHub App token via Azure Key Vault. +# This template can be used in release jobs where checkout is not available. +# The CLI script from microsoft/create-github-app-token-via-key-vault is inlined below. +# +# The token is created and stored in an Azure Pipelines variable (default: GH_TOKEN). +# A revocation step runs at the end with condition: always(). +# To use the token, add your steps between this template's create and revoke steps +# by setting insertSteps. + +parameters: + - name: azureSubscription + type: string + default: 'TypeScript Public CI' + - name: owner + type: string + default: 'microsoft' + - name: repositories + type: string + - name: permissions + type: string + - name: tokenVariable + type: string + default: 'GH_TOKEN' + - name: condition + type: string + default: succeeded() + - name: revokeCondition + type: string + default: always() + - name: insertSteps + type: stepList + default: [] + +steps: + - task: AzureCLI@2 + displayName: Create GitHub App token + condition: ${{ parameters.condition }} + inputs: + azureSubscription: ${{ parameters.azureSubscription }} + scriptType: pscore + scriptLocation: inlineScript + inlineScript: | + @' + "use strict"; + + // src/api.ts + var defaultRefreshWindowMs = 5 * 60 * 1e3; + var defaultGitHubApiUrl = "https://api.github.com"; + var transientRetryCount = 3; + var GitHubRequestError = class extends Error { + status; + constructor(message, status) { + super(message); + this.status = status; + } + }; + function assertValue(value, message) { + if (!value) { + throw new Error(message); + } + return value; + } + function base64url(value) { + return Buffer.from(value).toString("base64url"); + } + async function sleep(ms) { + await new Promise((resolve) => setTimeout(resolve, ms)); + } + function isRetryableError(error) { + return error instanceof GitHubRequestError ? error.status >= 500 : error instanceof TypeError; + } + async function retryTransient(operation) { + for (let attempt = 0; ; attempt++) { + try { + return await operation(); + } catch (error) { + if (attempt >= transientRetryCount || !isRetryableError(error)) { + throw error; + } + await sleep(2 ** attempt * 1e3); + } + } + } + function splitRepositoryNames(repositories) { + if (Array.isArray(repositories)) { + return repositories.map((repo) => `${repo}`.trim()).filter(Boolean); + } + if (typeof repositories === "string") { + return repositories.split(/[,\n]/).map((repo) => repo.trim()).filter(Boolean); + } + return []; + } + function stableObject(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return value; + } + return Object.fromEntries( + Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, stableObject(entry)]) + ); + } + function githubHeaders(token, json = false) { + return { + "Accept": "application/vnd.github+json", + "Authorization": `Bearer ${token}`, + ...json ? { "Content-Type": "application/json" } : {}, + "X-GitHub-Api-Version": "2022-11-28" + }; + } + function isRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); + } + function requiredIntegerProperty(value, property, failureMessage) { + const propertyValue = isRecord(value) ? value[property] : void 0; + if (typeof propertyValue !== "number" || !Number.isInteger(propertyValue)) { + throw new Error(failureMessage); + } + return propertyValue; + } + function requiredStringProperty(value, property, failureMessage) { + const propertyValue = isRecord(value) ? value[property] : void 0; + if (typeof propertyValue !== "string" || !propertyValue) { + throw new Error(failureMessage); + } + return propertyValue; + } + function validatePermissionName(key) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) { + throw new Error(`Invalid permission name: ${key}`); + } + } + function validatePermissionLevel(key, level) { + if (level !== "read" && level !== "write" && level !== "admin") { + throw new Error(`Invalid permission level for ${key}: ${level}`); + } + return level; + } + function validatePermissions(value) { + if (value === void 0) { + return void 0; + } + if (!isRecord(value)) { + throw new Error("permissions must be an object"); + } + const permissions = {}; + for (const [key, level] of Object.entries(value)) { + validatePermissionName(key); + permissions[key] = validatePermissionLevel(key, level); + } + return Object.keys(permissions).length === 0 ? void 0 : permissions; + } + async function requestJson(url, init, failureMessage) { + const response = await fetch(url, init); + const body = await response.text(); + if (!response.ok) { + throw new GitHubRequestError( + `${failureMessage}: ${response.status} ${response.statusText}: ${body}`, + response.status + ); + } + try { + return JSON.parse(body); + } catch { + throw new Error(`${failureMessage}: GitHub returned invalid JSON`); + } + } + async function requestNoContent(url, init, failureMessage) { + const response = await fetch(url, init); + if (!response.ok) { + const body = await response.text(); + throw new GitHubRequestError( + `${failureMessage}: ${response.status} ${response.statusText}: ${body}`, + response.status + ); + } + } + function parseRepositoryInput(input) { + const parts = input.split("/"); + if (parts.length === 1 && parts[0]) { + return { input, name: parts[0] }; + } + if (parts.length === 2 && parts[0] && parts[1]) { + return { input, owner: parts[0], name: parts[1] }; + } + throw new Error(`Invalid repository '${input}'. Expected 'repository' or 'owner/repository'.`); + } + function normalizeRepositoryTarget(owner, repositories, defaultOwner) { + const parsedRepositories = repositories.map(parseRepositoryInput); + const repositoryOwner = parsedRepositories.find((repository) => repository.owner)?.owner; + const parsedOwner = owner || defaultOwner || repositoryOwner; + if (!parsedOwner) { + throw new Error("owner is required when repositories are provided"); + } + const mismatchedRepository = parsedRepositories.find( + (repository) => repository.owner && repository.owner.toLowerCase() !== parsedOwner.toLowerCase() + ); + if (mismatchedRepository) { + throw new Error( + `Repository '${mismatchedRepository.input}' includes owner '${mismatchedRepository.owner}', which does not match the resolved owner '${parsedOwner}'.` + ); + } + return { + owner: parsedOwner, + repositories: parsedRepositories.map((repository) => repository.name) + }; + } + function resolveInstallationTarget(options, defaultOwner) { + const repositories = splitRepositoryNames(options.repositories ?? options.repositoryNames); + if (options.enterprise) { + if (options.owner || repositories.length > 0) { + throw new Error("Cannot use 'enterprise' with 'owner' or 'repositories'"); + } + return { type: "enterprise", enterprise: options.enterprise }; + } + const owner = assertValue(options.owner ?? defaultOwner, "owner is required to discover installation ID"); + if (repositories.length === 0) { + return { type: "owner", owner }; + } + return { type: "repository", owner, repositories }; + } + function createGitHubAppAuth(options) { + assertValue(options.appClientId, "appClientId is required"); + assertValue(options.signer, "signer is required"); + const appClientId = options.appClientId; + const signer = options.signer; + const defaultOwner = options.defaultOwner; + const refreshWindowMs = options.refreshWindowMs ?? defaultRefreshWindowMs; + const githubApiUrl = options.githubApiUrl ?? defaultGitHubApiUrl; + const installationCache = /* @__PURE__ */ new Map(); + const tokenCache = /* @__PURE__ */ new Map(); + async function createJwt() { + const now = Math.floor(Date.now() / 1e3); + const iat = now - 60; + const exp = now + 9 * 60; + const header = base64url(JSON.stringify({ typ: "JWT", alg: "RS256" })); + const payload = base64url(JSON.stringify({ iat, exp, iss: appClientId })); + const signingInput = `${header}.${payload}`; + const signature = await signer(signingInput); + return `${signingInput}.${signature}`; + } + async function discoverInstallation(target) { + const cacheKey = JSON.stringify(target); + const cached = installationCache.get(cacheKey); + if (cached !== void 0) { + return cached; + } + const jwt = await createJwt(); + let installation; + switch (target.type) { + case "enterprise": + installation = await requestJson( + `${githubApiUrl}/enterprises/${target.enterprise}/installation`, + { headers: githubHeaders(jwt) }, + "Could not discover GitHub App installation ID" + ); + break; + case "owner": + try { + installation = await requestJson( + `${githubApiUrl}/orgs/${target.owner}/installation`, + { headers: githubHeaders(jwt) }, + "Could not discover GitHub App installation ID" + ); + } catch (error) { + if (!(error instanceof GitHubRequestError) || error.status !== 404) { + throw error; + } + installation = await requestJson( + `${githubApiUrl}/users/${target.owner}/installation`, + { headers: githubHeaders(jwt) }, + "Could not discover GitHub App installation ID" + ); + } + break; + case "repository": + installation = await requestJson( + `${githubApiUrl}/repos/${target.owner}/${assertValue(target.repositories[0], "repository is required")}/installation`, + { headers: githubHeaders(jwt) }, + "Could not discover GitHub App installation ID" + ); + break; + } + const result = { + id: requiredIntegerProperty(installation, "id", "GitHub did not return an installation ID"), + appSlug: requiredStringProperty(installation, "app_slug", "GitHub did not return an App slug") + }; + installationCache.set(cacheKey, result); + return result; + } + async function getInstallationToken(options2) { + const target = resolveInstallationTarget(options2, defaultOwner); + const permissions = validatePermissions(options2.permissions); + return retryTransient(async () => { + const installation = await discoverInstallation(target); + const repositories = target.type === "repository" ? target.repositories : []; + const cacheKey = JSON.stringify({ + installationId: installation.id, + repositories: [...repositories].sort(), + permissions: stableObject(permissions) + }); + const cached = tokenCache.get(cacheKey); + if (cached && Date.now() < new Date(cached.expiresAt).getTime() - refreshWindowMs) { + return cached; + } + const jwt = await createJwt(); + const body = { + ...repositories.length > 0 ? { repositories } : {}, + ...permissions ? { permissions } : {} + }; + const token = await requestJson( + `${githubApiUrl}/app/installations/${installation.id}/access_tokens`, + { + method: "POST", + headers: githubHeaders(jwt, true), + body: JSON.stringify(body) + }, + "Could not create GitHub App installation token" + ); + const result = { + token: requiredStringProperty(token, "token", "GitHub did not return an installation token"), + expiresAt: requiredStringProperty( + token, + "expires_at", + "GitHub did not return an installation token expiration" + ), + installationId: installation.id, + appSlug: installation.appSlug, + repositories, + permissions: isRecord(token) && isRecord(token["permissions"]) ? token["permissions"] : permissions ?? {} + }; + tokenCache.set(cacheKey, result); + return result; + }); + } + async function getToken(options2) { + return (await getInstallationToken(options2)).token; + } + async function revokeToken(token) { + await requestNoContent( + `${githubApiUrl}/installation/token`, + { + method: "DELETE", + headers: githubHeaders(token) + }, + "Could not revoke GitHub App installation token" + ); + } + return { + getInstallationToken, + getToken, + revokeToken + }; + } + + // src/azureCliSigner.ts + var import_node_child_process = require("node:child_process"); + var import_node_crypto = require("node:crypto"); + var cachedAzCommand; + function isRecord2(value) { + return typeof value === "object" && value !== null; + } + function base64ToBase64url(value) { + return value.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ""); + } + function commandExists(command) { + try { + (0, import_node_child_process.execFileSync)("where.exe", [command], { + encoding: "utf8", + stdio: ["ignore", "ignore", "ignore"] + }); + return true; + } catch { + return false; + } + } + function azCommand() { + if (cachedAzCommand) { + return cachedAzCommand; + } + if (process.platform !== "win32") { + cachedAzCommand = { command: "az", argsPrefix: [] }; + return cachedAzCommand; + } + for (const command of ["az.exe", "az.cmd", "az.bat", "az"]) { + if (commandExists(command)) { + cachedAzCommand = command.endsWith(".exe") ? { command, argsPrefix: [] } : { command: process.env["ComSpec"] || "cmd.exe", argsPrefix: ["/d", "/s", "/c", command] }; + return cachedAzCommand; + } + } + throw new Error("Azure CLI (`az`) was not found on PATH"); + } + function signDigest(keyId, digest) { + const { command, argsPrefix } = azCommand(); + try { + return (0, import_node_child_process.execFileSync)(command, [ + ...argsPrefix, + "keyvault", + "key", + "sign", + "--id", + keyId, + "--algorithm", + "RS256", + "--digest", + digest, + "--query", + "signature", + "--output", + "tsv", + "--only-show-errors" + ], { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"] + }).trim(); + } catch (error) { + if (isRecord2(error)) { + if (error["code"] === "ENOENT") { + throw new Error("Azure CLI (`az`) was not found on PATH"); + } + const errorStderr = error["stderr"]; + const stderr = typeof errorStderr === "string" ? errorStderr.trim() : ""; + if (typeof error["status"] === "number") { + throw new Error( + `Azure Key Vault signing failed with exit code ${error["status"]}${stderr ? `: ${stderr}` : ""}` + ); + } + } + throw new Error("Azure Key Vault signing failed"); + } + } + function createAzureCliKeyVaultSigner(keyId) { + if (!keyId) { + throw new Error("keyId is required"); + } + return async (signingInput) => { + const digest = (0, import_node_crypto.createHash)("sha256").update(signingInput).digest("base64"); + const signature = signDigest(keyId, digest); + if (!signature) { + throw new Error("Azure Key Vault did not return a signature"); + } + return base64ToBase64url(signature); + }; + } + + // src/proxy.ts + var proxyEnvironmentKeys = [ + "https_proxy", + "HTTPS_PROXY", + "http_proxy", + "HTTP_PROXY" + ]; + function proxyEnvironmentConfigured() { + return proxyEnvironmentKeys.some((key) => process.env[key]); + } + function nativeProxySupportEnabled() { + return process.env["NODE_USE_ENV_PROXY"] === "1"; + } + function ensureNativeProxySupport() { + if (!proxyEnvironmentConfigured() || nativeProxySupportEnabled()) { + return; + } + throw new Error( + "A proxy environment variable is set, but Node.js native proxy support is not enabled. Set NODE_USE_ENV_PROXY=1 before running this tool." + ); + } + + // src/cli.ts + function requiredEnv(name) { + const value = process.env[name]; + if (!value) { + throw new Error(`${name} must be set`); + } + return value; + } + function getAppClientId() { + const appClientId = process.env["APP_CLIENT_ID"]; + if (!appClientId) { + throw new Error("APP_CLIENT_ID must be set"); + } + return appClientId; + } + function validatePermissionName2(key) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) { + throw new Error(`Invalid permission name: ${key}`); + } + } + function validatePermissionLevel2(key, level) { + if (level !== "read" && level !== "write" && level !== "admin") { + throw new Error(`Invalid permission level for ${key}: ${level}`); + } + return level; + } + function parsePermissions(value) { + if (!value) { + return void 0; + } + const permissions = {}; + for (const entry of splitRepositoryNames(value)) { + const parts = entry.split(":"); + if (parts.length !== 2) { + throw new Error(`Permission entry must include an explicit level: ${entry}`); + } + const key = parts[0]?.trim(); + const rawLevel = parts[1]?.trim(); + if (!key) { + throw new Error(`Permission entry must include a permission name: ${entry}`); + } + validatePermissionName2(key); + if (Object.hasOwn(permissions, key)) { + throw new Error(`Duplicate permission: ${key}`); + } + permissions[key] = validatePermissionLevel2(key, rawLevel); + } + return Object.keys(permissions).length === 0 ? void 0 : permissions; + } + function validateVariableName(name, envName) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) { + throw new Error(`${envName} must be an environment-style variable name`); + } + } + function parseOutputMode(value) { + const output = (value || "stdout").trim().toLowerCase(); + if (output === "azure" || output === "azure-pipelines" || output === "stdout") { + return output; + } + throw new Error('OUTPUT must be "azure", "azure-pipelines", or "stdout"'); + } + function getTokenOptions() { + const enterprise = process.env["ENTERPRISE"]; + const owner = process.env["OWNER"]; + const repositories = splitRepositoryNames(process.env["REPOSITORIES"]); + const permissions = parsePermissions(process.env["PERMISSIONS"]); + if (enterprise) { + if (owner || repositories.length > 0) { + throw new Error("Cannot use ENTERPRISE with OWNER or REPOSITORIES"); + } + return { enterprise, permissions }; + } + if (repositories.length > 0) { + return { ...normalizeRepositoryTarget(owner, repositories, void 0), permissions }; + } + if (owner) { + return { owner, permissions }; + } + throw new Error("OWNER, REPOSITORIES, or ENTERPRISE must be set"); + } + function writeAzurePipelinesOutput(installationToken) { + const variableName = requiredEnv("AZURE_TOKEN_VARIABLE"); + validateVariableName(variableName, "AZURE_TOKEN_VARIABLE"); + process.stdout.write(`##vso[task.setvariable variable=${variableName};isSecret=true]${installationToken.token} + `); + } + function writeOutput(installationToken, output) { + switch (output) { + case "azure": + case "azure-pipelines": + writeAzurePipelinesOutput(installationToken); + break; + case "stdout": + process.stdout.write(`${installationToken.token} + `); + break; + } + } + function reportError(error) { + const message = error instanceof Error ? error.message : String(error); + console.error(`error: ${message}`); + } + async function main() { + ensureNativeProxySupport(); + const githubApiUrl = process.env["GITHUB_API_URL"] || "https://api.github.com"; + const revokeTokenValue = process.env["REVOKE_TOKEN"]; + if (revokeTokenValue) { + const response = await fetch(`${githubApiUrl}/installation/token`, { + method: "DELETE", + headers: { + "Accept": "application/vnd.github+json", + "Authorization": `Bearer ${revokeTokenValue}`, + "X-GitHub-Api-Version": "2022-11-28" + } + }); + if (!response.ok) { + const body = await response.text(); + throw new Error(`Could not revoke token: ${response.status} ${response.statusText}: ${body}`); + } + return; + } + const githubAuth = createGitHubAppAuth({ + appClientId: getAppClientId(), + signer: createAzureCliKeyVaultSigner(requiredEnv("KEY_ID")), + githubApiUrl + }); + const installationToken = await githubAuth.getInstallationToken(getTokenOptions()); + writeOutput(installationToken, parseOutputMode(process.env["OUTPUT"])); + } + void main().catch((error) => { + reportError(error); + process.exitCode = 1; + }); + '@ | Set-Content -LiteralPath "$(Agent.TempDirectory)/create-github-app-token.cjs" -Encoding utf8NoBOM + node "$(Agent.TempDirectory)/create-github-app-token.cjs" + env: + APP_CLIENT_ID: $(TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID) + KEY_ID: $(TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID) + OWNER: ${{ parameters.owner }} + REPOSITORIES: ${{ parameters.repositories }} + PERMISSIONS: ${{ parameters.permissions }} + OUTPUT: azure-pipelines + AZURE_TOKEN_VARIABLE: ${{ parameters.tokenVariable }} + NODE_USE_ENV_PROXY: "1" + + - ${{ each step in parameters.insertSteps }}: + - ${{ step }} + + - task: PowerShell@2 + displayName: Revoke GitHub App token + condition: ${{ parameters.revokeCondition }} + continueOnError: true + inputs: + targetType: inline + pwsh: true + script: node "$(Agent.TempDirectory)/create-github-app-token.cjs" + env: + REVOKE_TOKEN: $(${{ parameters.tokenVariable }}) + NODE_USE_ENV_PROXY: "1"