Tutorials

How to Fix GitHub Actions and Node.js Scripts for SHA-256 Git Repositories

GitHub's SHA-256 repository preview exposes a hidden assumption in existing CI scripts: commit IDs are not always 40 characters long. Learn how to update validation, webhook handlers, and storage schemas.

A deployment script receives a commit ID from GitHub Actions, checks whether it is valid, and uses it to identify the application build.

The validation might have been written several years ago:

const sha = process.env.GITHUB_SHA ?? "";

if (!/^[a-f0-9]{40}$/.test(sha)) {
  throw new Error("Invalid commit SHA");
}

There was little reason to question the number 40. GitHub repositories traditionally used SHA-1, and their full commit identifiers contained exactly 40 hexadecimal characters.

But on December 3, 2026, GitHub announced public preview support for repositories using SHA-256.

A newly created repository can now use a different object format. Its full commit IDs contain 64 characters instead of 40.

The script above would reject every valid commit ID from such a repository.

What makes this problem interesting is that nothing needs to change in the application itself. The same source code, build commands, and deployment configuration may work perfectly until a piece of surrounding infrastructure encounters an identifier longer than expected.

What changed on GitHub?

SHA-256 repositories have existed in Git since version 2.30, released in December 2020.

GitHub’s December 3 announcement makes this repository format available in public preview on its hosting platform.

The difference extends beyond commits. Git uses object identifiers for blobs, trees, commits, and annotated tags.

Property SHA-1 SHA-256
Hash size 160 bits 256 bits
Binary identifier size 20 bytes 32 bytes
Full hexadecimal object ID 40 characters 64 characters
Available when creating GitHub repositories Yes Public preview

Existing repositories continue using their original algorithm.

GitHub does not currently support changing a repository’s hash algorithm after creation, so an existing SHA-1 repository will not suddenly begin returning 64-character commit IDs.

The compatibility problem primarily concerns tools shared across multiple repositories, especially those that may eventually receive data from newly created SHA-256 projects.

1. Reproduce the problem locally

There is no need to create a GitHub repository to investigate the difference.

First, check your Git version:

git --version

GitHub requires Git 2.30 or later for working with SHA-256 repositories. Cloning an empty SHA-256 repository requires Git 2.41 or later.

Create a local test repository:

git init --object-format=sha256 sha256-demo
cd sha256-demo

Create an empty commit:

git -c user.name=Tester \
    -c [email protected] \
    commit --allow-empty -m "Initial commit"

These commands use temporary commit-author settings without modifying your global Git configuration.

Now inspect the repository:

git rev-parse --show-object-format
git rev-parse HEAD

In a local test using Git 2.47.3, the commands returned:

sha256
d5f027ba4e9cd598b0f98c450418f7bc803ac522c48a29b669215c97572f9e4d

Your commit ID will differ because commit contents include metadata such as timestamps.

What remains consistent is the length.

Create a file named check-sha.mjs:

import { execFileSync } from "node:child_process";

const sha = execFileSync(
  "git",
  ["rev-parse", "HEAD"],
  { encoding: "utf8" },
).trim();

console.log("Commit length:", sha.length);
console.log("Valid:", /^[a-f0-9]{40}$/.test(sha));

Run it:

node check-sha.mjs

The result:

Commit length: 64
Valid: false

Git successfully created the commit and returned its identifier. The error belongs to the application’s validation logic.

2. Detect the repository’s hash algorithm

An obvious correction would be to allow both lengths:

const isValid =
  /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha);

For a generic tool receiving identifiers from different repositories, this may be sufficient as an initial format check.

But consider a script running inside a specific SHA-1 repository.

Should it accept a 64-character object ID simply because that length is valid in another repository?

Probably not.

Git can provide the repository’s actual object format:

git rev-parse --show-object-format

The command returns sha1 or sha256 for the repository formats discussed here.

Create a reusable TypeScript utility:

// git-oid.ts

import { execFileSync } from "node:child_process";

export type GitHashFormat = "sha1" | "sha256";

export function readFormat(
  cwd = process.cwd(),
): GitHashFormat {
  const format = execFileSync(
    "git",
    ["rev-parse", "--show-object-format"],
    {
      cwd,
      encoding: "utf8",
    },
  ).trim();

  if (format !== "sha1" && format !== "sha256") {
    throw new Error(
      `Unsupported Git format: ${format}`,
    );
  }

  return format;
}

This function obtains the algorithm directly from Git instead of inferring it from an identifier.

The distinction becomes particularly useful in services that process different repositories.

A malformed identifier should not be able to determine which validation rules apply to itself.

