Skip to content
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <email> <file>`.
- 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.
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <email>`. After too many failed sign-ins an account waits 15 minutes; `refract users unlock <email>` lets it in at once. To delete an account with its projects (those in the trash too), chats and connections, run `refract users remove <email>`: 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 <directory>` 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 <email> <file>` 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.
Expand Down Expand Up @@ -614,6 +618,7 @@ refract users rename <a> <b> change an account's email, keeping its data
refract users signout <email> end all of an account's sessions
refract users unlock <email> clear an account's failed sign-ins and email limit (--all: every account and address)
refract users remove <email> delete an account and everything it owns, trash included (asks for --yes)
refract users export <email> <file> write a ZIP of an account's projects, history, chats and settings
refract users list list accounts
refract version print the version
```
Expand Down
3 changes: 3 additions & 0 deletions cmd/refract/account_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 5 additions & 2 deletions cmd/refract/account_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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())
Expand Down
183 changes: 183 additions & 0 deletions cmd/refract/account_export.go
Original file line number Diff line number Diff line change
@@ -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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: The archive can be stale. start hands back an existing preparing job, or a ready one that hasn't been downloaded, so the edits flushPending() saved just before this click aren't in the ZIP. Example: someone clicks Export, closes the tab before the download starts, edits for a few minutes, then clicks Export again. They get the old ZIP, which doesn't have those edits. Fix: let a new POST replace a ready job that hasn't been downloaded. For a preparing job, note when it started and rebuild if a newer request arrives (or return the existing job only when it started after the client's flush).

return existing.status, true
}
// A small number of simultaneous git packs keeps a shared server responsive.
if e.running >= 2 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): When two exports are already running server-wide, POST returns 503 "account export is busy". The client turns that into the generic "Could not export your data. Try again.", so the user can't tell a busy server from a real failure. Fix: queue the request, or have the UI show a separate "busy, try again in a few minutes" message for 503.

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")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: Exports are staged in the system temp dir (os.CreateTemp("", ...), and os.MkdirTemp("", ...) for each git bundle in internal/projects/account_export.go:61), not the server's configured <data>/tmp. On a container with a read-only root filesystem, or a small tmpfs /tmp, every export fails, and the user only sees "Could not export your data". Temp ZIPs left behind by a crash or by shutdown while a build is running (close() cancels the build but doesn't wait for it) are never cleaned up. Fix: create both under filepath.Join(dataDir, "tmp"), the folder projectsAPI.tmp already uses, and sweep leftover refract-account-export-* files at startup.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): os.Remove(job.path) ignores its error. On Windows, removing a file that downloadExport still has open (a download running when the retention timer fires, or a new export starts) fails, and the ZIP stays in the temp dir for good. Fix: log the error and retry the removal after the download closes the file, or remove it from downloadExport's defer once the job has been discarded.

}
}

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)
}
Loading
Loading