Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Keep new backups local until a remote is configured, preserve saved remotes and existing origins, and report whether an upload occurred. Thanks @NasAndNora for raising the shared default-remote issue.

- Batch main CodeQL analysis weekly while preserving PR and manual scans.

### Dependencies
Expand Down
21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ shards.
It is local-first:

- Normal archive/search commands do not upload data.
- `backup push` uploads only age-encrypted shards when you run it explicitly.
- `backup init` and `backup push` upload only with a configured remote; `--no-push` keeps changes local.
- Telegram message text, chat names, sender names, contact phone numbers,
contact usernames, avatar path metadata, and media metadata stay inside
encrypted backup payloads.
Expand Down Expand Up @@ -288,16 +288,17 @@ telecrawl backup push
telecrawl backup status
```

For compatibility, the built-in default backup config still points at the
maintainer's repository. Other users should override `--remote` as above;
running the default commands does not create a repository in your account:
There is no default remote. Without `--remote`, a saved `remote`, or an existing
Git `origin`, `backup init` and `backup push` commit locally without uploading.
Their output reports `pushed: false` when no upload occurs. `--no-push` also
keeps changes local when a remote exists. Existing saved remotes and Git origins
keep working and are not silently rewritten; an existing origin takes precedence.

```json
{
"repo": "~/Projects/backup-telecrawl",
"remote": "https://github.com/steipete/backup-telecrawl.git",
"identity": "~/.telecrawl/age.key"
}
Initialize a local-only backup without GitHub access:

```bash
telecrawl backup init
telecrawl backup push
```

