diff --git a/.gitattributes b/.gitattributes index dfe0770..73e21b7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,3 @@ # Auto detect text files and perform LF normalization * text=auto +/vendor/** linguist-vendored whitespace=-blank-at-eol,-blank-at-eof,-space-before-tab diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..bc2a776 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @ColinMario diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..0295b27 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 +updates: + - package-ecosystem: gomod + directory: / + schedule: + interval: monthly + groups: + go-dependencies: + patterns: ['*'] + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly + groups: + github-actions: + patterns: ['*'] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b345724 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,90 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + GOFLAGS: -mod=vendor + +jobs: + test: + name: Test (${{ matrix.os }}, Go ${{ matrix.go }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + go: [1.25.12, 1.26.5] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: ${{ matrix.go }} + cache: true + - run: go version + - run: go test -count=1 ./... + - run: go vet ./... + - name: Race detector + if: matrix.go == '1.26.5' + run: go test -race -count=1 ./... + - name: Coverage floor + if: matrix.os == 'ubuntu-latest' && matrix.go == '1.26.5' + run: | + go test -coverpkg=./... -coverprofile=coverage.out ./... + total="$(go tool cover -func=coverage.out | awk '/^total:/ {gsub(/%/, "", $3); print $3}')" + awk -v total="$total" 'BEGIN { if (total < 25.0) { printf "coverage %.1f%% is below 25.0%%\n", total; exit 1 } }' + + quality: + name: Static and security checks + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: 1.26.5 + cache: true + - run: go mod verify + - name: Verify generated module files + run: | + GOFLAGS=-mod=mod go mod tidy + GOFLAGS=-mod=mod go mod vendor + git diff --exit-code -- go.mod go.sum vendor + - run: test -z "$(gofmt -l cmd internal tools)" + - run: GOFLAGS=-mod=mod go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./... + - run: GOFLAGS=-mod=mod go run github.com/securego/gosec/v2/cmd/gosec@v2.28.0 -quiet ./... + - run: GOFLAGS=-mod=mod go run golang.org/x/vuln/cmd/govulncheck@v1.6.0 ./... + + cross-build: + name: Cross-build release targets + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: 1.26.5 + cache: true + - run: | + for target in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 freebsd/amd64; do + GOOS="${target%/*}" GOARCH="${target#*/}" CGO_ENABLED=0 go build -trimpath -buildvcs=false -o /tmp/protondrive-${target//\//-} ./cmd/protondrive + done + + packaging: + name: Packaging metadata + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - run: sudo apt-get update && sudo apt-get install -y appstream desktop-file-utils flatpak-builder libxml2-utils + - run: appstreamcli validate --no-net packaging/flatpak/io.github.colinmario.protondriveforlinux.metainfo.xml + - run: desktop-file-validate packaging/flatpak/io.github.colinmario.protondriveforlinux.desktop + - run: xmllint --noout packaging/flatpak/io.github.colinmario.protondriveforlinux.svg + - run: flatpak-builder --show-manifest packaging/flatpak/io.github.colinmario.protondriveforlinux.yml >/dev/null diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ac31156 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,60 @@ +name: Release + +on: + push: + tags: ['v*'] + +permissions: + contents: write + id-token: write + attestations: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + fetch-depth: 0 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: 1.26.5 + cache: true + - uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 + with: + cosign-release: v3.1.1 + - uses: anchore/sbom-action/download-syft@e22c389904149dbc22b58101806040fa8d37a610 # v0.24.0 + with: + syft-version: v1.46.0 + - name: Verify release source + run: | + tag_pattern='^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$' + [[ "$GITHUB_REF_NAME" =~ $tag_pattern ]] + version="${GITHUB_REF_NAME#v}" + git fetch origin main + git merge-base --is-ancestor "$GITHUB_SHA" origin/main + grep -F "## [$version]" CHANGELOG.md + grep -F "tag: $GITHUB_REF_NAME" packaging/flatpak/io.github.colinmario.protondriveforlinux.yml + test -z "$(git status --porcelain)" + go version + go test -count=1 ./... + go vet ./... + - name: Build, sign, and publish + uses: goreleaser/goreleaser-action@f06c13b6b1a9625abc9e6e439d9c05a8f2190e94 # v7.2.3 + with: + distribution: goreleaser + version: v2.17.0 + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GOFLAGS: -mod=vendor + - name: Attest release artifacts + uses: actions/attest@a1948c3f048ba23858d222213b7c278aabede763 # v4.1.1 + with: + subject-path: | + dist/*.tar.gz + dist/*.deb + dist/*.rpm + dist/SHA256SUMS.txt + dist/*.spdx.json + dist/*.sigstore.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a28552a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/dist/ +/build/ +/coverage.out +/coverage.html +/protondrive +/.flatpak-builder/ +/packaging/flatpak/.flatpak-builder/ +/packaging/flatpak/build-dir/ diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..70cf8d0 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,88 @@ +version: 2 + +project_name: protondrive + +before: + hooks: + - go test ./... + +builds: + - id: protondrive + main: ./cmd/protondrive + binary: protondrive + env: + - CGO_ENABLED=0 + - GOFLAGS=-mod=vendor + goos: [linux, darwin] + goarch: [amd64, arm64] + flags: [-trimpath, -buildvcs=false] + mod_timestamp: '{{ .CommitTimestamp }}' + ldflags: + - >- + -s -w + -X main.version={{.Version}} + -X main.commit={{.FullCommit}} + -X main.buildDate={{.CommitDate}} + +archives: + - id: archives + formats: [tar.gz] + name_template: 'protondrive_{{ .Version }}_{{ .Os }}_{{ .Arch }}' + files: + - README.md + - CHANGELOG.md + - LICENSE + - NOTICE.md + +nfpms: + - id: native-packages + package_name: protondrive + ids: [protondrive] + vendor: ColinMario + homepage: https://github.com/ColinMario/Protondrive-for-Linux + maintainer: ColinMario + description: Unofficial command-line helper for safe Proton Drive transfers and mounts + license: GPL-3.0-only + formats: [deb, rpm] + bindir: /usr/bin + mtime: '{{ .CommitDate }}' + rpm: + buildhost: reproducible.invalid + +checksum: + name_template: SHA256SUMS.txt + +sboms: + - id: archive-sbom + artifacts: archive + documents: + - '${artifact}.spdx.json' + cmd: go + args: + - run + - ../tools/reproducible-sbom + - '${artifact}' + - '${document}' + - '{{ .CommitDate }}' + +signs: + - id: checksum-signature + cmd: cosign + artifacts: checksum + signature: '${artifact}.sigstore.json' + args: + - sign-blob + - --yes + - --bundle=${signature} + - ${artifact} + +changelog: + use: git + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' + +release: + prerelease: auto diff --git a/CHANGELOG.md b/CHANGELOG.md index ed92ad1..491ff2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,49 @@ All notable changes to this project are documented here. The format follows [Kee ## [Unreleased] +## [0.3.0] - 2026-07-14 +### Added +- Added explicit safe `copy` and destructive `mirror` transfer operations with confirmation, deletion limits, source guards, and automatic destination backup directories. +- Added strict versioned sync-config validation, collision-resistant state filenames, JSON status output with stable exit codes, and build/version metadata. +- Added authenticated macOS WebDAV mounts with private logs and process identity tracking. +- Added Linux/macOS CI, security scanners, cross-builds, packaging validation, Dependabot, reproducible GoReleaser archives, SPDX SBOMs, Sigstore checksum signatures, and GitHub build attestations. +- Added security, contribution, notice, and full GPL-3.0 documentation. + +### Changed +- Updated the supported Go baseline to 1.25 and refreshed all Go dependencies and vendored sources. +- Validated the private session bridge against Proton Drive CLI 0.5.0 while retaining 0.4.x compatibility and fail-closed handling for future format series. +- Changed rclone transfers to non-destructive copy semantics by default; exact destination mirroring now requires `--operation mirror --confirm-mirror`. +- Watch mode now retries failures with exponential backoff and remains available for later changes. +- Persistent systemd/OpenRC services now use atomic files, exact artifact/state rollback, update restarts, readiness checks, verified removal, and propagated errors. +- Flatpak release builds now use an immutable Git tag; local source builds use a separate development manifest. Flatpak host/home permissions are documented as a distribution tradeoff rather than a sandbox boundary. +- Flatpak release builds now embed the tagged application version and deterministic release metadata instead of reporting a development build. + +### Fixed +- Fixed documented rclone passthrough by consuming the wrapper's standalone `--` delimiter. +- Fixed `status` returning success for missing remotes or failed authentication. +- Kept machine-readable status output single-shot by suppressing duplicate top-level error rendering. +- Prevented transient network errors from triggering destructive credential reconfiguration. +- Prevented one-time 2FA codes from being persisted or reused by staging them in a private temporary rclone config, and migrates legacy vaults when unlocked. +- Made rclone config, session, vault, and state writes atomic with cooperative locks, backups, and verification rollback. +- Refused transactional edits of encrypted rclone configs instead of risking plaintext replacement or corruption. +- Bounded ZIP extraction by bytes actually read instead of trusting archive metadata, and escaped systemd specifier and environment expansion in generated service paths. +- Blocked passthrough/config overrides of dry-run, deletion limits, backup handling, error handling, and other wrapper-owned mirror safeguards. +- Validated remote names before config rendering so colon ambiguity and INI section injection cannot redirect or corrupt rclone configuration. +- Rejected mirror backup directories nested inside the destination, including root-mirror recursion on the same remote. +- Removed the local vault passphrase from every child-process environment, including Flatpak host bridges. +- Enforced HTTPS-only dependency downloads and redirects, constrained Proton CLI assets to the official download path, and strictly validated rclone release versions. +- Made binaries, archives, native packages, and SPDX SBOMs reproducible from commit-derived timestamps and artifact digests; CI/release builds pin patched Go 1.25.12 and 1.26.5 toolchains, and tags fail unless they are SemVer, reachable from `main`, represented in the changelog, and matched by the immutable Flatpak source. +- Rejected conflicting credential sources, session-import modes, and unexpected positional arguments instead of silently ignoring them. +- Made empty-source checks ignore the sentinel itself, require regular-file sentinels, count actual remote files, and resolve symlink aliases before root/backup safety decisions. +- Expanded state/vault filename hashes to 64 bits and removes legacy unhashed files after a successful migration. +- Resolved sync, mount, unmount, backup, and persistent-service config paths to stable absolute locations. +- Prevented mount passthrough from overriding daemon/state, authentication, cache, read-only, config, and remote-control settings managed by the wrapper. +- Restricted recorded mount cleanup to generated direct-child bcrypt files so corrupted metadata cannot remove unrelated files. +- Removed the macOS Keychain fallback that exposed session JSON through process arguments. +- Prevented stale mount PIDs from signaling unrelated processes and verifies WebDAV shutdown after unmount. +- Removed the macOS WebDAV password from `mount_webdav` arguments by supplying it through a private pseudo-terminal conversation instead. +- Canonicalized mount-table paths so macOS `/var`/`/private/var` and other symlinked mount points are recognized correctly. + ## [0.2.5] - 2026-06-29 ### Fixed - Prevented `auto` sync from silently falling back to `rclone sync` when Proton's official CLI is unavailable, avoiding unintended mirror deletion semantics. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b4136f9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,21 @@ +# Contributing + +Use Go 1.25 or 1.26 and keep `vendor/` synchronized with `go.mod` and `go.sum`. +Before opening a pull request, run: + +```bash +go mod tidy +go mod vendor +gofmt -w cmd internal tools +go test -race ./... +go vet ./... +``` + +Changes to transfer semantics must include tests proving whether destination +deletions can occur. Changes to authentication, secret storage, mount helpers, +or service generation must include failure-path tests and must not put secrets +in process arguments or logs. + +Release tags are created only from a clean, reviewed `main` commit. The release +workflow produces four archives plus native packages, signed checksums, SPDX +SBOMs, and GitHub build attestations. diff --git a/LICENSE b/LICENSE index 7a230e1..f288702 100644 --- a/LICENSE +++ b/LICENSE @@ -1,17 +1,674 @@ -GNU GENERAL PUBLIC LICENSE -Version 3, 29 June 2007 + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 -Copyright (C) 2025 donniedice + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. + Preamble -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + The GNU General Public License is a free, copyleft license for +software and other kinds of works. -You should have received a copy of the GNU General Public License -along with this program. If not, see . \ No newline at end of file + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..d3ab0d2 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,14 @@ +# Notices + +Protondrive-for-Linux is an unofficial community project and is not affiliated +with, endorsed by, or supported by Proton AG. Proton and Proton Drive are +trademarks of their respective owner. + +The repository history identifies ColinMario and Colin-Mario as the authors of +the project. An earlier short-form license file named `donniedice` as a 2025 +copyright holder. That historical notice is retained here pending any further +provenance clarification; no authorship or ownership claim is inferred from it. + +Third-party Go modules and optional external programs such as Proton Drive CLI, +rclone, GoReleaser, Syft, and Cosign remain subject to their own licenses. This +repository does not redistribute Proton Drive CLI or rclone in its source tree. diff --git a/README.md b/README.md index 1e6fd7f..9e7d904 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # Protondrive-for-Linux -![Go Version](https://img.shields.io/badge/Go-1.21%2B-00ADD8.svg) ![Proton Drive CLI](https://img.shields.io/badge/Proton%20Drive%20CLI-0.4.x-6d4aff.svg) ![rclone](https://img.shields.io/badge/rclone-optional%20mount%2Fsync-5d2fbe.svg) ![License](https://img.shields.io/badge/License-GPLv3-green.svg) +![Go Version](https://img.shields.io/badge/Go-1.25%2B-00ADD8.svg) ![Proton Drive CLI](https://img.shields.io/badge/Proton%20Drive%20CLI-0.5.x-6d4aff.svg) ![rclone](https://img.shields.io/badge/rclone-copy%2Fmirror%2Fmount-5d2fbe.svg) ![License](https://img.shields.io/badge/License-GPLv3-green.svg) > This is an unofficial community project and is not affiliated with Proton AG or Proton Drive. -Go-based convenience CLI for Proton Drive on Linux and other POSIX shells. The tool now prefers Proton's official `proton-drive` CLI for login, browsing, uploads, and downloads, while keeping the existing rclone backend for features Proton's CLI does not yet provide, especially FUSE mounts and exact `rclone sync` workflows. +Go-based convenience CLI for Proton Drive on Linux and other POSIX shells. The tool prefers Proton's official `proton-drive` CLI for login, browsing, uploads, and downloads, while retaining rclone for mounts and controlled copy/mirror workflows. Transfers are non-destructive by default; destination deletion is never implied by the command name. ## What changed @@ -16,20 +16,20 @@ This repository now supports three backend modes: | --- | --- | --- | | `auto` | Default. Prefer official `proton-drive` where the command maps cleanly. | `configure`, `status`, `browse`, and simple `sync` transfers when `proton-drive` is installed. | | `proton` | Force Proton's official CLI. | Use this when you want SDK-backed auth and transfers without rclone config. | -| `rclone` | Force the legacy rclone backend. | Required for `mount`, custom rclone remotes, `--dry-run`, extra rclone flags, and exact rclone mirroring behavior. | +| `rclone` | Force the legacy rclone backend. | Required for `mount`, custom rclone remotes, `--dry-run`, extra rclone flags, and explicit mirroring. | The upstream Proton Drive SDK is still evolving and Proton documents direct SDK usage as not yet ready for commercial/production third-party apps. For that reason this project integrates through the official `proton-drive` CLI instead of compiling directly against unstable SDK internals. ## Requirements -- Go 1.21+ to build this wrapper. +- Go 1.25 or 1.26 to build this wrapper. - Proton's official Drive CLI for the modern backend. You can install it manually from [proton.me/download/drive/cli](https://proton.me/download/drive/cli/index.html) or run `protondrive bootstrap --proton-drive`. - A Proton account and browser access for `proton-drive auth login`. - Linux secret storage for Proton's CLI sessions, for example libsecret with GNOME Keyring or KWallet. - Linux `secret-tool` from `libsecret-tools` when importing Proton's official CLI session into rclone. - rclone only when you need `mount`, named rclone remotes, rclone dry-runs, or rclone-specific sync flags. - Linux: FUSE/fusermount when using `mount`. -- macOS: no macFUSE is required for the default mount path; `mount` uses rclone WebDAV plus macOS `mount_webdav` in `auto` mode. Install/approve macFUSE only if you force `--mount-method fuse`. +- macOS: no macFUSE is required for the default mount path; `mount` uses rclone WebDAV plus the system `mount_webdav` and `expect` tools in `auto` mode. Install/approve macFUSE only if you force `--mount-method fuse`. ## Installation @@ -52,7 +52,7 @@ Or install Proton's official CLI manually: ```bash # Example for Linux x64. Verify the current version and checksum on Proton's download page. -curl -L -o proton-drive https://proton.me/download/drive/cli/0.4.6/linux-x64/proton-drive +curl -L -o proton-drive https://proton.me/download/drive/cli/0.5.0/linux-x64/proton-drive chmod +x proton-drive sudo install -m 0755 proton-drive /usr/local/bin/proton-drive ``` @@ -66,16 +66,16 @@ The Flatpak packages only this GPLv3 wrapper. It does not redistribute Proton's Build locally: ```bash -flatpak install flathub org.freedesktop.Platform//24.08 org.freedesktop.Sdk//24.08 org.freedesktop.Sdk.Extension.golang//24.08 +flatpak install flathub org.freedesktop.Platform//25.08 org.freedesktop.Sdk//25.08 org.freedesktop.Sdk.Extension.golang//25.08 flatpak-builder --force-clean --user --install-deps-from=flathub \ - build-dir packaging/flatpak/io.github.colinmario.protondriveforlinux.yml + build-dir packaging/flatpak/io.github.colinmario.protondriveforlinux.devel.yml ``` Install locally: ```bash flatpak-builder --user --install --force-clean --install-deps-from=flathub \ - build-dir packaging/flatpak/io.github.colinmario.protondriveforlinux.yml + build-dir packaging/flatpak/io.github.colinmario.protondriveforlinux.devel.yml ``` Run: @@ -93,6 +93,12 @@ the current upstream release and verified against the release `SHA256SUMS`. See [packaging/flatpak/README.md](packaging/flatpak/README.md) for packaging notes and Flathub submission details. +The Flatpak needs home-directory access for arbitrary CLI transfer paths and +uses `flatpak-spawn --host` for explicitly selected host helpers. Host commands +run outside the sandbox, so the package is a distribution format rather than a +security boundary. Native release archives/packages are recommended for FUSE +mounts and persistent system services. + ## Quick start ```bash @@ -104,6 +110,10 @@ protondrive --backend rclone configure --from-proton-cli-session # Check CLI version and auth/listing state protondrive status --details +protondrive status --json + +# Inspect the wrapper build itself +protondrive version --json # Browse folders in /my-files protondrive browse @@ -137,6 +147,11 @@ Global options: Using a custom `--remote` selects the rclone backend automatically because Proton's official CLI manages its own account session instead of named remotes. +`status` is suitable for monitoring. It verifies authentication even without +`--details` and uses stable exit codes: `0` healthy, `3` not configured, `4` +authentication failed, and `5` backend/tool failure. Use `--json` for structured +output or `--informational` when a human-readable check must always exit zero. + ## CLI usage ```text @@ -146,9 +161,9 @@ protondrive [--backend auto|proton|rclone] [--remote name] [options] | Command | Proton backend | rclone backend | | --- | --- | --- | | `configure` | Runs `proton-drive auth login`. | Creates/updates an rclone Proton Drive remote. | -| `status` | Prints official CLI version and verifies Drive listing. | Checks the rclone remote and optional details. | +| `status` | Prints official CLI version and verifies Drive listing. | Verifies the configured rclone remote and authentication. | | `browse` | Runs `proton-drive filesystem list`. Defaults to `/my-files`. | Runs `rclone lsd` or `rclone ls`. | -| `sync` | Runs `filesystem upload` or `filesystem download`. | Runs `rclone sync`. | +| `sync` | Runs non-destructive `filesystem upload` or `filesystem download`. | Runs `rclone copy` by default; `rclone sync` only for explicit mirror operations. | | `mount` | Not supported by Proton's CLI. | Runs `rclone mount` on Linux and rclone WebDAV + `mount_webdav` by default on macOS. | | `unmount` | Uses OS unmount helpers. | Uses OS unmount helpers. | | `configs` | Backend-independent JSON templates. | Backend-independent JSON templates. | @@ -199,6 +214,19 @@ With 2FA and the local credential vault: `--headless` never starts Proton's browser login. In `auto` mode it uses rclone's Proton password-auth flow to initialize cached Proton tokens, then writes a compatible official Proton CLI session into the OS secret store (`ch.proton.drive/drive-sdk-cli` / `auth-session`). That gives you both a working rclone mount remote and a browserless `proton-drive` CLI session for later `browse`/`sync` commands. The command behaves like `--non-interactive` and fails if required values are missing. Use `--skip-verify` only when `proton-drive` is not installed yet; rclone still performs one real listing so the session tokens can be captured. +One-time 2FA codes are used only through a private temporary rclone config for +the current verification request; the file is removed immediately afterward, +and the code is never retained in the normal rclone config or credential vault. +Unlocking an older vault once rewrites it with the current schema and removes +any legacy stored TOTP value. + +The transactional config editor preserves unknown rclone remote options and +backs up plaintext configs before changing them. It deliberately refuses to +edit an rclone-obscured `RCLONE_ENCRYPT_V0` config (including configurations +unlocked through `RCLONE_CONFIG_PASS`) because rewriting encrypted content as +plaintext would corrupt the file. Import the session into a separate plaintext +config with mode `0600`, or manage that encrypted remote directly with rclone. + On headless Linux where no Secret Service is available, you can opt into Proton CLI's official plaintext file session mode: ```bash @@ -223,7 +251,7 @@ Export an already-initialized rclone session back into Proton's official CLI sec protondrive --backend rclone configure --from-rclone-session ``` -The session import reads Proton's OS secret-store entry (`ch.proton.drive/drive-sdk-cli` / `auth-session`) and writes an rclone Proton Drive remote containing the SDK session fields rclone needs. It uses macOS Keychain on macOS and `secret-tool`/Secret Service on Linux. The old encrypted credential vault remains available for password-based rclone auto-refresh. +The session import reads Proton's OS secret-store entry (`ch.proton.drive/drive-sdk-cli` / `auth-session`) and writes an rclone Proton Drive remote containing the SDK session fields rclone needs. It uses macOS Keychain on macOS and `secret-tool`/Secret Service on Linux. On macOS, private-session export requires Bun's Keychain API; the wrapper fails closed instead of putting session JSON in `security` process arguments. Private session bridging is version-gated to the validated Proton CLI 0.4.x/0.5.x format and fails closed for future format series. The old encrypted credential vault remains available for password-based rclone auto-refresh. ### Browse @@ -253,19 +281,43 @@ Proton conflict strategies: - `--folder-conflict-strategy merge|keep-both|replace|skip` - `--skip-thumbnails` for uploads -Use rclone when you need exact rclone mirror semantics, `--dry-run`, or passthrough flags: +Use rclone when you need dry-runs, passthrough flags, or an explicitly destructive mirror. The safe default is `rclone copy`: ```bash +# Non-destructive copy; files missing locally remain on Proton Drive protondrive --backend rclone sync ~/Documents --remote-path backups --dry-run -protondrive --backend rclone sync ~/Documents --remote-path backups -- --delete-after + +# Inspect an exact mirror first +protondrive --backend rclone sync ~/Documents --remote-path backups \ + --operation mirror --dry-run + +# Apply it with deletion limit, source sentinel, and automatic backup directory +protondrive --backend rclone sync ~/Documents --remote-path backups \ + --operation mirror --confirm-mirror --max-delete 25 \ + --source-sentinel .protondrive-source ``` In `auto` mode, simple upload/download transfers require Proton's official CLI. -The wrapper does not silently fall back to `rclone sync` for those transfers, -because `rclone sync` mirrors deletions into the destination. Pass -`--backend rclone` explicitly when destructive mirror semantics are intended. - -Watch mode still works with both upload backends by rerunning the selected transfer after filesystem changes settle: +When rclone is selected, the wrapper still uses non-destructive copy semantics +unless `--operation mirror` is present. A live mirror additionally requires +`--confirm-mirror`; remote/filesystem roots and empty sources are rejected by +default. Each mirror is limited to 25 deletions unless changed with +`--max-delete`, and replaced/deleted destination files are moved to an automatic +timestamped backup directory unless `--no-backup-dir` is explicitly supplied. +The backup must be outside the destination; a same-remote root mirror therefore +requires either a backup on another remote or explicit `--no-backup-dir`. +Sentinel files must be regular files and do not count as source content, so a +marker-only or directory-only source is still blocked as empty. + +The standalone `--` delimiter is consumed by the wrapper, so passthrough flags +are forwarded correctly. Destructive rclone deletion flags are rejected for +copy operations. Passthrough cannot override wrapper-owned dry-run, deletion +limit, backup, error-handling, or in-place safeguards. + +Watch mode works with both upload backends by rerunning the selected transfer +after filesystem changes settle. Failed runs retry with bounded exponential +backoff; a later filesystem event can recover the watcher after retries are +exhausted. Proton watch mode requires an explicit conflict strategy. ```bash protondrive sync ~/Paperless/export --remote-path /my-files/Backups/Paperless --watch --watch-debounce 45s @@ -287,7 +339,13 @@ If you authenticated headlessly through rclone first, create the official Proton protondrive --backend rclone configure --from-rclone-session ``` -On macOS, `auto` mode avoids stale or blocked macFUSE installations by serving the rclone remote over localhost WebDAV and mounting it with macOS `mount_webdav`: +On macOS, `auto` mode avoids stale or blocked macFUSE installations by serving +the rclone remote over authenticated localhost WebDAV and mounting it with +macOS `mount_webdav`. Each mount gets random credentials, a private log under +the wrapper config directory, a mode-`0600` bcrypt authentication file (removed +during cleanup or `unmount`), and recorded process/start identity so unmounting cannot +signal a reused PID. The password is supplied through a private pseudo-terminal +conversation and never appears in process arguments or environment variables: ```bash protondrive --backend rclone mount ~/ProtonDrive @@ -374,6 +432,7 @@ Notes: - OpenRC mounts use OpenRC user services under `${XDG_CONFIG_HOME:-~/.config}/rc/init.d`. They require `rc-service`, `rc-update`, `openrc-run`, and an OpenRC user session with `XDG_RUNTIME_DIR` set. - `--persist` uses FUSE/fusermount on Linux. Install `fuse3`/`fusermount3` or the equivalent package for your distribution. - Use `--rclone-flag` for extra rclone mount options. Positional passthrough flags are intentionally rejected for persistent units so the generated service stays deterministic. +- Wrapper-owned daemon, config, authentication, cache, read-only, and rclone remote-control flags cannot be overridden through mount passthrough. ## Reusable sync configs @@ -386,15 +445,22 @@ protondrive configs show paperless-ngx-export protondrive sync --config paperless-ngx-export ``` -Each JSON file can declare `name`, `description`, `local_path`, `remote_path`, `direction`, `watch`, `watch_debounce`, and `extra_rclone_args`. If `extra_rclone_args` is present, `auto` selects the rclone backend for that run. +Schema version 1 accepts `name`, `description`, `local_path`, `remote_path`, +`direction`, `operation`, `watch`, `watch_debounce`, `max_delete`, `backup_dir`, +`source_sentinel`, `allow_empty_source`, and `extra_rclone_args`. Unknown fields, +trailing JSON, unsafe sentinel paths, and destructive copy flags are rejected. +Version-less files from releases through 0.2.5 remain readable but migrate to +schema version 1 and safe `copy` behavior. Wrapper-owned mirror safety flags +cannot be overridden in `extra_rclone_args`. If `extra_rclone_args` is present, +`auto` selects rclone. ## Configuration locations | Path | Purpose | | --- | --- | | `${XDG_CONFIG_HOME:-~/.config}/protondrive` | Wrapper metadata. | -| `*.creds` | Legacy encrypted credential vault for rclone mode. | -| `*.state` | Last auth and mount metadata recorded by this wrapper. | +| `*-.creds` | Encrypted credential vault for rclone mode. Legacy names are migrated on use. | +| `*-.state` | Last auth and mount metadata. The hash prevents remote-name collisions. | | `sync-configs/*.json` | User sync config files. | Proton's official CLI stores cache, app data, logs, and credentials in its own OS-specific locations. See [Using Proton Drive CLI](https://proton.me/support/drive-cli) for the current upstream details. @@ -404,10 +470,14 @@ Proton's official CLI stores cache, app data, logs, and credentials in its own O ```bash go fmt ./... go vet ./... -go test ./... +go test -race ./... go build ./cmd/protondrive ``` +GitHub CI runs the suite on macOS and Linux with Go 1.25/1.26, checks the race +detector, formatting, vet, Staticcheck, Gosec, govulncheck, dependency/vendor +consistency, cross-builds, coverage floor, and Flatpak/AppStream metadata. + Manual integration checks: ```bash @@ -424,7 +494,9 @@ protondrive --backend rclone status --details - Headless Proton CLI setup fails before writing a session: rclone must complete one real listing so it can cache `client_uid`, access token, refresh token, and key password. Check credentials, 2FA, network access, and Proton rate limits. - `--from-proton-cli-session` cannot find a session: run `protondrive --backend proton configure` first, then ensure macOS Keychain or Linux Secret Service is unlocked. On Linux, install `libsecret-tools` so `secret-tool` is available. - `rclone not found`: install rclone or set `--rclone-bin`; rclone is still required for mounts. +- Encrypted rclone config is refused: this wrapper never rewrites `RCLONE_ENCRYPT_V0` files. Select a separate plaintext `RCLONE_CONFIG` protected with mode `0600`, or configure the encrypted remote directly with rclone. - macOS mount fails with macFUSE errors: use the default `--mount-method auto` or explicitly pass `--mount-method webdav`; this avoids macFUSE. +- macOS WebDAV mount reports that `expect` is unavailable: restore the system `/usr/bin/expect` tool or use a working `--mount-method fuse`; the wrapper will not fall back to exposing the WebDAV password in arguments. - Linux/FUSE mounts never become ready: rerun with `protondrive --backend rclone mount --foreground` and check FUSE/fusermount. - Proton upload/download prompts for conflicts: pass one of the conflict strategy flags for non-interactive automation. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c09473b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# Security policy + +Please report suspected vulnerabilities privately through GitHub's +**Security > Report a vulnerability** flow. Do not open a public issue for an +unfixed credential, authentication, data-loss, or command-execution problem. + +Security fixes are provided for the newest release. Reports should include the +affected version, operating system, backend, reproduction steps, and whether +real Proton Drive data or credentials may have been exposed. Never include real +passwords, session tokens, vault files, or rclone configuration in a report. + +The project is an unofficial wrapper. Proton account or service incidents +should be reported to Proton through its official security channels. diff --git a/cmd/protondrive/auth.go b/cmd/protondrive/auth.go new file mode 100644 index 0000000..e98473e --- /dev/null +++ b/cmd/protondrive/auth.go @@ -0,0 +1,1090 @@ +package main + +import ( + "bufio" + "bytes" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + "time" + + "github.com/ColinMario/Protondrive-for-Linux/internal/safefile" +) + +func configureRemote(remote, email, password, mailboxPassword string, quiet bool) error { + if !quiet { + fmt.Printf("Configuring rclone remote '%s'...\n", remote) + } + + obscuredPassword, err := obscureRcloneSecret(password) + if err != nil { + return fmt.Errorf("failed to process password: %w", err) + } + + values := map[string]string{ + "type": "protondrive", + "username": strings.TrimSpace(email), + "password": strings.TrimSpace(obscuredPassword), + } + if strings.TrimSpace(mailboxPassword) != "" { + obscuredMailboxPassword, err := obscureRcloneSecret(mailboxPassword) + if err != nil { + return fmt.Errorf("failed to process mailbox password: %w", err) + } + values["mailbox_password"] = strings.TrimSpace(obscuredMailboxPassword) + } + configPath, err := rcloneConfigFilePath() + if err != nil { + return err + } + if err := writeRcloneConfigSection(configPath, normalizedRemoteName(remote), values); err != nil { + return fmt.Errorf("rclone config update failed: %w", err) + } + if !quiet { + fmt.Println("Remote saved successfully.") + } + return nil +} + +type protonCLISessionSnapshot struct { + CachePassword string `json:"cachePassword"` + UserKeyPassword string `json:"userKeyPassword"` + Session struct { + UID string `json:"uid"` + AccessToken string `json:"accessToken"` + RefreshToken string `json:"refreshToken"` + } `json:"session"` +} + +var errProtonCLISessionNotFound = errors.New("proton CLI session secret not found") + +type protonCLISessionStoreSnapshot struct { + Exists bool + Payload []byte + Mode fs.FileMode +} + +func configureRemoteFromProtonCLISession(remote string, verify bool) error { + if err := validateProtonSessionBridgeVersion(false); err != nil { + return err + } + sessionSnapshot, err := loadProtonCLISessionSnapshot() + if err != nil { + return err + } + if strings.TrimSpace(sessionSnapshot.UserKeyPassword) == "" || + strings.TrimSpace(sessionSnapshot.Session.UID) == "" || + strings.TrimSpace(sessionSnapshot.Session.AccessToken) == "" || + strings.TrimSpace(sessionSnapshot.Session.RefreshToken) == "" { + return errors.New("official Proton Drive CLI session is incomplete; run 'protondrive --backend proton configure' first") + } + + obscuredPlaceholder, err := obscureRcloneSecret("proton-cli-session-placeholder") + if err != nil { + return fmt.Errorf("failed to prepare rclone placeholder password: %w", err) + } + configPath, err := rcloneConfigFilePath() + if err != nil { + return err + } + configSnapshot, err := captureRcloneConfigSnapshot(configPath) + if err != nil { + return err + } + values := map[string]string{ + "type": "protondrive", + "username": "proton-cli-session", + "password": strings.TrimSpace(obscuredPlaceholder), + "client_uid": sessionSnapshot.Session.UID, + "client_access_token": sessionSnapshot.Session.AccessToken, + "client_refresh_token": sessionSnapshot.Session.RefreshToken, + "client_salted_key_pass": base64.StdEncoding.EncodeToString([]byte(sessionSnapshot.UserKeyPassword)), + "enable_caching": "false", + } + if err := writeRcloneConfigSection(configPath, normalizedRemoteName(remote), values); err != nil { + return err + } + fmt.Printf("Imported official Proton Drive CLI session into rclone remote '%s'.\n", normalizedRemoteName(remote)) + fmt.Printf("Updated rclone config: %s\n", configPath) + if verify { + fmt.Println("Verifying imported rclone session...") + if err := verifyRemote(remote); err != nil { + return rollbackRcloneConfigError(configPath, configSnapshot, fmt.Errorf("imported session could not be verified: %w", err)) + } + fmt.Println("Imported rclone session verified.") + } + return nil +} + +func configureProtonCLISessionFromRcloneRemote(remote string, verify bool) error { + if err := validateProtonSessionBridgeVersion(!verify); err != nil { + return err + } + snapshot, err := protonCLISessionFromRcloneRemote(remote) + if err != nil { + return err + } + previous, err := captureProtonCLISessionStoreSnapshot() + if err != nil { + return fmt.Errorf("unable to snapshot the existing Proton CLI session before export: %w", err) + } + target, err := writeProtonCLISessionSnapshot(snapshot) + if err != nil { + return rollbackProtonCLISessionError(previous, err) + } + fmt.Printf("Wrote official Proton Drive CLI session to %s.\n", target) + if verify { + if err := ensureProtonDrive(); err != nil { + return rollbackProtonCLISessionError(previous, fmt.Errorf("proton CLI session could not be verified: %w", err)) + } + fmt.Println("Verifying Proton CLI session...") + if _, err := runProtonDriveCapture("filesystem", "list", "/"); err != nil { + return rollbackProtonCLISessionError(previous, fmt.Errorf("proton CLI session verification failed: %w", err)) + } + fmt.Println("Browserless Proton CLI session verified.") + } + return nil +} + +func validateProtonSessionBridgeVersion(allowUnavailable bool) error { + if truthyEnv(os.Getenv("PROTONDRIVE_UNSAFE_SESSION_BRIDGE")) { + fmt.Fprintln(os.Stderr, "Warning: bypassing Proton CLI private-session compatibility check.") + return nil + } + if err := ensureProtonDrive(); err != nil { + if allowUnavailable { + fmt.Fprintln(os.Stderr, "Warning: Proton CLI is unavailable; private-session compatibility could not be checked.") + return nil + } + return err + } + output, err := runProtonDriveCapture("version") + if err != nil { + return fmt.Errorf("unable to verify Proton CLI session compatibility: %w", err) + } + return validateProtonSessionBridgeVersionOutput(output) +} + +func validateProtonSessionBridgeVersionOutput(output string) error { + match := regexp.MustCompile(`\b(\d+)\.(\d+)\.(\d+)\b`).FindStringSubmatch(output) + if len(match) != 4 { + return fmt.Errorf("cannot recognize Proton CLI version %q; refusing to manipulate its private session format", strings.TrimSpace(output)) + } + if match[1] != "0" || (match[2] != "4" && match[2] != "5") { + return fmt.Errorf("proton CLI %s is outside the validated private-session bridge series 0.4.x and 0.5.x; use official browser authentication or set PROTONDRIVE_UNSAFE_SESSION_BRIDGE=true only after verifying the upstream format", match[0]) + } + return nil +} + +func protonCLISessionFromRcloneRemote(remote string) (protonCLISessionSnapshot, error) { + configPath, err := rcloneConfigFilePath() + if err != nil { + return protonCLISessionSnapshot{}, err + } + values, err := readRcloneConfigSection(configPath, normalizedRemoteName(remote)) + if err != nil { + return protonCLISessionSnapshot{}, err + } + return protonCLISessionFromRcloneConfigValues(values) +} + +func protonCLISessionFromRcloneConfigValues(values map[string]string) (protonCLISessionSnapshot, error) { + required := []string{"client_uid", "client_access_token", "client_refresh_token", "client_salted_key_pass"} + for _, key := range required { + if strings.TrimSpace(values[key]) == "" { + return protonCLISessionSnapshot{}, fmt.Errorf("rclone Proton Drive remote is missing %s; run browserless configure without --skip-verify so rclone can initialize cached tokens", key) + } + } + userKeyPassword := decodeRcloneSaltedKeyPass(values["client_salted_key_pass"]) + cachePassword, err := randomBase64(32) + if err != nil { + return protonCLISessionSnapshot{}, err + } + + var snapshot protonCLISessionSnapshot + snapshot.CachePassword = cachePassword + snapshot.UserKeyPassword = userKeyPassword + snapshot.Session.UID = strings.TrimSpace(values["client_uid"]) + snapshot.Session.AccessToken = strings.TrimSpace(values["client_access_token"]) + snapshot.Session.RefreshToken = strings.TrimSpace(values["client_refresh_token"]) + return snapshot, nil +} + +func decodeRcloneSaltedKeyPass(value string) string { + value = strings.TrimSpace(value) + decoded, err := base64.StdEncoding.DecodeString(value) + if err != nil || len(decoded) == 0 { + return value + } + text := string(decoded) + if !isPrintableSecret(text) { + return value + } + return text +} + +func isPrintableSecret(value string) bool { + if value == "" { + return false + } + for _, r := range value { + if r < 0x20 || r == 0x7f { + return false + } + } + return true +} + +func randomBase64(size int) (string, error) { + buf := make([]byte, size) + if _, err := rand.Read(buf); err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(buf), nil +} + +func loadProtonCLISessionSnapshot() (protonCLISessionSnapshot, error) { + raw, err := loadProtonCLISessionRaw() + if err != nil { + return protonCLISessionSnapshot{}, fmt.Errorf("unable to read official Proton Drive CLI session; run 'protondrive --backend proton configure' first: %w", err) + } + var snapshot protonCLISessionSnapshot + if err := json.Unmarshal(bytes.TrimSpace(raw), &snapshot); err != nil { + return protonCLISessionSnapshot{}, fmt.Errorf("official Proton Drive CLI session has unexpected format: %w", err) + } + return snapshot, nil +} + +func loadProtonCLISessionRaw() ([]byte, error) { + if truthyEnv(os.Getenv("PROTON_DRIVE_UNSAFE_SECRETS")) { + path, err := protonCLIUnsafeSessionFilePath() + if err != nil { + return nil, err + } + raw, err := os.ReadFile(path) // #nosec G304 -- explicitly configured Proton CLI compatibility path + if errors.Is(err, os.ErrNotExist) { + return nil, errProtonCLISessionNotFound + } + return raw, err + } + switch runtime.GOOS { + case "darwin": + output, err := safeExecCommand("security", "find-generic-password", "-s", protonCLISecretService, "-a", protonCLISecretName, "-w").CombinedOutput() + if err != nil { + if protonCLISessionSecretMissing(output) { + return nil, errProtonCLISessionNotFound + } + return nil, fmt.Errorf("macOS Keychain lookup failed: %w", err) + } + if len(bytes.TrimSpace(output)) == 0 { + return nil, errProtonCLISessionNotFound + } + return output, nil + case "linux": + return loadProtonCLISessionFromSecretTool() + default: + return nil, fmt.Errorf("importing the official Proton Drive CLI session is not implemented on %s", runtime.GOOS) + } +} + +func loadProtonCLISessionFromSecretTool() ([]byte, error) { + if _, err := exec.LookPath("secret-tool"); err != nil { + return nil, errors.New("secret-tool not found; install libsecret-tools or configure rclone with username/password") + } + candidates := [][]string{ + {"lookup", "service", protonCLISecretService, "name", protonCLISecretName}, + {"lookup", "service", protonCLISecretService, "account", protonCLISecretName}, + {"lookup", "application", protonCLISecretService, "name", protonCLISecretName}, + } + var lastDiagnostic string + for _, args := range candidates { + out, err := safeExecCommand("secret-tool", args...).CombinedOutput() // #nosec G204 -- fixed secret-tool command with fixed attribute candidates + if err == nil && len(bytes.TrimSpace(out)) > 0 { + return out, nil + } + if diagnostic := strings.TrimSpace(string(out)); diagnostic != "" { + lastDiagnostic = diagnostic + } + } + if lastDiagnostic != "" { + return nil, fmt.Errorf("system Secret Service lookup failed: %s", lastDiagnostic) + } + return nil, errProtonCLISessionNotFound +} + +func writeProtonCLISessionSnapshot(snapshot protonCLISessionSnapshot) (string, error) { + if strings.TrimSpace(snapshot.CachePassword) == "" || + strings.TrimSpace(snapshot.UserKeyPassword) == "" || + strings.TrimSpace(snapshot.Session.UID) == "" || + strings.TrimSpace(snapshot.Session.AccessToken) == "" || + strings.TrimSpace(snapshot.Session.RefreshToken) == "" { + return "", errors.New("cannot write incomplete Proton CLI session") + } + payload, err := json.Marshal(snapshot) + if err != nil { + return "", err + } + return writeProtonCLISessionPayload(payload) +} + +func writeProtonCLISessionPayload(payload []byte) (string, error) { + if truthyEnv(os.Getenv("PROTON_DRIVE_UNSAFE_SECRETS")) { + path, err := writeProtonCLIUnsafeSessionFile(payload) + if err != nil { + return "", err + } + return path, nil + } + switch runtime.GOOS { + case "darwin": + if err := writeProtonCLISessionWithBun(payload); err == nil { + return fmt.Sprintf("macOS Keychain via Bun.secrets (%s/%s)", protonCLISecretService, protonCLISecretName), nil + } else { + return "", fmt.Errorf("safe macOS Keychain writer unavailable: %w; install Bun so the session is read from a protected temporary file, or authenticate with the official Proton CLI", err) + } + case "linux": + if _, err := exec.LookPath("secret-tool"); err != nil { + return "", errors.New("secret-tool not found; install libsecret-tools to write the Proton CLI session, or set PROTON_DRIVE_UNSAFE_SECRETS=true with PROTON_DRIVE_CACHE_DIR for a plaintext file session") + } + cmd := safeExecCommand("secret-tool", "store", "--label", "Proton Drive CLI session", "service", protonCLISecretService, "name", protonCLISecretName) + cmd.Stdin = bytes.NewReader(payload) + if output, err := cmd.CombinedOutput(); err != nil { + return "", fmt.Errorf("unable to write Proton CLI session to Secret Service: %s", strings.TrimSpace(string(output))) + } + return fmt.Sprintf("Secret Service (%s/%s)", protonCLISecretService, protonCLISecretName), nil + default: + return "", fmt.Errorf("writing the Proton CLI session is not implemented on %s", runtime.GOOS) + } +} + +func captureProtonCLISessionStoreSnapshot() (protonCLISessionStoreSnapshot, error) { + raw, err := loadProtonCLISessionRaw() + if errors.Is(err, errProtonCLISessionNotFound) { + return protonCLISessionStoreSnapshot{}, nil + } + if err != nil { + return protonCLISessionStoreSnapshot{}, err + } + snapshot := protonCLISessionStoreSnapshot{Exists: true, Payload: append([]byte(nil), raw...), Mode: 0o600} + if truthyEnv(os.Getenv("PROTON_DRIVE_UNSAFE_SECRETS")) { + path, pathErr := protonCLIUnsafeSessionFilePath() + if pathErr != nil { + return protonCLISessionStoreSnapshot{}, pathErr + } + info, statErr := os.Stat(path) + if statErr != nil { + return protonCLISessionStoreSnapshot{}, statErr + } + snapshot.Mode = info.Mode().Perm() + } + return snapshot, nil +} + +func restoreProtonCLISessionStoreSnapshot(snapshot protonCLISessionStoreSnapshot) error { + if !snapshot.Exists { + return removeProtonCLISessionPayload() + } + if _, err := writeProtonCLISessionPayload(snapshot.Payload); err != nil { + return err + } + if truthyEnv(os.Getenv("PROTON_DRIVE_UNSAFE_SECRETS")) { + path, err := protonCLIUnsafeSessionFilePath() + if err != nil { + return err + } + if err := os.Chmod(path, snapshot.Mode); err != nil { + return err + } + } + return nil +} + +func rollbackProtonCLISessionError(snapshot protonCLISessionStoreSnapshot, cause error) error { + if err := restoreProtonCLISessionStoreSnapshot(snapshot); err != nil { + return errors.Join(cause, fmt.Errorf("failed to restore previous Proton CLI session: %w", err)) + } + return fmt.Errorf("%w (previous Proton CLI session state restored)", cause) +} + +func removeProtonCLISessionPayload() error { + if truthyEnv(os.Getenv("PROTON_DRIVE_UNSAFE_SECRETS")) { + path, err := protonCLIUnsafeSessionFilePath() + if err != nil { + return err + } + return safefile.Remove(path) + } + switch runtime.GOOS { + case "darwin": + output, err := safeExecCommand("security", "delete-generic-password", "-s", protonCLISecretService, "-a", protonCLISecretName).CombinedOutput() + if err == nil || protonCLISessionSecretMissing(output) { + return nil + } + return fmt.Errorf("macOS Keychain delete failed: %w", err) + case "linux": + if _, err := exec.LookPath("secret-tool"); err != nil { + return errors.New("secret-tool not found while rolling back Proton CLI session") + } + output, err := safeExecCommand("secret-tool", "clear", "service", protonCLISecretService, "name", protonCLISecretName).CombinedOutput() + if err == nil || len(bytes.TrimSpace(output)) == 0 { + return nil + } + return fmt.Errorf("system Secret Service delete failed: %s", strings.TrimSpace(string(output))) + default: + return fmt.Errorf("removing the Proton CLI session is not implemented on %s", runtime.GOOS) + } +} + +func protonCLISessionSecretMissing(output []byte) bool { + lower := strings.ToLower(string(output)) + for _, marker := range []string{"could not be found", "item not found", "not found", "no such item"} { + if strings.Contains(lower, marker) { + return true + } + } + return false +} + +func writeProtonCLISessionWithBun(payload []byte) error { + bunPath, err := exec.LookPath("bun") + if err != nil { + return err + } + dir, err := os.MkdirTemp("", "protondrive-bun-secret-*") + if err != nil { + return err + } + defer os.RemoveAll(dir) + + payloadPath := filepath.Join(dir, "session.json") + scriptPath := filepath.Join(dir, "write-session.js") + if err := safefile.Write(payloadPath, payload, 0o600); err != nil { + return err + } + script := fmt.Sprintf(`const value = await Bun.file(process.argv[2]).text(); +await Bun.secrets.set({ service: %q, name: %q, value }); +`, protonCLISecretService, protonCLISecretName) + if err := safefile.Write(scriptPath, []byte(script), 0o600); err != nil { + return err + } + cmd := safeExecCommand(bunPath, scriptPath, payloadPath) // #nosec G204 -- bun path is resolved via exec.LookPath and arguments are temp files + if output, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("bun secrets writer failed: %s", strings.TrimSpace(string(output))) + } + return nil +} + +func writeProtonCLIUnsafeSessionFile(payload []byte) (string, error) { + path, err := protonCLIUnsafeSessionFilePath() + if err != nil { + return "", err + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return "", err + } + if err := safefile.Write(path, payload, 0o600); err != nil { + return "", err + } + if err := os.Chmod(path, 0o600); err != nil { + return "", err + } + return path, nil +} + +func protonCLIUnsafeSessionFilePath() (string, error) { + if override := strings.TrimSpace(os.Getenv("PROTON_DRIVE_CACHE_DIR")); override != "" { + return filepath.Join(expandPath(override), "auth-session.json"), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + switch runtime.GOOS { + case "darwin": + return filepath.Join(home, "Library", "Application Support", "proton-drive-cli", "auth-session.json"), nil + case "linux": + dataHome := strings.TrimSpace(os.Getenv("XDG_DATA_HOME")) + if dataHome == "" { + dataHome = filepath.Join(home, ".local", "share") + } + return filepath.Join(expandPath(dataHome), "proton-drive-cli", "auth-session.json"), nil + case "windows": + localAppData := strings.TrimSpace(os.Getenv("LOCALAPPDATA")) + if localAppData == "" { + localAppData = filepath.Join(home, "AppData", "Local") + } + return filepath.Join(localAppData, "proton-drive-cli", "Data", "auth-session.json"), nil + default: + configDir, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(configDir, "proton-drive-cli", "auth-session.json"), nil + } +} + +func truthyEnv(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "1", "true", "yes", "y": + return true + default: + return false + } +} + +func rcloneConfigFilePath() (string, error) { + if config := strings.TrimSpace(os.Getenv("RCLONE_CONFIG")); config != "" { + return expandPath(config), nil + } + output, err := runRcloneCapture("config", "file") + if err != nil { + return "", err + } + var candidate string + for _, line := range strings.Split(output, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + if strings.HasPrefix(line, "/") || strings.HasPrefix(line, "~") || filepath.IsAbs(line) { + candidate = line + } + } + if candidate == "" { + return "", fmt.Errorf("unable to parse rclone config path from: %s", strings.TrimSpace(output)) + } + return expandPath(candidate), nil +} + +func obscureRcloneSecret(secret string) (string, error) { + cmd := externalCommand(currentOptions.RcloneBin, "obscure", "-") + cmd.Stdin = strings.NewReader(secret + "\n") + output, err := cmd.CombinedOutput() + if err != nil { + return "", fmt.Errorf("%s obscure failed: %s", currentOptions.RcloneBin, strings.TrimSpace(string(output))) + } + return strings.TrimSpace(string(output)), nil +} + +func readRcloneConfigSection(configPath, section string) (map[string]string, error) { + validatedSection, err := validateRemoteName(section) + if err != nil { + return nil, err + } + section = validatedSection + data, err := os.ReadFile(configPath) // #nosec G304 -- rclone config path is resolved from RCLONE_CONFIG or rclone itself + if err != nil { + return nil, err + } + if rcloneConfigEncrypted(data) { + return nil, errors.New("encrypted rclone configs are not supported by the wrapper's transactional editor; use a dedicated plaintext RCLONE_CONFIG with mode 0600") + } + header := "[" + strings.TrimSpace(section) + "]" + values := make(map[string]string) + inTarget := false + for _, line := range strings.Split(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n") { + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "#") || strings.HasPrefix(trimmed, ";") { + continue + } + if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") { + inTarget = trimmed == header + continue + } + if !inTarget { + continue + } + key, value, ok := strings.Cut(trimmed, "=") + if !ok { + continue + } + values[strings.TrimSpace(key)] = strings.TrimSpace(value) + } + if len(values) == 0 { + return nil, fmt.Errorf("rclone remote %q not found in %s", section, configPath) + } + return values, nil +} + +func writeRcloneConfigSection(configPath, section string, values map[string]string) error { + return updateRcloneConfigSection(configPath, section, values, true) +} + +func writeRcloneConfigSectionWithoutBackup(configPath, section string, values map[string]string) error { + return updateRcloneConfigSection(configPath, section, values, false) +} + +func updateRcloneConfigSection(configPath, section string, values map[string]string, backup bool) error { + validatedSection, err := validateRemoteName(section) + if err != nil { + return err + } + section = validatedSection + if strings.TrimSpace(os.Getenv("RCLONE_CONFIG_PASS")) != "" { + return errors.New("RCLONE_CONFIG_PASS is set, but the wrapper cannot safely rewrite encrypted rclone configs; use a dedicated plaintext RCLONE_CONFIG with mode 0600") + } + update := func(current []byte) ([]byte, fs.FileMode, error) { + if rcloneConfigEncrypted(current) { + return nil, 0, errors.New("refusing to overwrite an encrypted rclone config; use a dedicated plaintext RCLONE_CONFIG with mode 0600") + } + return renderRcloneConfigSection(current, section, values), 0o600, nil + } + if backup { + return safefile.UpdateWithBackup(configPath, 0o600, ".protondrive.bak", update) + } + return safefile.Update(configPath, 0o600, update) +} + +func rcloneConfigEncrypted(data []byte) bool { + return bytes.HasPrefix(bytes.TrimSpace(data), []byte("RCLONE_ENCRYPT_V0:")) +} + +func renderRcloneConfigSection(current []byte, section string, values map[string]string) []byte { + lines := strings.Split(strings.ReplaceAll(string(current), "\r\n", "\n"), "\n") + header := "[" + section + "]" + var out []string + var preservedTarget []string + inTarget := false + managed := make(map[string]bool) + for _, key := range managedRcloneConfigKeys() { + managed[key] = true + } + for _, line := range lines { + trimmed := strings.TrimSpace(line) + if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") { + inTarget = trimmed == header + if inTarget { + continue + } + } + if inTarget { + key, _, hasValue := strings.Cut(trimmed, "=") + if !hasValue || !managed[strings.TrimSpace(key)] { + preservedTarget = append(preservedTarget, line) + } + continue + } + if len(out) == 0 && strings.TrimSpace(line) == "" { + continue + } + out = append(out, line) + } + for len(out) > 0 && strings.TrimSpace(out[len(out)-1]) == "" { + out = out[:len(out)-1] + } + if len(out) > 0 { + out = append(out, "") + } + out = append(out, header) + for _, key := range managedRcloneConfigKeys() { + value, ok := values[key] + if ok { + out = append(out, fmt.Sprintf("%s = %s", key, sanitizeConfigValue(value))) + } + } + for len(preservedTarget) > 0 && strings.TrimSpace(preservedTarget[0]) == "" { + preservedTarget = preservedTarget[1:] + } + for len(preservedTarget) > 0 && strings.TrimSpace(preservedTarget[len(preservedTarget)-1]) == "" { + preservedTarget = preservedTarget[:len(preservedTarget)-1] + } + out = append(out, preservedTarget...) + return []byte(strings.Join(out, "\n") + "\n") +} + +func managedRcloneConfigKeys() []string { + return []string{ + "type", "username", "password", "mailbox_password", "2fa", + "client_uid", "client_access_token", "client_refresh_token", + "client_salted_key_pass", "enable_caching", + } +} + +type rcloneConfigSnapshot struct { + Exists bool + Data []byte + Mode fs.FileMode +} + +func captureRcloneConfigSnapshot(configPath string) (rcloneConfigSnapshot, error) { + info, err := os.Stat(configPath) + if errors.Is(err, os.ErrNotExist) { + return rcloneConfigSnapshot{Mode: 0o600}, nil + } + if err != nil { + return rcloneConfigSnapshot{}, err + } + data, err := os.ReadFile(configPath) // #nosec G304 -- caller supplies the resolved rclone config path + if err != nil { + return rcloneConfigSnapshot{}, err + } + return rcloneConfigSnapshot{Exists: true, Data: data, Mode: info.Mode().Perm()}, nil +} + +func rollbackRcloneConfigError(configPath string, snapshot rcloneConfigSnapshot, cause error) error { + var rollbackErr error + if snapshot.Exists { + rollbackErr = safefile.Write(configPath, snapshot.Data, snapshot.Mode) + } else { + rollbackErr = safefile.Remove(configPath) + } + if err := safefile.Remove(configPath + ".protondrive.bak"); err != nil { + rollbackErr = errors.Join(rollbackErr, fmt.Errorf("remove transient config backup: %w", err)) + } + if rollbackErr != nil { + return errors.Join(cause, fmt.Errorf("failed to restore previous rclone config: %w", rollbackErr)) + } + return fmt.Errorf("%w (previous rclone config restored)", cause) +} + +func sanitizeConfigValue(value string) string { + value = strings.ReplaceAll(value, "\r", "") + value = strings.ReplaceAll(value, "\n", "") + return strings.TrimSpace(value) +} + +func verifyRemote(remote string) error { + _, err := runRcloneCapture("lsd", remotePath(remote, "")) + return err +} + +func verifyRemoteWithOneTimeCode(remote, configPath, code string) (returnErr error) { + code = strings.TrimSpace(code) + if code == "" { + return verifyRemote(remote) + } + current, err := os.ReadFile(configPath) // #nosec G304 -- caller supplies the already-resolved rclone config path + if err != nil { + return err + } + values, err := readRcloneConfigSection(configPath, normalizedRemoteName(remote)) + if err != nil { + return err + } + values["2fa"] = code + temp, err := os.CreateTemp(filepath.Dir(configPath), ".protondrive-2fa-*.conf") + if err != nil { + return fmt.Errorf("unable to stage one-time 2FA config: %w", err) + } + tempPath := temp.Name() + if err := temp.Close(); err != nil { + _ = os.Remove(tempPath) + return err + } + defer func() { + if err := safefile.Remove(tempPath); err != nil { + returnErr = errors.Join(returnErr, fmt.Errorf("unable to remove one-time 2FA config: %w", err)) + } + }() + if err := safefile.Write(tempPath, renderRcloneConfigSection(current, normalizedRemoteName(remote), values), 0o600); err != nil { + return err + } + if _, err := runRcloneCaptureWithConfig(tempPath, "lsd", remotePath(remote, "")); err != nil { + return err + } + refreshed, err := readRcloneConfigSection(tempPath, normalizedRemoteName(remote)) + if err != nil { + return fmt.Errorf("unable to read refreshed rclone session: %w", err) + } + delete(refreshed, "2fa") + if err := writeRcloneConfigSectionWithoutBackup(configPath, normalizedRemoteName(remote), refreshed); err != nil { + return fmt.Errorf("unable to persist refreshed rclone session without the one-time 2FA code: %w", err) + } + return nil +} + +func ensureRemoteAuth(remote string) error { + return ensureRemoteAuthMode(remote, true) +} + +func ensureRemoteAuthForStatus(remote string) error { + return ensureRemoteAuthMode(remote, false) +} + +func ensureRemoteAuthMode(remote string, allowPrompt bool) error { + if authErr := verifyRemote(remote); authErr != nil { + recordAuthEvent(remote, "verify", false, strings.TrimSpace(authErr.Error())) + if !isAuthError(authErr) { + return authErr + } + if !hasStoredCredentials(remote) { + return fmt.Errorf("%w; re-run 'protondrive configure --store-credentials' to enable auto-refresh", authErr) + } + if !allowPrompt && strings.TrimSpace(os.Getenv(vaultPassphraseEnv)) == "" { + return fmt.Errorf("%w; automatic refresh requires %s in non-interactive status checks", authErr, vaultPassphraseEnv) + } + if allowPrompt { + fmt.Println("Remote authentication failed. Attempting to refresh credentials...") + } + if refreshErr := tryAutoRefresh(remote, allowPrompt); refreshErr != nil { + recordAuthEvent(remote, "auto-refresh", false, strings.TrimSpace(refreshErr.Error())) + return errors.Join(authErr, fmt.Errorf("automatic refresh failed: %w", refreshErr)) + } + if err := verifyRemote(remote); err != nil { + recordAuthEvent(remote, "auto-refresh", false, strings.TrimSpace(err.Error())) + return err + } + recordAuthEvent(remote, "auto-refresh", true, "") + return nil + } + + recordAuthEvent(remote, "verify", true, "") + return nil +} + +func isAuthError(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + if isTransientTransportMessage(msg) { + return false + } + if strings.Contains(msg, "username and password are required") { + return true + } + if strings.Contains(msg, "couldn't initialize a new proton drive instance") { + return true + } + if strings.Contains(msg, "401") && strings.Contains(msg, "unauthorized") { + return true + } + if strings.Contains(msg, "invalid_grant") { + return true + } + if strings.Contains(msg, "token") && strings.Contains(msg, "expired") { + return true + } + if strings.Contains(msg, "session") && strings.Contains(msg, "expired") { + return true + } + if strings.Contains(msg, "refresh token") && (strings.Contains(msg, "invalid") || strings.Contains(msg, "expired")) { + return true + } + return false +} + +func isTransientTransportMessage(msg string) bool { + for _, marker := range []string{ + "context deadline exceeded", "i/o timeout", "connection timed out", + "connection reset by peer", "connection refused", "no such host", + "temporary failure in name resolution", "tls handshake timeout", + "temporarily unavailable", "service unavailable", "bad gateway", + "broken pipe", "use of closed network connection", "network is unreachable", + } { + if strings.Contains(msg, marker) { + return true + } + } + return false +} + +func tryAutoRefresh(remote string, allowPrompt bool) error { + passphrase := strings.TrimSpace(os.Getenv(vaultPassphraseEnv)) + var err error + if passphrase == "" { + if !allowPrompt { + return fmt.Errorf("%s is required for non-interactive credential refresh", vaultPassphraseEnv) + } + passphrase, err = promptPassword("Credential vault passphrase: ") + if err != nil { + return err + } + } + if strings.TrimSpace(passphrase) == "" { + return errors.New("credential vault passphrase cannot be empty") + } + + creds, err := loadEncryptedCredentials(remote, passphrase) + if err != nil { + return err + } + // Re-encrypt legacy vaults with the current schema so one-time 2FA values + // written by <=0.2.5 are removed as soon as the vault is unlocked. + if _, err := saveEncryptedCredentials(remote, creds, passphrase); err != nil { + return fmt.Errorf("unable to migrate credential vault: %w", err) + } + configPath, err := rcloneConfigFilePath() + if err != nil { + return err + } + snapshot, err := captureRcloneConfigSnapshot(configPath) + if err != nil { + return err + } + if err := configureRemote(remote, creds.Email, creds.Password, creds.MailboxPassword, true); err != nil { + return err + } + if err := verifyRemote(remote); err != nil { + return rollbackRcloneConfigError(configPath, snapshot, fmt.Errorf("refreshed credentials could not be verified: %w", err)) + } + if allowPrompt { + fmt.Println("Credentials refreshed from the local vault.") + } + return nil +} + +func resolveVaultPassphrase(reader *bufio.Reader, provided string, fromStdin bool, nonInteractive bool) (string, error) { + if strings.TrimSpace(provided) != "" { + return provided, nil + } + if fromStdin { + text, err := readLine(reader) + if err != nil { + return "", err + } + if strings.TrimSpace(text) == "" { + return "", errors.New("vault passphrase cannot be empty") + } + return text, nil + } + if nonInteractive { + return "", errors.New("vault passphrase must be provided via --vault-passphrase when running non-interactively") + } + first, err := promptPassword("Credential vault passphrase: ") + if err != nil { + return "", err + } + if strings.TrimSpace(first) == "" { + return "", errors.New("passphrase cannot be empty") + } + second, err := promptPassword("Confirm passphrase: ") + if err != nil { + return "", err + } + if first != second { + return "", errors.New("passphrases did not match") + } + return first, nil +} + +type storedCredentials struct { + Email string `json:"email"` + Password string `json:"password"` + MailboxPassword string `json:"mailbox_password,omitempty"` + SavedAt time.Time `json:"saved_at"` +} + +type encryptedCredentialBlob struct { + Salt string `json:"salt"` + Nonce string `json:"nonce"` + Ciphertext string `json:"ciphertext"` +} + +func saveEncryptedCredentials(remote string, creds storedCredentials, passphrase string) (string, error) { + payload, err := encryptCredentials(passphrase, creds) + if err != nil { + return "", err + } + dir, err := ensureCredentialDir() + if err != nil { + return "", err + } + path := filepath.Join(dir, credentialFilename(remote)) + if err := safefile.Write(path, payload, 0o600); err != nil { + return "", err + } + legacy := filepath.Join(dir, sanitizedRemoteName(remote)+".creds") + if legacy != path { + if err := safefile.Remove(legacy); err != nil { + return path, fmt.Errorf("new credential vault was saved but legacy vault cleanup failed: %w", err) + } + } + return path, nil +} + +func loadEncryptedCredentials(remote, passphrase string) (storedCredentials, error) { + path, err := credentialFilePath(remote) + if err != nil { + return storedCredentials{}, err + } + data, err := os.ReadFile(path) // #nosec G304 -- credential path is generated under the app config directory + if err != nil { + return storedCredentials{}, err + } + return decryptCredentials(passphrase, data) +} + +func hasStoredCredentials(remote string) bool { + path, err := credentialFilePath(remote) + if err != nil { + return false + } + if _, err := os.Stat(path); err != nil { + return false + } + return true +} + +func credentialFilename(remote string) string { + return remoteStorageKey(remote) + ".creds" +} + +func remoteStateFilename(remote string) string { + return remoteStorageKey(remote) + ".state" +} + +func sanitizedRemoteName(remote string) string { + replacer := strings.NewReplacer("/", "_", "\\", "_", ":", "_", " ", "_") + name := normalizeRemote(remote) + if strings.TrimSpace(name) == "" { + name = remoteDefault + } + return replacer.Replace(name) +} + +func remoteStorageKey(remote string) string { + normalized := normalizedRemoteName(remote) + base := strings.Trim(sanitizedRemoteName(normalized), "._-") + if base == "" { + base = "remote" + } + digest := sha256.Sum256([]byte(normalized)) + return fmt.Sprintf("%s-%s", base, hex.EncodeToString(digest[:8])) +} + +func credentialDirPath() (string, error) { + base, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(base, "protondrive"), nil +} + +func ensureCredentialDir() (string, error) { + dir, err := credentialDirPath() + if err != nil { + return "", err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", err + } + return dir, nil +} + +func credentialFilePath(remote string) (string, error) { + dir, err := credentialDirPath() + if err != nil { + return "", err + } + current := filepath.Join(dir, credentialFilename(remote)) + if _, err := os.Stat(current); err == nil || !errors.Is(err, os.ErrNotExist) { + return current, nil + } + legacy := filepath.Join(dir, sanitizedRemoteName(remote)+".creds") + if _, err := os.Stat(legacy); err == nil { + return legacy, nil + } + return current, nil +} diff --git a/cmd/protondrive/bootstrap.go b/cmd/protondrive/bootstrap.go new file mode 100644 index 0000000..4370825 --- /dev/null +++ b/cmd/protondrive/bootstrap.go @@ -0,0 +1,527 @@ +package main + +import ( + "archive/zip" + "bufio" + "crypto/sha256" + "crypto/sha512" + "encoding/hex" + "errors" + "flag" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" + "syscall" + + "golang.org/x/term" +) + +type protonCLIAsset struct { + Platform string + URL string + SHA512 string +} + +type bootstrapOptions struct { + InstallProton bool + InstallRclone bool + InstallDir string + Force bool + Yes bool + AllowUnverifiedRclone bool +} + +func runBootstrap(args []string) error { + fs := flag.NewFlagSet("bootstrap", flag.ContinueOnError) + fs.SetOutput(io.Discard) + + installProton := fs.Bool("proton-drive", false, "Install Proton's official proton-drive CLI into the managed user bin directory") + installRclone := fs.Bool("rclone", false, "Install rclone into the managed user bin directory") + installAll := fs.Bool("all", false, "Install both proton-drive and rclone") + installDir := fs.String("install-dir", defaultManagedBinDir(), "Directory for managed dependency binaries") + force := fs.Bool("force", false, "Replace an existing managed binary") + yes := fs.Bool("yes", false, "Do not prompt before downloading executable dependencies") + allowUnverifiedRclone := fs.Bool("allow-unverified-rclone", false, "Allow rclone download if a release checksum cannot be verified") + + if err := fs.Parse(args); err != nil { + if errors.Is(err, flag.ErrHelp) { + printCommandUsage(fs) + return flag.ErrHelp + } + return err + } + if fs.NArg() != 0 { + return errors.New("bootstrap does not accept positional arguments") + } + + opts := bootstrapOptions{ + InstallProton: *installProton || *installAll, + InstallRclone: *installRclone || *installAll, + InstallDir: expandPath(*installDir), + Force: *force, + Yes: *yes, + AllowUnverifiedRclone: *allowUnverifiedRclone, + } + if !*installProton && !*installRclone && !*installAll { + opts.InstallProton = true + opts.InstallRclone = true + } + + if err := confirmBootstrap(opts); err != nil { + return err + } + if err := os.MkdirAll(opts.InstallDir, 0o755); err != nil { // #nosec G301 -- managed bin directory must be traversable to execute helpers + return fmt.Errorf("failed to create managed bin directory: %w", err) + } + + fmt.Printf("Managed dependency directory: %s\n", opts.InstallDir) + if opts.InstallProton { + if err := bootstrapProtonDrive(opts.InstallDir, opts.Force); err != nil { + return err + } + } + if opts.InstallRclone { + if err := bootstrapRclone(opts.InstallDir, opts.Force, opts.AllowUnverifiedRclone); err != nil { + return err + } + } + + fmt.Println("Bootstrap complete.") + fmt.Printf("Future runs will use managed dependencies automatically when %s or %s are not available on PATH.\n", protonDriveDefaultBin, rcloneDefaultBin) + if insideFlatpak() { + fmt.Println("Flatpak mode detected: managed tools are stored in user data and can be launched through flatpak-spawn when needed.") + } + return nil +} + +func confirmBootstrap(opts bootstrapOptions) error { + if opts.Yes { + return nil + } + tools := make([]string, 0, 2) + if opts.InstallProton { + tools = append(tools, "Proton Drive CLI") + } + if opts.InstallRclone { + tools = append(tools, "rclone") + } + if !term.IsTerminal(int(syscall.Stdin)) { + return errors.New("refusing to download executable dependencies without confirmation; rerun with --yes") + } + fmt.Fprintf(os.Stderr, "Download and install %s into %s? [y/N] ", strings.Join(tools, " and "), opts.InstallDir) + answer, err := bufio.NewReader(os.Stdin).ReadString('\n') + if err != nil && !errors.Is(err, io.EOF) { + return err + } + switch strings.ToLower(strings.TrimSpace(answer)) { + case "y", "yes": + return nil + default: + return errors.New("bootstrap cancelled") + } +} + +func bootstrapProtonDrive(installDir string, force bool) error { + target := filepath.Join(installDir, protonDriveDefaultBin) + if isExecutable(target) && !force { + fmt.Printf("proton-drive already installed: %s\n", target) + return nil + } + + platform, err := protonCLIPlatform(runtime.GOOS, runtime.GOARCH) + if err != nil { + return err + } + fmt.Printf("Resolving Proton Drive CLI download for %s...\n", platform) + indexHTML, err := fetchURLBytes(protonCLIDownloadIndex, 2<<20) + if err != nil { + return fmt.Errorf("failed to read Proton Drive CLI download index: %w", err) + } + assets := parseProtonCLIAssets(string(indexHTML)) + asset, ok := assets[platform] + if !ok { + return fmt.Errorf("proton-drive CLI download index did not contain an asset for %s", platform) + } + if err := validateProtonCLIAssetURL(asset.URL); err != nil { + return err + } + if err := downloadVerifiedBinary(asset.URL, target, asset.SHA512, "sha512"); err != nil { + return fmt.Errorf("failed to install proton-drive: %w", err) + } + fmt.Printf("Installed proton-drive: %s\n", target) + return nil +} + +func bootstrapRclone(installDir string, force, allowUnverified bool) error { + target := filepath.Join(installDir, rcloneDefaultBin) + if isExecutable(target) && !force { + fmt.Printf("rclone already installed: %s\n", target) + return nil + } + + goos, goarch, err := rclonePlatform(runtime.GOOS, runtime.GOARCH) + if err != nil { + return err + } + version, err := fetchRcloneVersion() + if err != nil { + return err + } + archiveName := fmt.Sprintf("rclone-%s-%s-%s.zip", version, goos, goarch) + archiveURL := fmt.Sprintf("%s/%s/%s", rcloneGitHubReleaseURL, version, archiveName) + checksumURL := fmt.Sprintf("%s/%s/SHA256SUMS", rcloneGitHubReleaseURL, version) + + fmt.Printf("Resolving rclone %s download for %s/%s...\n", version, goos, goarch) + expectedSHA256, checksumErr := fetchRcloneChecksum(checksumURL, archiveName) + if checksumErr != nil && !allowUnverified { + return fmt.Errorf("failed to verify rclone release checksum: %w; rerun with --allow-unverified-rclone only if you accept that risk", checksumErr) + } + if checksumErr != nil { + fmt.Fprintf(os.Stderr, "Warning: installing rclone without checksum verification: %v\n", checksumErr) + } + + archivePath, err := downloadTempFile(archiveURL, installDir, "rclone-*.zip") + if err != nil { + return fmt.Errorf("failed to download rclone archive: %w", err) + } + defer os.Remove(archivePath) + + if expectedSHA256 != "" { + if err := verifyFileChecksum(archivePath, expectedSHA256, "sha256"); err != nil { + return fmt.Errorf("rclone archive checksum verification failed: %w", err) + } + } + if err := extractBinaryFromZip(archivePath, rcloneDefaultBin, target); err != nil { + return fmt.Errorf("failed to extract rclone: %w", err) + } + fmt.Printf("Installed rclone: %s\n", target) + return nil +} + +func protonCLIPlatform(goos, goarch string) (string, error) { + var osName string + switch goos { + case "linux": + osName = "linux" + case "darwin": + osName = "macos" + default: + return "", fmt.Errorf("proton-drive CLI bootstrap is not supported on %s/%s", goos, goarch) + } + switch goarch { + case "amd64": + return osName + "/x64", nil + case "arm64": + return osName + "/arm64", nil + default: + return "", fmt.Errorf("proton-drive CLI bootstrap is not supported on %s/%s", goos, goarch) + } +} + +func parseProtonCLIAssets(html string) map[string]protonCLIAsset { + assets := make(map[string]protonCLIAsset) + rowPattern := regexp.MustCompile(`(?is)\s*\s*([^<]+?)\s*\s*\s*]*>.*?\s*\s*\s*\s*([0-9a-f]{128})\s*\s*\s*`) + for _, match := range rowPattern.FindAllStringSubmatch(html, -1) { + platform := strings.TrimSpace(match[1]) + assets[platform] = protonCLIAsset{ + Platform: platform, + URL: strings.TrimSpace(match[2]), + SHA512: strings.ToLower(strings.TrimSpace(match[3])), + } + } + return assets +} + +func validateProtonCLIAssetURL(rawURL string) error { + parsed, err := validateHTTPSURL(rawURL) + if err != nil { + return fmt.Errorf("invalid Proton Drive CLI asset URL: %w", err) + } + if !strings.EqualFold(parsed.Hostname(), "proton.me") || !strings.HasPrefix(parsed.EscapedPath(), "/download/drive/cli/") { + return fmt.Errorf("refusing Proton Drive CLI asset outside proton.me/download/drive/cli: %s", rawURL) + } + return nil +} + +func rclonePlatform(goos, goarch string) (string, string, error) { + switch goos { + case "linux": + case "darwin": + goos = "osx" + default: + return "", "", fmt.Errorf("rclone bootstrap is not supported on %s/%s", goos, goarch) + } + switch goarch { + case "amd64", "arm64": + return goos, goarch, nil + default: + return "", "", fmt.Errorf("rclone bootstrap is not supported on %s/%s", goos, goarch) + } +} + +func fetchRcloneVersion() (string, error) { + body, err := fetchURLBytes(rcloneVersionURL, 256<<10) + if err != nil { + return "", fmt.Errorf("failed to read rclone version: %w", err) + } + fields := strings.Fields(strings.TrimSpace(string(body))) + if len(fields) < 2 || fields[0] != "rclone" || !regexp.MustCompile(`^v\d+\.\d+\.\d+$`).MatchString(fields[1]) { + return "", fmt.Errorf("unexpected rclone version response: %s", strings.TrimSpace(string(body))) + } + return fields[1], nil +} + +func fetchRcloneChecksum(checksumURL, archiveName string) (string, error) { + body, err := fetchURLBytes(checksumURL, 2<<20) + if err != nil { + return "", err + } + sum, err := rcloneChecksumFromText(string(body), archiveName) + if err != nil { + return "", fmt.Errorf("%w in %s", err, checksumURL) + } + return sum, nil +} + +func rcloneChecksumFromText(text, archiveName string) (string, error) { + for _, line := range strings.Split(text, "\n") { + fields := strings.Fields(line) + if len(fields) >= 2 && fields[1] == archiveName { + sum := strings.ToLower(strings.TrimSpace(fields[0])) + if len(sum) != 64 { + return "", fmt.Errorf("invalid SHA256 checksum for %s", archiveName) + } + return sum, nil + } + } + return "", fmt.Errorf("checksum for %s not found", archiveName) +} + +func fetchURLBytes(rawURL string, limit int64) ([]byte, error) { + if _, err := validateHTTPSURL(rawURL); err != nil { + return nil, err + } + resp, err := httpClient().Get(rawURL) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return nil, fmt.Errorf("get %s returned %s", rawURL, resp.Status) + } + var reader io.Reader = resp.Body + if limit > 0 { + reader = io.LimitReader(resp.Body, limit+1) + } + body, err := io.ReadAll(reader) + if err != nil { + return nil, err + } + if limit > 0 && int64(len(body)) > limit { + return nil, fmt.Errorf("response exceeded %d bytes", limit) + } + return body, nil +} + +func downloadVerifiedBinary(rawURL, target, expected, algorithm string) error { + temp, err := downloadTempFile(rawURL, filepath.Dir(target), filepath.Base(target)+"-*") + if err != nil { + return err + } + defer os.Remove(temp) + if err := verifyFileChecksum(temp, expected, algorithm); err != nil { + return err + } + if err := os.Chmod(temp, 0o755); err != nil { // #nosec G302 -- downloaded helper binaries must be executable + return err + } + return os.Rename(temp, target) +} + +func downloadTempFile(rawURL, dir, pattern string) (string, error) { + if _, err := validateHTTPSURL(rawURL); err != nil { + return "", err + } + if err := os.MkdirAll(dir, 0o755); err != nil { // #nosec G301 -- helper download directory must be traversable for executable installation + return "", err + } + temp, err := os.CreateTemp(dir, pattern) + if err != nil { + return "", err + } + tempPath := temp.Name() + defer temp.Close() + + resp, err := httpClient().Get(rawURL) + if err != nil { + _ = os.Remove(tempPath) + return "", err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode > 299 { + _ = os.Remove(tempPath) + return "", fmt.Errorf("get %s returned %s", rawURL, resp.Status) + } + limited := io.LimitReader(resp.Body, maxDependencyDownloadBytes+1) + written, err := io.Copy(temp, limited) + if err != nil { + _ = os.Remove(tempPath) + return "", err + } + if written > maxDependencyDownloadBytes { + _ = os.Remove(tempPath) + return "", fmt.Errorf("download exceeded %d bytes", maxDependencyDownloadBytes) + } + return tempPath, nil +} + +func verifyFileChecksum(filePath, expected, algorithm string) error { + file, err := os.Open(filePath) // #nosec G304 -- checksum verification opens the temporary file just downloaded by this process + if err != nil { + return err + } + defer file.Close() + + var actual string + switch algorithm { + case "sha256": + hash := sha256.New() + if _, err := io.Copy(hash, file); err != nil { + return err + } + actual = hex.EncodeToString(hash.Sum(nil)) + case "sha512": + hash := sha512.New() + if _, err := io.Copy(hash, file); err != nil { + return err + } + actual = hex.EncodeToString(hash.Sum(nil)) + default: + return fmt.Errorf("unsupported checksum algorithm %q", algorithm) + } + if !strings.EqualFold(actual, expected) { + return fmt.Errorf("%s mismatch: got %s, want %s", algorithm, actual, strings.ToLower(expected)) + } + return nil +} + +func extractBinaryFromZip(archivePath, binaryName, target string) error { + reader, err := zip.OpenReader(archivePath) + if err != nil { + return err + } + defer reader.Close() + + for _, file := range reader.File { + if file.FileInfo().IsDir() || filepath.Base(file.Name) != binaryName { + continue + } + src, err := file.Open() + if err != nil { + return err + } + defer src.Close() + if file.UncompressedSize64 > uint64(maxDependencyDownloadBytes) { + return fmt.Errorf("%s in %s exceeded %d bytes", binaryName, archivePath, maxDependencyDownloadBytes) + } + + temp, err := os.CreateTemp(filepath.Dir(target), filepath.Base(target)+"-*") + if err != nil { + return err + } + tempPath := temp.Name() + written, copyErr := io.Copy(temp, io.LimitReader(src, maxDependencyDownloadBytes+1)) + closeErr := temp.Close() + if copyErr != nil { + _ = os.Remove(tempPath) + return copyErr + } + if written > maxDependencyDownloadBytes { + _ = os.Remove(tempPath) + return fmt.Errorf("%s in %s exceeded %d bytes while extracting", binaryName, archivePath, maxDependencyDownloadBytes) + } + if closeErr != nil { + _ = os.Remove(tempPath) + return closeErr + } + if err := os.Chmod(tempPath, 0o755); err != nil { // #nosec G302 -- extracted helper binaries must be executable + _ = os.Remove(tempPath) + return err + } + return os.Rename(tempPath, target) + } + return fmt.Errorf("%s not found in %s", binaryName, archivePath) +} + +func httpClient() *http.Client { + return &http.Client{ + Timeout: dependencyDownloadTimeout, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("too many download redirects") + } + if !strings.EqualFold(req.URL.Scheme, "https") { + return fmt.Errorf("refusing download redirect to non-HTTPS URL %s", req.URL.Redacted()) + } + return nil + }, + } +} + +func validateHTTPSURL(rawURL string) (*url.URL, error) { + parsed, err := url.Parse(rawURL) + if err != nil { + return nil, err + } + if !strings.EqualFold(parsed.Scheme, "https") || strings.TrimSpace(parsed.Host) == "" || parsed.User != nil { + return nil, fmt.Errorf("download URL must be absolute HTTPS without embedded credentials: %s", parsed.Redacted()) + } + return parsed, nil +} + +func defaultManagedBinDir() string { + if override := strings.TrimSpace(os.Getenv(managedBinDirEnv)); override != "" { + return expandPath(override) + } + if runtime.GOOS == "linux" { + if dataHome := strings.TrimSpace(os.Getenv("XDG_DATA_HOME")); dataHome != "" { + return filepath.Join(expandPath(dataHome), "protondrive", "bin") + } + if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" { + return filepath.Join(home, ".local", "share", "protondrive", "bin") + } + } + if runtime.GOOS == "darwin" { + if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" { + return filepath.Join(home, "Library", "Application Support", "protondrive", "bin") + } + } + if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" { + return filepath.Join(home, ".local", "share", "protondrive", "bin") + } + return filepath.Join(".", ".protondrive", "bin") +} + +func managedBinaryPath(bin string) (string, bool) { + base := filepath.Base(strings.TrimSpace(bin)) + switch base { + case protonDriveDefaultBin, rcloneDefaultBin: + default: + return "", false + } + return filepath.Join(defaultManagedBinDir(), base), true +} + +func isExecutable(path string) bool { + info, err := os.Stat(path) + if err != nil || info.IsDir() { + return false + } + return info.Mode()&0o111 != 0 +} diff --git a/cmd/protondrive/configs_command.go b/cmd/protondrive/configs_command.go new file mode 100644 index 0000000..849fe50 --- /dev/null +++ b/cmd/protondrive/configs_command.go @@ -0,0 +1,140 @@ +package main + +import ( + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + + "github.com/ColinMario/Protondrive-for-Linux/internal/customconfigs" + "github.com/ColinMario/Protondrive-for-Linux/internal/safefile" +) + +func runConfigs(remote string, args []string) error { + fs := flag.NewFlagSet("configs", flag.ContinueOnError) + force := fs.Bool("force", false, "Allow overwriting an existing file when using 'init'") + if err := parseCommandFlags(fs, args); err != nil { + if errors.Is(err, flag.ErrHelp) { + return nil + } + return err + } + forceSet := false + fs.Visit(func(current *flag.Flag) { + if current.Name == "force" { + forceSet = true + } + }) + + remaining := fs.Args() + if len(remaining) == 0 { + if forceSet { + return errors.New("--force is only valid with 'configs init'") + } + return printSyncConfigList() + } + if forceSet && remaining[0] != "init" { + return errors.New("--force is only valid with 'configs init'") + } + + switch remaining[0] { + case "list": + if len(remaining) != 1 { + return errors.New("usage: protondrive configs list") + } + return printSyncConfigList() + case "show": + if len(remaining) != 2 { + return errors.New("usage: protondrive configs show ") + } + return showSyncConfig(remaining[1]) + case "init": + if len(remaining) != 2 { + return errors.New("usage: protondrive configs init ") + } + dest, err := writeBuiltinConfig(remaining[1], *force) + if err != nil { + return err + } + fmt.Printf("Template copied to %s\n", dest) + return nil + default: + return fmt.Errorf("unknown subcommand %q (expected list, show, init)", remaining[0]) + } +} + +func printSyncConfigList() error { + builtins, err := customconfigs.List() + if err != nil { + return fmt.Errorf("unable to list built-in templates: %w", err) + } + fmt.Println("Built-in templates:") + if len(builtins) == 0 { + fmt.Println(" (none)") + } else { + for _, tpl := range builtins { + fmt.Printf(" - %s (%s)\n", tpl.ID, tpl.Description) + } + } + fmt.Println() + + customConfigs, dir, err := listCustomSyncConfigs() + if err != nil { + return fmt.Errorf("unable to list custom configs: %w", err) + } + fmt.Printf("Custom config directory: %s\n", dir) + if len(customConfigs) == 0 { + fmt.Println(" (no JSON configs found yet)") + } else { + for _, summary := range customConfigs { + fmt.Printf(" - %s (%s)\n", summary.Name, summary.Description) + fmt.Printf(" %s\n", summary.File) + } + } + fmt.Println("\nUse 'protondrive configs init