github-backup-cli 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 caelum0x
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,92 @@
1
- # Temporary Holding Version
1
+ # github-backup-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The problem: a GitHub account can get flagged, hacked, or suspended, and
4
+ every repo on it becomes unreachable until (or unless) it's fixed. It
5
+ happens to real accounts, not just hypothetical ones.
6
+
7
+ One command gets you a copy you hold yourself, independent of GitHub's
8
+ decisions about your account.
9
+
10
+ ```bash
11
+ npx github-backup-cli torvalds
12
+ ```
13
+
14
+ That clones every repo (full history, every branch and tag) into
15
+ `./github-backup-torvalds/`, plus an `issues.json` and `releases.json`
16
+ per repo. No GitHub token needed for public repos.
17
+
18
+ ## Backing up your own (incl. private) repos
19
+
20
+ ```bash
21
+ export GITHUB_TOKEN=ghp_xxx # a GitHub personal access token
22
+ npx github-backup-cli --dest ./my-backup
23
+ ```
24
+
25
+ With a token and no username, it backs up the token owner's own repos
26
+ (owner-affiliated only, not org repos you don't own).
27
+
28
+ ## Pushing the backup somewhere other than a local folder
29
+
30
+ ```bash
31
+ npx github-backup-cli myuser --remote "ssh://git@myserver/backups/{repo}.git"
32
+ ```
33
+
34
+ `{repo}` is replaced with each repo's name. This works with any git
35
+ remote — your own server, another host, anything that accepts
36
+ `git push --mirror`.
37
+
38
+ ## Optional: mirror straight into Rithub
39
+
40
+ If you'd rather not run your own git server, [Rithub](https://rithub.dev)
41
+ hosts it for you. `--to rithub` mirrors every repo into a Rithub account
42
+ in the same run, using Rithub's own migrate API (no local clone needed
43
+ for this part, though you can do both at once):
44
+
45
+ ```bash
46
+ npx github-backup-cli myuser --to rithub \
47
+ --rithub-user myuser --rithub-token $RITHUB_TOKEN
48
+ ```
49
+
50
+ Rithub access tokens: Settings → Applications → Generate New Token on
51
+ your Rithub account. `RITHUB_USER` / `RITHUB_TOKEN` / `RITHUB_HOST`
52
+ environment variables work the same as the flags.
53
+
54
+ Already-mirrored repos are skipped on re-runs, so this is safe to run
55
+ on a schedule.
56
+
57
+ ## All options
58
+
59
+ ```
60
+ npx github-backup-cli <github-user> [options]
61
+
62
+ <github-user> GitHub username to back up (required unless
63
+ --token is set, in which case it backs up the
64
+ token owner's own repos)
65
+
66
+ --dest <dir> Local folder for the mirrors (default:
67
+ ./github-backup-<user>)
68
+ --token <token> GitHub token (env GITHUB_TOKEN)
69
+ --no-meta Skip issues/releases JSON export
70
+ --no-local Skip the local mirror clone
71
+ --remote <template> Push each mirror to a git remote too,
72
+ "{repo}" replaced with the repo name
73
+ --to rithub Also migrate every repo into a Rithub account
74
+ --rithub-user <user> Rithub account to receive repos
75
+ --rithub-token <token> Rithub access token
76
+ --rithub-host <host> Rithub host (default rithub.dev)
77
+ ```
78
+
79
+ ## What this does not back up
80
+
81
+ Pull request review threads, project boards, GitHub Actions run
82
+ history, and GitHub Pages deployments are not covered — those live in
83
+ GitHub's own systems beyond a repo's git data and REST-visible issues
84
+ and releases.
85
+
86
+ ## Requirements
87
+
88
+ Node.js 18+, and `git` on your `PATH`. No other dependencies.
89
+
90
+ ## License
91
+
92
+ MIT
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env node
2
+ import { mkdirSync } from "node:fs";
3
+ import { listRepos } from "../lib/github.mjs";
4
+ import { mirrorRepoLocally, pushMirrorToRemote, saveMetadata } from "../lib/backup.mjs";
5
+ import { migrateRepoToRithub, repoExistsOnRithub } from "../lib/rithub.mjs";
6
+
7
+ const HELP = `github-backup-cli <github-user> [options]
8
+
9
+ Backs up all of a GitHub user's repos (full git history, every branch
10
+ and tag, + issues/releases metadata) with one command. Works fully
11
+ without Rithub.
12
+
13
+ <github-user> GitHub username to back up (required unless
14
+ --token is set, in which case it backs up the
15
+ token owner's own repos).
16
+
17
+ Options:
18
+ --dest <dir> Local folder for the mirrors (default:
19
+ ./github-backup-<user>)
20
+ --token <token> GitHub token (env GITHUB_TOKEN). Needed for
21
+ private repos or to raise the 60/hr rate limit.
22
+ --no-meta Skip issues/releases JSON export (on by default)
23
+ --no-local Skip the local mirror clone (useful with --to
24
+ rithub if you only want the server-side mirror)
25
+ --remote <template> Also push each mirror to a git remote. "{repo}"
26
+ in the URL is replaced with the repo name.
27
+ --to rithub Also migrate every repo straight into a Rithub
28
+ account, via Rithub's own migrate API.
29
+ --rithub-user <user> Rithub account to receive repos (env RITHUB_USER,
30
+ default: same as <github-user>)
31
+ --rithub-token <token> Rithub access token (env RITHUB_TOKEN)
32
+ --rithub-host <host> Rithub host (env RITHUB_HOST, default rithub.dev)
33
+ -h, --help Show this help
34
+
35
+ Examples:
36
+ npx github-backup-cli torvalds
37
+ npx github-backup-cli myorg --token $GITHUB_TOKEN --dest ./backups
38
+ npx github-backup-cli caelum0x --to rithub --rithub-token $RITHUB_TOKEN
39
+
40
+ The problem this solves: a flagged, hacked or suspended GitHub account
41
+ can take every repo you have with it. One command gets a copy you hold
42
+ yourself. If you'd rather not run your own git server, Rithub
43
+ (https://rithub.dev) hosts it for you — that's what --to rithub does.
44
+ `;
45
+
46
+ function parseArgs(argv) {
47
+ const args = { _: [] };
48
+ for (let i = 0; i < argv.length; i += 1) {
49
+ const a = argv[i];
50
+ if (a === "-h" || a === "--help") args.help = true;
51
+ else if (a === "--no-meta") args.meta = false;
52
+ else if (a === "--no-local") args.local = false;
53
+ else if (a === "--dest") args.dest = argv[++i];
54
+ else if (a === "--token") args.token = argv[++i];
55
+ else if (a === "--remote") args.remote = argv[++i];
56
+ else if (a === "--to") args.to = argv[++i];
57
+ else if (a === "--rithub-user") args.rithubUser = argv[++i];
58
+ else if (a === "--rithub-token") args.rithubToken = argv[++i];
59
+ else if (a === "--rithub-host") args.rithubHost = argv[++i];
60
+ else args._.push(a);
61
+ }
62
+ return args;
63
+ }
64
+
65
+ async function main() {
66
+ const args = parseArgs(process.argv.slice(2));
67
+ if (args.help || (!args._[0] && !process.env.GITHUB_TOKEN && !args.token)) {
68
+ process.stdout.write(HELP);
69
+ process.exit(args.help ? 0 : 1);
70
+ }
71
+
72
+ const token = args.token || process.env.GITHUB_TOKEN || "";
73
+ const login = args._[0] || "";
74
+ const includeMeta = args.meta !== false;
75
+ const includeLocal = args.local !== false;
76
+ const destDir = args.dest || `./github-backup-${login || "me"}`;
77
+ const toRithub = args.to === "rithub";
78
+
79
+ console.log(`github-backup-cli: listing repos for ${login || "(token owner)"}...`);
80
+ const repos = await listRepos({ login, token });
81
+ if (repos.length === 0) {
82
+ console.log("No repos found (check the username, or pass --token for private repos).");
83
+ return;
84
+ }
85
+ console.log(`Found ${repos.length} repo(s).`);
86
+
87
+ if (includeLocal) mkdirSync(destDir, { recursive: true });
88
+
89
+ let rithubUser = "";
90
+ let rithubToken = "";
91
+ let rithubHost = "";
92
+ if (toRithub) {
93
+ rithubUser = args.rithubUser || process.env.RITHUB_USER || login;
94
+ rithubToken = args.rithubToken || process.env.RITHUB_TOKEN || "";
95
+ rithubHost = args.rithubHost || process.env.RITHUB_HOST || "rithub.dev";
96
+ if (!rithubUser || !rithubToken) {
97
+ console.error("--to rithub needs --rithub-user and --rithub-token (or RITHUB_USER / RITHUB_TOKEN).");
98
+ process.exit(1);
99
+ }
100
+ }
101
+
102
+ let ok = 0;
103
+ let failed = 0;
104
+ for (const repo of repos) {
105
+ const label = repo.full_name || repo.name;
106
+ try {
107
+ if (includeLocal) {
108
+ const local = mirrorRepoLocally({ repo, destDir, token });
109
+ if (includeMeta) await saveMetadata({ repo, destDir, token });
110
+ if (args.remote) {
111
+ const remoteUrl = args.remote.replace("{repo}", repo.name);
112
+ pushMirrorToRemote({ localMirrorPath: local, remoteUrl });
113
+ }
114
+ console.log(`[local] backed up: ${label}`);
115
+ }
116
+ if (toRithub) {
117
+ const exists = await repoExistsOnRithub({
118
+ host: rithubHost,
119
+ rithubUser,
120
+ rithubToken,
121
+ name: repo.name,
122
+ });
123
+ if (exists) {
124
+ console.log(`[rithub] skip (already on ${rithubHost}): ${label}`);
125
+ } else {
126
+ const result = await migrateRepoToRithub({
127
+ repo,
128
+ host: rithubHost,
129
+ rithubUser,
130
+ rithubToken,
131
+ githubToken: token,
132
+ });
133
+ if (result.ok) console.log(`[rithub] mirrored: ${label} -> https://${rithubHost}/${rithubUser}/${repo.name}`);
134
+ else console.error(`[rithub] FAILED (HTTP ${result.status}): ${label} ${result.detail || ""}`);
135
+ }
136
+ }
137
+ ok += 1;
138
+ } catch (err) {
139
+ failed += 1;
140
+ console.error(`FAILED: ${label}: ${err.message || err}`);
141
+ }
142
+ }
143
+ console.log(`Done. ${ok} repo(s) processed, ${failed} failed.`);
144
+ if (includeLocal) console.log(`Local backups in: ${destDir}`);
145
+ }
146
+
147
+ main().catch((err) => {
148
+ console.error(`github-backup-cli: ${err.message || err}`);
149
+ process.exit(1);
150
+ });
package/lib/backup.mjs ADDED
@@ -0,0 +1,51 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { listIssues, listReleases } from "./github.mjs";
5
+
6
+ function run(cmd, args, opts = {}) {
7
+ const res = spawnSync(cmd, args, { stdio: "pipe", encoding: "utf8", ...opts });
8
+ if (res.status !== 0) {
9
+ const detail = (res.stderr || res.stdout || "").trim().slice(0, 400);
10
+ throw new Error(`${cmd} ${args.join(" ")} failed: ${detail}`);
11
+ }
12
+ return res;
13
+ }
14
+
15
+ // cloneUrlWithToken: embed a token for private repos without ever
16
+ // printing it (git itself never sees it on argv, only inside the URL
17
+ // passed straight to the clone/push subprocess).
18
+ function cloneUrlWithToken(httpsCloneUrl, token) {
19
+ if (!token) return httpsCloneUrl;
20
+ return httpsCloneUrl.replace("https://", `https://x-access-token:${token}@`);
21
+ }
22
+
23
+ // mirrorRepoLocally: `git clone --mirror` gets every branch, tag and ref
24
+ // in one shot — the same guarantee competing backup tools make. Returns
25
+ // the local bare-repo path.
26
+ export function mirrorRepoLocally({ repo, destDir, token }) {
27
+ const target = join(destDir, `${repo.name}.git`);
28
+ const url = cloneUrlWithToken(repo.clone_url, token);
29
+ run("git", ["clone", "--mirror", "--quiet", url, target]);
30
+ return target;
31
+ }
32
+
33
+ // pushMirrorToRemote: push every ref from the local bare mirror to an
34
+ // arbitrary git remote (another host, a second Rithub, a NAS, anything
35
+ // that accepts `git push --mirror`).
36
+ export function pushMirrorToRemote({ localMirrorPath, remoteUrl }) {
37
+ run("git", ["-C", localMirrorPath, "push", "--mirror", "--quiet", remoteUrl]);
38
+ }
39
+
40
+ // saveMetadata: issues + releases as plain JSON next to the mirror.
41
+ // Two API calls per repo — cheap, and skippable with --no-meta.
42
+ export async function saveMetadata({ repo, destDir, token }) {
43
+ const [issues, releases] = await Promise.all([
44
+ listIssues(repo.owner.login, repo.name, token).catch((err) => ({ error: String(err) })),
45
+ listReleases(repo.owner.login, repo.name, token).catch((err) => ({ error: String(err) })),
46
+ ]);
47
+ const metaDir = join(destDir, `${repo.name}.git`, "github-meta");
48
+ mkdirSync(metaDir, { recursive: true });
49
+ writeFileSync(join(metaDir, "issues.json"), JSON.stringify(issues, null, 2));
50
+ writeFileSync(join(metaDir, "releases.json"), JSON.stringify(releases, null, 2));
51
+ }
package/lib/github.mjs ADDED
@@ -0,0 +1,52 @@
1
+ // Minimal GitHub REST API client: just the list/paginate calls this CLI
2
+ // needs. No dependencies, no auth required for public repos.
3
+
4
+ const API = "https://api.github.com";
5
+
6
+ function authHeaders(token) {
7
+ const headers = { "User-Agent": "github-backup-cli" };
8
+ if (token) headers.Authorization = `Bearer ${token}`;
9
+ return headers;
10
+ }
11
+
12
+ async function getJson(url, token) {
13
+ const res = await fetch(url, { headers: authHeaders(token) });
14
+ if (!res.ok) {
15
+ const body = await res.text().catch(() => "");
16
+ throw new Error(`GitHub API ${res.status} on ${url}: ${body.slice(0, 200)}`);
17
+ }
18
+ return res.json();
19
+ }
20
+
21
+ async function paginate(urlBase, token) {
22
+ const out = [];
23
+ let page = 1;
24
+ // 100 is GitHub's max per_page; stop once a page comes back short.
25
+ for (;;) {
26
+ const sep = urlBase.includes("?") ? "&" : "?";
27
+ const page_data = await getJson(`${urlBase}${sep}per_page=100&page=${page}`, token);
28
+ if (!Array.isArray(page_data) || page_data.length === 0) break;
29
+ out.push(...page_data);
30
+ if (page_data.length < 100) break;
31
+ page += 1;
32
+ }
33
+ return out;
34
+ }
35
+
36
+ // listRepos: public repos of `login` if no token, else the token owner's
37
+ // own repos (owner affiliation only — no org repos, matching the plain
38
+ // "back up MY stuff" promise; private repos included when token is set).
39
+ export async function listRepos({ login, token }) {
40
+ if (token) {
41
+ return paginate(`${API}/user/repos?affiliation=owner&sort=full_name`, token);
42
+ }
43
+ return paginate(`${API}/users/${login}/repos?sort=full_name`, token);
44
+ }
45
+
46
+ export async function listIssues(owner, repo, token) {
47
+ return paginate(`${API}/repos/${owner}/${repo}/issues?state=all`, token);
48
+ }
49
+
50
+ export async function listReleases(owner, repo, token) {
51
+ return paginate(`${API}/repos/${owner}/${repo}/releases`, token);
52
+ }
package/lib/rithub.mjs ADDED
@@ -0,0 +1,94 @@
1
+ // --to rithub: mirror straight from GitHub into a Rithub account using
2
+ // Rithub's own migrate API (POST /api/v1/repos/migrate, HTTP Basic auth
3
+ // with a Rithub access token as the password). Same request shape proven
4
+ // live on rithub.dev: service "github", mirror: true, auth_token is the
5
+ // GitHub token (omit for public repos).
6
+
7
+ function authHeader(rithubUser, rithubToken) {
8
+ const basic = Buffer.from(`${rithubUser}:${rithubToken}`).toString("base64");
9
+ return { Authorization: `Basic ${basic}`, "User-Agent": "github-backup-cli" };
10
+ }
11
+
12
+ async function rithubRequest(host, method, path, rithubUser, rithubToken, body) {
13
+ const res = await fetch(`https://${host}${path}`, {
14
+ method,
15
+ headers: {
16
+ ...authHeader(rithubUser, rithubToken),
17
+ ...(body ? { "Content-Type": "application/json" } : {}),
18
+ },
19
+ body: body ? JSON.stringify(body) : undefined,
20
+ });
21
+ const text = await res.text().catch(() => "");
22
+ return { status: res.status, text };
23
+ }
24
+
25
+ export async function repoExistsOnRithub({ host, rithubUser, rithubToken, name }) {
26
+ const { status } = await rithubRequest(
27
+ host,
28
+ "GET",
29
+ `/api/v1/repos/${rithubUser}/${name}`,
30
+ rithubUser,
31
+ rithubToken,
32
+ );
33
+ return status === 200;
34
+ }
35
+
36
+ // disableActionsForMirror: best-effort. Gitea-family migrate has no
37
+ // create-time flag to skip Actions, and a mirrored repo with many tags
38
+ // can queue a CI run per historical ref (seen live on railyard-box — see
39
+ // plans/railyard.md). Never throws: a failed PATCH just leaves Actions on.
40
+ async function disableActionsForMirror({ host, rithubUser, rithubToken, name }) {
41
+ try {
42
+ await rithubRequest(
43
+ host,
44
+ "PATCH",
45
+ `/api/v1/repos/${rithubUser}/${name}`,
46
+ rithubUser,
47
+ rithubToken,
48
+ { has_actions: false },
49
+ );
50
+ } catch {
51
+ // intentionally swallowed — cosmetic cleanup only
52
+ }
53
+ }
54
+
55
+ // migrateRepoToRithub: one repo, one migrate call. Returns a short status
56
+ // string for the caller to print; never throws on an ordinary API error
57
+ // so one failed repo doesn't abort the whole run.
58
+ export async function migrateRepoToRithub({
59
+ repo,
60
+ host,
61
+ rithubUser,
62
+ rithubToken,
63
+ githubToken,
64
+ }) {
65
+ const body = {
66
+ clone_addr: repo.clone_url,
67
+ repo_name: repo.name,
68
+ repo_owner: rithubUser,
69
+ service: "github",
70
+ mirror: true,
71
+ mirror_interval: "8h",
72
+ private: Boolean(repo.private),
73
+ wiki: true,
74
+ issues: true,
75
+ pull_requests: true,
76
+ releases: true,
77
+ labels: true,
78
+ milestones: true,
79
+ ...(githubToken ? { auth_token: githubToken } : {}),
80
+ };
81
+ const { status, text } = await rithubRequest(
82
+ host,
83
+ "POST",
84
+ "/api/v1/repos/migrate",
85
+ rithubUser,
86
+ rithubToken,
87
+ body,
88
+ );
89
+ if (status >= 200 && status < 300) {
90
+ await disableActionsForMirror({ host, rithubUser, rithubToken, name: repo.name });
91
+ return { ok: true, status };
92
+ }
93
+ return { ok: false, status, detail: text.slice(0, 300) };
94
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "github-backup-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Back up all of a GitHub user's or org's repos (code + optional issues/releases metadata) to a local folder or any git remote with one command. Optional --to rithub mirrors everything into a Rithub account in the same run.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "github-backup-cli": "bin/github-backup-cli.mjs"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "lib",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://rithub.dev/caelum0x/github-backup-cli.git"
22
+ },
23
+ "homepage": "https://rithub.dev/caelum0x/github-backup-cli",
24
+ "bugs": {
25
+ "url": "https://rithub.dev/caelum0x/github-backup-cli/issues"
26
+ },
27
+ "keywords": [
28
+ "github",
29
+ "backup",
30
+ "mirror",
31
+ "git-backup",
32
+ "repo-backup",
33
+ "github-backup",
34
+ "rithub"
35
+ ],
36
+ "dependencies": {}
37
+ }