A practical overview · code backup

Your repositories protected against account lockouts and hacks

If your account disappears tomorrow, your code is still yours. A simple, layered plan that's almost entirely free.

Banner: protect your repositories — layered backup against account lockouts and hacks
In short

This guide is for anyone who stores code on GitHub (or a similar service) and wants to be ready in case their account is locked or hacked. It explains why copying everything to another account on the same service offers little protection, then lays out a three-layer plan: a copy with another company, dated snapshots on a drive you own, and, if you want, your own server. It includes the git commands for each step, free plan limits, and what would change if you left GitHub for good. You don't need to install anything to read it: this is the overview and method, ready for you to put into practice.

Video

Watch the video

The plan in three and a half minutes, from the problem to the three steps for today (in Portuguese).

▶ Open on YouTube

The problem

Keeping everything in one place creates a single point of failure

Code, history, published pages, automations, and deploys often live on the same service. One incident can take everything offline.

Grid banner: another account isn't enough, unlinked GitLab account, dated snapshots, Forgejo on a VPS, test a restore, plan limits

🚫 Account lockout

A report, an anti-fraud bot, a policy mistake. Your account is suspended, and you can't even download what's yours.

🕵️ Account takeover

Someone gets a token or password and deletes repositories, or rewrites the history with a push --force.

💻 "I have the folders here"

That's not a backup. You may be missing what you never cloned, branches may be missing, and your computer can also be targeted in an attack.

The first idea: duplicate everything to another GitHub account

Technically, it's easy, and --mirror copies everything: commits, branches, and tags. The problem is where that copy lives.

git clone --mirror https://github.com/conta-original/projeto.git
cd projeto.git
git push --mirror https://github.com/conta-backup/projeto.git
# first, create the empty repo in the backup account (GitHub does not create it on push)
# the "deny updating a hidden ref" warning for refs/pull/* is expected: those are PRs

On mobile, swipe the tables sideways.

ScenarioWill the other GitHub account save you?Why
Account lockoutMaybe notIt's the same company. Accounts linked by the same email, phone number, or device may be suspended together. And the terms limit the number of free accounts per person.
Account takeoverNoIf the same machine stores the tokens for both accounts, an attacker gets both and deletes the original and the copy.
Repository damageNoA mirror that syncs automatically copies the damage (a deleted repo or rewritten history) on the next run.
What a git copy includes and leaves out. Included: code, history, branches, and tags. The wiki is a separate repo (projeto.wiki.git): it is only included if you clone it too. Not included: issues, pull requests, comments, stars, releases with attachments, secrets, webhooks, or Pages settings. Git LFS files need git lfs fetch --all + git lfs push --all.
The layers

The golden rule of backup: 3-2-1

A copy only protects you if it's somewhere else, uses a different key, and keeps older versions.

3

copies of your data: the original + 2

2

different places: for example, cloud and drive

1

off-site: it survives if your home catches fire

And a fourth rule for protection against attacks: at least one copy that your everyday machine cannot delete. In the plan below, the off-site copy pulled by the VPS meets this rule (step 7).

The recommended setup

Keep working on GitHub as usual. Every day, a routine copies everything to three places.

GitHub (where you work)→ GitLab (another company)+ Dated snapshots on your drive+ Forgejo on a VPS (optional)
1

GitLab, in an unlinked account

A different company: a GitHub lockout won't affect it. Use a new email, phone number, and 2FA, private repos, and a token that can send code but cannot delete projects.

2

Dated snapshots on your drive

A mirror of each repo on a drive you own, plus one "snapshot" per day. A deleted or damaged repo elsewhere won't delete your old snapshots: you can go back to any day you choose.

3

Forgejo on a VPS (optional)

Your own "GitHub" on a rented server. No company can lock it out. It needs maintenance, so make it your third copy, not your only one. Installation (binary or Docker): forgejo.org/docs; after that, sending code works just like with GitLab—the address is the only thing that changes.

Before you start

What you need

Nothing paid. git handles almost everything.

git and gh installed

git on any Linux, Mac, or Windows computer. gh is GitHub's command-line tool: it lists your repos and gives you access to private ones.

git --version
gh auth login

A drive with enough space

Add up the size of your repos and reserve about 3 times that much for snapshots. An external hard drive works. The examples use the /backup folder; create it once and make it your own.

