diff --git a/CHANGELOG.md b/CHANGELOG.md index 09751e5..887238c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac ### Added +- **Settings → Account → Export my data** downloads a ZIP with the account's current project files, Git history, chats, and settings. The project list marks items in the trash. Provider and sign-in credentials are excluded. Administrators can make the same archive with `refract users export `. - Refract can read its encryption key, OpenID Connect client secret, SMTP URL and OpenAlex API key from files using the corresponding `REFRACT_*_FILE` variables. `refract users` and `refract local` also accept the encryption key from a file, and the systemd unit starts Refract directly with a systemd credential. - `REFRACT_OUTBOUND` (`any` by default, or `public`) chooses whether AI provider base URLs and git remotes may reach loopback and private networks. `public` does what `REFRACT_MODE=saas` did for outbound requests, and checks at startup that git is 2.37 or later. With `public`, provider requests and redirects must be https, and link-local git remotes are refused in every mode. `REFRACT_MODE=saas` no longer changes it. - Refract finds `tectonic`, `synctex`, `rg` and `git` in a bundled `libexec/refract` folder next to the executable (the executable's own folder on Windows) before the `PATH`, and runs them by absolute path; a bundled Git uses only its own helpers and templates. `REFRACT_TECTONIC_BIN`, `REFRACT_SYNCTEX_BIN`, `REFRACT_RG_BIN` and `REFRACT_GIT_BIN` override the lookup. The startup log shows where each was found, and the web app shows one notice when a tool is missing, saying what won't work, on whichever page opens first. On macOS and Linux a bundled tool in a folder that others can write, or that another user owns, is ignored. The same checks cover bundled Git's helpers and templates. diff --git a/README.md b/README.md index 775dd12..5487d78 100644 --- a/README.md +++ b/README.md @@ -320,6 +320,10 @@ docker exec refract refract users list Accounts you add this way count as confirmed: you vouch for the address. People can see and end their own sessions in Settings → Account. To end all of someone's sessions for them (a lost laptop, say), run `refract users signout `. After too many failed sign-ins an account waits 15 minutes; `refract users unlock ` lets it in at once. To delete an account with its projects (those in the trash too), chats and connections, run `refract users remove `: it lists what would go, and deletes only when run again with `--yes`. With Cloudflare Access, also remove the person from your Access policy, or they get a new, empty account on their next visit. +**Export my data** in **Settings → Account** prepares a ZIP in the background and downloads it when ready. It contains current project files, including edits saved since the last commit, and a `history.bundle` for each project. Use `git clone history.bundle ` to open a project's history. `projects.json` identifies projects in the trash by their `deleted_at` date and marks saved templates. Each project's `chats.json` contains its conversations and turns. The ZIP includes account settings and token totals. Refract excludes passwords, sessions, connection credentials, provider endpoints and raw provider errors. Files, commits and messages are exported as written. + +An administrator can create the same ZIP with `refract users export ` using the server's data folder and encryption key. The command requires a new destination file. + ### Sign in with OpenID Connect With `REFRACT_AUTH=builtin`, an OpenID Connect provider (Google, Microsoft Entra, Keycloak, Authentik, Authelia…) can add a **Continue with …** button next to the password form. @@ -614,6 +618,7 @@ refract users rename change an account's email, keeping its data refract users signout end all of an account's sessions refract users unlock clear an account's failed sign-ins and email limit (--all: every account and address) refract users remove delete an account and everything it owns, trash included (asks for --yes) +refract users export write a ZIP of an account's projects, history, chats and settings refract users list list accounts refract version print the version ``` diff --git a/cmd/refract/account_api.go b/cmd/refract/account_api.go index de5b469..1395103 100644 --- a/cmd/refract/account_api.go +++ b/cmd/refract/account_api.go @@ -311,6 +311,9 @@ func (a *loginAPI) deleteAccount(w http.ResponseWriter, r *http.Request) { projectError(w, err) return } + if a.exports != nil { + a.exports.discard(u.ID) + } if a.mailReady() { if m, ok := a.compose(users.RequestLang(r), mail.Deleted, acct, mail.Data{}); ok { a.mail.Send(m) diff --git a/cmd/refract/account_api_test.go b/cmd/refract/account_api_test.go index b5e0b23..67e6db0 100644 --- a/cmd/refract/account_api_test.go +++ b/cmd/refract/account_api_test.go @@ -69,9 +69,11 @@ func newAccountEnv(t *testing.T, o envOpts) *accountEnv { } t.Cleanup(func() { db.Close() }) people := &users.Service{DB: db, Key: make([]byte, 32)} - ps := &projects.Service{DB: db, Dir: filepath.Join(dir, "projects"), Limits: projects.DefaultLimits} + ps := &projects.Service{DB: db, Dir: filepath.Join(dir, "projects"), Limits: projects.DefaultLimits, Key: people.Key} e := &accountEnv{t: t, people: people, ps: ps, fake: &mail.Fake{}} - e.login = &loginAPI{users: people, mode: mode.SelfHost, signup: o.signup, destroy: destroyer(ps)} + exports := &accountExports{ctx: context.Background(), projects: ps} + t.Cleanup(exports.close) + e.login = &loginAPI{users: people, mode: mode.SelfHost, signup: o.signup, destroy: destroyer(ps), exports: exports} if !o.noMail { e.login.public = "https://r.test" e.outbox = mail.NewOutbox(e.fake) @@ -81,6 +83,7 @@ func newAccountEnv(t *testing.T, o envOpts) *accountEnv { app := http.NewServeMux() rt := &router{mux: app, acc: &access.Checker{DB: db}} (&projectsAPI{svc: ps}).routes(rt) + exports.routes(rt) e.login.accountRoutes(rt) mux := http.NewServeMux() mux.Handle("/api/auth/", e.login.handler()) diff --git a/cmd/refract/account_export.go b/cmd/refract/account_export.go new file mode 100644 index 0000000..cac2c5d --- /dev/null +++ b/cmd/refract/account_export.go @@ -0,0 +1,183 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "net/http" + "os" + "sync" + "time" + + "github.com/ponytojas/Refract/internal/accountexport" + "github.com/ponytojas/Refract/internal/projects" +) + +const exportRetention = 10 * time.Minute + +type accountExport struct { + status string // preparing, ready or failed + cancel context.CancelFunc + timer *time.Timer + path string + downloaded bool +} + +// accountExports keeps in-progress archives off request threads and finished +// archives on disk. The map is indexed by the authenticated account ID. +type accountExports struct { + ctx context.Context + projects *projects.Service + mu sync.Mutex + jobs map[string]*accountExport + running int + closed bool +} + +func (e *accountExports) start(owner string) (string, bool) { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed || e.ctx.Err() != nil { + return "", false + } + existing := e.jobs[owner] + if existing != nil && (existing.status == "preparing" || existing.status == "ready" && !existing.downloaded) { + return existing.status, true + } + // A small number of simultaneous git packs keeps a shared server responsive. + if e.running >= 2 { + return "", false + } + e.removeLocked(owner) + if e.jobs == nil { + e.jobs = make(map[string]*accountExport) + } + ctx, cancel := context.WithTimeout(e.ctx, 30*time.Minute) + job := &accountExport{status: "preparing", cancel: cancel} + e.jobs[owner] = job + e.running++ + go e.build(ctx, owner, job) + return job.status, true +} + +func (e *accountExports) build(ctx context.Context, owner string, job *accountExport) { + defer job.cancel() + f, err := os.CreateTemp("", "refract-account-export-*.zip") + var path string + if err == nil { + path = f.Name() + err = errors.Join(accountexport.Write(ctx, f, e.projects, owner), f.Close(), ctx.Err()) + } + e.mu.Lock() + defer e.mu.Unlock() + e.running-- + if e.jobs[owner] != job { + if path != "" { + os.Remove(path) + } + return + } + if err != nil { + if path != "" { + os.Remove(path) + } + slog.Warn("account export failed", "user", owner, "err", err) + job.status = "failed" + } else { + job.status, job.path = "ready", path + } + job.timer = time.AfterFunc(exportRetention, func() { + e.mu.Lock() + defer e.mu.Unlock() + if e.jobs[owner] == job { + e.removeLocked(owner) + } + }) +} + +func (e *accountExports) removeLocked(owner string) { + job := e.jobs[owner] + if job == nil { + return + } + delete(e.jobs, owner) + job.cancel() + if job.timer != nil { + job.timer.Stop() + } + if job.path != "" { + os.Remove(job.path) + } +} + +func (e *accountExports) discard(owner string) { + e.mu.Lock() + defer e.mu.Unlock() + e.removeLocked(owner) +} + +func (e *accountExports) close() { + e.mu.Lock() + defer e.mu.Unlock() + e.closed = true + for owner := range e.jobs { + e.removeLocked(owner) + } +} + +func (e *accountExports) routes(rt *router) { + rt.user("POST /api/account/export", e.startExport) + rt.user("GET /api/account/export", e.exportStatus) + rt.user("GET /api/account/export/download", e.downloadExport) +} + +func (e *accountExports) startExport(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + status, ok := e.start(requestUser(r.Context())) + if !ok { + httpError(w, errors.New("account export is busy"), http.StatusServiceUnavailable) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusAccepted) + writeJSON(w, map[string]string{"status": status}) +} + +func (e *accountExports) exportStatus(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + e.mu.Lock() + var status string + if job := e.jobs[requestUser(r.Context())]; job != nil { + status = job.status + } + e.mu.Unlock() + if status == "" { + http.NotFound(w, r) + return + } + writeJSON(w, map[string]string{"status": status}) +} + +func (e *accountExports) downloadExport(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + e.mu.Lock() + job := e.jobs[requestUser(r.Context())] + if job == nil || job.status != "ready" { + e.mu.Unlock() + http.NotFound(w, r) + return + } + f, err := os.Open(job.path) + if err == nil && r.Method != http.MethodHead { + job.downloaded = true + } + e.mu.Unlock() + if err != nil { + httpError(w, errors.New("account export is unavailable"), http.StatusInternalServerError) + return + } + defer f.Close() + w.Header().Set("Content-Type", "application/zip") + w.Header().Set("Content-Disposition", `attachment; filename="refract-account.zip"`) + http.ServeContent(w, r, "refract-account.zip", time.Time{}, f) +} diff --git a/cmd/refract/account_export_test.go b/cmd/refract/account_export_test.go new file mode 100644 index 0000000..9fda522 --- /dev/null +++ b/cmd/refract/account_export_test.go @@ -0,0 +1,260 @@ +package main + +import ( + "archive/zip" + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/ponytojas/Refract/internal/auth" + "github.com/ponytojas/Refract/internal/projects" + "github.com/ponytojas/Refract/internal/providers" + "github.com/ponytojas/Refract/internal/store" + "github.com/ponytojas/Refract/internal/tools" +) + +func readAccountZip(t *testing.T, raw []byte, forbidden ...string) map[string][]byte { + t.Helper() + archive, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + t.Fatal(err) + } + entries := map[string][]byte{} + for _, f := range archive.File { + r, err := f.Open() + if err != nil { + t.Fatal(err) + } + content, err := io.ReadAll(r) + r.Close() + if err != nil { + t.Fatal(err) + } + for _, secret := range forbidden { + if bytes.Contains(content, []byte(secret)) { + t.Errorf("%s contains a credential or data from another account", f.Name) + } + } + entries[f.Name] = content + } + return entries +} + +func TestAccountExport(t *testing.T) { + e := newAccountEnv(t, envOpts{noMail: true}) + ctx := context.Background() + const password = "fixture-owner-password" + ana, err := e.people.SetPassword(ctx, "ana@example.com", password) + if err != nil { + t.Fatal(err) + } + bob, err := e.people.SetPassword(ctx, "bob@example.com", "fixture-other-password") + if err != nil { + t.Fatal(err) + } + owner := auth.WithUser(ctx, ana) + if err := e.people.SetLang(ctx, ana.ID, "es"); err != nil { + t.Fatal(err) + } + create := func(ctx context.Context, name string) *projects.Project { + t.Helper() + p, err := e.ps.Create(ctx, name) + if err != nil { + t.Fatal(err) + } + return p + } + draft := create(owner, "Active draft") + trash := create(owner, "Deleted draft") + foreign := create(auth.WithUser(ctx, bob), "Another user's draft") + if err := e.ps.WriteFile(owner, draft.ID, "main.tex", strings.NewReader("Committed text")); err != nil { + t.Fatal(err) + } + if ok, err := e.ps.Checkpoint(owner, draft.ID, "second commit"); err != nil || !ok { + t.Fatalf("checkpoint: %t %v", ok, err) + } + if err := e.ps.WriteFile(owner, draft.ID, "main.tex", strings.NewReader("Latest uncommitted edit")); err != nil { + t.Fatal(err) + } + template, err := e.ps.SaveTemplate(owner, draft.ID, "Private starter") + if err != nil { + t.Fatal(err) + } + query := func(sql string, args ...any) { + t.Helper() + if _, err := e.people.DB.ExecContext(ctx, sql, args...); err != nil { + t.Fatal(err) + } + } + for _, p := range []*projects.Project{draft, trash, foreign} { + query(`INSERT INTO chats (id, project_id, title, created_at, updated_at) VALUES (?, ?, ?, 0, 0)`, p.ID, p.ID, p.Name+" conversation") + query(`INSERT INTO turns (id, chat_id, message, reply, status, error, created_at, updated_at) + VALUES (?, ?, ?, ?, 'failed', ?, 0, 0)`, p.ID, p.ID, "Prompt in "+p.Name, "Reply in "+p.Name, + `{"message":"fixture-raw-provider-error-secret"}`) + } + if err := e.ps.Trash(owner, trash.ID); err != nil { + t.Fatal(err) + } + const apiKey = "fixture-provider-key" + const endpointSecret = "fixture-endpoint-secret" + const gitSecret = "fixture-git-config-secret" + providerStore := &providers.Store{DB: e.people.DB, Key: e.people.Key} + err = providerStore.Save(ctx, ana.ID, providers.Config{ + ID: "compat", Kind: "compat", Name: "My provider", APIKey: apiKey, BaseURL: "https://example.com/v1?token=" + endpointSecret, + }) + if err != nil { + t.Fatal(err) + } + setting := store.UserKey(ana.ID, "providers") + sealed, err := store.GetSetting(ctx, e.people.DB, setting) + if err != nil || sealed == "" { + t.Fatalf("stored provider settings: %v", err) + } + var passwordHash string + if err := e.people.DB.QueryRowContext(ctx, `SELECT password FROM users WHERE id = ?`, ana.ID).Scan(&passwordHash); err != nil { + t.Fatal(err) + } + forbidden := []string{password, passwordHash, apiKey, endpointSecret, gitSecret, sealed, + "fixture-raw-provider-error-secret", foreign.Name, foreign.ID} + for key, value := range map[string]string{ + store.UserKey(ana.ID, "siwc.credentials"): "fixture-chatgpt-credentials", + store.UserKey(ana.ID, "github"): "fixture-github-token", + "remote:" + draft.ID: "fixture-git-remote-token", + } { + ciphertext, err := store.Seal(e.people.Key, []byte(value), key) + if err != nil { + t.Fatal(err) + } + if err := store.SetSetting(ctx, e.people.DB, key, ciphertext); err != nil { + t.Fatal(err) + } + forbidden = append(forbidden, value, ciphertext) + } + git, err := tools.Path("git") + if err != nil { + t.Fatal(err) + } + gitRun := func(args ...string) string { + t.Helper() + out, err := exec.Command(git, args...).CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return string(out) + } + gitRun("-C", e.ps.Path(draft.ID), "config", "remote.fixture.url", "https://example.com/"+gitSecret) + + login := func(email, password string) *browser { + b := e.browser() + b.expect(b.post("/api/auth/login", map[string]string{"email": email, "password": password}), http.StatusNoContent, "") + return b + } + a := login(ana.Email, password) + b := login(bob.Email, "fixture-other-password") + var sessionHash string + if err := e.people.DB.QueryRowContext(ctx, `SELECT id FROM sessions WHERE user_id = ?`, ana.ID).Scan(&sessionHash); err != nil { + t.Fatal(err) + } + forbidden = append(forbidden, sessionHash) + const endpoint = "/api/account/export" + b.expect(a.post(endpoint, nil), http.StatusAccepted, "") + for deadline := time.Now().Add(10 * time.Second); ; { + res := a.do("GET", endpoint, nil) + if res.Status == http.StatusOK && strings.Contains(res.Body, `"ready"`) { + break + } + if res.Status != http.StatusOK || strings.Contains(res.Body, `"failed"`) || time.Now().After(deadline) { + t.Fatalf("export status: %d %s", res.Status, res.Body) + } + time.Sleep(10 * time.Millisecond) + } + for _, path := range []string{endpoint, endpoint + "/download"} { + b.expect(b.do("GET", path, nil), http.StatusNotFound, "") + } + result := a.do("GET", endpoint+"/download", nil) + if result.Status != http.StatusOK { + t.Fatalf("download: %d %s", result.Status, result.Body) + } + entries := readAccountZip(t, []byte(result.Body), forbidden...) + var manifest []projects.ExportProject + if err := json.Unmarshal(entries["projects.json"], &manifest); err != nil || len(manifest) != 3 { + t.Fatalf("project manifest: %s (%v)", entries["projects.json"], err) + } + for _, p := range manifest { + if (p.DeletedAt != nil) != (p.ID == trash.ID) || p.IsTemplate != (p.ID == template.ID) { + t.Errorf("unexpected metadata: %+v", p) + } + prefix := fmt.Sprintf("projects/%s/", p.ID) + if len(entries[prefix+"history.bundle"]) == 0 || !json.Valid(entries[prefix+"chats.json"]) { + t.Errorf("%s is missing history or chats", p.Name) + } + if p.ID != template.ID { + for _, s := range []string{"Prompt in " + p.Name, "Reply in " + p.Name} { + if !bytes.Contains(entries[prefix+"chats.json"], []byte(s)) { + t.Errorf("%s lacks %s", prefix+"chats.json", s) + } + } + } + } + if settings := string(entries["settings.json"]); !strings.Contains(settings, `"email_language":"es"`) || + !strings.Contains(settings, "My provider") || strings.Contains(settings, "base_url") { + t.Errorf("unexpected settings: %s", settings) + } + prefix := "projects/" + draft.ID + "/" + if text := string(entries[prefix+"files/main.tex"]); text != "Latest uncommitted edit" { + t.Errorf("worktree file = %q", text) + } + dir := t.TempDir() + bundle := filepath.Join(dir, "repo.bundle") + if err := os.WriteFile(bundle, entries[prefix+"history.bundle"], 0o600); err != nil { + t.Fatal(err) + } + clone := filepath.Join(dir, "clone") + gitRun("clone", bundle, clone) + if n := strings.TrimSpace(gitRun("-C", clone, "rev-list", "--count", "HEAD")); n != "2" { + t.Errorf("bundle has %s commits, want 2", n) + } + if text := gitRun("-C", clone, "show", "HEAD:main.tex"); text != "Committed text" { + t.Errorf("bundle HEAD = %q", text) + } +} + +func TestUsersExport(t *testing.T) { + dir := t.TempDir() + t.Setenv("REFRACT_DATA_DIR", dir) + t.Setenv("REFRACT_SECRET_KEY", base64.StdEncoding.EncodeToString(make([]byte, 32))) + t.Setenv("REFRACT_SECRET_KEY_FILE", "") + if err := runUsers([]string{"add", "ana@example.com"}, io.Discard); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "ana.zip") + args := []string{"export", "ANA@example.com", path} + if err := runUsers(args, io.Discard); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + entries := readAccountZip(t, raw) + if !bytes.Contains(entries["settings.json"], []byte("ana@example.com")) { + t.Fatal("CLI archive is missing the selected account") + } + if err := runUsers(args, io.Discard); err == nil { + t.Fatal("export replaced an existing archive") + } + again, err := os.ReadFile(path) + if err != nil || !bytes.Equal(raw, again) { + t.Fatal("the existing archive changed") + } +} diff --git a/cmd/refract/api.go b/cmd/refract/api.go index 5db8a16..048d3c5 100644 --- a/cmd/refract/api.go +++ b/cmd/refract/api.go @@ -39,6 +39,7 @@ type api struct { providers *providers.Store // users' API-key providers outbound *http.Client // for those providers (see providers.HTTPClient) usage *usage.Recorder // what each model call used; nil records nothing + exports *accountExports users sync.Map // user id → *userAI } @@ -87,6 +88,7 @@ func (a *api) metered(kind string) func(context.Context) ai.Provider { func (a *api) missing() []string { return append([]string{}, a.missingTools...) } func (a *api) routes(rt *router) { + a.exports.routes(rt) rt.user("GET /api/me", func(w http.ResponseWriter, r *http.Request) { u, _ := auth.UserFrom(r.Context()) writeJSON(w, map[string]any{"id": u.ID, "email": u.Email, "can_sign_out": a.canSignOut, "mode": a.mode, "missing_tools": a.missing()}) diff --git a/cmd/refract/login_api.go b/cmd/refract/login_api.go index 6852efc..87ae56e 100644 --- a/cmd/refract/login_api.go +++ b/cmd/refract/login_api.go @@ -26,6 +26,7 @@ type loginAPI struct { public string // REFRACT_PUBLIC_URL, the base of links in emails; "" without mail *mail.Outbox // nil when the server can't send email destroy func(ctx context.Context, projectID string) error // deletes a project for good, for removing an account + exports *accountExports } const oidcCookie = "refract_oidc" diff --git a/cmd/refract/main.go b/cmd/refract/main.go index 2f62b54..b9dc513 100644 --- a/cmd/refract/main.go +++ b/cmd/refract/main.go @@ -63,6 +63,8 @@ Usage: let an account (or everyone) sign in again after too many failed attempts refract users remove [--yes] delete an account with its projects, chats and connections + refract users export + write an account archive with projects, history and chats refract users list list accounts refract version print the version ` @@ -289,6 +291,9 @@ func run(ctx context.Context, opts runOptions) error { svc: &projects.Service{DB: db, Dir: filepath.Join(dataDir, "projects"), Limits: projects.DefaultLimits, Key: key, PublicRemotes: publicOnly}, tmp: filepath.Join(dataDir, "tmp"), } + exports := &accountExports{ctx: ctx, projects: pa.svc} + defer exports.close() + a.exports = exports fontResolver := fonts.NewResolver(filepath.Join(dataDir, "font-cache")) fontResolver.Offline = os.Getenv("REFRACT_FONT_DOWNLOADS") == "0" @@ -362,6 +367,7 @@ func run(ctx context.Context, opts runOptions) error { login.mode, login.public = deployment, base login.signup = signup && mailReady login.destroy = destroyer(pa.svc) + login.exports = exports if mailReady { outbox = mail.NewOutbox(smtp) login.mail = outbox diff --git a/cmd/refract/users_cmd.go b/cmd/refract/users_cmd.go index 0b95a47..2a8f5e4 100644 --- a/cmd/refract/users_cmd.go +++ b/cmd/refract/users_cmd.go @@ -12,6 +12,7 @@ import ( "path/filepath" "slices" + "github.com/ponytojas/Refract/internal/accountexport" "github.com/ponytojas/Refract/internal/projects" "github.com/ponytojas/Refract/internal/store" "github.com/ponytojas/Refract/internal/users" @@ -23,12 +24,13 @@ const usersUsage = `usage: refract users signout end all of an account's sessions refract users unlock | --all let an account (or everyone) sign in again after too many failed attempts refract users remove [--yes] delete an account and everything it owns + refract users export write an account archive with projects, history and chats refract users list list accounts` // runUsers manages accounts on the server's own database (same // REFRACT_DATA_DIR and encryption key as the server). func runUsers(args []string, out io.Writer) error { - arity := map[string][]int{"list": {1}, "add": {2}, "rename": {3}, "signout": {2}, "unlock": {2}, "remove": {2, 3}} + arity := map[string][]int{"list": {1}, "add": {2}, "rename": {3}, "signout": {2}, "unlock": {2}, "remove": {2, 3}, "export": {3}} if len(args) == 0 || !slices.Contains(arity[args[0]], len(args)) || args[0] == "remove" && len(args) == 3 && args[2] != "--yes" { return errors.New(usersUsage) } @@ -95,6 +97,19 @@ func runUsers(args []string, out io.Writer) error { fmt.Fprintf(out, "%s can sign in again.\n", args[1]) case "remove": return removeUser(ctx, svc, filepath.Join(dataDir, "projects"), args[1], len(args) == 3, out) + case "export": + acct, err := svc.Lookup(ctx, args[1]) + if errors.Is(err, users.ErrNoAccount) { + return fmt.Errorf("there is no account %q", args[1]) + } + if err != nil { + return err + } + ps := &projects.Service{DB: db, Dir: filepath.Join(dataDir, "projects"), Key: key} + if err := accountexport.WriteFile(ctx, args[2], ps, acct.ID); err != nil { + return err + } + fmt.Fprintf(out, "Exported %s to %s.\n", acct.Email, args[2]) case "add": // A generated password: nothing to type into a shell history or a // terminal without echo control (docker exec without -t). diff --git a/internal/accountexport/export.go b/internal/accountexport/export.go new file mode 100644 index 0000000..349b344 --- /dev/null +++ b/internal/accountexport/export.go @@ -0,0 +1,112 @@ +// Package accountexport builds the account archive used by the web and CLI. +package accountexport + +import ( + "archive/zip" + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "time" + + "github.com/ponytojas/Refract/internal/assistant" + "github.com/ponytojas/Refract/internal/projects" + "github.com/ponytojas/Refract/internal/providers" + "github.com/ponytojas/Refract/internal/siwc" + "github.com/ponytojas/Refract/internal/usage" + "github.com/ponytojas/Refract/internal/users" +) + +// Only explicitly selected settings are exported. Provider endpoints may +// contain secrets in their paths or queries, even without URL userinfo. +type providerSettings struct { + ID string `json:"id"` + Kind string `json:"kind"` + Name string `json:"name"` + Models []string `json:"models,omitempty"` +} + +type settings struct { + Version int `json:"archive_version"` + Email string `json:"email"` + Lang string `json:"email_language"` + Verified bool `json:"email_verified"` + WelcomeSeen bool `json:"welcome_seen"` + Providers []providerSettings `json:"providers"` +} + +func Write(ctx context.Context, w io.Writer, ps *projects.Service, owner string) error { + acct, err := (&users.Service{DB: ps.DB}).AccountByID(ctx, owner) + if err != nil { + return err + } + configs, err := (&providers.Store{DB: ps.DB, Key: ps.Key}).List(ctx, owner) + if err != nil { + return fmt.Errorf("read provider settings: %w", err) + } + seen, err := (&siwc.Session{DB: ps.DB, Owner: owner}).WelcomeSeen(ctx) + if err != nil { + return err + } + cfg := settings{Version: 1, Email: acct.Email, Lang: acct.Lang, Verified: acct.Verified, WelcomeSeen: seen, + Providers: make([]providerSettings, 0, len(configs))} + for _, c := range configs { + cfg.Providers = append(cfg.Providers, providerSettings{ID: c.ID, Kind: c.Kind, Name: c.Name, Models: c.Models}) + } + items, err := ps.AccountProjects(ctx, owner) + if err != nil { + return err + } + totals, err := (&usage.Recorder{DB: ps.DB}).Since(ctx, owner, time.Time{}) + if err != nil { + return err + } + zw := zip.NewWriter(w) + for _, entry := range []struct { + name string + value any + }{{"settings.json", cfg}, {"projects.json", items}, {"usage.json", totals}} { + dst, err := zw.Create(entry.name) + if err != nil { + return err + } + if err := json.NewEncoder(dst).Encode(entry.value); err != nil { + return err + } + } + chats := &assistant.Service{DB: ps.DB} + for _, item := range items { + if err := ps.WriteAccountProject(ctx, zw, owner, item.ID); err != nil { + return fmt.Errorf("export project %s: %w", item.ID, err) + } + dst, err := zw.Create("projects/" + item.ID + "/chats.json") + if err != nil { + return err + } + if err := chats.WriteAccountChats(ctx, dst, owner, item.ID); err != nil { + return fmt.Errorf("export chats for %s: %w", item.ID, err) + } + } + return zw.Close() +} + +// WriteFile publishes the complete archive with owner-only permissions and +// refuses to replace an existing destination. +func WriteFile(ctx context.Context, path string, ps *projects.Service, owner string) error { + f, err := os.CreateTemp(filepath.Dir(path), ".refract-export-*.zip") + if err != nil { + return err + } + defer os.Remove(f.Name()) + err = Write(ctx, f, ps, owner) + closeErr := f.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + return os.Link(f.Name(), path) +} diff --git a/internal/assistant/assistant.go b/internal/assistant/assistant.go index 37a7f51..c6b19a8 100644 --- a/internal/assistant/assistant.go +++ b/internal/assistant/assistant.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "log/slog" "slices" "strings" @@ -179,7 +180,11 @@ func (s *Service) Chats(ctx context.Context, projectID string) ([]Chat, error) { if _, err := s.Projects.Get(ctx, projectID); err != nil { return nil, err } - rows, err := s.DB.QueryContext(ctx, `SELECT id, project_id, title, model, effort, created_at, updated_at FROM chats WHERE project_id = ? ORDER BY updated_at DESC`, projectID) + return s.chats(ctx, projectID) +} + +func (s *Service) chats(ctx context.Context, projectID string) ([]Chat, error) { + rows, err := s.DB.QueryContext(ctx, `SELECT id, project_id, title, model, effort, created_at, updated_at FROM chats WHERE project_id = ? ORDER BY updated_at DESC, id`, projectID) if err != nil { return nil, err } @@ -239,6 +244,10 @@ func (s *Service) Turns(ctx context.Context, chatID string) ([]Turn, error) { if _, err := s.chat(ctx, chatID); err != nil { return nil, err } + return s.turns(ctx, chatID) +} + +func (s *Service) turns(ctx context.Context, chatID string) ([]Turn, error) { rows, err := s.DB.QueryContext(ctx, `SELECT `+turnCols+` FROM turns WHERE chat_id = ? ORDER BY created_at, rowid`, chatID) if err != nil { return nil, err @@ -255,6 +264,50 @@ func (s *Service) Turns(ctx context.Context, chatID string) ([]Turn, error) { return out, rows.Err() } +// WriteAccountChats writes the owner's conversations and turns, including +// for projects in the trash. Provider errors can echo credentials and are +// excluded. A failed turn still has its status, prompt, and saved response. +func (s *Service) WriteAccountChats(ctx context.Context, w io.Writer, owner, projectID string) error { + var exists int + err := s.DB.QueryRowContext(ctx, `SELECT 1 FROM projects WHERE id = ? AND owner = ?`, projectID, owner).Scan(&exists) + if errors.Is(err, sql.ErrNoRows) { + return projects.ErrNotFound + } + if err != nil { + return err + } + chats, err := s.chats(ctx, projectID) + if err != nil { + return err + } + if _, err := io.WriteString(w, "[\n"); err != nil { + return err + } + enc := json.NewEncoder(w) + for index, chat := range chats { + turns, err := s.turns(ctx, chat.ID) + if err != nil { + return err + } + for i := range turns { + turns[i].Error = nil + } + if index > 0 { + if _, err := io.WriteString(w, ","); err != nil { + return err + } + } + if err := enc.Encode(struct { + Chat + Turns []Turn `json:"turns"` + }{chat, turns}); err != nil { + return err + } + } + _, err = io.WriteString(w, "]\n") + return err +} + func (s *Service) turn(ctx context.Context, id string) (*Turn, *Chat, error) { t, err := scanTurn(s.DB.QueryRowContext(ctx, `SELECT `+turnCols+` FROM turns WHERE id = ?`, id)) if errors.Is(err, sql.ErrNoRows) { diff --git a/internal/projects/account_export.go b/internal/projects/account_export.go new file mode 100644 index 0000000..b6e7729 --- /dev/null +++ b/internal/projects/account_export.go @@ -0,0 +1,86 @@ +package projects + +import ( + "archive/zip" + "context" + "database/sql" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" +) + +// ExportProject describes one project in an account archive, including its +// deletion time if it is in the trash. +type ExportProject struct { + Project + DeletedAt *time.Time `json:"deleted_at,omitempty"` +} + +func (s *Service) AccountProjects(ctx context.Context, owner string) ([]ExportProject, error) { + rows, err := s.DB.QueryContext(ctx, `SELECT `+projectCols+`, deleted_at FROM projects WHERE owner = ? ORDER BY id`, owner) + if err != nil { + return nil, err + } + defer rows.Close() + out := []ExportProject{} + for rows.Next() { + var deleted int64 + p, err := scan(rows, &deleted) + if err != nil { + return nil, err + } + item := ExportProject{Project: *p} + if deleted > 0 { + at := time.Unix(deleted, 0).UTC() + item.DeletedAt = &at + } + out = append(out, item) + } + return out, rows.Err() +} + +// WriteAccountProject writes the complete reachable git history and a copy +// of the current files, including edits made since the last checkpoint. +func (s *Service) WriteAccountProject(ctx context.Context, zw *zip.Writer, owner, id string) error { + if !filepath.IsLocal(id) || filepath.Base(id) != id || id == "." || strings.Contains(id, "\\") { + return fmt.Errorf("invalid project ID %q", id) + } + defer lockRepo(id)() + var exists int + err := s.DB.QueryRowContext(ctx, `SELECT 1 FROM projects WHERE id = ? AND owner = ?`, id, owner).Scan(&exists) + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + if err != nil { + return err + } + dir, err := os.MkdirTemp("", "refract-git-bundle-") + if err != nil { + return err + } + defer os.RemoveAll(dir) + bundle := filepath.Join(dir, "history.bundle") + repo := s.Path(id) + if _, err := git(ctx, repo, "bundle", "create", bundle, "--all", "HEAD"); err != nil { + return err + } + f, err := os.Open(bundle) + if err != nil { + return err + } + defer f.Close() + prefix := "projects/" + id + "/" + // A git bundle is already compressed. + dst, err := zw.CreateHeader(&zip.FileHeader{Name: prefix + "history.bundle", Method: zip.Store}) + if err != nil { + return err + } + if _, err := io.Copy(dst, f); err != nil { + return err + } + return writeFilesToZip(ctx, zw, repo, prefix+"files/") +} diff --git a/internal/projects/projects.go b/internal/projects/projects.go index 34c6869..e997b6d 100644 --- a/internal/projects/projects.go +++ b/internal/projects/projects.go @@ -266,26 +266,43 @@ func (s *Service) Export(ctx context.Context, id string, w io.Writer) error { if _, err := s.Get(ctx, id); err != nil { return err } - dir := s.Path(id) + zw := zip.NewWriter(w) + if err := writeFilesToZip(ctx, zw, s.Path(id), ""); err != nil { + return err + } + return zw.Close() +} + +func writeFilesToZip(ctx context.Context, zw *zip.Writer, dir, prefix string) error { + root, err := os.OpenRoot(dir) + if err != nil { + return err + } + defer root.Close() var files []string if err := walkFiles(dir, func(rel string, _ fs.FileInfo) error { + if err := ctx.Err(); err != nil { + return err + } files = append(files, rel) return nil }); err != nil { return err } slices.Sort(files) // deterministic archive - zw := zip.NewWriter(w) for _, rel := range files { - if err := addToZip(zw, dir, rel); err != nil { + if err := ctx.Err(); err != nil { + return err + } + if err := addToZip(zw, root, rel, prefix+rel); err != nil { return err } } - return zw.Close() + return nil } -func addToZip(zw *zip.Writer, dir, rel string) error { - f, err := os.Open(filepath.Join(dir, filepath.FromSlash(rel))) +func addToZip(zw *zip.Writer, root *os.Root, rel, name string) error { + f, err := root.Open(filepath.FromSlash(rel)) if err != nil { return err } @@ -298,7 +315,7 @@ func addToZip(zw *zip.Writer, dir, rel string) error { if err != nil { return err } - hdr.Name, hdr.Method = rel, zip.Deflate + hdr.Name, hdr.Method = name, zip.Deflate dst, err := zw.CreateHeader(hdr) if err != nil { return err diff --git a/web/e2e/account-export.spec.ts b/web/e2e/account-export.spec.ts new file mode 100644 index 0000000..94d6c2b --- /dev/null +++ b/web/e2e/account-export.spec.ts @@ -0,0 +1,21 @@ +import { expect, test } from '@playwright/test' +import { readFile } from 'node:fs/promises' + +test('account settings downloads the ZIP when the export is ready', async ({ page, request }) => { + await page.addInitScript(() => localStorage.setItem('refract-prefs', JSON.stringify({ language: 'en' }))) + const project = await request.post('/api/projects', { + headers: { 'X-Refract': '1' }, + data: { name: 'Archive test project' }, + }) + expect(project.ok()).toBeTruthy() + await page.goto('/') + await page.getByRole('button', { name: 'Account menu', exact: true }).click() + await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() + await page.getByRole('tab', { name: 'Account', exact: true }).click() + const finished = page.waitForEvent('download') + await page.getByRole('button', { name: 'Export my data', exact: true }).click() + const archive = await finished + expect(archive.suggestedFilename()).toBe('refract-account.zip') + const content = await readFile(await archive.path()) + expect(content.subarray(0, 4)).toEqual(Buffer.from([0x50, 0x4b, 0x03, 0x04])) +}) diff --git a/web/src/Settings.tsx b/web/src/Settings.tsx index c9c13df..9010e06 100644 --- a/web/src/Settings.tsx +++ b/web/src/Settings.tsx @@ -17,7 +17,7 @@ import { UserRound, } from 'lucide-react' import { toast } from 'sonner' -import { api, describe, errorText, modelsChanged, RequestError, type ChatGPTStatus } from './api' +import { api, describe, download, errorText, modelsChanged, RequestError, type ChatGPTStatus } from './api' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { device } from '@/lib/device' @@ -54,6 +54,7 @@ import { setTheme, useTheme, type Theme } from '@/lib/theme' import PlanBadge from './PlanBadge' import { useMe } from '@/components/AccountMenu' import { useAccount } from '@/components/useAccount' +import { flushPending } from '@/lib/flush' import { chatgptOffered } from '@/lib/mode' type Props = { status: ChatGPTStatus | null; onChange: (s: ChatGPTStatus) => void } @@ -61,7 +62,6 @@ type Props = { status: ChatGPTStatus | null; onChange: (s: ChatGPTStatus) => voi // Settings as a modal over whatever page is open (Prism-style): sections on the left, rows on the right. export default function SettingsDialog({ status, onChange }: Props) { const section = useSettingsSection() - const me = useMe() return ( !o && openSettings(null)}> @@ -76,11 +76,9 @@ export default function SettingsDialog({ status, onChange }: Props) { }> {t('General')} - {me?.can_sign_out && ( - }> - {t('Account')} - - )} + }> + {t('Account')} + }> {t('Editor')} @@ -95,7 +93,7 @@ export default function SettingsDialog({ status, onChange }: Props) { - {me?.can_sign_out && } + @@ -334,8 +332,59 @@ function AssistantPane({ status, onChange }: Props) { ) } -// The account Refract signs in itself (REFRACT_AUTH=builtin): email, password and deleting it. function AccountPane() { + const me = useMe() + return ( + + + {me?.can_sign_out && } + + ) +} + +function ExportGroup() { + const [busy, setBusy] = useState(false) + + async function exportData() { + setBusy(true) + try { + if (!(await flushPending())) { + toast.error(t('Could not save your edits before exporting. Try again.')) + return + } + type ExportStatus = { status: 'preparing' | 'ready' | 'failed' } + const path = '/api/account/export' + let job = await api(path, { method: 'POST' }) + while (job.status === 'preparing') { + await new Promise((resolve) => setTimeout(resolve, 1000)) + job = await api(path) + } + if (job.status !== 'ready') throw new Error('account export failed') + await download(path + '/download', 'refract-account.zip') + } catch { + toast.error(t('Could not export your data. Try again.')) + } finally { + setBusy(false) + } + } + + return ( + + + + + + ) +} + +// The account Refract signs in itself (REFRACT_AUTH=builtin): email, password and deleting it. +function AccountManagement() { const me = useMe() const { account, sending, reload, resend } = useAccount() const [passwordChanges, setPasswordChanges] = useState(0) @@ -350,7 +399,7 @@ function AccountPane() { } return ( - + <> setPasswordChanges((count) => count + 1)} /> - + ) } diff --git a/web/src/locales/es/app.ts b/web/src/locales/es/app.ts index fd7072e..3736159 100644 --- a/web/src/locales/es/app.ts +++ b/web/src/locales/es/app.ts @@ -139,6 +139,13 @@ export default { Account: 'Cuenta', 'Signed in as {email}.': 'Sesión iniciada como {email}.', 'Current password': 'Contraseña actual', + 'Export my data': 'Exportar mis datos', + 'Download your projects, history, chats and account settings as a ZIP file.': + 'Descarga tus proyectos, historial, conversaciones y ajustes de la cuenta en un archivo ZIP.', + 'Preparing download…': 'Preparando la descarga…', + 'Could not save your edits before exporting. Try again.': + 'No se pudieron guardar tus cambios antes de exportar. Inténtalo de nuevo.', + 'Could not export your data. Try again.': 'No se pudieron exportar tus datos. Inténtalo de nuevo.', 'New password (8+ characters)': 'Contraseña nueva (8 caracteres o más)', 'New password': 'Contraseña nueva', Change: 'Cambiar',