Skip to main content
jg-packages

Search

    GitHub

    jg-github

    GitHub App authentication for Node.js: app tokens, scoped installation tokens, webhook signatures, and rate-limit retry times.

    v0.2.1Node.jsESMMIT

    npm

    npm install jg-github

    pnpm

    pnpm add jg-github

    Usage

    Create an installation token for exactly the repositories and the permissions a job needs, and revoke it when the job is done:

    ts
    import { createInstallationToken, revokeInstallationToken } from 'jg-github';
    
    declare const privateKey: string;
    
    const { token, expiresAt } = await createInstallationToken({
      appId: 123456,
      privateKey,
      installationId: 12345678,
      repositories: ['app', 'docs'], // or repositoryIds: [101, 102]
      permissions: { contents: 'read', pull_requests: 'write' },
      userAgent: 'acme-release-bot',
    });
    try {
      // call the API with createGithubHeaders(token, { userAgent: 'acme-release-bot' })
    } finally {
      await revokeInstallationToken(token, { userAgent: 'acme-release-bot' });
    }

    permissions is required and can’t be empty, because GitHub grants every permission of the installation to a request without it. The repositories are named by name or by ID, never both, with no repeats. Anything else throws GITHUB_INVALID_ARGUMENT before a request is sent. GitHub’s answer must match the request exactly: only the selected repositories, the same ones, compared by name ignoring case or by ID as you named them, and the same permissions, plus the metadata: 'read' GitHub adds. A token that doesn’t match, or that had already expired, is revoked before the error is thrown, and the error’s isRevoked says whether that worked.

    Verify a webhook delivery before parsing its body:

    ts
    import { verifyGithubWebhookSignature } from 'jg-github';
    
    declare const rawBody: Buffer;
    declare const headers: Record<string, string | string[] | undefined>;
    declare const webhookSecret: string;
    
    const isAuthentic = verifyGithubWebhookSignature(
      rawBody,
      headers['x-hub-signature-256'],
      webhookSecret,
    );

    It’s false for a header that’s missing, repeated, longer than 71 characters, or not sha256= and 64 lowercase hexadecimal characters, and compares the signature in constant time.

    Find when to retry a rate limited request:

    ts
    import { getGithubRateLimitDeadline } from 'jg-github';
    
    declare const response: Response;
    
    const retryAt = getGithubRateLimitDeadline({
      status: response.status,
      headers: response.headers,
      retryCount: 0,
    }); // a Date, or null when the response isn't rate limited

    A 429 is rate limited, and so is a 403 with Retry-After, with no requests remaining, or with hasRateLimitMessage, and a success that used the last request. The deadline is the latest future one of Retry-After, as whole seconds or a strict IMF-fixdate, and x-ratelimit-reset when no requests remain; without one, it’s a minute from now, doubled for each retry already made.

    The rest of the API:

    • createGithubAppJwt({ appId, privateKey }), the App’s own JWT, signed with RS256, issued 60 seconds back and expiring 540 seconds ahead, inside GitHub’s ten-minute limit even with a clock a minute ahead. assertGithubAppPrivateKey(pem) checks the key at startup: an unencrypted RSA key, PKCS#1 or PKCS#8.
    • createGithubHeaders(token, { userAgent, apiVersion }), the headers every request sends, with X-GitHub-Api-Version set to GITHUB_API_VERSION unless you pass another.
    • buildGithubApiUrl(segments, query, { apiOrigin }) and buildGithubRawContentUrl(location, { rawContentOrigin }), which encode each value, so a branch’s / or a .. can’t change the path. apiOrigin, such as GitHub Enterprise Server’s https://ghe.example.com/api/v3, must be https, or http on a loopback host for a test server.

    Requests go through jg-fetch with redirect: 'error', a 10-second timeout, a 128 KiB response limit, and no retries, because creating or revoking a token twice isn’t safe.

    Errors

    Code When
    GITHUB_PRIVATE_KEY_INVALID The App’s private key isn’t an unencrypted RSA key, PEM-encoded as PKCS#1 or PKCS#8
    GITHUB_INVALID_ARGUMENT An argument isn’t valid, such as missing or empty permissions, a repeated repository, or an installation ID not digits
    GITHUB_REQUEST_FAILED A request fails: an error status, a redirect, a timeout, an abort, or no answer
    GITHUB_RESPONSE_INVALID GitHub’s answer isn’t in the expected format, or is larger than maxResponseBytes
    GITHUB_TOKEN_SCOPE_MISMATCH The granted token reaches other repositories, or has other permissions, than requested
    GITHUB_TOKEN_EXPIRED The granted token had already expired
    GITHUB_TOKEN_REVOKE_FAILED GitHub answers a revocation with anything but 204, or not at all

    GITHUB_REQUEST_FAILED’s data holds jg-fetch’s kind of failure, the status, and the rateLimitDeadline as an ISO string, or null. GITHUB_TOKEN_SCOPE_MISMATCH’s data says what differs, repository_selection, repositories, or permissions, and, like GITHUB_TOKEN_EXPIRED’s and GITHUB_RESPONSE_INVALID’s when GitHub granted a token, whether it was revoked. No error has a cause or holds a token, the App’s JWT, the private key, or a response body. verifyGithubWebhookSignature throws jg-crypto’s INVALID_HMAC_SECRET for an empty secret.

    Generated from TSDoc

    API reference

    Every export of [email protected], 30 in all, with its signature, its errors, and an example.

    Functions

    assertGithubAppPrivateKey

    function

    Checks that a GitHub App's private key can sign its JWTs: an unencrypted RSA key, PEM-encoded as PKCS#1, the RSA PRIVATE KEY GitHub downloads, or PKCS#8, the PRIVATE KEY it converts to. Run it at startup, so a bad key fails before the first request. The error never holds the key.

    Signature
    assertGithubAppPrivateKey(pem: string): void

    Parameters

    pemstring

    The key.

    Throws

    • GITHUB_PRIVATE_KEY_INVALIDThe GitHub App's private key isn't an unencrypted RSA private key.
    Example
    import { assertGithubAppPrivateKey } from 'jg-github';
    
    declare const privateKey: string;
    
    assertGithubAppPrivateKey(privateKey);

    buildGithubApiUrl

    function

    Builds a REST API URL from its path segments, each encoded on its own, so a branch's / becomes %2F and no value can climb out of the path, plus the query parameters.

    Signature
    buildGithubApiUrl(
      segments: readonly (string | number)[],
      query?: IGithubQuery,
      options?: IGithubApiUrlOptions,
    ): string

    Parameters

    segmentsreadonly (string | number)[]

    The path's segments, such as ['repos', owner, repository, 'branches', branch].

    query?IGithubQuery

    The query parameters; undefined ones are left out.

    Defaults to {}.

    options?IGithubApiUrlOptions

    The API's base URL, for GitHub Enterprise Server or a test server.

    Defaults to {}.

    Returns

    string

    The URL.

    Throws

    • GITHUB_INVALID_ARGUMENTAn argument isn't valid.
    Example
    import { buildGithubApiUrl } from 'jg-github';
    
    buildGithubApiUrl(['repos', 'acme', 'app', 'branches', 'feature/login'], { per_page: 100 });
    // 'https://api.github.com/repos/acme/app/branches/feature%2Flogin?per_page=100'

    buildGithubRawContentUrl

    function

    Builds the URL of a file's raw content at a ref, with the owner and the repository encoded as one segment each, and the ref's and the path's /s kept.

    Signature
    buildGithubRawContentUrl(
      location: IGithubRawContentLocation,
      options?: IGithubRawContentUrlOptions,
    ): string

    Parameters

    locationIGithubRawContentLocation

    The repository, the ref, and the file's path.

    options?IGithubRawContentUrlOptions

    The raw content's base URL, for a test server.

    Defaults to {}.

    Returns

    string

    The URL.

    Throws

    • GITHUB_INVALID_ARGUMENTAn argument isn't valid.
    Example
    import { buildGithubRawContentUrl } from 'jg-github';
    
    buildGithubRawContentUrl({ owner: 'acme', repository: 'app', ref: 'main', path: 'docs/setup.md' });
    // 'https://raw.githubusercontent.com/acme/app/main/docs/setup.md'

    createGithubAppJwt

    function

    Creates the JWT a GitHub App authenticates as itself with, signed with RS256: issued 60 seconds back, for a GitHub clock behind this one, and expiring 540 seconds ahead, inside GitHub's ten-minute limit even with this clock a minute ahead.

    Signature
    createGithubAppJwt(options: ICreateGithubAppJwtOptions): string

    Parameters

    optionsICreateGithubAppJwtOptions

    The App's ID, its private key, and the time.

    Returns

    string

    The JWT.

    Throws

    • GITHUB_INVALID_ARGUMENTAn argument isn't valid.
    • GITHUB_PRIVATE_KEY_INVALIDThe GitHub App's private key isn't an unencrypted RSA private key.
    Example
    import { createGithubAppJwt } from 'jg-github';
    
    declare const privateKey: string;
    
    const jwt = createGithubAppJwt({ appId: 123456, privateKey });

    createGithubHeaders

    function

    Builds the headers a request to GitHub's REST API sends: the media type, the token as a bearer credential, the User-Agent GitHub requires, and the API version.

    Signature
    createGithubHeaders(
      token: string,
      options: IGithubHeadersOptions,
    ): Record<string, string>

    Parameters

    tokenstring

    The token, such as an installation token or an App JWT.

    optionsIGithubHeadersOptions

    The User-Agent and the API version.

    Returns

    Record<string, string>

    The headers, with lowercase names.

    Throws

    • GITHUB_INVALID_ARGUMENTAn argument isn't valid.
    Example
    import { createGithubHeaders } from 'jg-github';
    
    declare const token: string;
    
    const response = await fetch('https://api.github.com/installation/repositories', {
      headers: createGithubHeaders(token, { userAgent: 'acme-deploy-bot' }),
    });

    createInstallationToken

    function

    Creates an installation token for exactly the repositories and the permissions asked for, with POST /app/installations/{id}/access_tokens, authenticated as the App. permissions is required, because GitHub grants every permission of the installation without it, and the repositories are named by name or by ID, never both. The granted token must reach exactly those repositories, only the selected ones, with exactly those permissions, plus metadata: 'read', and must not have expired; otherwise it's revoked before the error is thrown, and the error's data says whether that worked. Nothing is retried, and no error holds the token or the App's JWT.

    Signature
    createInstallationToken(
      options: ICreateInstallationTokenOptions,
    ): Promise<IInstallationToken>

    Parameters

    optionsICreateInstallationTokenOptions

    The App, the installation, the scope, and the request's limits.

    Returns

    Promise<IInstallationToken>

    A promise that resolves to the token, when it expires, and what it reaches.

    Throws

    • GITHUB_INVALID_ARGUMENTAn argument isn't valid.
    • GITHUB_PRIVATE_KEY_INVALIDThe GitHub App's private key isn't an unencrypted RSA private key.
    • GITHUB_REQUEST_FAILEDThe GitHub request failed.
    • GITHUB_RESPONSE_INVALIDGitHub's response isn't in the expected format.
    • GITHUB_TOKEN_SCOPE_MISMATCHThe installation token's scope isn't the one requested.
    • GITHUB_TOKEN_EXPIREDThe installation token had already expired.
    Example
    import { createInstallationToken, revokeInstallationToken } from 'jg-github';
    
    declare const privateKey: string;
    
    const { token } = await createInstallationToken({
      appId: 123456,
      privateKey,
      installationId: 12345678,
      repositories: ['app'],
      permissions: { contents: 'read' },
      userAgent: 'acme-deploy-bot',
    });
    try {
      // read the repository's contents with the token
    } finally {
      await revokeInstallationToken(token, { userAgent: 'acme-deploy-bot' });
    }

    getGithubRateLimitDeadline

    function

    Gives the time to retry a GitHub request at after a rate limit, or null when the response isn't rate limited. A 429 is, and so is a 403 with Retry-After, with no requests remaining, or with a rate-limit message, and a success that used the last remaining request. The deadline is the latest of Retry-After, as whole seconds or a strict IMF-fixdate, and x-ratelimit-reset when no requests remain, counting only future times; without one, it's a minute from now, doubled for each retry already made.

    Signature
    getGithubRateLimitDeadline(
      options: IGithubRateLimitDeadlineOptions,
    ): Date | null

    Parameters

    optionsIGithubRateLimitDeadlineOptions

    The response's status and headers, the retries made, and the time.

    Returns

    Date | null

    The time to retry at, or null.

    Throws

    • GITHUB_INVALID_ARGUMENTAn argument isn't valid.
    Example
    import { getGithubRateLimitDeadline } from 'jg-github';
    
    declare const response: Response;
    
    const deadline = getGithubRateLimitDeadline({
      status: response.status,
      headers: response.headers,
      retryCount: 0,
    });

    revokeInstallationToken

    function

    Revokes an installation token before it expires, such as when the work it was for is done, with DELETE /installation/token, which GitHub answers with 204. It never retries. The error never holds the token.

    Signature
    revokeInstallationToken(
      token: string,
      options: IGithubRequestOptions,
    ): Promise<void>

    Parameters

    tokenstring

    The installation token.

    optionsIGithubRequestOptions

    The User-Agent, the API's base URL and version, and the limits.

    Returns

    Promise<void>

    A promise that resolves once GitHub has revoked it.

    Throws

    • GITHUB_INVALID_ARGUMENTAn argument isn't valid.
    • GITHUB_TOKEN_REVOKE_FAILEDThe installation token couldn't be revoked.
    Example
    import { revokeInstallationToken } from 'jg-github';
    
    declare const token: string;
    
    await revokeInstallationToken(token, { userAgent: 'acme-deploy-bot' });

    verifyGithubWebhookSignature

    function

    Verifies a GitHub webhook delivery's X-Hub-Signature-256 header against the body's exact bytes, in constant time. A header that's missing, repeated, longer than 71 characters, or not sha256= and 64 lowercase hexadecimal characters is false, like a wrong signature. Verify the raw body before parsing it, because parsing and serializing can change its bytes.

    Signature
    verifyGithubWebhookSignature(
      rawBody: string | Uint8Array<ArrayBufferLike>,
      header: unknown,
      secret: string | Uint8Array<ArrayBufferLike>,
    ): boolean

    Parameters

    rawBodystring | Uint8Array<ArrayBufferLike>

    The request's body, as received.

    headerunknown

    The X-Hub-Signature-256 header, as the framework gives it.

    secretstring | Uint8Array<ArrayBufferLike>

    The webhook's secret.

    Returns

    boolean

    Whether the signature is the body's.

    Throws

    • INVALID_HMAC_SECRETThe HMAC secret must be a non-empty string or byte array.
    Example
    import { verifyGithubWebhookSignature } from 'jg-github';
    
    declare const rawBody: Buffer;
    declare const headers: Record<string, string | string[] | undefined>;
    declare const webhookSecret: string;
    
    if (!verifyGithubWebhookSignature(rawBody, headers['x-hub-signature-256'], webhookSecret)) {
      // answer 401
    }

    Constants

    DEFAULT_GITHUB_MAX_RESPONSE_BYTES

    const

    the bytes a response from GitHub may take when the options don't say (128 KiB)

    Declaration
    const DEFAULT_GITHUB_MAX_RESPONSE_BYTES: 131072

    DEFAULT_GITHUB_TIMEOUT_SECONDS

    const

    the seconds a request to GitHub may take when the options don't say

    Declaration
    const DEFAULT_GITHUB_TIMEOUT_SECONDS: 10

    ERRORS

    const

    the codes for every error thrown by the package

    Declaration
    const ERRORS: { GITHUB_PRIVATE_KEY_INVALID: "GITHUB_PRIVATE_KEY_INVALID"; GITHUB_INVALID_ARGUMENT: "GITHUB_INVALID_ARGUMENT"; GITHUB_REQUEST_FAILED: "GITHUB_REQUEST_FAILED"; GITHUB_RESPONSE_INVALID: "GITHUB_RESPONSE_INVALID"; GITHUB_TOKEN_SCOPE_MISMATCH: "GITHUB_TOKEN_SCOPE_MISMATCH"; GITHUB_TOKEN_EXPIRED: "GITHUB_TOKEN_EXPIRED"; GITHUB_TOKEN_REVOKE_FAILED: "GITHUB_TOKEN_REVOKE_FAILED" }

    GITHUB_API_ORIGIN

    const

    the origin of GitHub's REST API on github.com

    Declaration
    const GITHUB_API_ORIGIN: "https://api.github.com"

    GITHUB_API_VERSION

    const

    the REST API version every request asks for, in the X-GitHub-Api-Version header

    Declaration
    const GITHUB_API_VERSION: "2026-03-10"

    GITHUB_RAW_CONTENT_ORIGIN

    const

    the origin GitHub serves a repository's raw files from

    Declaration
    const GITHUB_RAW_CONTENT_ORIGIN: "https://raw.githubusercontent.com"

    Types

    ICreateGithubAppJwtOptions

    type

    what createGithubAppJwt takes

    Declaration
    type ICreateGithubAppJwtOptions = {
        appId: string | number;
        privateKey: string;
        now?: Date | undefined;
    };

    Members

    • appIdproperty
      string | number

      the App's ID, such as 123456, or its client ID

    • privateKeyproperty
      string

      the App's private key, PEM-encoded, as GitHub downloads it

    • nowproperty
      Date

      the time the JWT is issued at. Defaults to now

    ICreateInstallationTokenOptions

    type

    what createInstallationToken takes

    Declaration
    type ICreateInstallationTokenOptions = IGithubRequestOptions & IInstallationTokenRepositories & {
        appId: string | number;
        privateKey: string;
        installationId: string | number;
        permissions: IGithubPermissions;
        maxResponseBytes?: number | undefined;
    };

    IGithubApiUrlOptions

    type

    what buildGithubApiUrl takes

    Declaration
    type IGithubApiUrlOptions = {
        apiOrigin?: string | undefined;
    };

    Members

    • apiOriginproperty
      string

      the API's base URL, such as https://ghe.example.com/api/v3 for GitHub Enterprise Server. Defaults to GITHUB_API_ORIGIN

    IGithubHeadersOptions

    type

    what createGithubHeaders takes

    Declaration
    type IGithubHeadersOptions = {
        userAgent: string;
        apiVersion?: string | undefined;
    };

    Members

    • userAgentproperty
      string

      the User-Agent GitHub requires on every request, such as the app's name

    • apiVersionproperty
      string

      the REST API version. Defaults to GITHUB_API_VERSION

    IGithubPermissionLevel

    type

    the access a GitHub App permission grants

    Declaration
    type IGithubPermissionLevel = 'read' | 'write' | 'admin';

    IGithubPermissions

    type

    the permissions of an installation token, by GitHub's names, such as { contents: 'read' }

    Declaration
    type IGithubPermissions = Record<string, IGithubPermissionLevel>;

    IGithubQuery

    type

    the query parameters a URL builder appends; undefined ones are left out

    Declaration
    type IGithubQuery = Record<string, string | number | boolean | undefined>;

    IGithubRateLimitDeadlineOptions

    type

    what getGithubRateLimitDeadline takes

    Declaration
    type IGithubRateLimitDeadlineOptions = {
        status: number;
        headers: IGithubResponseHeaders;
        retryCount: number;
        hasRateLimitMessage?: boolean | undefined;
        now?: Date | undefined;
    };

    Members

    • statusproperty
      number

      the response's HTTP status

    • headersproperty
      IGithubResponseHeaders

      the response's headers

    • retryCountproperty
      number

      the retries already made for this request, from 0, which doubles the fallback wait

    • hasRateLimitMessageproperty
      boolean

      whether the response's message says a rate limit was hit, which makes a bare 403 count. Defaults to false

    • nowproperty
      Date

      the current time. Defaults to now

    IGithubRawContentLocation

    type

    a file in a repository, at a ref

    Declaration
    type IGithubRawContentLocation = {
        owner: string;
        repository: string;
        ref: string;
        path: string;
    };

    Members

    • ownerproperty
      string

      the account that owns the repository

    • repositoryproperty
      string

      the repository's name

    • refproperty
      string

      the branch, tag, or commit, such as main or feature/login

    • pathproperty
      string

      the file's path from the repository's root, such as docs/setup.md

    IGithubRawContentUrlOptions

    type

    what buildGithubRawContentUrl takes

    Declaration
    type IGithubRawContentUrlOptions = {
        rawContentOrigin?: string | undefined;
    };

    Members

    • rawContentOriginproperty
      string

      the raw content's base URL. Defaults to GITHUB_RAW_CONTENT_ORIGIN

    IGithubRepository

    type

    a repository an installation token can reach

    Declaration
    type IGithubRepository = {
        id: number;
        fullName: string;
    };

    Members

    • idproperty
      number

      the repository's ID

    • fullNameproperty
      string

      the repository's owner and name, such as 'acme/app'

    IGithubRequestOptions

    type

    what every request to GitHub's REST API takes

    Declaration
    type IGithubRequestOptions = {
        userAgent: string;
        apiOrigin?: string | undefined;
        apiVersion?: string | undefined;
        timeoutSeconds?: number | undefined;
        signal?: AbortSignal | undefined;
    };

    Members

    • userAgentproperty
      string

      the User-Agent GitHub requires on every request, such as the app's name

    • apiOriginproperty
      string

      the API's base URL, such as https://ghe.example.com/api/v3 for GitHub Enterprise Server. Defaults to GITHUB_API_ORIGIN

    • apiVersionproperty
      string

      the REST API version. Defaults to GITHUB_API_VERSION

    • timeoutSecondsproperty
      number

      the seconds the request may take. Defaults to 10

    • signalproperty
      AbortSignal

      stops the request when it aborts

    IGithubResponseHeaders

    type

    a response's headers: a Headers object, or a record with lowercase names, as Node.js's IncomingHttpHeaders has

    Declaration
    type IGithubResponseHeaders = Headers | Readonly<Record<string, string | readonly string[] | undefined>>;

    IInstallationToken

    type

    an installation token, scoped as requested

    Declaration
    type IInstallationToken = {
        token: string;
        expiresAt: Date;
        permissions: Record<string, string>;
        repositories: IGithubRepository[];
    };

    Members

    • tokenproperty
      string

      the token, sent as a bearer credential

    • expiresAtproperty
      Date

      when it expires, an hour after it was created

    • permissionsproperty
      Record<string, string>

      the permissions it grants: the ones requested, and metadata: 'read' when GitHub adds it

    • repositoriesproperty
      IGithubRepository[]

      the repositories it reaches, exactly the ones requested

    IInstallationTokenRepositories

    type

    the repositories an installation token is for: by name or by ID, never both

    Declaration
    type IInstallationTokenRepositories = {
        repositories: readonly string[];
        repositoryIds?: undefined;
    } | {
        repositoryIds: readonly number[];
        repositories?: undefined;
    };