df -h   # free space
sudo mkdir -p /backup && sudo chown $USER /backup

A new GitLab account

On gitlab.com, using an email and phone number you don't use for your other accounts, with 2FA enabled.

# gitlab.com → Register
Step by step

From scratch to a tested backup

The commands below use conta, projeto, and /backup as examples: replace them with your own names and folders.

The folder and variable names in the commands are intentionally in Portuguese; you can replace them with any names you like.

1

Secure your accounts first (prevention)

It's inexpensive and prevents most problems.

  • Enable 2FA on every account, preferably with an app or physical key, not SMS.
  • Delete old tokens and SSH keys you no longer use.
  • Use "fine-grained" tokens: only the permissions you need, with an expiration date.
  • Enable branch protection (block push --force and deletion) on important repos. GitHub's free plan only offers it for public repos; private repos require a paid plan. On GitLab, the default branch is protected from the start.
2

Create an unlinked backup account

On GitLab, use an email, phone number, and 2FA that are different from those on your other accounts. Never add it as a collaborator to your other accounts, fork repos, or enable Pages. You don't need to create projects one by one: on the first push, GitLab creates the private project automatically ("push to create").

3

Create a token that can send but not delete

On GitLab, click your avatar → Edit profile → Access tokens (Personal access tokens) and create a token with only the read_repository and write_repository scopes and an expiration date. Without the api scope, it cannot delete projects.

On GitHub, also create a read-only fine-grained token (Settings → Developer settings → Fine-grained tokens, all repos, Contents: Read-only permission). The routine uses this token in cron, where the normal gh login (stored in the system keychain) does not work.

Store both in a file that only you can read. read -s prompts for the token without displaying it or saving it in your terminal history:

mkdir -p ~/.config/backup-repos
read -rs -p "token do GitLab: " T1; echo
read -rs -p "token do GitHub: " T2; echo
printf 'GITLAB_TOKEN=%s\nGH_TOKEN=%s\n' "$T1" "$T2" > ~/.config/backup-repos/tokens.env
chmod 600 ~/.config/backup-repos/tokens.env; unset T1 T2

What this doesn't prevent: an attacker who gets into the machine can still push commits or overwrite unprotected branches. On GitLab, only the default branch is protected from the start (other branches accept push --force and can be deleted with the token). It rejects push --force, which is why the step 7 routine warns you when GitLab rejects something. Dated snapshots from step 5 cover the rest.

4

Create a local mirror of each repo

A --mirror clone stores all branches and tags. After that, the daily routine only updates it. For private repos, run gh auth setup-git once: git will ask gh for the password, and it will use the GH_TOKEN from the file.

mkdir -p /backup/espelho
git clone --mirror https://github.com/conta/projeto.git /backup/espelho/projeto.git
# every day:
git -C /backup/espelho/projeto.git remote update --prune
5

Take today's snapshot

A git bundle is a single file containing the entire repo. git doesn't create the folder automatically, so you need mkdir -p.

DIA=$(date +%F)                          # e.g.: 2026-11-05
mkdir -p /backup/fotos/$DIA
git -C /backup/espelho/projeto.git bundle create /backup/fotos/$DIA/projeto.bundle --all
git -C /backup/espelho/projeto.git bundle verify /backup/fotos/$DIA/projeto.bundle   # checks the file
# alternative: take a snapshot of the /backup/espelho folder with restic or borg
6

Push to GitLab

Push branches and tags (--all + --tags), not --mirror. That way, a branch deleted on GitHub won't be deleted in the copy, and internal pull request references (refs/pull/*) that would cause an error are left out.

set -a; source ~/.config/backup-repos/tokens.env; set +a
U="https://oauth2:$GITLAB_TOKEN@gitlab.com/conta-backup/projeto.git"
git -C /backup/espelho/projeto.git push "$U" --all
git -C /backup/espelho/projeto.git push "$U" --tags
7

Combine everything into a routine for all repos

A script goes through your account's repo list, runs steps 4 through 6 for each one, deletes old snapshots, and logs failures. Save it as /backup/rotina-diaria.sh and run chmod +x on it. Replace the two account names at the top.