If Git cannot identify the repository or returns an unsupported format, the function fails rather than silently assuming SHA-1.

3. Validate object IDs and handle zero values

Once the repository format is known, validation becomes relatively straightforward.

However, length is not the only consideration.

GitHub’s push webhook uses an all-zero object ID to represent the absence of an earlier or subsequent commit when a ref is created or deleted.

That value has the correct length and contains valid hexadecimal characters. Yet it does not identify an actual commit.

We can account for this by distinguishing three cases:

export type OidKind = "object" | "zero" | "invalid";

export function classifyOid(
  value: unknown,
  format: GitHashFormat,
): OidKind {
  const length = format === "sha1" ? 40 : 64;

  if (
    typeof value !== "string" ||
    value.length !== length ||
    /[^0-9a-f]/.test(value)
  ) {
    return "invalid";
  }

  return /^0+$/.test(value) ? "zero" : "object";
}

Here, "object" means that the identifier has the expected syntax and is not the zero sentinel.

It does not prove that the object exists.

The validation process can be represented as follows:

flowchart TD
    A["Receive Git object ID"] --> B["Read repository hash format"]
    B --> C{"Hash format"}
    C -->|SHA-1| D["Expect 40 hex characters"]
    C -->|SHA-256| E["Expect 64 hex characters"]
    D --> F{"Correct length and characters?"}
    E --> F
    F -->|No| G["Invalid identifier"]
    F -->|Yes| H{"All zeros?"}
    H -->|Yes| I["Zero sentinel"]
    H -->|No| J["Object ID candidate"]

The additional distinction prevents webhook handlers from attempting to retrieve a nonexistent commit.

When the object must exist locally, Git itself can perform the stronger check:

export function verifyCommit(
  sha: string,
  cwd = process.cwd(),
): string {
  const format = readFormat(cwd);

  if (classifyOid(sha, format) !== "object") {
    throw new Error("Invalid commit identifier");
  }

  return execFileSync(
    "git",
    ["rev-parse", "--verify", `${sha}^{commit}`],
    { cwd, encoding: "utf8" },
  ).trim();
}

The ^{commit} suffix asks Git to resolve the supplied object to a commit.

For example, a syntactically valid but nonexistent identifier passes the initial shape validation and then fails during Git verification.

A shallow clone may also lack an otherwise valid commit, so this check establishes local availability rather than global existence.

4. Update GitHub Actions workflows

A typical CI workflow might obtain the commit ID directly from an environment variable:

const sha = process.env.GITHUB_SHA;

That remains a valid approach. The problem arises when another part of the script assumes the value is always 40 characters long.

There is also a separate compatibility question: can the checkout action initialize and fetch a SHA-256 repository?

GitHub’s actions/[email protected] already introduced fixes for SHA-256 repository initialization and merge-commit hash validation.

Use a reviewed release containing these fixes rather than assuming every older checkout action supports the new repository format.

For example:

name: Verify Git object format

on:
  push:
  pull_request:

permissions:
  contents: read

jobs:
  verify:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false

      - uses: actions/setup-node@v4
        with:
          node-version: "22"

      - name: Inspect Git repository
        run: |
          git --version
          git rev-parse --show-object-format
          git rev-parse HEAD

      - name: Validate checked-out commit
        run: node scripts/check-commit.mjs

For production workflows, action references can additionally be pinned to reviewed full commit IDs.

The script can validate the checked-out commit:

// scripts/check-commit.mjs

import { execFileSync } from "node:child_process";

function git(...args) {
  return execFileSync("git", args, {
    encoding: "utf8",
  }).trim();
}

const format = git(
  "rev-parse",
  "--show-object-format",
);

const sha = git("rev-parse", "HEAD");

const lengths = {
  sha1: 40,
  sha256: 64,
};

const expectedLength = lengths[format];

if (expectedLength === undefined) {
  throw new Error(`Unsupported format: ${format}`);
}

if (
  sha.length !== expectedLength ||
  /[^0-9a-f]/.test(sha) ||
  /^0+$/.test(sha)
) {
  throw new Error(`Invalid ${format} commit ID`);
}

console.log("Git format:", format);
console.log("Commit:", sha);

One detail is worth separating from the SHA-256 change.

GITHUB_SHA and git rev-parse HEAD are not necessarily interchangeable in every workflow.

On an ordinary pull_request event, GITHUB_SHA normally identifies the generated merge commit. If the checkout configuration explicitly selects the pull request’s head commit, the checked-out HEAD may differ.

Use the identifier that corresponds to what your script actually needs.

For build metadata, that is often the commit currently checked out rather than the commit associated with the workflow event.

