Project page
You can find the app here: proton-drive-nextcloud-backup

One copy is no copy Link to heading

Self-hosting your files with Nextcloud is great, right up until the disk dies. Then you remember that your “cloud” is a single box under a desk, and that one copy of your data is no copy at all.

The fix is old and boring: keep a copy somewhere else. I already pay for Proton Drive, it’s end-to-end encrypted, and it’s off-site. The only thing missing was a way to get files from Nextcloud into it without me remembering to do it.

So I built a Nextcloud app for that. You pick the files and folders you care about and how often they should be backed up, and the app does one of two things. It either keeps a mirror of them on Proton Drive, uploading only what changed, or it zips them, optionally encrypts the ZIP, uploads it, checks it arrived intact and cleans up the old ones. All from the Nextcloud settings page.

Borrowing Proton’s CLI Link to heading

Proton Drive doesn’t have a simple public REST API you can throw a token at. Everything is end-to-end encrypted, so the client has to do the cryptography itself, and reimplementing that in PHP was not something I wanted to do.

Luckily, Proton ships an official Proton Drive CLI, built on their own SDK. It does everything I need: auth login, filesystem upload, filesystem create-folder, filesystem list, filesystem info and filesystem trash. The app bundles the Linux binaries (amd64 and arm64) in bin/ and picks the right one at runtime:

$binaryName = in_array(php_uname('m'), ['aarch64', 'arm64'], true)
    ? 'proton-drive-linux-arm64'
    : 'proton-drive-linux-amd64';

So the whole app is really a PHP wrapper around a CLI. Every action ends up as a shell command, with every argument passed through escapeshellarg().

A keyring with no one to unlock it Link to heading

Here’s where it got annoying. The CLI doesn’t store its session tokens in a plain file: it uses the Linux Secret Service API, the same thing your desktop uses to remember Wi-Fi passwords. That means it expects a D-Bus session and a keyring daemon to be running.

A Nextcloud container has neither. There’s no desktop, no logged-in user, and nobody around to type a keyring password. So the container needs a few extra packages, and the official image has to be extended:

FROM nextcloud:latest