#!/usr/bin/env bash
# rotina-diaria.sh — espelho + foto do dia + envio ao GitLab
set -u
CONTA=sua-conta-github; GL=sua-conta-gitlab
set -a; source ~/.config/backup-repos/tokens.env; set +a   # GITLAB_TOKEN e GH_TOKEN
BASE=/backup; DIA=$(date +%F); FALHAS=0
mkdir -p "$BASE/espelho" "$BASE/fotos/$DIA"
# se a lista falhar ou vier vazia, para e registra: nunca grava "0 falha(s)" sem ter copiado nada
LISTA=$(gh repo list "$CONTA" --limit 2000 --json name -q '.[].name') && [ -n "$LISTA" ] || { echo "$DIA: ERRO gh repo list falhou" >> "$BASE/rotina.log"; exit 1; }
for R in $LISTA; do
  E="$BASE/espelho/$R.git"
  [ -d "$E" ] || git clone -q --mirror "https://github.com/$CONTA/$R.git" "$E"
  git -C "$E" remote update --prune >/dev/null || { echo "falhou atualizar $R"; FALHAS=$((FALHAS+1)); continue; }
  [ -n "$(git -C "$E" for-each-ref)" ] || continue          # repo vazio: nada a guardar
  git -C "$E" bundle create -q "$BASE/fotos/$DIA/$R.bundle" --all || { echo "foto falhou $R"; FALHAS=$((FALHAS+1)); }
  U="https://oauth2:$GITLAB_TOKEN@gitlab.com/$GL/$R.git"
  { git -C "$E" push -q "$U" --all && git -C "$E" push -q "$U" --tags; } || { echo "GitLab recusou $R"; FALHAS=$((FALHAS+1)); }
done
# rotação: apaga fotos com mais de 35 dias, menos as do dia 01 (ficam como mensais; apague à mão as muito antigas)
find "$BASE/fotos" -mindepth 1 -maxdepth 1 -type d -mtime +35 ! -name '*-01' -exec rm -rf {} +
echo "$DIA: $FALHAS falha(s)" >> "$BASE/rotina.log"

Before the first full copy, do two checks. First, test with 3 repos: do steps 4 to 6 by hand on 3 of them and the restore in step 8; continue only if the numbers match. Then check the largest repos: GitLab Free accepts up to 10 GiB per project and 5 GiB per push. The command below lists the 5 largest, in KB (GitHub’s own estimate). A repo over the limit is kept only in the snapshots and the off-site copy, and the routine will log "GitLab recusou" (GitLab refused) for it every day.

gh repo list sua-conta-github --limit 2000 --json name,diskUsage -q '.[] | "\(.diskUsage) \(.name)"' | sort -n | tail -5

Then run it once by hand (/backup/rotina-diaria.sh) before putting it on a schedule: with hundreds of repos, the first run can take hours. Then add it to cron (crontab -e), with PATH on the first line, because cron doesn't load the one from your terminal:

PATH=/usr/local/bin:/usr/bin:/bin
0 3 * * * /backup/rotina-diaria.sh >> /backup/cron.log 2>&1

To check whether it ran: tail /backup/cron.log and tail /backup/rotina.log.