5. Determine the hash algorithm through GitHub’s REST API

Local Git commands work when the repository has already been cloned.

But what about a backend receiving GitHub webhooks?

Cloning every repository merely to determine its hash algorithm would be unnecessary.

GitHub provides a REST endpoint:

GET /repos/{owner}/{repo}/hash-algorithm

A successful response contains the repository’s algorithm:

{
  "hash_algorithm": "sha256"
}

With GitHub CLI, you can query it using:

gh api repos/OWNER/REPO/hash-algorithm

Replace OWNER and REPO with the actual repository owner and name.

The endpoint is accessible without authentication for public repositories. Accessing private repositories requires appropriate authentication, including read access to repository metadata.

A Node.js application can wrap the endpoint in a small utility:

import type { GitHashFormat } from "./git-oid.js";

export async function getRepositoryHashFormat(
  owner: string,
  repository: string,
  token?: string,
): Promise<GitHashFormat> {
  const path = [
    "repos",
    encodeURIComponent(owner),
    encodeURIComponent(repository),
    "hash-algorithm",
  ].join("/");

  const response = await fetch(
    `https://api.github.com/${path}`,
    {
      headers: {
        Accept: "application/vnd.github+json",
        "X-GitHub-Api-Version": "2026-03-10",
        ...(token
          ? { Authorization: `Bearer ${token}` }
          : {}),
      },
    },
  );

  if (!response.ok) {
    throw new Error(
      `GitHub API returned ${response.status}`,
    );
  }

  const data: unknown = await response.json();

  if (
    typeof data === "object" &&
    data !== null &&
    "hash_algorithm" in data &&
    (
      data.hash_algorithm === "sha1" ||
      data.hash_algorithm === "sha256"
    )
  ) {
    return data.hash_algorithm;
  }

  throw new Error("Unknown repository hash format");
}

The .js import extension assumes TypeScript is compiled to JavaScript using Node-compatible ESM module resolution.

Since GitHub does not currently allow changing a repository’s hash algorithm, a service can cache this information by repository ID rather than requesting it for every webhook delivery.

Caching by repository name alone is less reliable. A repository can be renamed, deleted, or replaced by another repository using the same name.

6. Fix push webhook handlers

Consider a backend that receives a push event.

It validates the after property and then retrieves the associated commit.

This works for ordinary pushes but fails conceptually when a branch is deleted.

A push webhook can contain the following combination:

{
  "deleted": true,
  "after": "0000000000000000000000000000000000000000000000000000000000000000"
}

This simplified example represents deletion of a ref in a SHA-256 repository.

The zero value is intentional.

A handler that only checks hexadecimal characters and length might mistake it for a commit and attempt to retrieve it through the API.

Instead, the handler should consider the event’s meaning:

interface PushPayload {
  before: string;
  after: string;
  deleted: boolean;
  created: boolean;
}

export function handlePush(
  payload: PushPayload,
  format: GitHashFormat,
) {
  const before = classifyOid(payload.before, format);
  const after = classifyOid(payload.after, format);

  if (before === "invalid" || after === "invalid") {
    throw new Error("Invalid push object IDs");
  }

  if (payload.deleted) {
    if (after !== "zero") {
      throw new Error("Unexpected deletion payload");
    }

    return {
      action: "ref-deleted",
    } as const;
  }

  if (after !== "object") {
    throw new Error("Missing target commit");
  }

  return {
    action: payload.created
      ? "ref-created"
      : "ref-updated",
    objectId: payload.after,
  } as const;
}

The example assumes the webhook signature and payload structure have already been validated.

It also deliberately returns an object ID rather than immediately treating every pushed object as a commit. Tags and branches can require different handling.

There is another potential source of confusion: GitHub’s X-Hub-Signature-256 webhook header already uses HMAC-SHA-256.

That signature is independent of the Git repository’s object format.

Switching a repository to SHA-256 does not change how webhook signatures should be verified.

7. Check your database schema

Validation errors are usually easy to identify because they cause explicit failures.

Storage restrictions can be less obvious.

For example, a PostgreSQL table might declare:

commit_sha VARCHAR(40) NOT NULL

A valid SHA-256 commit ID cannot fit into that column.

For a service supporting both formats, the schema can be widened:

ALTER TABLE deployments
ALTER COLUMN commit_sha TYPE VARCHAR(64);

However, accepting up to 64 characters also permits strings with lengths that are not valid full Git object identifiers.

A database constraint can preserve the expected structure:

ALTER TABLE deployments
ADD CONSTRAINT valid_commit_sha
CHECK (
  commit_sha ~ '^([0-9a-f]{40}|[0-9a-f]{64})$'
  AND commit_sha !~ '^0+$'
);

This example assumes existing records are compatible with the new constraint.

For a service that manages many repositories, it may be better to store the hash algorithm alongside the identifier and validate the corresponding length.

There is no need to convert existing SHA-1 values into SHA-256.

They are identifiers of existing objects, not strings waiting to be upgraded.

Hashing an existing SHA-1 commit ID with Node.js’s createHash("sha256") would produce another hash, but it would not produce the SHA-256 identifier of the corresponding Git commit.

Git object identifiers depend on the serialized object contents and their internal references.

8. Test both repository formats automatically

Rather than testing the utility with invented hexadecimal strings alone, we can create actual Git repositories during a unit test.

The following example uses Node.js’s built-in test runner.

// git-oid.test.ts

import { test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import {
  classifyOid,
  readFormat,
} from "./git-oid.ts";

for (const format of ["sha1", "sha256"] as const) {
  test(`Validates ${format} object IDs`, () => {
    const cwd = mkdtempSync(
      join(tmpdir(), "git-oid-"),
    );

    try {
      function git(...args: string[]) {
        return execFileSync("git", args, {
          cwd,
          encoding: "utf8",
        }).trim();
      }

      git("init", "-q", `--object-format=${format}`);

      git(
        "-c", "user.name=Tester",
        "-c", "[email protected]",
        "commit",
        "-q",
        "--allow-empty",
        "-m", "Initial commit",
      );

      const sha = git("rev-parse", "HEAD");

      assert.equal(readFormat(cwd), format);

      assert.equal(
        classifyOid(sha, format),
        "object",
      );

      assert.equal(
        classifyOid("0".repeat(sha.length), format),
        "zero",
      );

      assert.equal(
        classifyOid(
          sha,
          format === "sha1" ? "sha256" : "sha1",
        ),
        "invalid",
      );

      assert.equal(
        classifyOid(sha.slice(0, -1) + "\n", format),
        "invalid",
      );
    } finally {
      rmSync(cwd, {
        recursive: true,
        force: true,
      });
    }
  });
}

With Node.js 22.16.0 or a compatible newer version, you can execute this TypeScript test using native type stripping:

node --experimental-strip-types --test git-oid.test.ts

For TypeScript projects using native execution, configure .ts imports appropriately. Projects compiling tests to JavaScript should use their normal module-resolution and test-runner configuration instead.

The equivalent JavaScript test was executed locally using Git 2.47.3 and Node.js 22.16.0.

Both repository formats passed.

Test SHA-1 SHA-256
Repository initialization Passed Passed
Legacy 40-character validator Accepted Rejected
Format-aware validation Passed Passed
Zero sentinel detection Passed Passed
Wrong algorithm rejection Passed Passed
Invalid character rejection Passed Passed

Testing actual Git repositories also verifies that the application receives identifiers from the Git executable rather than relying exclusively on artificial fixtures.

Where else can 40-character assumptions hide?

A search through the repository is a useful starting point.

Look for expressions and declarations such as:

{40}
VARCHAR(40)
CHAR(40)
Buffer.alloc(20)
sha.length === 40

These patterns are not necessarily incorrect.

Some may belong to unrelated SHA-1 operations or intentionally fixed-format protocols.

But when they are used for Git object identifiers, they deserve inspection.

Also examine deployment metadata, artifact names, API schemas, commit links, and cache keys.

Code that displays only the first seven characters of a commit ID may continue working, since abbreviation and full identifier validation are different operations.

For abbreviations that need to identify an object within a repository, prefer Git’s own mechanism:

git rev-parse --short HEAD

A hard-coded seven-character prefix is not guaranteed to remain unique as a repository grows.

Should existing projects move to SHA-256?

There is no immediate requirement to migrate.

GitHub’s support is still in public preview, and existing SHA-1 repositories cannot be converted in place through a repository setting.

Repositories using different hash algorithms also cannot directly exchange Git objects through ordinary push and fetch operations.

For an existing application, the more useful preparation may be to update its surrounding tooling first.

A deployment service should be able to store a 64-character commit ID. A webhook handler should understand zero sentinels of either length. A CI workflow should not depend on checkout tooling that only understands SHA-1.

Once those assumptions have been removed, creating a separate SHA-256 test repository becomes a much smaller compatibility exercise.

The GitHub update does not invalidate every existing script.

It exposes an assumption that was reasonable for years but is no longer universally true: a Git object ID is not necessarily a 40-character string.

External Sources used for this article

Related Articles

View all →