RUN apt-get update && apt-get install -y \
    dbus \
    libsecret-1-0 \
    gnome-keyring \
    && rm -rf /var/lib/apt/lists/*

Then, every time the app calls the CLI, it wraps it in a throwaway D-Bus session and points HOME and the XDG directories at a session folder of its own, so the keyring files live there instead of in www-data’s home:

$binaryCmd = sprintf(
    '%s dbus-run-session -- %s %s 2>%s',
    $this->sessionEnv($userId),   // HOME + XDG_* for this user's session
    escapeshellarg($this->getBinaryPath()),
    $command,
    escapeshellarg($stderrFile)
);

There’s one session folder per Nextcloud user, named after a SHA-256 hash of their user ID. That matters: the CLI only knows one Proton account per HOME, so if everyone shared a folder, everyone would upload to whichever account logged in last. With separate folders, each user connects their own Proton account, and nobody can see or log out anyone else’s session.

The folders live inside Nextcloud’s data directory (under appdata_<instance id>/protondrivebackup/sessions). The data directory is already a persistent volume in any sane container setup, so the sessions survive restarts and you don’t have to log in again every time you update the image. If you’d rather keep them somewhere else, set protondrivebackup.session_dir in config.php.

There’s one more wrinkle, and it’s a pure Unix one. The keyring daemon and D-Bus talk over Unix domain sockets, and a Unix socket path can’t be longer than 108 bytes. Left to its own devices, gnome-keyring puts its control socket deep inside the session folder, and the session folder already lives several directories down inside the data directory. That path blows past 108 bytes, the socket never binds, and the secrets service silently never starts. So the session’s XDG_RUNTIME_DIR (where those sockets go) is a short path under the system temp dir, keyed by the first few characters of the same hash:

sprintf(
    'HOME=%s XDG_CONFIG_HOME=%s XDG_DATA_HOME=%s XDG_RUNTIME_DIR=%s',
    escapeshellarg($sessionDir),
    escapeshellarg($sessionDir . '/.config'),
    escapeshellarg($sessionDir . '/.local/share'),
    escapeshellarg($this->getRuntimeDir($userId))   // short, for the sockets
);

The last trick is the keyring itself. GNOME Keyring would normally ask for a password to create or unlock it. To keep it quiet, the app writes a login.keyring file before starting the daemon, so it finds a keyring that already exists and needs no unlocking:

file_put_contents($keyringDir . '/default', 'login');
file_put_contents(
    $keyringDir . '/login.keyring',
    "[keyring]\nbuilding=false\nfile-format=1\nlock-on-idle=false\nlock-after=false\n"
);
This is not a vault
An unlocked keyring on disk protects the Proton session about as well as a plain file would. The session folders are created with 0700 permissions, but anyone with root on the server (or access to the data directory) can use your session. The security here comes from the server itself, not from the keyring.

Logging in from a server Link to heading

The other problem is logging in. proton-drive auth login doesn’t ask for a username and password; it prints a URL to account.proton.me and waits for you to approve the session in a browser. On a server, nobody is looking at the terminal.

So when you click Connect to Proton Drive, the app starts the login in the background, in its own process group, sends its output to a log file, and then watches that file for up to 5 seconds looking for the URL:

$deadline = microtime(true) + 5;
while (microtime(true) < $deadline) {
    $output = file_exists($logFile) ? (string)file_get_contents($logFile) : '';
    if (preg_match('/https:\/\/account\.proton\.me\/\S+/', $output, $matches)) {
        $authUrl = $matches[0];
        break;
    }
    usleep(200000); // 200ms
}

Once it finds it, it hands it back to the browser, which opens it in a new tab. You approve it there, the CLI (still waiting in the background) receives the session and saves it to the keyring, and the settings page notices. To check whether you’re connected, the app just runs filesystem list /: if that works, you’re in.

A login that nobody finishes shouldn’t wait forever, so the background process carries its own watchdog and gives up after 10 minutes. If your browser blocked the pop-up, the page keeps a link to open the Proton login again, and a Cancel button stops a login you don’t want to finish.

Mirroring, one way Link to heading

Every job has a backup format: a mirror, a ZIP archive, or an encrypted ZIP archive. Mirror is the default, because most of the time what I actually want is for Proton Drive to look like my Nextcloud drive: the same folders, the same files, browsable from Proton’s own apps. Each item keeps its place, so /Documents/cv.pdf ends up at <Proton Drive folder>/Documents/cv.pdf. You can even select the root folder and mirror the whole drive.

It’s one way only. Nextcloud is the source, and nothing on Proton Drive is ever copied back.

The tricky part is knowing what to do on each run without re-uploading everything. For that, each mirror job keeps a manifest: a table with every file and folder the job has put on Proton Drive, along with the size, modification time and etag each file had when it was uploaded. Each run collects the current files, compares them with the manifest, and builds a plan:

  • files that are new, or whose size, mtime or etag changed, get uploaded;
  • folders that don’t exist yet get created, parents first;
  • things that were deleted in Nextcloud (or newly excluded, or removed from the job) get moved to the Proton Drive trash, or just forgotten, if you set the job to keep them.

The plan is pure logic, with no Nextcloud or Proton in it, so it’s easy to test. And the manifest is updated after every step, so a run that’s interrupted halfway loses nothing: the next one simply has less left to do.

Uploads are grouped by the folder they go into, up to 50 files per CLI call. A file that already exists on Proton Drive gets a new revision instead of a duplicate, so Proton keeps the older versions in its history:

$command = sprintf(
    'filesystem upload --json%s -f create-new-revision -d merge %s %s',
    $skipThumbnails ? ' --skip-thumbnails' : '',
    implode(' ', array_map('escapeshellarg', $localPaths)),
    escapeshellarg($remoteDir)
);

The --json output gives a summary with the files that failed and why, so one bad file doesn’t sink the whole batch. That’s how I found out the CLI makes a thumbnail of every image, and refuses to upload one it can’t read as an image: a damaged photo, or some other file that happens to have a .jpg extension. Those would fail on every single run, so the app picks them out of the failures and uploads them again with --skip-thumbnails.

Not deleting the wrong thing Link to heading

A tool that moves things to trash on its own deserves some paranoia, so the mirror has a few rules:

  • It only trashes what it uploaded. Anything else in the Proton Drive folder isn’t in the manifest, so it’s never touched. Folders that already existed on Proton Drive before the job are never trashed either, only the mirrored files inside them.
  • A missing folder stops the run. If a selected folder can’t be found, it’s most likely an unmounted external storage, and mirroring “nothing” would trash the whole copy. So the run fails without changing anything on Proton Drive.
  • Mass deletions need a human. A scheduled run refuses to move more than half of the mirror to trash (once there are at least 20 items involved). If you really did delete all those files, click Run Now, which is allowed to go ahead.
  • Archives are off-limits. You can have a mirror of the whole drive and ZIP archive jobs saving inside it, say in Backups/. A mirror never trashes a folder that holds another job’s archives.

And trash really is trash: everything the app removes stays in the Proton Drive trash, where it can be restored, until you empty it.

Big drives and broken mirrors Link to heading

The first run of a mirror can be huge. The app treats any run still going after 12 hours as dead, so a mirror run stops itself well before that, after 6 hours, and shows as Paused. The job stays due, so the next background check carries on where it stopped, and nothing already uploaded goes up again.

The opposite problem is the mirror going missing on the Proton side: you delete or move a folder there by hand, and the manifest is now lying. Every run checks that each selected item’s copy is still on Proton Drive, and when an upload or folder creation fails because its parent folder is gone, the app works out the outermost missing folder, forgets that part of the manifest and plans again. The missing part is simply uploaded again, and the run’s details say so.

Zipping, natively Link to heading

A mirror is great for browsing, but sometimes you want a snapshot instead: one file per run, that you can keep a history of, and optionally encrypt. That’s what the ZIP formats are for.

The first version used 7-Zip to build the archives. It worked, but it meant one more package in the container. PHP has the zip extension built in, and it’s enabled in the official Nextcloud image anyway, so I switched to ZipArchive.

The app walks the selected files and folders through Nextcloud’s own file API, so it sees exactly what the user sees. Where it can, it hands ZipArchive the real file on disk instead of reading it into memory:

$storage = $node->getStorage();
if ($storage->isLocal()) {
    return $storage->getLocalFile($node->getInternalPath());
}
// On external or object storage there is no local file, so stream a copy into
// the build folder first, rather than loading the whole thing into memory.

The mirror uses the same trick for its uploads, copying at most 1 GB of files off non-local storage at a time.

With the encrypted format, every entry is encrypted with AES-256. Proton already encrypts everything it stores, so this is a second layer: even if someone gets into your Proton account, the archives are useless without the password.

if ($encrypt) {
    $zip->setEncryptionName($localPath, ZipArchive::EM_AES_256, $password);
}

Of course, the app has to remember that password to build the next archive at 3 AM, so it has to be stored somewhere. Before it goes into the database, it’s encrypted with Nextcloud’s own ICrypto, which uses the instance’s secret from config.php, and it’s only decrypted at the moment the archive is built:

$job->setArchivePassword($this->crypto->encrypt($password));

So a leaked database dump alone doesn’t give away your archive passwords.

The archive is built in full before it’s uploaded, in the app’s own folder in the data directory rather than /tmp, which is usually small. The app checks there’s room for it first and fails with a clear message if there isn’t, instead of filling the disk. If you’d rather build somewhere else, there’s protondrivebackup.work_dir.

There’s also a bit of tidying before zipping, or mirroring. If you select /Documents and /Documents/Taxes, the second one is already inside the first, so it’s dropped, otherwise it would be backed up twice. You can also leave things out on purpose with exclude patterns (*.tmp, node_modules, /Photos/Raw/*, cache/) or skip any file over a size you choose.

Jobs, schedules and pruning Link to heading

You don’t set up “a backup”, you set up backup jobs. Each job has its own files, its own format, its own schedule (every N hours, days, weeks or months), its own Proton Drive folder and, for archives, its own encryption password and retention rules. They’re stored in a small table the app creates.

Names are optional. Leave the archive name blank and it takes the name of the selected folder (or the folder holding the selected file, or the closest folder the selected items share); leave the job name blank and it takes the archive name. If that name is already used by another job in the same Proton Drive folder, a short random suffix is added, so Documents becomes something like Documents-3f9a.

Scheduling uses Nextcloud’s own background jobs. The app registers a task that runs every 15 minutes and checks which jobs are due, meaning the ones that never ran or whose next run is already in the past. Each due job runs and gets a new last_run. Since the check only happens every 15 minutes, a backup can start up to about 15 minutes after it’s due, which for backups is perfectly fine.

Working out “the next run” is a bit trickier than it sounds, because a month isn’t a fixed number of seconds. Hours, days and weeks are easy to turn into seconds, but months aren’t, so the check is done in PHP with real calendar dates:

$next = (new \DateTimeImmutable('@' . $lastRun))
    ->modify(sprintf('+%d %s', $value, $unit))
    ->getTimestamp();

So “every 1 month” from January 15 means February 15, not “30 days later”.

An archive job can also skip a run when nothing has changed. Before zipping, the app fingerprints the selected files (their paths, sizes and modification times); if that fingerprint matches the last successful backup, the scheduled run is skipped instead of uploading an identical archive. (A manual run always uploads, because you asked for it.) Mirrors get this for free: when the plan is empty, the run is just “Already up to date”.

Pruning is how old archives get cleaned up. Every archive is named <archive name>_<YYYYMMDD>_<HHMMSS>.zip, so after each upload the app lists the remote folder, finds the archives with that job’s prefix, and decides what to keep. There are two rules, and you can use either or both: keep the last N archives, and keep anything from the last N days. An archive survives if either rule keeps it, and the newest one is always kept. Each job has its own folder on Proton Drive, so a job named docs can never delete another job’s mydocs archives.

Pruned archives go to the Proton Drive trash, and that’s as far as the app goes. The CLI can only delete things permanently from the trash, and once something is in the trash it can’t be reached by its path anymore. That’s not a bad outcome for a backup tool anyway: a pruned archive can still be restored until you empty the trash from Proton Drive.

If a scheduled backup fails, it’s retried about an hour later rather than hammered at every 15-minute check.

Knowing it worked Link to heading

A backup you can’t trust isn’t a backup. So after each archive upload, the app asks Proton Drive for the uploaded file’s size and SHA-1 and checks them against the local archive before it prunes anything:

if ($size !== $expectedSize) {
    return 'The uploaded archive is a different size on Proton Drive.';
}
if (is_string($sha1) && $sha1 !== '' && strcasecmp($sha1, $expectedSha1) !== 0) {
    return 'The uploaded archive\'s checksum does not match the local archive.';
}

Older archives are only pruned once the new one is confirmed intact. If the check fails, the old ones are kept, and the run is marked failed.

Every run is recorded, too. Each job keeps its last 50 runs, each with its status, how long it took and the error if it failed. For archives, that’s the archive’s name and size, how many files went in and how many old archives were pruned; for mirrors, how much was uploaded, how many files, and how many items went to the trash. Besides success, failed and skipped, a mirror run can be Partly done, when some files couldn’t be uploaded (they’re retried on the next run), or Paused. The job card shows the latest result at a glance, and its ⋯ → Show history lists the rest.

And when a backup fails, or a mirror is only partly done, you get a Nextcloud notification linking back to the page. You only get one per streak of problems, not one every retry, and it clears itself once a backup succeeds again. If you’ve turned on email for notifications, it comes by email as well, so a backup that’s been quietly failing for a week can’t go unnoticed.

Using it Link to heading

You’ll need Nextcloud 31 or newer, running on an image with the packages above. Clone the app into your custom_apps folder and enable it:

cd /path/to/nextcloud/custom_apps/
git clone https://codeberg.org/davidjosearaujo/proton-drive-nextcloud-backup.git protondrivebackup

podman exec -u www-data -w /var/www/html <nextcloud-container> php occ app:enable protondrivebackup

The folder must be called protondrivebackup, since that’s the app ID.

Then go to Personal Settings → Proton Drive Backup, click Connect to Proton Drive, and approve the session in the tab that opens. Every Nextcloud user does this for themselves, with their own Proton account. Once it says Connected, click + New Backup Job, pick your files with Nextcloud’s own file picker, choose the format (Mirror, ZIP archive or ZIP archive, encrypted), fill in the job details (schedule, Proton Drive folder, exclusions, and retention or what to do with deleted files) and save. To change a job later, its ⋯ menu has Edit, Show history and Delete. The only thing you can’t change is mirror versus ZIP; for that, create a new job.

Run now
You don’t have to wait for the schedule. Every job has a Run Now button that does the whole thing right away: archive, upload, verify, prune, or a full mirror sync. It runs in the background, so a large backup doesn’t time out in your browser, and the job’s status updates live while you watch. It’s also the fastest way to check that everything is working.

Use a real cron Link to heading

Scheduled backups depend on Nextcloud’s background jobs actually running, and by default they don’t run on their own. Nextcloud starts in AJAX mode, where background jobs only run while someone has a Nextcloud page open. On a quiet home server, that means your backups run late, or not at all.

So switch to Cron, either in Administration settings → Basic settings → Background jobs or with occ:

podman exec -u www-data -w /var/www/html <nextcloud-container> php occ background:cron

Then make something actually call cron.php every 5 minutes. On a bare-metal install, that’s a line in www-data’s crontab:

*/5 * * * * php -f /var/www/html/cron.php