Organization or client repos: gh repo list "$CONTA" only lists repos owned by your account. Repos in an organization (or belonging to clients who gave you access) are left out without warning. Run the script once for each owner (replace CONTA with the organization's name) and, in the GitHub token settings, select each owner under Resource owner or create one token per owner.

Off-site, without giving the attacker a key: the VPS does the copying, pulling snapshots from your machine once a week. That way, your machine has no access to the VPS and can't delete that copy. The VPS needs to reach your machine over SSH (for example, through Tailscale). This cron job runs on the VPS:

0 5 * * 0 rsync -a usuario@sua-maquina:/backup/fotos/ /backup/fotos/

Be careful: the VPS will connect to your machine. Restrict its key (in your machine's ~/.ssh/authorized_keys) to read-only access to the snapshots with command="rrsync -ro /backup/fotos"; with this restriction, the path becomes relative to the allowed folder, and the VPS cron job becomes 0 5 * * 0 rsync -a usuario@sua-maquina:/ /backup/fotos/. rrsync comes with rsync 3.2.4 or newer (/usr/bin/rrsync); on older versions, it is at /usr/share/doc/rsync/scripts/rrsync.gz. Create the /backup/fotos folder on the VPS first. Because rsync runs without --delete, the VPS never deletes snapshots: its drive will only fill up, so clean it out from time to time.

If the VPS can't reach your machine, use restic with a rest-server --append-only on the VPS instead: your machine can add snapshots but can't delete them.

Check /backup/rotina.log from time to time: "0 falha(s)" is what you want to see. If GitLab rejects a repo every day, it's almost always because of a legitimate push --force on GitHub (a rebase, for example): check whether you did it and, if so, allow force-pushing on that branch in GitLab for one run only. Three things to keep in mind: the routine doesn't save wikis (to save them, repeat the clone with $R.wiki.git); it doesn't save Git LFS files either (run git lfs fetch --all in the mirror); and the token in the URL appears in the machine's process list, so if the machine is shared, use a git credential helper.

8

Test a restore (the part everyone forgets)

Choose 3 repos, restore them somewhere new, and compare. A backup that has never been restored is only a hope.

git clone --mirror /backup/fotos/2026-11-05/projeto.bundle projeto.git
cd projeto.git
git log --oneline --all | wc -l       # nº de commits: compare com o espelho em /backup/espelho
git for-each-ref | wc -l              # nº de branches + tags: compare também com o espelho
git push https://gitlab.com/conta-nova/projeto.git --all    # sobe as branches para qualquer serviço
git push https://gitlab.com/conta-nova/projeto.git --tags   # e as tags

Compare with the mirror, not the repo on GitHub: the mirror and snapshot also contain refs/pull/*, which the regular repo doesn't show. For the same reason, restoring uses --all + --tags, not --mirror.

Repeat every month. Pick 3 repos at random and restore them from the latest snapshot. A single test at the start won’t tell you if the routine breaks later.

ls /backup/espelho | shuf -n 3     # picks 3 repos for this month’s test
What about issues, PRs, and releases? git doesn't include them. To save those too: GitHub lets you export all your account data under Settings → Account → Export account data; gh can save them per repo (gh issue list --state all --json number,title,body,comments > issues.json); and the GitLab importer (New project → Import project → GitHub) brings over a repo's issues and PRs in one go. Note: the importer asks for a GitHub token inside your GitLab account, linking the two accounts; if you use it, do so in a third account, not the backup account.
Comparison

Free plan limits

Checked in November 2026. The GitHub, GitLab, and Codeberg information comes from their official pages; the Bitbucket information comes from third-party sites. Limits change, so check before deciding.

GitHubGitLab.comCodebergBitbucketForgejo on your VPS
Size per repo~1 GB recommended, max file size 100 MB10 GiB per project~750 MiB (ask for more)not confirmed: check the current limit per workspacethe VPS drive
Maximum push size2 GB5 GiB——no limit
Private reposunlimitedunlimitedonly 100 MB totalunlimitedunlimited
CI (minutes/month)2,000 for private repos, unlimited for public repos400limited, by request50unlimited
Pages1 GB per site1 GB, custom domainyesyes (workspace.bitbucket.io)you set it up
Usersunlimited5 per private group—5unlimited
Content rulesgeneralgeneralopen-source software only; AI content restricted; backups are not welcomegeneralyour rules

✅ GitLab: the cloud backup destination

Enough room for hundreds of repos. The 400 CI minutes don't matter: the backup doesn't run CI.

⛔ Codeberg: great, but not for backups

Made for open-source software. Its current terms restrict AI-generated content, allow little private storage, and discourage backup use.

🟡 Bitbucket: it works, but has no edge

It works for backup alone, but 50 CI minutes and 5 users don't make it a permanent home.

🏠 Forgejo: the most independent option

No account with any company needed. The trade-off is looking after the server: updates and security.

Two terms you'll see often

⚙️ CI (continuous integration)

Automation that runs on its own with every git push: publishes a page, runs tests, builds a project. On GitHub, it's called Actions. A "runner" does the work: the service's machine uses "minutes per month"; your own machine doesn't. CI doesn't matter for backups.

🏗️ Forgejo

Free software that works like your own "GitHub," installed on your server: repos, issues, pull requests, wiki, and releases. It powers Codeberg. It's lightweight enough for a small VPS. It has its own CI (Forgejo Actions), which works almost like GitHub Actions.

What if I want to leave for good?

What changes in a permanent migration

It's possible, but it affects everything built on GitHub. Here's a real example from a content creator with about 860 repos:

What exists todayWhat changes
~690 usuario.github.io/... links on the website, in groups, and in video descriptionsThey become usuario.gitlab.io/projeto. Old links break, and video descriptions and group messages can't be updated in bulk.
Pages with strong Google rankingsThey start from scratch at the new address.
~320 repos with Actions workflowsOn GitLab, each one becomes .gitlab-ci.yml; the free plan only gives you 400 minutes/month unless you run your own runner.
~20 sites deployed through VercelVercel supports GitLab, but each one must be reconnected. Codeberg does not connect.
~70 scripts that use ghThey switch to glab (GitLab) or the Forgejo API.
Community, stars, project discoveryThey stay on GitHub.

➕ Benefits of migrating

Independence from a single company; CI, image registry, and Pages all in one place on GitLab; the option to host your own server later; a different data policy.

🎯 The takeaway

For someone already established on GitHub, a permanent migration costs a lot for a benefit that layered backups already provide. Back up your repos and change what really ties you down: the address of your pages.

The step that really removes the dependency: your own domain. Put new pages behind an address you own (e.g., guias.seudominio.com/projeto). If you switch services one day, you can change the DNS without breaking any links.
Glossary

The terms, in one line

For anyone just getting started.

Repository (repo)
A project folder with its full change history, managed by git.
Mirror (--mirror)
A complete copy of a repo, with all branches and tags, that can be updated.
Bundle
A single file containing an entire repo; you can clone from it.
Token
A "machine password" with limited permissions, used by scripts.
Fine-grained token
A token that lets you choose what it can do, which repos it can access, and when it expires.
2FA
Two-factor authentication: password + app or physical key.
CI / runner
Automation that runs with every push / the machine that runs that automation.
Pages
Free hosting for a static site from a repo.
Forgejo
Free software for running your own "GitHub" on a server.
VPS
A cloud server rented just for you.
push --force
A push that overwrites the history on the other side; it's how an attacker erases work.
Protected branch
A branch where the service rejects push --force and deletion.
Git LFS
A git extension for large files (video, model, dataset), stored separately.
cron / systemd timer
Linux's "alarm clock": it runs a command automatically at a scheduled time.
restic / borg
Backup programs that keep dated snapshots of a folder without repeating what hasn't changed.
SSH / rsync
Secure access to another computer / a folder copy that only sends what has changed.
gh / glab
GitHub / GitLab command-line tools.
Deploy / Vercel
Publishing a site online / a service that publishes sites with every push.
DNS / custom domain
The internet's "address book" / an address you own (e.g., yourdomain.com) that you point wherever you want.
Token scope
What the token can do: read_repository reads, write_repository pushes, and api does everything (including deleting).
Push to create
On GitLab, pushing to an address that doesn't exist yet creates the project as a private project.
refs/pull/*
Internal references GitHub creates for each pull request; they come with --mirror and can't be pushed back.
remote update --prune
Updates the mirror and removes branches that disappeared from the original (older snapshots still have them).
Fork / collaborator
A copy linked to the original repo / a person with access to another account's repo. Both link the accounts.
Append-only
A backup destination that accepts new data but won't let you delete or change old data.
Tailscale
A private network that connects your devices over the internet as if they were in the same home.
SSH key
A pair of files that replaces a password when accessing another computer.
Credential helper
A git feature that stores and provides a password or token without leaving it on the command line.
Rebase
Rewriting a branch's history to reorganize commits; afterward, pushing requires push --force.
3-2-1
3 copies, 2 places, 1 off-site.
Next steps

How to put this in place without getting lost

The order that gets results fastest.

Today
Prevention2FA everywhere, clean up tokens and keys, protect branches in important repos.
Week 1
Mirror + snapshots on your driveLocal mirrors of all repos, daily snapshots, and your first restore test with 3 repos.
Week 2
Copy to GitLabAn unlinked account, a push-only token (read_repository + write_repository), and daily pushes; GitLab creates each private project on the first push.
Later
Off-site copy and your own domainThe VPS pulls snapshots every week (or you set up Forgejo), and new pages use a domain you own.

Sources: GitLab.com settings · GitLab Storage · Codeberg FAQ · Codeberg Terms of Use · GitHub: large files · Codeberg and AI content · Forgejo