Use a different repository or config path:
Expand Down
12 changes: 9 additions & 3 deletions internal/backup/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type archiveMetadata struct {
type ShardEntry = ckbackup.ShardEntry

type Result struct {
Pushed bool `json:"pushed"`
Repo string `json:"repo"`
Changed bool `json:"changed"`
Encrypted bool `json:"encrypted"`
Expand Down Expand Up @@ -145,8 +146,13 @@ func Push(ctx context.Context, st *store.Store, opts Options) (Result, error) {
if err != nil {
return Result{}, err
}
pushWithTag := opts.Push && strings.TrimSpace(opts.Tag) != ""
changed, err := commitAndPush(ctx, cfg, "sync: update encrypted telecrawl backup", opts.Push && !pushWithTag, toCrawlkitManifest(oldManifest), toCrawlkitManifest(manifest))
hasRemote, err := HasRemote(ctx, cfg)
if err != nil {
return Result{}, err
}
push := opts.Push && hasRemote
pushWithTag := push && strings.TrimSpace(opts.Tag) != ""
changed, err := commitAndPush(ctx, cfg, "sync: update encrypted telecrawl backup", push && !pushWithTag, toCrawlkitManifest(oldManifest), toCrawlkitManifest(manifest))
if err != nil {
return Result{}, err
}
Expand All @@ -164,7 +170,7 @@ func Push(ctx context.Context, st *store.Store, opts Options) (Result, error) {
return Result{}, err
}
}
return Result{Repo: cfg.Repo, Changed: changed, Encrypted: true, Shards: len(manifest.Shards), Messages: manifest.Counts.Messages, Tag: tag}, nil
return Result{Pushed: push, Repo: cfg.Repo, Changed: changed, Encrypted: true, Shards: len(manifest.Shards), Messages: manifest.Counts.Messages, Tag: tag}, nil
}

func Pull(ctx context.Context, st *store.Store, opts Options) (Result, error) {
Expand Down
5 changes: 0 additions & 5 deletions internal/backup/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@ import (
"strings"
)

const (
defaultRemote = "https://github.com/steipete/backup-telecrawl.git"
)

type Config struct {
Repo string `json:"repo"`
Remote string `json:"remote"`
Expand All @@ -38,7 +34,6 @@ type Options struct {
func DefaultConfig() Config {
return Config{
Repo: "~/Projects/backup-telecrawl",
Remote: defaultRemote,
Identity: "~/.telecrawl/age.key",
}
}
Expand Down
22 changes: 22 additions & 0 deletions internal/backup/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,24 @@ func ensureRepoForRead(ctx context.Context, cfg Config) error {
return mirror.Fetch(ctx, syncOptions(cfg))
}

// HasRemote reports whether a saved/explicit remote or an existing origin is configured.
// Existing origins remain authoritative and are never rewritten here.
func HasRemote(ctx context.Context, cfg Config) (bool, error) {
if strings.TrimSpace(cfg.Remote) != "" {
return true, nil
}
remotes, err := scopeGit(ctx, cfg.Repo, "remote")
if err != nil {
return false, err
}
for _, remote := range strings.Fields(string(remotes)) {
if remote == "origin" {
return true, nil
}
}
return false, nil
}

func commitAndPush(ctx context.Context, cfg Config, message string, push bool, manifests ...ckbackup.Manifest) (bool, error) {
paths, err := ownedPathspecs(ctx, cfg, manifests...)
if err != nil {
Expand All @@ -72,6 +90,10 @@ func commitAndPush(ctx context.Context, cfg Config, message string, push bool, m
if err != nil || !push {
return changed, err
}
hasRemote, err := HasRemote(ctx, cfg)
if err != nil || !hasRemote {
return changed, err
}
if err := verifyPendingHistory(ctx, cfg); err != nil {
return changed, err
}
Expand Down
131 changes: 131 additions & 0 deletions internal/backup/local_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package backup

import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
)

func TestBackupDefaultsToLocal(t *testing.T) {
if got := DefaultConfig().Remote; got != "" {
t.Fatalf("default remote = %q, want empty", got)
}
for _, body := range []string{"", "{}", `{"remote":""}`} {
path := filepath.Join(t.TempDir(), "backup.json")
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadConfig(path)
if err != nil || cfg.Remote != "" {
t.Fatalf("load %q: remote=%q, error=%v", body, cfg.Remote, err)
}
}
}

func TestBackupInitWithoutRemote(t *testing.T) {
root := t.TempDir()
opts := Options{ConfigPath: filepath.Join(root, "backup.json"), Repo: filepath.Join(root, "repo"), Identity: filepath.Join(root, "age.key"), Push: true}
cfg, _, err := Init(context.Background(), opts)
if err != nil {
t.Fatal(err)
}
if cfg.Remote != "" {
t.Fatalf("remote = %q, want empty", cfg.Remote)
}
if remotes := auditGitBytes(t, cfg.Repo, "remote"); len(remotes) != 0 {
t.Fatalf("unexpected remotes: %s", remotes)
}
}

func TestSavedBackupRemoteIsPreserved(t *testing.T) {
path := filepath.Join(t.TempDir(), "backup.json")
body := []byte(`{"remote":"https://example.invalid/personal-backup.git"}`)
if err := os.WriteFile(path, body, 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadConfig(path)
if err != nil || cfg.Remote != "https://example.invalid/personal-backup.git" {
t.Fatalf("remote=%q, error=%v", cfg.Remote, err)
}
after, err := os.ReadFile(path)
if err != nil || !bytes.Equal(body, after) {
t.Fatal("loading rewrote saved config")
}
}

func TestBackupPushWithoutRemoteStaysLocal(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
trace := filepath.Join(root, "git.trace")
t.Setenv("GIT_TRACE", trace)
opts := Options{ConfigPath: filepath.Join(root, "backup.json"), Repo: filepath.Join(root, "repo"), Identity: filepath.Join(root, "age.key"), Push: true}
if _, _, err := Init(ctx, opts); err != nil {
t.Fatal(err)
}
st := openFixtureStore(t, "local.db")
for _, tag := range []string{"", "snapshot/local"} {
opts.Tag = tag
result, err := Push(ctx, st, opts)
if err != nil {
t.Fatal(err)
}
if result.Pushed || result.Tag != tag {
t.Fatalf("unexpected local result: %+v", result)
}
}
if got := strings.TrimSpace(string(auditGitBytes(t, opts.Repo, "tag", "--list"))); got != "snapshot/local" {
t.Fatalf("local tag=%q", got)
}
logs, err := os.ReadFile(trace)
if err != nil {
t.Fatal(err)
}
for _, transport := range []string{"git clone", "git fetch", "git push", "git ls-remote", "upload-pack", "receive-pack"} {
if bytes.Contains(logs, []byte(transport)) {
t.Fatalf("local backup attempted transport %q", transport)
}
}
}

func TestBackupUsesExistingOriginWithoutSavedRemote(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
remote := filepath.Join(root, "remote.git")
runGit(t, root, "init", "--bare", remote)
opts := Options{ConfigPath: filepath.Join(root, "backup.json"), Repo: filepath.Join(root, "repo"), Identity: filepath.Join(root, "age.key"), Remote: remote}
cfg, _, err := Init(ctx, opts)
if err != nil {
t.Fatal(err)
}
cfg.Remote = ""
if err := SaveConfig(opts.ConfigPath, cfg); err != nil {
t.Fatal(err)
}
before, err := os.ReadFile(opts.ConfigPath)
if err != nil {
t.Fatal(err)
}
opts.Remote = ""
opts.Push = true
st := openFixtureStore(t, "origin.db")
for _, tag := range []string{"", "snapshot/origin"} {
opts.Tag = tag
result, err := Push(ctx, st, opts)
if err != nil || !result.Pushed {
t.Fatalf("origin push=%+v, error=%v", result, err)
}
}
if !bytes.Equal(auditGitBytes(t, opts.Repo, "rev-parse", "HEAD"), auditGitBytes(t, remote, "rev-parse", "refs/heads/main")) {
t.Fatal("origin did not receive snapshot")
}
if got := strings.TrimSpace(string(auditGitBytes(t, opts.Repo, "remote", "get-url", "origin"))); got != remote {
t.Fatalf("origin changed to %q", got)
}
after, err := os.ReadFile(opts.ConfigPath)
if err != nil || !bytes.Equal(before, after) {
t.Fatal("push rewrote saved config")
}
}
39 changes: 39 additions & 0 deletions internal/cli/backup_local_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package cli

import (
"bytes"
"context"
"encoding/json"
"path/filepath"
"strings"
"testing"
)

func TestBackupInitReportsLocalOnly(t *testing.T) {
root := t.TempDir()
var out, errOut bytes.Buffer
args := []string{"--json", "--db", filepath.Join(root, "archive.db"), "--source", filepath.Join(root, "source"), "backup", "init", "--config", filepath.Join(root, "backup.json"), "--repo", filepath.Join(root, "repo"), "--identity", filepath.Join(root, "age.key")}
if err := Run(context.Background(), args, &out, &errOut); err != nil {
t.Fatalf("init: %v, %s", err, &errOut)
}
var result struct {
Remote string `json:"remote"`
Pushed *bool `json:"pushed"`
}
if err := json.Unmarshal(out.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result.Remote != "" || result.Pushed == nil || *result.Pushed {
t.Fatalf("expected local-only output, got %s", &out)
}
}

func TestBackupHelpExplainsLocalOnly(t *testing.T) {
var out, errOut bytes.Buffer
if err := Run(context.Background(), []string{"--help"}, &out, &errOut); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "pushed=false") {
t.Fatalf("unexpected help: %s", &out)
}
}
9 changes: 7 additions & 2 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@
})
}

func storeImportResult(ctx context.Context, st *store.Store, result *telegramdesktop.ImportResult, chatFilter string, restore bool) error {

Check failure on line 256 in internal/cli/cli.go

View workflow job for this annotation

GitHub Actions / lint

unreachable func: storeImportResult
return storeImportResultCached(ctx, st, result, chatFilter, restore, nil)
}

Expand Down Expand Up @@ -1032,7 +1032,11 @@
if err != nil {
return err
}
return r.print(map[string]any{"repo": cfg.Repo, "remote": cfg.Remote, "identity": cfg.Identity, "recipient": recipient})
hasRemote, err := backup.HasRemote(r.ctx, cfg)
if err != nil {
return err
}
return r.print(map[string]any{"repo": cfg.Repo, "remote": cfg.Remote, "identity": cfg.Identity, "recipient": recipient, "pushed": opts.Push && hasRemote})
}

func (r *runtime) backupPush(args []string) error {
Expand Down Expand Up @@ -1266,7 +1270,8 @@
imports and backup pulls merge by default; --restore replaces the entire existing archive
--adopt-source non-destructively records a verified legacy archive's current source
import archives local cached Postbox media by default; --fetch-media also tries Telegram cloud media, bounded by --fetch-media-max-age (for example 168h) and --fetch-media-max-mb when set
backup writes encrypted age shards to a git repo
backup writes encrypted age shards to a git repo; pushed=false means the backup stays local
backup init/push uploads only with --remote, a saved remote, or an existing origin; --no-push keeps it local
`)
}

Expand Down
Loading