With containers, you can do the same from the host’s crontab:

*/5 * * * * podman exec -u www-data <nextcloud-container> php -f /var/www/html/cron.php

Or run a second container from the same image with /cron.sh as its entrypoint, sharing Nextcloud’s volumes.

You don’t have to remember any of this, though. The app checks Nextcloud’s background job mode and when cron last ran, and if the mode isn’t Cron or cron hasn’t run in over an hour, it tells you: a banner at the top of its settings page (with a link to the right settings for admins, and an “ask your administrator” for everyone else), and a Proton Drive Backup scheduling warning in Administration settings → Overview. It never changes the setting itself, since that’s an instance-wide decision that also needs a system cron entry. And Run Now works either way.

If you just want to try it out, the repo has a dev.sh script that starts a local Nextcloud with the app mounted live, a cron container next to it, an admin/admin login and a few test files to back up. It uses Podman if you have it, Docker otherwise, and prints the address to open.

Conclusion Link to heading

Most of this project wasn’t about backups at all. Zipping files and uploading them is easy; the hard part was getting a CLI built for desktops to run happily inside a container with no desktop, no user and no one to type a password. A throwaway D-Bus session, a keyring that’s already unlocked, a socket path kept under 108 bytes and a log file watched for a URL were enough to make it work. The rest was making sure that a tool allowed to move files to trash on its own only ever trashes what it put there.

Now my files have a second home, off-site and encrypted, either as a browsable mirror or as snapshots the app checks actually arrived, and I don’t have to remember anything.

Happy backing up!