### Fetch Installation Details and Revoke Token Example Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/request.md Demonstrates how to use the request function to fetch an organization's installation ID and how to revoke an installation access token using their respective API routes. ```javascript import request from './lib/request.js'; // Get installation for organization const orgResponse = await request('GET /users/{username}/installation', { username: 'my-org', request: { hook: auth.hook, // Use authenticated requests } }); console.log(orgResponse.data.id); // Installation ID // Revoke token await request('DELETE /installation/token', { headers: { authorization: `token ${myToken}`, } }); ``` -------------------------------- ### Get User Installation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/MANIFEST.md Retrieves the installation for a given user. ```APIDOC ## GET /users/{username}/installation ### Description Retrieves the installation for a given user. ### Method GET ### Endpoint /users/{username}/installation ``` -------------------------------- ### Get Enterprise Installation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/MANIFEST.md Retrieves the installation for a given enterprise. ```APIDOC ## GET /enterprises/{enterprise}/installation ### Description Retrieves the installation for a given enterprise. ### Method GET ### Endpoint /enterprises/{enterprise}/installation ``` -------------------------------- ### Get Repository Installation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/MANIFEST.md Retrieves the installation for a given repository. ```APIDOC ## GET /repos/{owner}/{repo}/installation ### Description Retrieves the installation for a given repository. ### Method GET ### Endpoint /repos/{owner}/{repo}/installation ``` -------------------------------- ### Enterprise Installation Error Message Example Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md A user-friendly error message format for 404 responses when an enterprise installation is not found. ```text No enterprise installation found matching the enterprise slug "{enterprise}". ``` -------------------------------- ### Example Installation Response Structure Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/types.md Illustrates a common response structure for an installation object from the GitHub API. This includes fields like ID, app slug, permissions, and repository count. ```typescript { id: number; app_slug: string; permissions: Record; repositories_count: number; // ... other fields } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/actions/create-github-app-token/blob/main/CONTRIBUTING.md Run this command to install all necessary Node.js dependencies for the project. ```console npm install ``` -------------------------------- ### Create App Installation Access Token Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/MANIFEST.md Creates an access token for an app installation. ```APIDOC ## POST /app/installations/{id}/access_tokens ### Description Creates an access token for an app installation. ### Method POST ### Endpoint /app/installations/{id}/access_tokens ``` -------------------------------- ### Create Installation Access Token Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md Creates a time-limited access token for a GitHub App installation. This token can be used to authenticate API requests on behalf of the installation. ```APIDOC ## POST /app/installations/{installation_id}/access_tokens ### Description Creates a time-limited access token for a GitHub App installation. This token can be used to authenticate API requests on behalf of the installation. ### Method POST ### Endpoint `/app/installations/{installation_id}/access_tokens` ### Parameters #### Path Parameters - **installation_id** (number) - Required - The ID of the GitHub App installation. #### Request Body - **type** (string) - Required - Must be `"installation"`. - **installationId** (number) - Required - GitHub App installation ID. - **permissions** (object) - Optional - Permission overrides (e.g., `{ contents: 'write' }`). - **repositoryNames** (string[]) - Optional - Repository name restrictions. ### Response #### Success Response (201) - **token** (string) - Access token valid for 1 hour. - **expiresAt** (string) - ISO 8601 expiration timestamp. - **permissions** (object) - Granted permissions. #### Response Example ```json { "token": "your_generated_token", "expiresAt": "2023-10-27T10:00:00Z", "permissions": { "contents": "read" } } ``` ``` -------------------------------- ### Get User or Organization Installation Endpoint Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md Retrieve the GitHub App installation for a user or organization account. This endpoint is used during token creation when the 'owner' input is set without 'repositories'. ```bash GET /users/{username}/installation ``` -------------------------------- ### Get Enterprise Installation Endpoint Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md Retrieve the GitHub App installation for an enterprise account. This endpoint is used during token creation when the 'enterprise' input is set. ```bash GET /enterprises/{enterprise}/installation ``` -------------------------------- ### Get Enterprise Installation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md Retrieves the GitHub App installation for an enterprise account. This is used during token creation when an enterprise is specified. ```APIDOC ## GET /enterprises/{enterprise}/installation ### Description Retrieve GitHub App installation for an enterprise account. ### Method GET ### Endpoint /enterprises/{enterprise}/installation ### Parameters #### Path Parameters - **enterprise** (string) - Required - Enterprise account slug (URL-friendly name) ### Response #### Success Response (200) - **id** (number) - Installation ID - **app_slug** (string) - GitHub App slug - **permissions** (object) - Installation permissions ### Response Example { "id": 1, "app_slug": "my-app", "permissions": {} } ### Status Codes - 200: Success - installation found - 401: Unauthorized - invalid app credentials - 403: Forbidden - app not installed for this enterprise - 404: Not Found - enterprise doesn't exist or app not installed ``` -------------------------------- ### Example Workflow for Token Creation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/configuration.md This example demonstrates how to use the create-github-app-token action to generate a token for all repositories within an organization and then use that token to create a pull request. ```yaml jobs: token-creation: runs-on: ubuntu-latest steps: - name: Create token for all org repos id: app-token uses: actions/create-github-app-token@v3 with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: my-org permission-contents: read permission-pull-requests: write - name: Use token run: | gh pr create --title "My PR" env: GH_TOKEN: ${{ steps.app-token.outputs.token }} ``` -------------------------------- ### Get User or Organization Installation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md Retrieves the GitHub App installation for a specified user or organization account. This is used during token creation when the owner is provided without specific repositories. ```APIDOC ## GET /users/{username}/installation ### Description Retrieve GitHub App installation for a user or organization account. ### Method GET ### Endpoint /users/{username}/installation ### Parameters #### Path Parameters - **username** (string) - Required - The organization or user account name ### Response #### Success Response (200) - **id** (number) - Installation ID - **app_slug** (string) - GitHub App slug - **permissions** (object) - Installation permissions - **repositories_count** (number) - Count of accessible repositories ### Response Example { "id": 1, "app_slug": "my-app", "permissions": {}, "repositories_count": 10 } ### Status Codes - 200: Success - installation found - 401: Unauthorized - invalid app credentials - 403: Forbidden - app not installed for this account - 404: Not Found - account doesn't exist ``` -------------------------------- ### Get Repository Installation Endpoint Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md Retrieve the GitHub App installation for a specific repository. This endpoint is used during token creation when the 'repositories' input is set, by calling with the first repository. ```bash GET /repos/{owner}/{repo}/installation ``` -------------------------------- ### Get Repository Installation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md Retrieves the GitHub App installation for a specific repository. This is used during token creation when a repository is provided. ```APIDOC ## GET /repos/{owner}/{repo}/installation ### Description Retrieve GitHub App installation for a specific repository. ### Method GET ### Endpoint /repos/{owner}/{repo}/installation ### Parameters #### Path Parameters - **owner** (string) - Required - Repository owner name - **repo** (string) - Required - Repository name ### Response #### Success Response (200) - **id** (number) - Installation ID - **app_slug** (string) - GitHub App slug - **permissions** (object) - Installation permissions ### Response Example { "id": 1, "app_slug": "my-app", "permissions": {} } ### Status Codes - 200: Success - installation found - 401: Unauthorized - invalid app credentials - 403: Forbidden - app not installed for this repository - 404: Not Found - repository doesn't exist ``` -------------------------------- ### createInstallationAuthResult Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/modules.md Wraps an authentication result with installation metadata, including the token, expiration, installation ID, and app slug. It accepts the Octokit app auth strategy, installation object, optional permission overrides, and additional auth options. ```APIDOC ## createInstallationAuthResult(auth, installation, permissions, options) ### Description Wraps authentication result with installation metadata. ### Parameters - **auth** (object) - Octokit app auth strategy - **installation** (object) - Installation object from API - **permissions** (object) - Optional permission overrides - **options** (object) - Additional auth options (e.g., repositoryNames) ### Returns InstallationAuthResult with token, expiration, installation ID, app slug ### Internal Calls `auth({ type: 'installation', ... })` to create token ``` -------------------------------- ### Create Token for Another Owner's Installation Source: https://github.com/actions/create-github-app-token/blob/main/README.md This snippet demonstrates how to create a token for a GitHub App installation belonging to a different owner. Ensure the app is installed on that owner's account. ```yaml on: [issues] jobs: hello-world: runs-on: ubuntu-latest steps: - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: another-owner - uses: peter-evans/create-or-update-comment@v4 with: token: ${{ steps.app-token.outputs.token }} issue-number: ${{ github.event.issue.number }} body: "Hello, World!" ``` -------------------------------- ### GitHub Actions Workflow Example Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/QUICK_REFERENCE.md Example of a GitHub Actions workflow that uses the create-github-app-token action to generate a token with 'write' permissions for contents and 'read' for issues on specified repositories. ```yaml name: Example on: [push] jobs: create-token: runs-on: ubuntu-latest steps: - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: my-org repositories: repo1,repo2 permission-contents: write permission-issues: read - run: | gh pr create --title "Hello" env: GH_TOKEN: ${{ steps.app-token.outputs.token }} ``` -------------------------------- ### Error Properties for Installation Not Found Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/errors.md When an installation is not found, Octokit returns an error object with status, message, and documentation_url properties. ```javascript { status: 404, message: "Not Found", documentation_url: "https://docs.github.com/rest/..." } ``` -------------------------------- ### Usage Example for ensureNativeProxySupport Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/request.md Call this function at action startup to validate proxy configuration. It throws an error if a proxy is configured but native support isn't enabled, otherwise, requests will honor proxy environment variables. ```javascript import { ensureNativeProxySupport } from './lib/request.js'; // Call at action startup to validate proxy configuration ensureNativeProxySupport(); // Throws if proxy is configured but native support isn't enabled // If no exception, requests will honor HTTP_PROXY and HTTPS_PROXY env vars ``` -------------------------------- ### Create Tokens for Multiple Accounts with Matrix Strategy Source: https://github.com/actions/create-github-app-token/blob/main/README.md Utilize a matrix strategy to create tokens for multiple user or organization accounts. This example shows how to define owners and repositories within the matrix. ```yaml on: [workflow_dispatch] jobs: set-matrix: runs-on: ubuntu-latest outputs: matrix: ${{ steps.set.outputs.matrix }} steps: - id: set run: echo 'matrix=[{"owner":"owner1"},{"owner":"owner2","repos":["repo1"]}]' >>"$GITHUB_OUTPUT" use-matrix: name: "@${{ matrix.owners-and-repos.owner }} installation" needs: [set-matrix] runs-on: ubuntu-latest strategy: matrix: owners-and-repos: ${{ fromJson(needs.set-matrix.outputs.matrix) }} steps: - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: ${{ matrix.owners-and-repos.owner }} repositories: ${{ join(matrix.owners-and-repos.repos) }} - uses: octokit/request-action@v2.x id: get-installation-repositories with: route: GET /installation/repositories env: GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} - run: echo "$MULTILINE_JSON_STRING" env: MULTILINE_JSON_STRING: ${{ steps.get-installation-repositories.outputs.data }} ``` -------------------------------- ### post Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/modules.md Revokes the installation access token created in the main step. It reads the token and expiration from state, checks the skip-token-revoke input, skips revocation if the token has expired, and calls the DELETE /installation/token endpoint. ```APIDOC ## post(core, request) ### Description Revokes the installation access token created in main step. ### Parameters - **core** (object) - GitHub Actions core for logging and state management - **request** (function) - Pre-configured request function ### Responsibility 1. Read token and expiration from state 2. Check skip-token-revoke input 3. Skip if token expired 4. Call DELETE /installation/token endpoint 5. Log result (info on success, warning on failure) ``` -------------------------------- ### No Permissions Set Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/get-permissions-from-inputs.md Illustrates the behavior when no permission inputs are provided. The function returns 'undefined', indicating that the token should inherit all available installation permissions. ```javascript undefined ``` -------------------------------- ### Delete Installation Token Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/MANIFEST.md Deletes an existing installation token. ```APIDOC ## DELETE /installation/token ### Description Deletes an existing installation token. ### Method DELETE ### Endpoint /installation/token ``` -------------------------------- ### Create Token for an Enterprise Installation Source: https://github.com/actions/create-github-app-token/blob/main/README.md Use this configuration to generate a token for a GitHub App installed at the enterprise level. You need to provide the enterprise's slug. ```yaml on: [workflow_dispatch] jobs: hello-world: runs-on: ubuntu-latest steps: - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} enterprise: my-enterprise-slug - name: Call enterprise management REST API with gh run: | gh api /enterprises/my-enterprise-slug/apps/installable_organizations env: GH_TOKEN: ${{ steps.app-token.outputs.token }} ``` -------------------------------- ### JavaScript Example for Creating GitHub App Token Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/main.md This snippet demonstrates how to use the main function to create a GitHub App token. It includes necessary imports and error handling. Ensure you replace placeholder values with your actual app credentials and target details. ```javascript import { main } from './lib/main.js'; import * as core from '@actions/core'; import { createAppAuth } from '@octokit/auth-app'; import request from './lib/request.js'; try { await main( 'your-app-client-id', '-----BEGIN RSA PRIVATE KEY-----\n...key content...\n-----END RSA PRIVATE KEY-----', '', // enterprise (empty for non-enterprise) 'your-org', // owner ['repo1', 'repo2'], // repositories { contents: 'write', issues: 'read' }, // permissions core, createAppAuth, request, false // skipTokenRevoke ); console.log('Token created and available as output'); } catch (error) { core.setFailed(error.message); } ``` -------------------------------- ### Token Creation for Enterprise Installation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/README.md Create a token for an enterprise account. This is used when your GitHub App is installed at the enterprise level. ```yaml - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} enterprise: my-enterprise ``` -------------------------------- ### Basic Token Creation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/README.md Create a token for the current repository. This is the simplest way to get a token for your GitHub App. ```yaml - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - run: | gh pr create --title "My PR" env: GH_TOKEN: ${{ steps.app-token.outputs.token }} ``` -------------------------------- ### Example of Invalid Permissions Error Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/errors.md This snippet illustrates an invalid permissions error where the requested permission (e.g., contents: write) is not granted to the app's installation. ```yaml // App installation doesn't have contents permission with: permission-contents: write // Error: not granted ``` -------------------------------- ### Installation Authentication Result Type Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/types.md Represents the structure of the response received after a successful token creation operation. This includes the token, expiration, and installation details. ```typescript type InstallationAuthResult = { authentication: { token: string; expiresAt: string; type: "installation"; tokenType: "installation"; permissions: Record; }; installationId: number; appSlug: string; } ``` -------------------------------- ### getTokenFromEnterprise Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/modules.md Creates a token for an enterprise installation. It takes a pre-configured request function, Octokit app auth strategy, enterprise slug, and optional permission overrides. ```APIDOC ## getTokenFromEnterprise(request, auth, enterprise, permissions) ### Description Creates token for enterprise installation. ### Parameters - **request** (function) - Pre-configured request function - **auth** (object) - Octokit app auth strategy - **enterprise** (string) - Enterprise slug - **permissions** (object) - Optional permission overrides ### API Call `GET /enterprises/{enterprise}/installation` ### Error Handling Converts 404 to user-friendly "enterprise not found" error ``` -------------------------------- ### Invalid Repository Format Example Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/errors.md Illustrates incorrect formats for the repository input, such as extra segments, leading/trailing slashes, or empty strings. ```yaml # Correct: repositories: | repo1 repo2 owner/repo3 # Incorrect: repositories: owner/repo1/extra ``` -------------------------------- ### Main Function Signature for Token Creation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/README.md This is the core orchestration function for creating a GitHub App installation access token. It accepts various parameters for authentication, target resolution, and permission configuration. ```javascript export async function main( clientId, // string - GitHub App Client ID privateKey, // string - GitHub App private key (PEM) enterprise, // string - Enterprise slug (optional) owner, // string - Organization/user name (optional) repositories, // string[] - Repository names (optional) permissions, // Record | undefined - Permission overrides core, // @actions/core - GitHub Actions integration createAppAuth, // @octokit/auth-app.createAppAuth - Auth factory request, // @octokit/request - HTTP request function skipTokenRevoke // boolean - Skip token revocation ) ``` -------------------------------- ### getPermissionsFromInputs Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/get-permissions-from-inputs.md Extracts and normalizes GitHub App permissions from GitHub Actions input environment variables. It filters environment variables starting with 'INPUT_PERMISSION-', skips empty values, removes the prefix, converts to lowercase, and replaces hyphens with underscores to match GitHub API naming conventions. Returns an object mapping permission names to levels, or undefined if no permissions are set, in which case the token inherits all installation permissions. ```APIDOC ## getPermissionsFromInputs(env) ### Description Extracts and normalizes GitHub App permissions from GitHub Actions input environment variables. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **env** (`NodeJS.ProcessEnv`) - Required - Process environment object (typically `process.env`), which contains GitHub Actions input variables. ### Request Example ```javascript // Example when workflow sets: // with: // permission-contents: write // permission-pull-requests: read const env = { INPUT_PERMISSION-CONTENTS: 'write', INPUT_PERMISSION-PULL-REQUESTS: 'read', // ... other env vars }; const permissions = getPermissionsFromInputs(env); // permissions will be: { contents: 'write', pull_requests: 'read' } ``` ### Response #### Success Response - **Type:** `Record | undefined` - **Description:** An object mapping permission names to permission levels (e.g., `{ contents: 'write', issues: 'read' }`). Keys are normalized permission names in snake_case, and values are permission levels as strings ('read' or 'write'). Returns `undefined` if no permission inputs are provided, causing the token to inherit all installation permissions. #### Response Example ```json { "contents": "write", "pull_requests": "read" } ``` Or ```json undefined ``` ``` -------------------------------- ### File Locations for Project Structure Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/MANIFEST.md This snippet shows the directory structure and file locations for the project, including navigation guides, overviews, configuration, API details, error handling, types, architecture, and specific API references. ```text /workspace/home/output/ ├── INDEX.md (navigation guide) ├── QUICK_REFERENCE.md (lookup tables) ├── README.md (main overview) ├── configuration.md (inputs/outputs) ├── endpoints.md (GitHub API) ├── errors.md (error catalog) ├── types.md (type definitions) ├── modules.md (architecture) └── api-reference/ ├── main.md (token creation) ├── post.md (token revocation) ├── request.md (HTTP requests) └── get-permissions-from-inputs.md (permission parsing) Total: 12 files, 3,251 lines, 124 KB ``` -------------------------------- ### getTokenRetryDescription Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/modules.md Formats a target description for logging purposes, providing a human-readable string for the installation target. ```APIDOC ## getTokenRetryDescription(target) ### Description Formats target description for logging. ### Parameters - **target** (object) - InstallationTarget ### Returns Human-readable description (e.g., "my-org") ``` -------------------------------- ### Usage Example for post() Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/post.md Demonstrates how to use the post() function within a GitHub Actions workflow. This function is automatically called in the post-action step to revoke a previously created token. ```javascript import { post } from './lib/post.js'; import * as core from '@actions/core'; import request from './lib/request.js'; // This is called automatically in the post-action step // Token was previously saved by main() function await post(core, request); // - If token exists and hasn't expired: revokes it via API // - Otherwise: logs reason and returns ``` -------------------------------- ### Revoke Installation Access Token Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/endpoints.md Revokes an existing installation access token, invalidating it immediately. This is useful for cleaning up tokens after use. ```APIDOC ## DELETE /installation/token ### Description Revokes an existing installation access token, invalidating it immediately. This is useful for cleaning up tokens after use. ### Method DELETE ### Endpoint `/installation/token` ### Parameters #### Request Body - **Authorization** (string) - Required - Token to revoke (format: `token {token_value}`) ### Response #### Success Response (204) - No content on success. #### Error Response - **401** - Unauthorized - token invalid or expired - **403** - Forbidden - **404** - Not Found - token doesn't exist ``` -------------------------------- ### Repository Owner Mismatch Example Scenario Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/errors.md Demonstrates a scenario where the 'owner' input conflicts with the owner specified within the 'repositories' input, leading to an error. ```yaml with: owner: my-org # Owner = 'my-org' repositories: other-org/repo1 # Repository specifies 'other-org' ``` -------------------------------- ### Create Token with Specific Permissions Source: https://github.com/actions/create-github-app-token/blob/main/README.md Generate a token with specific permissions for issues. Ensure the selected permissions are granted to the app installation; otherwise, an error will occur. ```yaml on: [issues] jobs: hello-world: runs-on: ubuntu-latest steps: - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: ${{ github.repository_owner }} permission-issues: write - uses: peter-evans/create-or-update-comment@v4 with: token: ${{ steps.app-token.outputs.token }} issue-number: ${{ github.event.issue.number }} body: "Hello, World!" ``` -------------------------------- ### Decode Private Key Before Generating Token Source: https://github.com/actions/create-github-app-token/blob/main/README.md This example demonstrates how to decode a Base64 encoded private key from secrets before passing it to the create-github-app-token action. This is useful if your private key is stored in a Base64 format. ```yaml steps: - name: Decode the GitHub App Private Key id: decode run: | private_key=$(echo "${{ secrets.APP_PRIVATE_KEY }}" | base64 -d | awk 'BEGIN {ORS="\n"} {print}' | head -c -2) &> /dev/null echo "::add-mask::$private_key" echo "private-key=$private_key" >> "$GITHUB_OUTPUT" - name: Generate GitHub App Token id: app-token uses: actions/create-github-app-token@v3 with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ steps.decode.outputs.private-key }} ``` -------------------------------- ### Create Token for All Repositories Source: https://github.com/actions/create-github-app-token/blob/main/README.md Use this snippet to generate a token for all repositories within the current owner's GitHub App installation. Ensure you have set up the necessary client ID and private key. ```yaml on: [workflow_dispatch] jobs: hello-world: runs-on: ubuntu-latest steps: - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: ${{ github.repository_owner }} - uses: peter-evans/create-or-update-comment@v4 with: token: ${{ steps.app-token.outputs.token }} issue-number: ${{ github.event.issue.number }} body: "Hello, World!" ``` -------------------------------- ### ActionCore Interface Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/types.md The ActionCore interface provides methods for interacting with GitHub Actions core functionalities, such as getting inputs, setting outputs, and logging messages. ```APIDOC ## ActionCore Interface Interface for GitHub Actions core module (`@actions/core`). ```typescript interface ActionCore { getInput(name: string): string; getBooleanInput(name: string): boolean; setOutput(name: string, value: string | number): void; setSecret(secret: string): void; setFailed(message: string): void; saveState(name: string, value: string): void; getState(name: string): string; info(message: string): void; warning(message: string): void; error(message: string): void; } ``` **Methods Used:** | Method | Purpose | |--------|---------| | `getInput()` | Read action input by name | | `getBooleanInput()` | Read boolean action input | | `setOutput()` | Set action output | | `setSecret()` | Register string as secret (masked in logs) | | `setFailed()` | Mark step as failed with message | | `saveState()` | Save data for post-action step | | `getState()` | Retrieve data from main step | | `info()` | Log informational message | | `warning()` | Log warning message | | `error()` | Log error message | **Source:** `@actions/core` npm package ``` -------------------------------- ### Enterprise Installation Target Type Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/types.md Defines the structure for targeting an enterprise account when creating a token. Use this when you need to create a token scoped to an entire enterprise. ```typescript type EnterpriseInstallationTarget = { type: "enterprise"; enterprise: string; } ``` -------------------------------- ### Repository Installation Target Type Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/types.md Defines the structure for targeting specific repositories when creating a token. Use this to create a token with access limited to a list of named repositories within a given owner. ```typescript type RepositoryInstallationTarget = { type: "repository"; owner: string; repositories: string[]; } ``` -------------------------------- ### Owner Installation Target Type Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/types.md Defines the structure for targeting an organization or user account when creating a token. Use this to create a token that grants access to all repositories within a specified owner. ```typescript type OwnerInstallationTarget = { type: "owner"; owner: string; } ``` -------------------------------- ### Create Token for Multiple Specific Repositories Source: https://github.com/actions/create-github-app-token/blob/main/README.md Generate a token for a specific list of repositories within the current owner's installation. You can list repositories individually or use `${{ github.repository }}` to include the current one. ```yaml on: [issues] jobs: hello-world: runs-on: ubuntu-latest steps: - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: ${{ github.repository_owner }} repositories: | repo1 repo2 - uses: peter-evans/create-or-update-comment@v4 with: token: ${{ steps.app-token.outputs.token }} issue-number: ${{ github.event.issue.number }} body: "Hello, World!" ``` ```yaml repositories: ${{ github.repository }},repo2 ``` -------------------------------- ### Invalid Repository Format Error Message Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/errors.md This error occurs when the repository input does not conform to the expected 'repository' or 'owner/repository' format. Examples include too many segments or empty segments. ```text Invalid repository '{input}'. Expected 'repository' or 'owner/repository'. ``` -------------------------------- ### Create Git Committer String for App Installation Source: https://github.com/actions/create-github-app-token/blob/main/README.md Generate a Git committer string using the app's slug and bot user ID. This is useful for attributing commits made by the app's bot user. ```yaml on: [pull_request] jobs: auto-format: runs-on: ubuntu-latest steps: - uses: actions/create-github-app-token@v3 id: app-token with: # required client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - name: Get GitHub App User ID id: get-user-id run: echo "user-id=$(gh api "/users/${{ steps.app-token.outputs.app-slug }}[bot]" --jq .id)" >> "$GITHUB_OUTPUT" env: GH_TOKEN: ${{ steps.app-token.outputs.token }} - id: committer run: echo "string=${{ steps.app-token.outputs.app-slug }}[bot] <${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com>" >> "$GITHUB_OUTPUT" - run: echo "committer string is ${{ steps.committer.outputs.string }}" ``` -------------------------------- ### File Organization of create-github-app-token Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/modules.md Illustrates the directory structure for the create-github-app-token action, showing the main entry points, library files, bundled output, and test suite. ```plaintext create-github-app-token/ ├── main.js # Main action entry point ├── post.js # Post action entry point ├── action.yml # Action metadata ├── package.json # Dependencies and scripts ├── lib/ │ ├── main.js # Core orchestration logic │ ├── post.js # Token revocation logic │ ├── request.js # Configured request module │ └── get-permissions-from-inputs.js # Permission extraction ├── dist/ # Bundled compiled output │ ├── main.cjs # Bundled main for Node.js │ └── post.cjs # Bundled post for Node.js └── tests/ # Test suite ``` -------------------------------- ### Module Dependencies for main.js Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/QUICK_REFERENCE.md Lists the direct dependencies for the main entry point of the action, including core libraries and external modules. ```text main.js → lib/main.js → lib/request.js → lib/get-permissions-from-inputs.js → @actions/core → @octokit/auth-app → p-retry → is-network-error ``` -------------------------------- ### Run Local Tests Source: https://github.com/actions/create-github-app-token/blob/main/CONTRIBUTING.md Execute this command to run the project's test suite locally. Refer to tests/README.md for more details on the testing framework. ```console npm test ``` -------------------------------- ### Permissions Type Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/types.md Defines the type for GitHub App permissions, which can be a record mapping permission names to levels or undefined to inherit all installation permissions. ```typescript type Permissions = Record | undefined; ``` ```javascript // Example permissions object { "contents": "write", "issues": "read", "pull_requests": "write" } // Or undefined (inherits all installation permissions) undefined ``` -------------------------------- ### Run Workflow Against GitHub Enterprise Server Source: https://github.com/actions/create-github-app-token/blob/main/README.md This workflow demonstrates how to use the create-github-app-token action to generate a token for an organization in GitHub Enterprise Server and then use that token to create an issue. ```yaml on: [push] jobs: create_issue: runs-on: self-hosted steps: - name: Create GitHub App token id: create_token uses: actions/create-github-app-token@v3 with: client-id: ${{ vars.GHES_APP_CLIENT_ID }} private-key: ${{ secrets.GHES_APP_PRIVATE_KEY }} owner: ${{ vars.GHES_INSTALLATION_ORG }} github-api-url: ${{ vars.GITHUB_API_URL }} - name: Create issue uses: octokit/request-action@v2.x with: route: POST /repos/${{ github.repository }}/issues title: "New issue from workflow" body: "This is a new issue created from a GitHub Action workflow." env: GITHUB_TOKEN: ${{ steps.create_token.outputs.token }} ``` -------------------------------- ### Module Dependencies for post.js Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/QUICK_REFERENCE.md Lists the direct dependencies for the post-action script, primarily used for token revocation. ```text post.js → lib/post.js → lib/request.js → @actions/core → @octokit/request ``` -------------------------------- ### main() - Create GitHub App Token Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/main.md The core function that orchestrates GitHub App token creation. It takes various parameters to define the scope and authentication for the token. ```APIDOC ## main() - Create GitHub App Token ### Description This is the main action execution entry point that orchestrates GitHub App token creation. It handles authentication, installation target resolution, and token generation based on provided inputs. ### Function Signature ```javascript export async function main( clientId, privateKey, enterprise, owner, repositories, permissions, core, createAppAuth, request, skipTokenRevoke ) ``` ### Parameters #### Path Parameters - **clientId** (string) - Yes - GitHub App Client ID used for authentication - **privateKey** (string) - Yes - GitHub App private key (PEM format, escaped newlines converted to actual newlines) - **enterprise** (string) - No - Enterprise account slug; mutually exclusive with `owner` and `repositories` - **owner** (string) - No - Organization or user account name for token scope; defaults to current repository owner - **repositories** (string[]) - No - Array of repository names to scope token to; supports both bare names and `owner/repo` format - **permissions** (Record | undefined) - No - Map of permission names to permission levels (e.g., `{ contents: 'write', issues: 'read' }`); if undefined, inherits all installation permissions - **core** (import("@actions/core")) - Yes - GitHub Actions core module for logging and state management - **createAppAuth** (import("@octokit/auth-app").createAppAuth) - Yes - Octokit auth-app factory function for creating authentication strategy - **request** (import("@octokit/request").request) - Yes - Pre-configured request function with GitHub API defaults - **skipTokenRevoke** (boolean) - Yes - If true, token is not revoked in post-action step ### Return Type `Promise` - Sets GitHub Actions outputs and state but does not return a value. ### Outputs Set - **token** (string) - GitHub App installation access token (masked in logs) - **installation-id** (string | number) - GitHub App installation ID for the target scope - **app-slug** (string) - GitHub App slug identifier ### State Set (when `skipTokenRevoke` is false) - **token** (string) - Token stored for revocation in post-action step - **expiresAt** (string) - ISO 8601 timestamp when token expires ### Errors #### Input Validation - **Error:** "Cannot use 'enterprise' input with 'owner' or 'repositories' inputs" - **Condition:** Both `enterprise` and either `owner` or non-empty `repositories` are provided - **Error:** "Invalid repository '{input}'. Expected 'repository' or 'owner/repository'." - **Condition:** Repository input contains more than two slash-separated segments or empty segments - **Error:** "Repository '{owner}/{name}' includes owner '{repository.owner}', which does not match the resolved owner '{parsedOwner}'." - **Condition:** A repository in `repositories` array specifies an owner that doesn't match the resolved owner #### API Errors - **Error:** "No enterprise installation found matching the enterprise slug \"{enterprise}\"." - **Condition:** HTTP 404 response when requesting enterprise installation - **Network/Server Errors:** 5xx responses or network errors trigger automatic retry (3 attempts max) - **Retry Logic:** `lib/main.js:42-45` ``` -------------------------------- ### Token Creation for Multiple Repositories Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/README.md Create a token that grants access to a specific list of repositories within an organization. Ensure the 'owner' and 'repositories' inputs are correctly formatted. ```yaml - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: my-org repositories: | repo1 repo2 repo3 ``` -------------------------------- ### Post Function Signature for Token Revocation Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/README.md This function is responsible for revoking the installation access token at the end of a job. It retrieves saved state and calls the GitHub API to perform the revocation. ```javascript export async function post( core, // @actions/core - State and logging request // @octokit/request - HTTP requests ) ``` -------------------------------- ### Token Creation with GitHub Enterprise Server Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/README.md Use the action with a custom GitHub API endpoint for GitHub Enterprise Server instances. Ensure the 'github-api-url' is set correctly. ```yaml - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.GHES_APP_CLIENT_ID }} private-key: ${{ secrets.GHES_APP_PRIVATE_KEY }} github-api-url: https://ghes.example.com/api/v3 ``` -------------------------------- ### Configure Proxy Support Source: https://github.com/actions/create-github-app-token/blob/main/README.md This snippet shows how to configure proxy settings for the action. Ensure NODE_USE_ENV_PROXY is set to "1" to honor HTTP_PROXY and HTTPS_PROXY environment variables. ```yaml - uses: actions/create-github-app-token@v3 id: app-token env: HTTPS_PROXY: http://proxy.example.com:8080 NO_PROXY: github.example.com NODE_USE_ENV_PROXY: "1" with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} ``` -------------------------------- ### Default Request Module Export Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/request.md The default export is an Octokit request function pre-configured with a specific User-Agent header and the GitHub API Base URL. This setup identifies requests from the action and directs them to the correct API endpoint. ```javascript export default request.defaults({ headers: { "user-agent": "actions/create-github-app-token" }, baseUrl, }) ``` -------------------------------- ### post() - Revoke GitHub App Token Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/api-reference/post.md Revokes the GitHub App installation access token at the end of a GitHub Actions job step. This function is executed automatically as the post-action step. It checks for early exit conditions such as skipping revocation, no token in state, or an expired token before attempting to call the `DELETE /installation/token` endpoint. ```APIDOC ## post() - Revoke GitHub App Token ### Description Revokes the GitHub App installation access token at the end of the GitHub Actions job step. This is executed as the post-action step. ### Method `post(core, request)` ### Parameters #### Parameters - **core** (`import("@actions/core")`) - Required - GitHub Actions core module for state retrieval and logging - **request** (`import("@octokit/request").request`) - Required - Pre-configured request function with GitHub API defaults ### Return Type `Promise` - Does not return a value. ### Behavior #### Early Exit Conditions The function exits early without calling the revocation API in these cases: 1. `skip-token-revoke` input is true - Token revocation is disabled 2. No token in state - `core.getState("token")` returns empty string 3. Token has expired - Current time is past `expiresAt` timestamp - Calculated via `tokenExpiresIn(expiresAt) < 0` - Prevents calling GitHub API with an expired token #### Token Revocation When proceeding to revocation, the function: 1. Calls `DELETE /installation/token` endpoint 2. Passes token via authorization header: `authorization: token ${token}` 3. Logs success message on completion 4. Logs warning message if revocation fails (does not throw) ### Errors Token revocation failures are non-fatal and logged as warnings: - Network Errors: Connection failures, timeouts - HTTP Errors: 4xx or 5xx responses - Invalid Token: Token already revoked or invalid All errors result in a warning log message: `Token revocation failed: {error.message}` ### Usage Example ```javascript import { post } from './lib/post.js'; import * as core from '@actions/core'; import request from './lib/request.js'; // This is called automatically in the post-action step // Token was previously saved by main() function await post(core, request); // - If token exists and hasn't expired: revokes it via API // - Otherwise: logs reason and returns ``` ``` -------------------------------- ### createTokenRetryOptions Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/modules.md Creates retry configuration for token creation, including error handling for HTTP 5xx or network errors, logging of failed attempts, and a maximum of 3 retries. ```APIDOC ## createTokenRetryOptions(core, description) ### Description Creates retry configuration for token creation. ### Parameters - **core** (object) - GitHub Actions core for logging - **description** (string) - Target description for log messages ### Returns RetryOptions object ### Behavior - Retries on HTTP 5xx or network errors - Logs each failed attempt - Max 3 retries ``` -------------------------------- ### Create Token for Current Repository Source: https://github.com/actions/create-github-app-token/blob/main/README.md Use this snippet to create a GitHub App token for the current repository. Ensure your App's Client ID and private key are stored as repository variables and secrets. ```yaml name: Run tests on staging on: push: branches: - main jobs: hello-world: runs-on: ubuntu-latest steps: - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - uses: ./actions/staging-tests with: token: ${{ steps.app-token.outputs.token }} ``` -------------------------------- ### Retry Configuration for Failed Attempts Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/QUICK_REFERENCE.md Configuration object for retrying failed attempts when using the create-github-app-token action. Specifies conditions for retrying, actions on failed attempts, and the maximum number of retries. ```javascript { shouldRetry: (context) => error.status >= 500 || isNetworkError(error), onFailedAttempt: (context) => core.info(message), retries: 3 } ``` -------------------------------- ### Token Creation with Specific Permissions Source: https://github.com/actions/create-github-app-token/blob/main/_autodocs/README.md Create a token with read-only permissions for contents and pull requests. Use this when you need to limit the token's access. ```yaml - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} permission-contents: read permission-pull-requests: read ```