Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c57006672a | ||
|
|
881a7336ec | ||
|
|
11d0908325 | ||
|
|
b4d09eb632 | ||
|
|
d60269ca3d | ||
|
|
7a40ebcce4 | ||
|
|
9eeba9fe82 | ||
|
|
7f06063bf5 | ||
|
|
664d981cb5 | ||
|
|
03345a6304 | ||
|
|
a237ff9a15 | ||
|
|
57e229c13f | ||
|
|
fb1188ac37 | ||
|
|
9f3ea43414 | ||
|
|
ba8cd2d7a1 | ||
|
|
02fd716314 | ||
|
|
846879f62d | ||
|
|
d67a05a01d | ||
|
|
127b16cafa | ||
|
|
d6423b9d15 | ||
|
|
00e20a0147 | ||
|
|
e0454798b4 | ||
|
|
4adb352172 |
No files matched your search
@@ -15,8 +15,30 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
guard-submodule-urls:
|
||||
name: Submodule URLs are public HTTPS
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# Plain checkout on purpose: the guard must not depend on fetching
|
||||
# the submodules it validates (an SSH URL would break that fetch).
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Reject non-HTTPS submodule URLs
|
||||
run: |
|
||||
set -eu
|
||||
if [ ! -f .gitmodules ]; then echo "no submodules - ok"; exit 0; fi
|
||||
bad=$(grep -nE '^[[:space:]]*url[[:space:]]*=' .gitmodules \
|
||||
| grep -vE '^[0-9]+:[[:space:]]*url[[:space:]]*=[[:space:]]*https://' || true)
|
||||
if [ -n "$bad" ]; then
|
||||
echo "::error::Non-HTTPS submodule URL(s) break fresh clones and CI:$bad"
|
||||
exit 1
|
||||
fi
|
||||
echo "all submodule URLs HTTPS - ok"
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
needs: guard-submodule-urls
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -33,7 +55,7 @@ jobs:
|
||||
run: |
|
||||
test -s build/site/index.html
|
||||
test -s build/site/app/index.html
|
||||
test -s build/site/app/gopass.wasm
|
||||
test -s build/site/app/pass.wasm
|
||||
- name: Check formatting
|
||||
run: test -z "$(find . -path ./vendor -prune -o -name '*.go' -type f -print | xargs gofmt -l)"
|
||||
|
||||
@@ -68,6 +90,52 @@ jobs:
|
||||
run: make package-deb
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: gopass-gui-linux-${{ matrix.arch }}
|
||||
path: build/gopass-gui
|
||||
name: pass-gui-linux-${{ matrix.arch }}
|
||||
path: build/pass-gui
|
||||
if-no-files-found: error
|
||||
|
||||
build-android:
|
||||
name: Android debug build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
needs: guard-submodule-urls
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v3
|
||||
- name: Cache Android SDK packages
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
${{ env.ANDROID_HOME }}/platforms/android-36
|
||||
${{ env.ANDROID_HOME }}/build-tools/34.0.0
|
||||
${{ env.ANDROID_HOME }}/ndk/28.2.13676358
|
||||
${{ env.ANDROID_HOME }}/cmake/3.22.1
|
||||
key: android-sdk-${{ runner.os }}-${{ runner.arch }}-api36-bt34-ndk28-cmake322
|
||||
restore-keys: |
|
||||
android-sdk-${{ runner.os }}-${{ runner.arch }}-
|
||||
- name: Cache Android native build
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
droid/app/.cxx
|
||||
droid/app/build/intermediates/cxx
|
||||
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'native/*.c', 'droid/app/src/main/cpp/*.c', 'vendor/kryon/src/**/*.c', 'vendor/kryon/include/**/*.h', 'vendor/kryon/vendor/raylib/src/**') }}
|
||||
restore-keys: |
|
||||
android-native-${{ runner.os }}-${{ runner.arch }}-
|
||||
- name: Install Android SDK components
|
||||
run: |
|
||||
set -euo pipefail
|
||||
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
|
||||
yes | "$SDKMANAGER" --licenses >/dev/null || true
|
||||
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
|
||||
- name: Build debug APK
|
||||
run: |
|
||||
set -euo pipefail
|
||||
chmod +x droid/gradlew
|
||||
make android-debug
|
||||
@@ -32,11 +32,11 @@ jobs:
|
||||
TARGET_ARCH: ${{ matrix.arch }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
name="gopass-cli-${TARGET_OS}-${TARGET_ARCH}"
|
||||
name="pass-cli-${TARGET_OS}-${TARGET_ARCH}"
|
||||
mkdir -p "build/release/$name"
|
||||
suffix=""
|
||||
[ "$TARGET_OS" = windows ] && suffix=".exe"
|
||||
CGO_ENABLED=0 GOOS="$TARGET_OS" GOARCH="$TARGET_ARCH" go build -trimpath -ldflags='-s -w' -o "build/release/$name/gopass$suffix" ./cmd/gopass
|
||||
CGO_ENABLED=0 GOOS="$TARGET_OS" GOARCH="$TARGET_ARCH" go build -trimpath -ldflags='-s -w' -o "build/release/$name/pass$suffix" ./cmd/pass
|
||||
cp LICENSE README.md "build/release/$name/"
|
||||
if [ "$TARGET_OS" = windows ]; then
|
||||
(cd build/release && zip -qr "$name.zip" "$name")
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: cli-${{ matrix.os }}-${{ matrix.arch }}
|
||||
path: build/release/gopass-cli-${{ matrix.os }}-${{ matrix.arch }}.*
|
||||
path: build/release/pass-cli-${{ matrix.os }}-${{ matrix.arch }}.*
|
||||
if-no-files-found: error
|
||||
|
||||
gui:
|
||||
@@ -75,9 +75,9 @@ jobs:
|
||||
- run: make gui
|
||||
- name: Package GUI tarball and Debian package
|
||||
run: |
|
||||
name="gopass-gui-linux-${{ matrix.arch }}"
|
||||
name="pass-gui-linux-${{ matrix.arch }}"
|
||||
mkdir -p "build/release/$name"
|
||||
cp build/gopass-gui LICENSE README.md "build/release/$name/"
|
||||
cp build/pass-gui LICENSE README.md "build/release/$name/"
|
||||
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
|
||||
make package-deb
|
||||
- name: Package AppImage
|
||||
@@ -94,11 +94,81 @@ jobs:
|
||||
with:
|
||||
name: gui-linux-${{ matrix.arch }}
|
||||
path: |
|
||||
build/release/gopass-gui-linux-${{ matrix.arch }}.tar.gz
|
||||
build/release/pass-gui-linux-${{ matrix.arch }}.tar.gz
|
||||
build/release/*.deb
|
||||
build/release/*.AppImage
|
||||
if-no-files-found: error
|
||||
|
||||
android:
|
||||
name: Android
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v3
|
||||
- name: Cache Android SDK packages
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
${{ env.ANDROID_HOME }}/platforms/android-36
|
||||
${{ env.ANDROID_HOME }}/build-tools/34.0.0
|
||||
${{ env.ANDROID_HOME }}/ndk/28.2.13676358
|
||||
${{ env.ANDROID_HOME }}/cmake/3.22.1
|
||||
key: android-sdk-${{ runner.os }}-${{ runner.arch }}-api36-bt34-ndk28-cmake322
|
||||
restore-keys: |
|
||||
android-sdk-${{ runner.os }}-${{ runner.arch }}-
|
||||
- name: Cache Android native build
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
droid/app/.cxx
|
||||
droid/app/build/intermediates/cxx
|
||||
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'native/*.c', 'droid/app/src/main/cpp/*.c', 'vendor/kryon/src/**/*.c', 'vendor/kryon/include/**/*.h', 'vendor/kryon/vendor/raylib/src/**') }}
|
||||
restore-keys: |
|
||||
android-native-${{ runner.os }}-${{ runner.arch }}-
|
||||
- name: Install Android SDK components
|
||||
run: |
|
||||
set -euo pipefail
|
||||
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
|
||||
yes | "$SDKMANAGER" --licenses >/dev/null || true
|
||||
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
|
||||
- name: Prepare Android signing key
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -n "$KEYSTORE_BASE64" || { echo "::error::KEYSTORE_BASE64 secret is empty or missing"; exit 1; }
|
||||
mkdir -p "$HOME/.android"
|
||||
printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$HOME/.android/pass-release.keystore"
|
||||
- name: Build release APK
|
||||
env:
|
||||
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
|
||||
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -n "$KEYSTORE_PASSWORD" || { echo "::error::KEYSTORE_PASSWORD secret is empty or missing"; exit 1; }
|
||||
test -n "$KEY_ALIAS" || { echo "::error::KEY_ALIAS secret is empty or missing"; exit 1; }
|
||||
chmod +x droid/gradlew
|
||||
./droid/gradlew -p droid assembleRelease \
|
||||
-Pkeystore.path="$HOME/.android/pass-release.keystore" \
|
||||
-Pkeystore.alias="$KEY_ALIAS" \
|
||||
-Pkeystore.password="$KEYSTORE_PASSWORD" \
|
||||
--stacktrace
|
||||
mkdir -p build/release
|
||||
cp droid/app/build/outputs/apk/release/app-release.apk build/release/pass-android.apk
|
||||
test -s build/release/pass-android.apk
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: android
|
||||
path: build/release/pass-android.apk
|
||||
if-no-files-found: error
|
||||
|
||||
web:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -108,15 +178,15 @@ jobs:
|
||||
go-version: 1.24.x
|
||||
cache: false
|
||||
- run: make site
|
||||
- run: cd build/site && zip -qr ../gopass-web.zip .
|
||||
- run: cd build/site && zip -qr ../pass-web.zip .
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: web
|
||||
path: build/gopass-web.zip
|
||||
path: build/pass-web.zip
|
||||
if-no-files-found: error
|
||||
|
||||
publish:
|
||||
needs: [cli, gui, web]
|
||||
needs: [cli, gui, web, android]
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
released: ${{ steps.version.outputs.released }}
|
||||
@@ -124,6 +194,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: build/artifacts
|
||||
@@ -148,6 +219,43 @@ jobs:
|
||||
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
|
||||
git tag -a "${{ steps.version.outputs.tag }}" -m "Release ${{ steps.version.outputs.tag }}"
|
||||
git push origin "${{ steps.version.outputs.tag }}"
|
||||
- name: Generate Update Appcast
|
||||
if: steps.version.outputs.released == 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' version.go)
|
||||
TAG="v$VERSION"
|
||||
BASE="https://github.com/waozixyz/pass/releases/download/$TAG"
|
||||
# appcast channel names use dpkg arch naming (amd64/arm64);
|
||||
# the artifacts use uname -m naming (x86_64/aarch64)
|
||||
arch_name() {
|
||||
case "$1" in
|
||||
x86_64) echo amd64 ;;
|
||||
aarch64|arm64) echo arm64 ;;
|
||||
*) echo "$1" ;;
|
||||
esac
|
||||
}
|
||||
channels=()
|
||||
for img in build/artifacts/*.AppImage; do
|
||||
[ -e "$img" ] || continue
|
||||
arch=$(basename "$img" | sed -n 's/^pass-.*-\([^-]*\)\.AppImage$/\1/p')
|
||||
channels+=("--channel" "appimage-$(arch_name "$arch")=$img")
|
||||
done
|
||||
DEB="$(find build/artifacts -maxdepth 1 -name '*.deb' -print -quit || true)"
|
||||
TAR="$(find build/artifacts -maxdepth 1 -name 'pass-gui-linux-*.tar.gz' -print -quit || true)"
|
||||
[ -n "$DEB" ] && channels+=("--channel" "deb=$DEB")
|
||||
[ -n "$TAR" ] && channels+=("--channel" "tarball=$TAR")
|
||||
if [ ${#channels[@]} -eq 0 ]; then
|
||||
echo "no release artifacts found for the appcast"
|
||||
exit 1
|
||||
fi
|
||||
python3 vendor/kryon/scripts/make_appcast.py \
|
||||
--version "$VERSION" \
|
||||
--base-url "$BASE" \
|
||||
--notes-url "https://github.com/waozixyz/pass/releases/tag/$TAG" \
|
||||
--changelog CHANGELOG.md \
|
||||
--out build/artifacts/appcast.json \
|
||||
"${channels[@]}"
|
||||
- name: Publish GitHub release
|
||||
if: steps.version.outputs.released == 'true'
|
||||
uses: softprops/action-gh-release@v2
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
name: Security
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
privacy:
|
||||
name: Privacy scan
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# Prove the scanner works using only a synthetic term — the guard
|
||||
# itself must never contain, or reveal, real private values.
|
||||
- name: Self-test the scanner with a synthetic canary
|
||||
run: |
|
||||
canary=zzq-canary-7f3a
|
||||
printf '%s\n' "$canary" > /tmp/canary-terms
|
||||
mkdir /tmp/canary-dir
|
||||
printf 'const token = "%s";\n' "$canary" > /tmp/canary-dir/leak.js
|
||||
if scripts/privacy_scan.sh /tmp/canary-terms /tmp/canary-dir; then
|
||||
echo "scanner failed to detect the canary" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! scripts/privacy_scan.sh /tmp/canary-terms scripts; then
|
||||
echo "scanner reported a false positive on its own source" >&2
|
||||
exit 1
|
||||
fi
|
||||
rm -rf /tmp/canary-dir /tmp/canary-terms
|
||||
|
||||
# The deny-list comes from the encrypted PRIVATE_TERMS repository
|
||||
# secret (one fixed-string term per line) so the private values are
|
||||
# never part of this repository. Fork pull requests cannot read
|
||||
# secrets; those runs skip with a warning and the scan re-runs on
|
||||
# the push that lands the merge.
|
||||
- name: Scan the repository for private terms
|
||||
env:
|
||||
PRIVATE_TERMS: ${{ secrets.PRIVATE_TERMS }}
|
||||
run: |
|
||||
if [ -z "$PRIVATE_TERMS" ]; then
|
||||
echo "::warning::PRIVATE_TERMS secret is not set; privacy scan skipped"
|
||||
exit 0
|
||||
fi
|
||||
printf '%s\n' "$PRIVATE_TERMS" > /tmp/terms
|
||||
chmod 600 /tmp/terms
|
||||
status=0
|
||||
scripts/privacy_scan.sh /tmp/terms HEAD || status=1
|
||||
if [ "$GITHUB_EVENT_NAME" = push ]; then
|
||||
before="${{ github.event.before }}"
|
||||
if [ "$before" != "0000000000000000000000000000000000000000" ]; then
|
||||
for commit in $(git rev-list "$before..$GITHUB_SHA"); do
|
||||
scripts/privacy_scan.sh /tmp/terms "$commit" || status=1
|
||||
done
|
||||
fi
|
||||
fi
|
||||
exit $status
|
||||
@@ -28,10 +28,10 @@ jobs:
|
||||
make site
|
||||
test -s build/site/index.html
|
||||
test -s build/site/app/index.html
|
||||
test -s build/site/app/gopass.wasm
|
||||
test -s build/site/app/pass.wasm
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: gopass-site
|
||||
name: pass-site
|
||||
path: build/site
|
||||
if-no-files-found: error
|
||||
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: gopass-site
|
||||
name: pass-site
|
||||
path: build/site
|
||||
- name: Install Netlify CLI
|
||||
run: npm install --global netlify-cli
|
||||
@@ -71,15 +71,15 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: gopass-site
|
||||
name: pass-site
|
||||
path: build/site
|
||||
- name: Package Site
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -s build/site/index.html
|
||||
cd build/site
|
||||
zip -qr ../gopass-site.zip .
|
||||
test -s ../gopass-site.zip
|
||||
zip -qr ../pass-site.zip .
|
||||
test -s ../pass-site.zip
|
||||
- name: Deploy Production To Netlify
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -92,7 +92,7 @@ jobs:
|
||||
-X POST \
|
||||
-H "Authorization: Bearer $auth_token" \
|
||||
-H "Content-Type: application/zip" \
|
||||
--data-binary "@build/gopass-site.zip" \
|
||||
--data-binary "@build/pass-site.zip" \
|
||||
"https://api.netlify.com/api/v1/sites/$site_id/deploys")"
|
||||
|
||||
python3 -c 'import json, sys; deploy = json.loads(sys.argv[1]); state = deploy.get("state", ""); url = deploy.get("ssl_url") or deploy.get("url") or deploy.get("deploy_ssl_url") or deploy.get("deploy_url") or deploy.get("id"); print(f"Netlify deploy {state}: {url}"); raise SystemExit(1 if state in ("error", "failed") else 0)' "$response"
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
/build/
|
||||
/gopass
|
||||
/gui/gopass-gui
|
||||
/pass
|
||||
/gui/pass-gui
|
||||
+38
-1
@@ -1,10 +1,47 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.2] - 2026-08-20
|
||||
|
||||
- Install pass on Android: a signed APK is now downloadable from
|
||||
pass.waozi.xyz alongside the desktop, terminal, and browser downloads.
|
||||
- Fix the Android master-password fingerprint and secure storage so the
|
||||
stored master password unlocks reliably across launches.
|
||||
|
||||
## [0.2.1] - 2026-08-19
|
||||
|
||||
- The desktop GUI now checks for new releases and can update itself: AppImage
|
||||
builds download the checksum-verified update and restart straight into it,
|
||||
while tarball and Debian package installs get a link to the release page.
|
||||
|
||||
## [0.2.0] - 2026-08-18
|
||||
|
||||
- Copy passwords through a built-in pure-Go X11 clipboard on Linux, with no
|
||||
external clipboard tool required; other systems keep using wl-copy, xclip,
|
||||
xsel, pbcopy, or clip.exe.
|
||||
- Clear copied passwords automatically after a delay with `--clear-after`;
|
||||
by default they stay until another application takes the clipboard.
|
||||
- Read the master password from an OpenSSL-encrypted vault with `--vault`;
|
||||
the vault passphrase is asked for on the terminal or read from piped input,
|
||||
so the master password never appears in argv or the environment.
|
||||
- Save named profiles (a login plus default settings) in an optional
|
||||
configuration file and generate with `--profile`.
|
||||
- Print the current clipboard contents with `--read-clipboard`.
|
||||
- Install the binary as `pass` to use the compact `pass PROFILE SITE` form,
|
||||
which copies without printing.
|
||||
|
||||
## [0.1.3] - 2026-08-17
|
||||
|
||||
- Generate passwords directly on the website's home page: the full browser
|
||||
generator now runs in the front-page card, with no separate page to open.
|
||||
- The browser generator loads only when you start using it, keeping the
|
||||
front page fast for everyone else.
|
||||
- The standalone web app page remains available with the same generator.
|
||||
|
||||
## [0.1.2] - 2026-08-17
|
||||
|
||||
- Make keyboard navigation reliable: click a field, then use Tab and Shift+Tab
|
||||
to move through the form.
|
||||
- Keep one gopass window open by default; launching it again replaces the
|
||||
- Keep one pass window open by default; launching it again replaces the
|
||||
existing window.
|
||||
- Keep long editing sessions responsive and stable.
|
||||
|
||||
|
||||
@@ -1,35 +1,45 @@
|
||||
.PHONY: all cli gui native run test native-test web site install-gui uninstall-gui package-deb package-appimage android-debug
|
||||
.PHONY: all cli gui native run test native-test web site install install-cli uninstall-cli install-gui uninstall-gui package-deb package-appimage android-debug
|
||||
|
||||
BIN_DIR ?= $(HOME)/bin
|
||||
DATA_DIR ?= $(if $(XDG_DATA_HOME),$(XDG_DATA_HOME),$(HOME)/.local/share)
|
||||
|
||||
KRYON_ARCH ?= $(shell uname -m)
|
||||
KRYON_BUILD_DIR := vendor/kryon/build/linux-$(KRYON_ARCH)
|
||||
KRYON_RUNTIME_SOURCES := $(shell find vendor/kryon/src vendor/kryon/include -type f)
|
||||
|
||||
all: cli gui
|
||||
|
||||
cli:
|
||||
go build -o gopass ./cmd/gopass
|
||||
go build -o pass ./cmd/pass
|
||||
|
||||
$(KRYON_BUILD_DIR)/libkryon.a:
|
||||
$(KRYON_BUILD_DIR)/libkryon.a: $(KRYON_RUNTIME_SOURCES) vendor/kryon/Makefile
|
||||
$(MAKE) -C vendor/kryon -f Makefile all
|
||||
|
||||
gui: $(KRYON_BUILD_DIR)/libkryon.a
|
||||
cd gui && go build -o ../build/gopass-gui .
|
||||
cd gui && go build -o ../build/pass-gui .
|
||||
|
||||
native: all
|
||||
|
||||
run: gui
|
||||
./build/gopass-gui
|
||||
./build/pass-gui
|
||||
|
||||
install: install-cli install-gui
|
||||
|
||||
install-cli: cli
|
||||
mkdir -p $(BIN_DIR)
|
||||
install -m 0755 pass $(BIN_DIR)/pass
|
||||
|
||||
uninstall-cli:
|
||||
rm -f $(BIN_DIR)/pass
|
||||
|
||||
install-gui: gui
|
||||
mkdir -p $(BIN_DIR) $(DATA_DIR)/applications $(DATA_DIR)/icons/hicolor/512x512/apps
|
||||
cp build/gopass-gui $(BIN_DIR)/gopass-gui
|
||||
install -m 0755 build/pass-gui $(BIN_DIR)/pass-gui
|
||||
cp packaging/linux/xyz.waozi.pass.desktop $(DATA_DIR)/applications/xyz.waozi.pass.desktop
|
||||
cp assets/app/icon.png $(DATA_DIR)/icons/hicolor/512x512/apps/gopass.png
|
||||
cp assets/app/icon.png $(DATA_DIR)/icons/hicolor/512x512/apps/pass.png
|
||||
|
||||
uninstall-gui:
|
||||
rm -f $(BIN_DIR)/gopass-gui $(DATA_DIR)/applications/xyz.waozi.pass.desktop $(DATA_DIR)/icons/hicolor/512x512/apps/gopass.png
|
||||
rm -f $(BIN_DIR)/pass-gui $(DATA_DIR)/applications/xyz.waozi.pass.desktop $(DATA_DIR)/icons/hicolor/512x512/apps/pass.png
|
||||
|
||||
test:
|
||||
go test ./...
|
||||
@@ -38,8 +48,8 @@ test:
|
||||
# Checks the C generator (used by the Android app) against the same fixed
|
||||
# vectors as the Go tests.
|
||||
native-test:
|
||||
cc -Wall -Wextra -O2 -Inative native/gopass_core.c native/gopass_core_test.c -o build/gopass_core_test
|
||||
./build/gopass_core_test
|
||||
cc -Wall -Wextra -O2 -Inative native/pass_core.c native/pass_core_test.c -o build/pass_core_test
|
||||
./build/pass_core_test
|
||||
|
||||
ANDROID_DIR := droid
|
||||
ANDROID_ABIS ?= armeabi-v7a,arm64-v8a
|
||||
@@ -47,14 +57,14 @@ ANDROID_ABIS ?= armeabi-v7a,arm64-v8a
|
||||
android-debug:
|
||||
cd $(ANDROID_DIR) && ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS)
|
||||
mkdir -p build
|
||||
cp $(ANDROID_DIR)/app/build/outputs/apk/debug/app-debug.apk build/gopass-android-debug.apk
|
||||
cp $(ANDROID_DIR)/app/build/outputs/apk/debug/app-debug.apk build/pass-android-debug.apk
|
||||
|
||||
web:
|
||||
./web/build.sh
|
||||
|
||||
site: web
|
||||
test -f build/site/index.html
|
||||
test -f build/site/app/gopass.wasm
|
||||
test -f build/site/app/pass.wasm
|
||||
|
||||
package-deb: gui
|
||||
./scripts/package-deb.sh
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# gopass
|
||||
# pass
|
||||
|
||||
Website and browser app: [pass.waozi.xyz](https://pass.waozi.xyz/)
|
||||
|
||||
`gopass` is a stateless password generator: the same site, login, master
|
||||
`pass` is a stateless password generator: the same site, login, master
|
||||
password, and settings produce the same result without a password database.
|
||||
It is a new, independently written implementation of the LessPass generation
|
||||
algorithm. Compatibility does not imply endorsement by or affiliation with the
|
||||
@@ -16,42 +16,85 @@ Prebuilt CLI and desktop downloads are available from
|
||||
With Go 1.24 or newer:
|
||||
|
||||
```sh
|
||||
go install github.com/waozixyz/gopass/cmd/gopass@latest
|
||||
go install github.com/waozixyz/pass/cmd/pass@latest
|
||||
```
|
||||
|
||||
Or build the command from a checkout:
|
||||
|
||||
```sh
|
||||
go build ./cmd/gopass
|
||||
go build ./cmd/pass
|
||||
```
|
||||
|
||||
## Use
|
||||
|
||||
```text
|
||||
gopass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
|
||||
pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
|
||||
```
|
||||
|
||||
The default password has 16 characters and includes lowercase letters,
|
||||
uppercase letters, digits, and symbols. The default counter is 1.
|
||||
|
||||
Passing a master password as an argument can expose it to process inspection
|
||||
and shell history. Omitting it is safer: `gopass` first checks
|
||||
and shell history. Omitting it is safer: `pass` first checks
|
||||
`LESSPASS_MASTER_PASSWORD`, then reads from the controlling terminal or console
|
||||
with echo disabled. Use `--prompt` to bypass the environment and always ask. For
|
||||
example:
|
||||
|
||||
```sh
|
||||
gopass --prompt example.com alice
|
||||
gopass --length 24 --counter 2 example.com alice
|
||||
gopass --no-symbols --exclude '0O1Il' example.com alice
|
||||
pass --prompt example.com alice
|
||||
pass --length 24 --counter 2 example.com alice
|
||||
pass --no-symbols --exclude '0O1Il' example.com alice
|
||||
```
|
||||
|
||||
`--copy` sends the result through standard input to an available clipboard
|
||||
program (`wl-copy`, `xclip`, `xsel`, `pbcopy`, or `clip.exe`) and does not print
|
||||
the generated password. The command reports an error if no supported clipboard
|
||||
tool can be used.
|
||||
`--copy` sends the result to the clipboard without printing it. On Linux a
|
||||
built-in pure-Go X11 clipboard is used when an X server (X.Org, Xlibre, or
|
||||
XWayland) is reachable, so no external tool is needed; otherwise `pass`
|
||||
falls back to `wl-copy`, `xclip`, `xsel`, `pbcopy`, or `clip.exe` and reports
|
||||
an error if none can be used. The copied password is served by a small
|
||||
detached process and disappears when another application takes the clipboard;
|
||||
`--clear-after 90s` releases it automatically after a delay (built-in X11
|
||||
clipboard only), and `--read-clipboard` prints the current contents.
|
||||
|
||||
Run `gopass --help` for all flags.
|
||||
## Profiles
|
||||
|
||||
An optional configuration file at `$XDG_CONFIG_HOME/pass/profiles.json`
|
||||
(usually `~/.config/pass/profiles.json`) can store named profiles — a login
|
||||
plus default settings — so daily invocations shrink to one flag:
|
||||
|
||||
```sh
|
||||
pass --profile work example.com
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"vault": "~/.vault",
|
||||
"copy": true,
|
||||
"clear_after": "90s",
|
||||
"profiles": {
|
||||
"work": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Profiles hold no secrets. Command-line flags always win over profile values,
|
||||
and without a configuration file pass behaves exactly as before.
|
||||
|
||||
## Master password from a vault
|
||||
|
||||
`--vault PATH` reads the master password from a file encrypted with OpenSSL:
|
||||
|
||||
```sh
|
||||
printf 'master password' | openssl enc -aes-256-cbc -md sha512 -a \
|
||||
-pbkdf2 -iter 100000 -salt -pass pass:... > ~/.vault
|
||||
pass --vault ~/.vault example.com alice
|
||||
```
|
||||
|
||||
The vault passphrase is requested on the terminal with echo disabled, or read
|
||||
from piped standard input, and the decrypted contents are used as the master
|
||||
password — the master itself never appears in argv or the environment. The
|
||||
vault path can also be set once in the profiles file.
|
||||
|
||||
Run `pass --help` for all flags.
|
||||
|
||||
## Desktop app
|
||||
|
||||
@@ -63,14 +106,14 @@ unless the clipboard has since been replaced.
|
||||
```sh
|
||||
git submodule update --init --recursive
|
||||
make gui
|
||||
./build/gopass-gui
|
||||
./build/pass-gui
|
||||
```
|
||||
|
||||
## Library
|
||||
|
||||
```go
|
||||
settings := gopass.DefaultOptions()
|
||||
result, err := gopass.Generate("example.com", "alice", master, settings)
|
||||
settings := pass.DefaultOptions()
|
||||
result, err := pass.Generate("example.com", "alice", master, settings)
|
||||
```
|
||||
|
||||
All inputs are interpreted as UTF-8 strings. Excluded characters are removed
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
password "github.com/waozixyz/gopass"
|
||||
)
|
||||
|
||||
const environmentVariable = "LESSPASS_MASTER_PASSWORD"
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "gopass: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(arguments []string, stdout, stderr io.Writer) error {
|
||||
options := password.DefaultOptions()
|
||||
flags := flag.NewFlagSet("gopass", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
flags.Usage = func() { printHelp(stderr) }
|
||||
|
||||
flags.IntVar(&options.Length, "L", options.Length, "password length")
|
||||
flags.IntVar(&options.Length, "length", options.Length, "password length")
|
||||
flags.Uint64Var(&options.Counter, "C", options.Counter, "generation counter")
|
||||
flags.Uint64Var(&options.Counter, "counter", options.Counter, "generation counter")
|
||||
flags.BoolVar(&options.Lowercase, "l", options.Lowercase, "include lowercase letters")
|
||||
flags.BoolVar(&options.Lowercase, "lowercase", options.Lowercase, "include lowercase letters")
|
||||
flags.BoolVar(&options.Uppercase, "u", options.Uppercase, "include uppercase letters")
|
||||
flags.BoolVar(&options.Uppercase, "uppercase", options.Uppercase, "include uppercase letters")
|
||||
flags.BoolVar(&options.Digits, "d", options.Digits, "include digits")
|
||||
flags.BoolVar(&options.Digits, "digits", options.Digits, "include digits")
|
||||
flags.BoolVar(&options.Symbols, "s", options.Symbols, "include symbols")
|
||||
flags.BoolVar(&options.Symbols, "symbols", options.Symbols, "include symbols")
|
||||
var noLowercase, noUppercase, noDigits, noSymbols bool
|
||||
flags.BoolVar(&noLowercase, "no-lowercase", false, "exclude lowercase letters")
|
||||
flags.BoolVar(&noUppercase, "no-uppercase", false, "exclude uppercase letters")
|
||||
flags.BoolVar(&noDigits, "no-digits", false, "exclude digits")
|
||||
flags.BoolVar(&noSymbols, "no-symbols", false, "exclude symbols")
|
||||
flags.StringVar(&options.Exclude, "exclude", "", "characters to exclude")
|
||||
|
||||
var forcePrompt, copyPassword, showVersion bool
|
||||
flags.BoolVar(&forcePrompt, "p", false, "prompt for the master password")
|
||||
flags.BoolVar(&forcePrompt, "prompt", false, "prompt for the master password")
|
||||
flags.BoolVar(©Password, "c", false, "copy the password to the clipboard")
|
||||
flags.BoolVar(©Password, "copy", false, "copy the password to the clipboard")
|
||||
flags.BoolVar(&showVersion, "v", false, "show version")
|
||||
flags.BoolVar(&showVersion, "version", false, "show version")
|
||||
|
||||
if err := flags.Parse(normalizeArguments(arguments)); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if noLowercase {
|
||||
options.Lowercase = false
|
||||
}
|
||||
if noUppercase {
|
||||
options.Uppercase = false
|
||||
}
|
||||
if noDigits {
|
||||
options.Digits = false
|
||||
}
|
||||
if noSymbols {
|
||||
options.Symbols = false
|
||||
}
|
||||
if showVersion {
|
||||
fmt.Fprintf(stdout, "gopass %s\n", password.Version)
|
||||
return nil
|
||||
}
|
||||
|
||||
positional := flags.Args()
|
||||
if len(positional) < 2 || len(positional) > 3 {
|
||||
printHelp(stderr)
|
||||
return errors.New("expected SITE LOGIN and an optional MASTER_PASSWORD")
|
||||
}
|
||||
if forcePrompt && len(positional) == 3 {
|
||||
return errors.New("MASTER_PASSWORD cannot be supplied together with --prompt")
|
||||
}
|
||||
|
||||
master, err := masterPassword(positional, forcePrompt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
generated, err := password.Generate(positional[0], positional[1], master, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if copyPassword {
|
||||
if err := copyToClipboard(generated); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(stderr, "Password copied to the clipboard.")
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintln(stdout, generated)
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeArguments lets callers place options before or after SITE and
|
||||
// LOGIN. The standard flag package stops at the first positional argument,
|
||||
// while command wrappers naturally append profile options after the site.
|
||||
func normalizeArguments(arguments []string) []string {
|
||||
valueFlags := map[string]bool{
|
||||
"-L": true, "--length": true,
|
||||
"-C": true, "--counter": true,
|
||||
"--exclude": true,
|
||||
}
|
||||
options := make([]string, 0, len(arguments))
|
||||
positional := make([]string, 0, 3)
|
||||
|
||||
for i := 0; i < len(arguments); i++ {
|
||||
argument := arguments[i]
|
||||
if argument == "--" {
|
||||
positional = append(positional, arguments[i+1:]...)
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(argument, "-") && argument != "-" {
|
||||
options = append(options, argument)
|
||||
if valueFlags[argument] && i+1 < len(arguments) {
|
||||
i++
|
||||
options = append(options, arguments[i])
|
||||
}
|
||||
continue
|
||||
}
|
||||
positional = append(positional, argument)
|
||||
}
|
||||
return append(options, positional...)
|
||||
}
|
||||
|
||||
func masterPassword(positional []string, forcePrompt bool) (string, error) {
|
||||
if !forcePrompt && len(positional) == 3 {
|
||||
return positional[2], nil
|
||||
}
|
||||
if !forcePrompt {
|
||||
if value, exists := os.LookupEnv(environmentVariable); exists {
|
||||
return value, nil
|
||||
}
|
||||
}
|
||||
return readPassword("Master password: ")
|
||||
}
|
||||
|
||||
func printHelp(output io.Writer) {
|
||||
fmt.Fprintln(output, `Usage: gopass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
|
||||
|
||||
Derive a site-specific password. If MASTER_PASSWORD is omitted, gopass reads
|
||||
LESSPASS_MASTER_PASSWORD or asks for it on the controlling terminal.
|
||||
|
||||
Options:
|
||||
-L, --length N password length (default 16)
|
||||
-C, --counter N generation counter (default 1)
|
||||
-l, --lowercase include lowercase letters
|
||||
-u, --uppercase include uppercase letters
|
||||
-d, --digits include digits
|
||||
-s, --symbols include symbols
|
||||
--no-lowercase exclude lowercase letters
|
||||
--no-uppercase exclude uppercase letters
|
||||
--no-digits exclude digits
|
||||
--no-symbols exclude symbols
|
||||
--exclude CHARS remove characters from all enabled classes
|
||||
-p, --prompt always ask for the master password
|
||||
-c, --copy copy result without printing it
|
||||
-v, --version show version
|
||||
-h, --help show this help`)
|
||||
}
|
||||
@@ -3,9 +3,11 @@ package main
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type clipboardCommand struct {
|
||||
@@ -13,7 +15,15 @@ type clipboardCommand struct {
|
||||
args []string
|
||||
}
|
||||
|
||||
func copyToClipboard(value string) error {
|
||||
func copyToClipboard(value string, clearAfter time.Duration) error {
|
||||
// The built-in pure-Go X11 clipboard doubles as the only backend that can
|
||||
// auto-clear: it owns the selection from a daemon and releases it on time.
|
||||
if handled, err := copyViaX11(value, clearAfter); handled {
|
||||
return err
|
||||
}
|
||||
if clearAfter > 0 {
|
||||
fmt.Fprintln(os.Stderr, "warning: --clear-after needs the built-in X11 clipboard; copying without auto-clear")
|
||||
}
|
||||
commands := clipboardCommands()
|
||||
var failures []error
|
||||
for _, candidate := range commands {
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The built-in X11 clipboard is Linux-only; other platforms always fall back
|
||||
// to external clipboard tools.
|
||||
|
||||
func copyViaX11(text string, clearAfter time.Duration) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func runClipboardDaemon(timeout time.Duration) error {
|
||||
return errors.New("the built-in clipboard daemon is Linux-only")
|
||||
}
|
||||
|
||||
func readClipboardSelection() (string, error) {
|
||||
return "", errors.New("reading the clipboard is Linux-only")
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/xgb"
|
||||
"github.com/BurntSushi/xgb/xproto"
|
||||
)
|
||||
|
||||
// Pure-Go X11 clipboard. Xlibre is protocol-compatible with X.Org, so the
|
||||
// regular CLIPBOARD selection works there too. No xclip/xsel/wl-copy needed.
|
||||
|
||||
const (
|
||||
selClipboard = "CLIPBOARD"
|
||||
atomUTF8 = "UTF8_STRING"
|
||||
atomString = "STRING"
|
||||
atomText = "TEXT"
|
||||
atomTextPlain = "text/plain"
|
||||
atomPlainUTF8 = "text/plain;charset=utf-8"
|
||||
atomTargets = "TARGETS"
|
||||
atomMultiple = "MULTIPLE"
|
||||
propName = "PASS_SELECTION"
|
||||
)
|
||||
|
||||
type xAtoms map[string]xproto.Atom
|
||||
|
||||
func allAtomNames() []string {
|
||||
return []string{selClipboard, atomUTF8, atomString, atomText, atomTextPlain,
|
||||
atomPlainUTF8, atomTargets, atomMultiple, propName}
|
||||
}
|
||||
|
||||
func internAtoms(c *xgb.Conn, names ...string) (xAtoms, error) {
|
||||
m := make(xAtoms, len(names))
|
||||
for _, n := range names {
|
||||
rep, err := xproto.InternAtom(c, false, uint16(len(n)), n).Reply()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m[n] = rep.Atom
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// serveClipboard takes ownership of the X11 CLIPBOARD selection and answers
|
||||
// paste requests until another client takes ownership or timeout elapses
|
||||
// (timeout <= 0 means "until replaced"). If ready is non-nil it is closed once
|
||||
// ownership has been confirmed.
|
||||
func serveClipboard(text string, timeout time.Duration, ready chan<- struct{}) error {
|
||||
c, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot connect to X server: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
atoms, err := internAtoms(c, allAtomNames()...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
screen := xproto.Setup(c).DefaultScreen(c)
|
||||
wid, err := c.NewId()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = xproto.CreateWindowChecked(c, 0, xproto.Window(wid), screen.Root,
|
||||
-1, -1, 1, 1, 0, 0, 0, 0, nil).Check()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
xproto.SetSelectionOwner(c, xproto.Window(wid), atoms[selClipboard], xproto.TimeCurrentTime)
|
||||
|
||||
rep, err := xproto.GetSelectionOwner(c, atoms[selClipboard]).Reply()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rep.Owner != xproto.Window(wid) {
|
||||
return errors.New("failed to acquire CLIPBOARD ownership")
|
||||
}
|
||||
if ready != nil {
|
||||
close(ready)
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- selectionEventLoop(c, text, atoms) }()
|
||||
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
defer signal.Stop(sig)
|
||||
|
||||
if timeout > 0 {
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-timer.C:
|
||||
return nil
|
||||
case <-sig:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-sig:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func selectionEventLoop(c *xgb.Conn, text string, atoms xAtoms) error {
|
||||
for {
|
||||
ev, err := c.WaitForEvent()
|
||||
if err != nil { // connection closed or protocol error
|
||||
return err
|
||||
}
|
||||
switch e := ev.(type) {
|
||||
case xproto.SelectionClearEvent:
|
||||
return nil // another client owns the clipboard now
|
||||
case xproto.DestroyNotifyEvent:
|
||||
return nil
|
||||
case xproto.SelectionRequestEvent:
|
||||
handleSelectionRequest(c, e, text, atoms)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleSelectionRequest(c *xgb.Conn, e xproto.SelectionRequestEvent, text string, atoms xAtoms) {
|
||||
prop := e.Property
|
||||
if prop == xproto.AtomNone {
|
||||
prop = e.Target
|
||||
}
|
||||
|
||||
ok := false
|
||||
switch e.Target {
|
||||
case atoms[atomTargets]:
|
||||
targets := []xproto.Atom{
|
||||
atoms[atomTargets], atoms[atomMultiple],
|
||||
atoms[atomUTF8], atoms[atomPlainUTF8],
|
||||
atoms[atomText], atoms[atomTextPlain], atoms[atomString],
|
||||
}
|
||||
buf := make([]byte, 4*len(targets))
|
||||
for i, t := range targets {
|
||||
binary.LittleEndian.PutUint32(buf[i*4:], uint32(t))
|
||||
}
|
||||
ok = changeProperty(c, e.Requestor, prop, xproto.AtomAtom, 32, buf)
|
||||
case atoms[atomUTF8], atoms[atomPlainUTF8], atoms[atomText], atoms[atomTextPlain], atoms[atomString]:
|
||||
// Generated passwords are plain ASCII, so serving the same bytes for
|
||||
// STRING (Latin-1) and TEXT targets is safe.
|
||||
ok = changeProperty(c, e.Requestor, prop, e.Target, 8, []byte(text))
|
||||
}
|
||||
if !ok {
|
||||
prop = xproto.AtomNone // refuse this target
|
||||
}
|
||||
|
||||
// Reply with a SelectionNotify event (event code 31).
|
||||
b := make([]byte, 32)
|
||||
b[0] = 31
|
||||
binary.LittleEndian.PutUint32(b[4:], uint32(e.Time))
|
||||
binary.LittleEndian.PutUint32(b[8:], uint32(e.Requestor))
|
||||
binary.LittleEndian.PutUint32(b[12:], uint32(e.Selection))
|
||||
binary.LittleEndian.PutUint32(b[16:], uint32(e.Target))
|
||||
binary.LittleEndian.PutUint32(b[20:], uint32(prop))
|
||||
xproto.SendEvent(c, false, e.Requestor, 0, string(b))
|
||||
}
|
||||
|
||||
func changeProperty(c *xgb.Conn, win xproto.Window, prop, typ xproto.Atom, format byte, data []byte) bool {
|
||||
units := uint32(len(data))
|
||||
if format == 32 {
|
||||
units /= 4
|
||||
}
|
||||
return xproto.ChangePropertyChecked(c, xproto.PropModeReplace, win, prop,
|
||||
typ, format, units, data).Check() == nil
|
||||
}
|
||||
|
||||
// copyViaX11 copies through the built-in clipboard server. It reports false
|
||||
// when no X server is reachable, so the caller can fall back to external
|
||||
// clipboard tools.
|
||||
func copyViaX11(text string, clearAfter time.Duration) (bool, error) {
|
||||
if os.Getenv("DISPLAY") == "" {
|
||||
return false, nil
|
||||
}
|
||||
probe, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
return false, nil
|
||||
}
|
||||
probe.Close()
|
||||
return true, spawnClipboardDaemon(text, clearAfter)
|
||||
}
|
||||
|
||||
// spawnClipboardDaemon re-executes this binary detached (new session) so the
|
||||
// clipboard keeps working after the terminal is closed. The password travels
|
||||
// over a pipe; it is never in argv or the environment.
|
||||
func spawnClipboardDaemon(text string, timeout time.Duration) error {
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd := exec.Command(selfPath(), "--serve-clipboard", "--clear-after="+timeout.String())
|
||||
cmd.ExtraFiles = []*os.File{r}
|
||||
cmd.Env = os.Environ() // keep DISPLAY for the child
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
r.Close()
|
||||
w.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := io.WriteString(w, text); err != nil {
|
||||
return err
|
||||
}
|
||||
w.Close()
|
||||
r.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// selfPath returns the absolute path of this running executable, so the
|
||||
// detached clipboard daemon can re-exec itself reliably.
|
||||
func selfPath() string {
|
||||
if p, err := os.Executable(); err == nil {
|
||||
return p
|
||||
}
|
||||
return os.Args[0]
|
||||
}
|
||||
|
||||
// runClipboardDaemon is the detached child process: it receives the password
|
||||
// over the pipe passed as fd 3 and serves the X11 clipboard until it is
|
||||
// replaced or the timeout elapses.
|
||||
func runClipboardDaemon(timeout time.Duration) error {
|
||||
f := os.NewFile(uintptr(3), "pipe")
|
||||
if f == nil {
|
||||
return errors.New("no pipe on fd 3")
|
||||
}
|
||||
data := make([]byte, 0, 64)
|
||||
buf := make([]byte, 64)
|
||||
for {
|
||||
n, err := f.Read(buf)
|
||||
data = append(data, buf[:n]...)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
f.Close()
|
||||
if len(data) == 0 {
|
||||
return errors.New("empty clipboard payload")
|
||||
}
|
||||
return serveClipboard(string(data), timeout, nil)
|
||||
}
|
||||
|
||||
// readClipboardSelection requests the current CLIPBOARD contents as
|
||||
// UTF8_STRING (equivalent of "xclip -o -selection clipboard").
|
||||
func readClipboardSelection() (string, error) {
|
||||
c, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot connect to X server: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
atoms, err := internAtoms(c, allAtomNames()...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
screen := xproto.Setup(c).DefaultScreen(c)
|
||||
wid, err := c.NewId()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := xproto.CreateWindowChecked(c, 0, xproto.Window(wid), screen.Root,
|
||||
-1, -1, 1, 1, 0, 0, 0, 0, nil).Check(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
xproto.ConvertSelection(c, xproto.Window(wid), atoms[selClipboard],
|
||||
atoms[atomUTF8], atoms[propName], xproto.TimeCurrentTime)
|
||||
|
||||
// Wait for the SelectionNotify reply.
|
||||
var prop xproto.Atom
|
||||
found := false
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !found {
|
||||
if time.Now().After(deadline) {
|
||||
return "", errors.New("timed out waiting for the clipboard owner")
|
||||
}
|
||||
ev, err := c.WaitForEvent()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if sn, ok := ev.(xproto.SelectionNotifyEvent); ok {
|
||||
if sn.Selection != atoms[selClipboard] {
|
||||
continue
|
||||
}
|
||||
if sn.Property == xproto.AtomNone {
|
||||
return "", errors.New("clipboard owner refused the request")
|
||||
}
|
||||
prop = sn.Property
|
||||
found = true
|
||||
}
|
||||
}
|
||||
|
||||
rep, err := xproto.GetProperty(c, false, xproto.Window(wid), prop,
|
||||
xproto.GetPropertyTypeAny, 0, 1<<20).Reply()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(rep.Value), nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Live X11 round trip: take ownership of the CLIPBOARD selection, then read
|
||||
// it back as a separate X client.
|
||||
func TestClipboardRoundTrip(t *testing.T) {
|
||||
if os.Getenv("DISPLAY") == "" {
|
||||
t.Skip("no X11 display available")
|
||||
}
|
||||
|
||||
text := "TestPassword123"
|
||||
ready := make(chan struct{})
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- serveClipboard(text, 10*time.Second, ready) }()
|
||||
|
||||
select {
|
||||
case <-ready:
|
||||
case err := <-done:
|
||||
t.Fatalf("clipboard server exited early: %v", err)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for clipboard ownership")
|
||||
}
|
||||
|
||||
// Reading immediately can race with clipboard managers stealing the
|
||||
// selection; poll briefly for the expected content.
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
got, err := readClipboardSelection()
|
||||
if err == nil && got == text {
|
||||
return // success
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("clipboard round trip failed: last read = %q, err = %v", got, err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
password "github.com/waozixyz/pass"
|
||||
"github.com/waozixyz/pass/vault"
|
||||
)
|
||||
|
||||
const environmentVariable = "LESSPASS_MASTER_PASSWORD"
|
||||
|
||||
// promptVaultPassphrase asks for the vault passphrase on the terminal, or
|
||||
// reads it from standard input when stdin is piped ("echo pw | pass ...").
|
||||
func promptVaultPassphrase() (string, error) {
|
||||
if info, err := os.Stdin.Stat(); err == nil && info.Mode()&os.ModeCharDevice == 0 {
|
||||
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil && line == "" {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimRight(line, "\r\n"), nil
|
||||
}
|
||||
return readPassword("Vault passphrase: ")
|
||||
}
|
||||
|
||||
// readVaultPassphrase is the hook tests replace to decrypt a synthetic vault.
|
||||
var readVaultPassphrase = promptVaultPassphrase
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "pass: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(arguments []string, stdout, stderr io.Writer) error {
|
||||
config, err := loadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := password.DefaultOptions()
|
||||
flags := flag.NewFlagSet("pass", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
flags.Usage = func() { printHelp(stderr) }
|
||||
|
||||
flags.IntVar(&options.Length, "L", options.Length, "password length")
|
||||
flags.IntVar(&options.Length, "length", options.Length, "password length")
|
||||
flags.Uint64Var(&options.Counter, "C", options.Counter, "generation counter")
|
||||
flags.Uint64Var(&options.Counter, "counter", options.Counter, "generation counter")
|
||||
flags.BoolVar(&options.Lowercase, "l", options.Lowercase, "include lowercase letters")
|
||||
flags.BoolVar(&options.Lowercase, "lowercase", options.Lowercase, "include lowercase letters")
|
||||
flags.BoolVar(&options.Uppercase, "u", options.Uppercase, "include uppercase letters")
|
||||
flags.BoolVar(&options.Uppercase, "uppercase", options.Uppercase, "include uppercase letters")
|
||||
flags.BoolVar(&options.Digits, "d", options.Digits, "include digits")
|
||||
flags.BoolVar(&options.Digits, "digits", options.Digits, "include digits")
|
||||
flags.BoolVar(&options.Symbols, "s", options.Symbols, "include symbols")
|
||||
flags.BoolVar(&options.Symbols, "symbols", options.Symbols, "include symbols")
|
||||
var noLowercase, noUppercase, noDigits, noSymbols bool
|
||||
flags.BoolVar(&noLowercase, "no-lowercase", false, "exclude lowercase letters")
|
||||
flags.BoolVar(&noUppercase, "no-uppercase", false, "exclude uppercase letters")
|
||||
flags.BoolVar(&noDigits, "no-digits", false, "exclude digits")
|
||||
flags.BoolVar(&noSymbols, "no-symbols", false, "exclude symbols")
|
||||
flags.StringVar(&options.Exclude, "exclude", "", "characters to exclude")
|
||||
|
||||
var forcePrompt, copyPassword, noCopy, showVersion, readClipboard, serveClipboard bool
|
||||
flags.BoolVar(&forcePrompt, "p", false, "prompt for the master password")
|
||||
flags.BoolVar(&forcePrompt, "prompt", false, "prompt for the master password")
|
||||
flags.BoolVar(©Password, "c", false, "copy the password to the clipboard")
|
||||
flags.BoolVar(©Password, "copy", false, "copy the password to the clipboard")
|
||||
flags.BoolVar(&noCopy, "no-copy", false, "print instead of copying when the profile says to copy")
|
||||
flags.BoolVar(&showVersion, "v", false, "show version")
|
||||
flags.BoolVar(&showVersion, "version", false, "show version")
|
||||
|
||||
var profileName, vaultFlag string
|
||||
var clearAfter time.Duration
|
||||
flags.StringVar(&profileName, "P", "", "use a named profile from the configuration file")
|
||||
flags.StringVar(&profileName, "profile", "", "use a named profile from the configuration file")
|
||||
flags.StringVar(&vaultFlag, "vault", "", "read the master password from an OpenSSL-encrypted vault")
|
||||
flags.DurationVar(&clearAfter, "clear-after", 0, "clear the clipboard after this long; 0 keeps it until replaced (built-in X11 clipboard only)")
|
||||
flags.BoolVar(&readClipboard, "read-clipboard", false, "print the current clipboard contents")
|
||||
flags.BoolVar(&serveClipboard, "serve-clipboard", false, "") // internal: detached clipboard daemon mode
|
||||
|
||||
if err := flags.Parse(normalizeArguments(arguments)); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
explicit := map[string]bool{}
|
||||
flags.Visit(func(f *flag.Flag) { explicit[f.Name] = true })
|
||||
if noLowercase {
|
||||
options.Lowercase = false
|
||||
}
|
||||
if noUppercase {
|
||||
options.Uppercase = false
|
||||
}
|
||||
if noDigits {
|
||||
options.Digits = false
|
||||
}
|
||||
if noSymbols {
|
||||
options.Symbols = false
|
||||
}
|
||||
if showVersion {
|
||||
fmt.Fprintf(stdout, "pass %s\n", password.Version)
|
||||
return nil
|
||||
}
|
||||
if serveClipboard {
|
||||
return runClipboardDaemon(clearAfter)
|
||||
}
|
||||
if readClipboard {
|
||||
text, err := readClipboardSelection()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(stdout, text)
|
||||
return nil
|
||||
}
|
||||
|
||||
positional := flags.Args()
|
||||
if profileName == "" && len(positional) == 2 && config != nil {
|
||||
if _, ok := config.Profiles[positional[0]]; ok {
|
||||
profileName = positional[0]
|
||||
positional = positional[1:]
|
||||
}
|
||||
}
|
||||
|
||||
var profile Profile
|
||||
if profileName != "" {
|
||||
if config == nil {
|
||||
return fmt.Errorf("unknown profile %q: no configuration file at %s", profileName, configPath())
|
||||
}
|
||||
found, ok := config.Profiles[profileName]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown profile %q", profileName)
|
||||
}
|
||||
if found.Login == "" {
|
||||
return fmt.Errorf("profile %q has no login", profileName)
|
||||
}
|
||||
profile = found
|
||||
profile.apply(&options, explicit)
|
||||
}
|
||||
|
||||
if profileName != "" {
|
||||
if len(positional) != 1 {
|
||||
printHelp(stderr)
|
||||
return errors.New("expected SITE with --profile")
|
||||
}
|
||||
} else if len(positional) < 2 || len(positional) > 3 {
|
||||
printHelp(stderr)
|
||||
return errors.New("expected SITE LOGIN and an optional MASTER_PASSWORD")
|
||||
}
|
||||
if forcePrompt && len(positional) == 3 {
|
||||
return errors.New("MASTER_PASSWORD cannot be supplied together with --prompt")
|
||||
}
|
||||
|
||||
site, login := positional[0], ""
|
||||
if profileName != "" {
|
||||
login = profile.Login
|
||||
} else {
|
||||
login = positional[1]
|
||||
}
|
||||
|
||||
// Explicit command-line password sources win. A configured vault beats
|
||||
// LESSPASS_MASTER_PASSWORD because profiles are meant to be complete
|
||||
// saved identities, including the master source.
|
||||
vaultPath := vaultFlag
|
||||
if vaultPath == "" {
|
||||
if !forcePrompt && len(positional) < 3 {
|
||||
switch {
|
||||
case profile.Vault != "":
|
||||
vaultPath = expandHome(profile.Vault)
|
||||
case config != nil && config.Vault != "":
|
||||
vaultPath = expandHome(config.Vault)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !noCopy && !anySet(explicit, "c", "copy") {
|
||||
switch {
|
||||
case profile.Copy != nil:
|
||||
copyPassword = *profile.Copy
|
||||
case config != nil && config.Copy != nil:
|
||||
copyPassword = *config.Copy
|
||||
}
|
||||
}
|
||||
if noCopy {
|
||||
copyPassword = false
|
||||
}
|
||||
if !anySet(explicit, "clear-after") {
|
||||
setting := profile.ClearAfter
|
||||
if setting == "" && config != nil {
|
||||
setting = config.ClearAfter
|
||||
}
|
||||
if setting != "" {
|
||||
duration, err := time.ParseDuration(setting)
|
||||
if err != nil {
|
||||
return fmt.Errorf("clear_after: %w", err)
|
||||
}
|
||||
clearAfter = duration
|
||||
}
|
||||
}
|
||||
|
||||
master, err := masterPassword(positional, forcePrompt, vaultPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
generated, err := password.Generate(site, login, master, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if copyPassword {
|
||||
if err := copyToClipboard(generated, clearAfter); err != nil {
|
||||
return err
|
||||
}
|
||||
if clearAfter > 0 {
|
||||
fmt.Fprintf(stderr, "Password copied to the clipboard (auto-clears in %s).\n", clearAfter)
|
||||
} else {
|
||||
fmt.Fprintln(stderr, "Password copied to the clipboard.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintln(stdout, generated)
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeArguments lets callers place options before or after SITE and
|
||||
// LOGIN. The standard flag package stops at the first positional argument,
|
||||
// while command wrappers naturally append profile options after the site.
|
||||
func normalizeArguments(arguments []string) []string {
|
||||
valueFlags := map[string]bool{
|
||||
"-L": true, "--length": true,
|
||||
"-C": true, "--counter": true,
|
||||
"--exclude": true,
|
||||
"-P": true, "--profile": true,
|
||||
"--vault": true, "--clear-after": true,
|
||||
}
|
||||
options := make([]string, 0, len(arguments))
|
||||
positional := make([]string, 0, 3)
|
||||
|
||||
for i := 0; i < len(arguments); i++ {
|
||||
argument := arguments[i]
|
||||
if argument == "--" {
|
||||
positional = append(positional, arguments[i+1:]...)
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(argument, "-") && argument != "-" {
|
||||
options = append(options, argument)
|
||||
if valueFlags[argument] && i+1 < len(arguments) {
|
||||
i++
|
||||
options = append(options, arguments[i])
|
||||
}
|
||||
continue
|
||||
}
|
||||
positional = append(positional, argument)
|
||||
}
|
||||
return append(options, positional...)
|
||||
}
|
||||
|
||||
func masterPassword(positional []string, forcePrompt bool, vaultPath string) (string, error) {
|
||||
if vaultPath != "" {
|
||||
if forcePrompt {
|
||||
return "", errors.New("--vault cannot be combined with --prompt")
|
||||
}
|
||||
if len(positional) == 3 {
|
||||
return "", errors.New("--vault cannot be combined with MASTER_PASSWORD")
|
||||
}
|
||||
passphrase, err := readVaultPassphrase()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return vault.Decrypt(vaultPath, passphrase)
|
||||
}
|
||||
if !forcePrompt && len(positional) == 3 {
|
||||
return positional[2], nil
|
||||
}
|
||||
if !forcePrompt {
|
||||
if value, exists := os.LookupEnv(environmentVariable); exists {
|
||||
return value, nil
|
||||
}
|
||||
}
|
||||
return readPassword("Master password: ")
|
||||
}
|
||||
|
||||
func printHelp(output io.Writer) {
|
||||
fmt.Fprintln(output, `Usage: pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
|
||||
pass [OPTIONS] PROFILE SITE
|
||||
|
||||
Derive a site-specific password. If MASTER_PASSWORD is omitted, pass reads
|
||||
LESSPASS_MASTER_PASSWORD or asks for it on the controlling terminal. With
|
||||
--vault it instead decrypts an OpenSSL-encrypted vault and uses its contents
|
||||
as the master password. A named profile from the configuration file can be
|
||||
used either as "pass PROFILE SITE" or with --profile; it supplies the login
|
||||
and default settings.
|
||||
|
||||
Options:
|
||||
-L, --length N password length (default 16)
|
||||
-C, --counter N generation counter (default 1)
|
||||
-l, --lowercase include lowercase letters
|
||||
-u, --uppercase include uppercase letters
|
||||
-d, --digits include digits
|
||||
-s, --symbols include symbols
|
||||
--no-lowercase exclude lowercase letters
|
||||
--no-uppercase exclude uppercase letters
|
||||
--no-digits exclude digits
|
||||
--no-symbols exclude symbols
|
||||
--exclude CHARS remove characters from all enabled classes
|
||||
-p, --prompt always ask for the master password
|
||||
-c, --copy copy result without printing it
|
||||
--no-copy print instead of copying when the profile says to copy
|
||||
-P, --profile NAME use a named profile from the configuration file
|
||||
--vault PATH read the master password from an OpenSSL-encrypted vault
|
||||
--clear-after DUR clear the clipboard after DUR; 0 keeps it until replaced
|
||||
--read-clipboard print the current clipboard contents
|
||||
-v, --version show version
|
||||
-h, --help show this help`)
|
||||
}
|
||||
@@ -2,12 +2,24 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
password "github.com/waozixyz/gopass"
|
||||
password "github.com/waozixyz/pass"
|
||||
)
|
||||
|
||||
// TestMain isolates every test in this package from the developer's real
|
||||
// profiles file: without this, a machine with ~/.config/pass/profiles.json
|
||||
// would feed private configuration into the tests.
|
||||
func TestMain(m *testing.M) {
|
||||
configPath = func() string {
|
||||
return filepath.Join(os.TempDir(), "pass-tests-absent-profiles.json")
|
||||
}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestRunWithArgument(t *testing.T) {
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"example.com", "alice", "correct horse battery staple"}, &output, &diagnostics)
|
||||
@@ -52,8 +64,8 @@ func TestRunInformationOptions(t *testing.T) {
|
||||
argument string
|
||||
want string
|
||||
}{
|
||||
{"--version", "gopass " + password.Version},
|
||||
{"--help", "Usage: gopass"},
|
||||
{"--version", "pass " + password.Version},
|
||||
{"--help", "Usage: pass"},
|
||||
} {
|
||||
var output, diagnostics bytes.Buffer
|
||||
if err := run([]string{test.argument}, &output, &diagnostics); err != nil {
|
||||
@@ -0,0 +1,119 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
password "github.com/waozixyz/pass"
|
||||
)
|
||||
|
||||
// Profile holds the saved settings for one named identity: a login plus the
|
||||
// generator options and clipboard behavior to use with it. Profiles contain
|
||||
// no secrets — the master password always comes from a prompt, the
|
||||
// environment, or an encrypted vault referenced by path.
|
||||
type Profile struct {
|
||||
Login string `json:"login"`
|
||||
Counter uint64 `json:"counter,omitempty"`
|
||||
Length int `json:"length,omitempty"`
|
||||
Lowercase *bool `json:"lowercase,omitempty"`
|
||||
Uppercase *bool `json:"uppercase,omitempty"`
|
||||
Digits *bool `json:"digits,omitempty"`
|
||||
Symbols *bool `json:"symbols,omitempty"`
|
||||
Exclude string `json:"exclude,omitempty"`
|
||||
Vault string `json:"vault,omitempty"`
|
||||
Copy *bool `json:"copy,omitempty"`
|
||||
ClearAfter string `json:"clear_after,omitempty"`
|
||||
}
|
||||
|
||||
// Config is the optional profiles file. Every field is a default that flags
|
||||
// and profile entries override; a missing file leaves pass fully stateless.
|
||||
type Config struct {
|
||||
Vault string `json:"vault,omitempty"`
|
||||
Copy *bool `json:"copy,omitempty"`
|
||||
ClearAfter string `json:"clear_after,omitempty"`
|
||||
Profiles map[string]Profile `json:"profiles"`
|
||||
}
|
||||
|
||||
// configPath is a variable so tests can point it at a temporary file.
|
||||
var configPath = defaultConfigPath
|
||||
|
||||
func defaultConfigPath() string {
|
||||
if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" {
|
||||
return filepath.Join(dir, "pass", "profiles.json")
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, ".config", "pass", "profiles.json")
|
||||
}
|
||||
|
||||
// loadConfig reads the profiles file. A missing file is not an error: the
|
||||
// feature is simply off and pass behaves as a plain stateless generator.
|
||||
func loadConfig() (*Config, error) {
|
||||
path := configPath()
|
||||
if path == "" {
|
||||
return nil, nil
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var config Config
|
||||
if err := json.Unmarshal(raw, &config); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
// apply fills the option fields that were not set explicitly on the command
|
||||
// line, so the precedence is always flag > profile > built-in default.
|
||||
func (p Profile) apply(options *password.Options, explicit map[string]bool) {
|
||||
if p.Length > 0 && !anySet(explicit, "L", "length") {
|
||||
options.Length = p.Length
|
||||
}
|
||||
if p.Counter > 0 && !anySet(explicit, "C", "counter") {
|
||||
options.Counter = p.Counter
|
||||
}
|
||||
if p.Lowercase != nil && !anySet(explicit, "l", "lowercase", "no-lowercase") {
|
||||
options.Lowercase = *p.Lowercase
|
||||
}
|
||||
if p.Uppercase != nil && !anySet(explicit, "u", "uppercase", "no-uppercase") {
|
||||
options.Uppercase = *p.Uppercase
|
||||
}
|
||||
if p.Digits != nil && !anySet(explicit, "d", "digits", "no-digits") {
|
||||
options.Digits = *p.Digits
|
||||
}
|
||||
if p.Symbols != nil && !anySet(explicit, "s", "symbols", "no-symbols") {
|
||||
options.Symbols = *p.Symbols
|
||||
}
|
||||
if p.Exclude != "" && !anySet(explicit, "exclude") {
|
||||
options.Exclude = p.Exclude
|
||||
}
|
||||
}
|
||||
|
||||
func anySet(explicit map[string]bool, names ...string) bool {
|
||||
for _, name := range names {
|
||||
if explicit[name] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// expandHome resolves a leading ~ so config entries stay portable.
|
||||
func expandHome(path string) string {
|
||||
if path == "~" || strings.HasPrefix(path, "~/") {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
return filepath.Join(home, strings.TrimPrefix(path, "~"))
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
password "github.com/waozixyz/pass"
|
||||
)
|
||||
|
||||
// withConfig points the config loader at a temporary file for one test.
|
||||
func withConfig(t *testing.T, content string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "profiles.json")
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := configPath
|
||||
configPath = func() string { return path }
|
||||
t.Cleanup(func() { configPath = original })
|
||||
}
|
||||
|
||||
func withVaultPassphrase(t *testing.T, passphrase string) {
|
||||
t.Helper()
|
||||
original := readVaultPassphrase
|
||||
readVaultPassphrase = func() (string, error) { return passphrase, nil }
|
||||
t.Cleanup(func() { readVaultPassphrase = original })
|
||||
}
|
||||
|
||||
func TestRunWithProfileSettings(t *testing.T) {
|
||||
withConfig(t, `{
|
||||
"copy": true,
|
||||
"clear_after": "90s",
|
||||
"profiles": {
|
||||
"w": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
|
||||
}
|
||||
}`)
|
||||
t.Setenv(environmentVariable, "correct horse battery staple")
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := password.Generate("example.com", "alice", "correct horse battery staple", password.Options{
|
||||
Length: 23, Counter: 9, Lowercase: true, Uppercase: true, Digits: true, Symbols: false,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); got != want {
|
||||
t.Fatalf("output = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunWithProfileShorthand(t *testing.T) {
|
||||
withConfig(t, `{
|
||||
"profiles": {
|
||||
"w": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
|
||||
}
|
||||
}`)
|
||||
t.Setenv(environmentVariable, "correct horse battery staple")
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"w", "example.com", "--no-copy"}, &output, &diagnostics)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := password.Generate("example.com", "alice", "correct horse battery staple", password.Options{
|
||||
Length: 23, Counter: 9, Lowercase: true, Uppercase: true, Digits: true, Symbols: false,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); got != want {
|
||||
t.Fatalf("output = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileSettingsDoNotOverrideExplicitFlags(t *testing.T) {
|
||||
withConfig(t, `{"profiles": {"w": {"login": "alice", "length": 23, "symbols": false}}}`)
|
||||
t.Setenv(environmentVariable, "correct horse battery staple")
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"-P", "w", "-L", "10", "example.com"}, &output, &diagnostics)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); len(got) != 10 {
|
||||
t.Fatalf("output length = %d, want 10 (flag must beat profile)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRejectsBadProfileNames(t *testing.T) {
|
||||
withConfig(t, `{"profiles": {"w": {"login": "alice"}, "n": {}}}`)
|
||||
t.Setenv(environmentVariable, "x")
|
||||
|
||||
var output, diagnostics bytes.Buffer
|
||||
if err := run([]string{"-P", "x", "example.com"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "unknown profile") {
|
||||
t.Fatalf("error = %v, want unknown profile", err)
|
||||
}
|
||||
if err := run([]string{"-P", "n", "example.com"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "has no login") {
|
||||
t.Fatalf("error = %v, want missing login", err)
|
||||
}
|
||||
// A profile without a configuration file at all.
|
||||
original := configPath
|
||||
configPath = func() string { return filepath.Join(t.TempDir(), "absent.json") }
|
||||
defer func() { configPath = original }()
|
||||
if err := run([]string{"-P", "w", "example.com"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "no configuration file") {
|
||||
t.Fatalf("error = %v, want missing configuration", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRejectsInvalidConfig(t *testing.T) {
|
||||
withConfig(t, `{"profiles":`)
|
||||
var output, diagnostics bytes.Buffer
|
||||
if err := run([]string{"example.com", "alice", "master"}, &output, &diagnostics); err == nil {
|
||||
t.Fatal("expected error for malformed configuration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRejectsInvalidClearAfter(t *testing.T) {
|
||||
withConfig(t, `{"clear_after": "not-a-duration", "profiles": {"w": {"login": "alice"}}}`)
|
||||
t.Setenv(environmentVariable, "x")
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics)
|
||||
if err == nil || !strings.Contains(err.Error(), "clear_after") {
|
||||
t.Fatalf("error = %v, want clear_after parse failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVaultMasterPasswordBeatsEnvironmentAndPositional(t *testing.T) {
|
||||
if _, err := exec.LookPath("openssl"); err != nil {
|
||||
t.Skip("openssl not available")
|
||||
}
|
||||
vaultFile := filepath.Join(t.TempDir(), ".vault")
|
||||
encrypt := `printf 'my-top-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
|
||||
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
|
||||
withVaultPassphrase(t, "masterpw")
|
||||
t.Setenv(environmentVariable, "environment-must-be-ignored")
|
||||
|
||||
var output, diagnostics bytes.Buffer
|
||||
err := run([]string{"--vault", vaultFile, "example.com", "alice"}, &output, &diagnostics)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := password.Generate("example.com", "alice", "my-top-secret", password.DefaultOptions())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); got != want {
|
||||
t.Fatalf("output = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
if err := run([]string{"--vault", vaultFile, "example.com", "alice", "master"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "cannot be combined") {
|
||||
t.Fatalf("error = %v, want source conflict with MASTER_PASSWORD", err)
|
||||
}
|
||||
if err := run([]string{"--vault", vaultFile, "--prompt", "example.com", "alice"}, &output, &diagnostics); err == nil ||
|
||||
!strings.Contains(err.Error(), "cannot be combined") {
|
||||
t.Fatalf("error = %v, want source conflict with --prompt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigVaultIsUsedForProfile(t *testing.T) {
|
||||
if _, err := exec.LookPath("openssl"); err != nil {
|
||||
t.Skip("openssl not available")
|
||||
}
|
||||
vaultFile := filepath.Join(t.TempDir(), ".vault")
|
||||
encrypt := `printf 'cfg-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
|
||||
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
|
||||
withConfig(t, `{"vault": "`+vaultFile+`", "profiles": {"w": {"login": "alice"}}}`)
|
||||
withVaultPassphrase(t, "masterpw")
|
||||
t.Setenv(environmentVariable, "environment-must-be-ignored")
|
||||
|
||||
var output, diagnostics bytes.Buffer
|
||||
if err := run([]string{"w", "example.com", "--no-copy"}, &output, &diagnostics); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := password.Generate("example.com", "alice", "cfg-secret", password.DefaultOptions())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.TrimSpace(output.String()); got != want {
|
||||
t.Fatalf("output = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandHome(t *testing.T) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
t.Skip("no home directory")
|
||||
}
|
||||
for _, test := range []struct{ in, want string }{
|
||||
{"~", home},
|
||||
{"~/bin/.vault", filepath.Join(home, "bin", ".vault")},
|
||||
{"/abs/path", "/abs/path"},
|
||||
{"relative", "relative"},
|
||||
} {
|
||||
if got := expandHome(test.in); got != test.want {
|
||||
t.Errorf("expandHome(%q) = %q, want %q", test.in, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVaultPassphraseFromPipedStdin(t *testing.T) {
|
||||
if _, err := exec.LookPath("openssl"); err != nil {
|
||||
t.Skip("openssl not available")
|
||||
}
|
||||
vaultFile := filepath.Join(t.TempDir(), ".vault")
|
||||
encrypt := `printf 'piped-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
|
||||
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
contents string
|
||||
}{
|
||||
{"newline", "masterpw\n"},
|
||||
{"crlf", "masterpw\r\n"},
|
||||
{"no trailing newline", "masterpw"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input, err := os.CreateTemp(t.TempDir(), "stdin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := input.WriteString(test.contents); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := input.Seek(0, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous := os.Stdin
|
||||
os.Stdin = input
|
||||
defer func() { os.Stdin = previous }()
|
||||
|
||||
got, err := promptVaultPassphrase()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "masterpw" {
|
||||
t.Fatalf("passphrase = %q, want %q", got, "masterpw")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+23
-2
@@ -12,12 +12,32 @@ android {
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
def keystorePropsFile = rootProject.file("local.properties")
|
||||
def keystoreProps = new Properties()
|
||||
if (keystorePropsFile.exists()) {
|
||||
keystoreProps.load(new FileInputStream(keystorePropsFile))
|
||||
}
|
||||
|
||||
def getKeystorePath = { -> project.findProperty('keystore.path') ?: keystoreProps['keystore.path'] ?: System.getenv("HOME") + "/.android/pass-release.keystore" }
|
||||
def getKeystoreAlias = { -> project.findProperty('keystore.alias') ?: keystoreProps['keystore.alias'] ?: "pass-key" }
|
||||
|
||||
def releasePassword = project.findProperty('keystore.password') ?: ""
|
||||
|
||||
signingConfigs {
|
||||
release {
|
||||
storeFile getKeystorePath() ? file(getKeystorePath()) : null
|
||||
storePassword releasePassword
|
||||
keyAlias getKeystoreAlias()
|
||||
keyPassword releasePassword
|
||||
}
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId 'xyz.waozi.pass'
|
||||
minSdk 21
|
||||
targetSdk 36
|
||||
versionCode 2
|
||||
versionName "0.1.2"
|
||||
versionCode 3
|
||||
versionName "0.2.2"
|
||||
// Default to the two realistic phone targets; override with
|
||||
// -Pabi=x86_64 etc. for emulator builds.
|
||||
def abis = project.findProperty('abi') ?: 'armeabi-v7a,arm64-v8a'
|
||||
@@ -28,6 +48,7 @@ android {
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
signingConfig project.hasProperty('fDroidBuild') ? null : signingConfigs.release
|
||||
minifyEnabled false
|
||||
}
|
||||
debug {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- gopass generates passwords entirely offline; no permissions needed. -->
|
||||
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
|
||||
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
|
||||
|
||||
<application
|
||||
android:hasCode="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
project(Gopass C)
|
||||
project(Pass C)
|
||||
|
||||
set(REPO_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../..")
|
||||
set(KRYON_DIR "${REPO_ROOT}/vendor/kryon")
|
||||
set(RAYLIB_DIR "${KRYON_DIR}/vendor/raylib/src")
|
||||
set(GOPASS_NATIVE_DIR "${REPO_ROOT}/native")
|
||||
set(PASS_NATIVE_DIR "${REPO_ROOT}/native")
|
||||
set(NATIVE_APP_GLUE_DIR "${ANDROID_NDK}/sources/android/native_app_glue")
|
||||
|
||||
file(GLOB_RECURSE KRYON_SOURCES CONFIGURE_DEPENDS "${KRYON_DIR}/src/*.c")
|
||||
@@ -12,24 +12,26 @@ file(GLOB_RECURSE KRYON_SOURCES CONFIGURE_DEPENDS "${KRYON_DIR}/src/*.c")
|
||||
# no-raylib hosts; Android links real raylib, so compiling both is a
|
||||
# duplicate-symbol link error.
|
||||
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/backend/.*")
|
||||
# gopass uses no 2D physics; mirror the desktop Makefile's physics filter.
|
||||
# pass uses no 2D physics; mirror the desktop Makefile's physics filter.
|
||||
list(REMOVE_ITEM KRYON_SOURCES
|
||||
"${KRYON_DIR}/src/scene/physics_world.c"
|
||||
"${KRYON_DIR}/src/scene/node_body2d.c"
|
||||
"${KRYON_DIR}/src/scene/node_area2d.c"
|
||||
"${KRYON_DIR}/src/scene/node_collision_shape2d.c")
|
||||
# Ksync account crypto requires liboqs and gopass never syncs; runtime asset
|
||||
# downloads need an Android download backend gopass does not provide.
|
||||
# Ksync account crypto requires liboqs and pass never syncs; runtime asset
|
||||
# downloads need an Android download backend pass does not provide.
|
||||
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/ksync/.*")
|
||||
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/runtime_assets/.*")
|
||||
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/notification/.*")
|
||||
list(REMOVE_ITEM KRYON_SOURCES "${KRYON_DIR}/src/file_dialog/file_dialog.c")
|
||||
|
||||
set(GOPASS_FONT_ASSET "vendor/kryon/fonts/noto/NotoSans-Regular.ttf")
|
||||
set(GOPASS_EMBEDDED_ASSETS_C "${CMAKE_BINARY_DIR}/gopass_embedded_assets.c")
|
||||
set(PASS_FONT_ASSET "vendor/kryon/fonts/noto/NotoSans-Regular.ttf")
|
||||
set(PASS_EMOJI_FONT_ASSET "gui/assets/emoji.ttf")
|
||||
set(PASS_EMBEDDED_ASSETS_C "${CMAKE_BINARY_DIR}/pass_embedded_assets.c")
|
||||
add_custom_command(
|
||||
OUTPUT "${GOPASS_EMBEDDED_ASSETS_C}"
|
||||
COMMAND sh "${KRYON_DIR}/scripts/embed-assets.sh" "${GOPASS_EMBEDDED_ASSETS_C}" "${GOPASS_FONT_ASSET}"
|
||||
DEPENDS "${KRYON_DIR}/scripts/embed-assets.sh" "${KRYON_DIR}/fonts/noto/NotoSans-Regular.ttf"
|
||||
OUTPUT "${PASS_EMBEDDED_ASSETS_C}"
|
||||
COMMAND sh "${KRYON_DIR}/scripts/embed-assets.sh" "${PASS_EMBEDDED_ASSETS_C}" "${PASS_FONT_ASSET}" "${PASS_EMOJI_FONT_ASSET}"
|
||||
DEPENDS "${KRYON_DIR}/scripts/embed-assets.sh" "${KRYON_DIR}/fonts/noto/NotoSans-Regular.ttf" "${REPO_ROOT}/${PASS_EMOJI_FONT_ASSET}"
|
||||
WORKING_DIRECTORY "${REPO_ROOT}"
|
||||
VERBATIM
|
||||
)
|
||||
@@ -73,10 +75,10 @@ target_include_directories(raylib PUBLIC
|
||||
|
||||
add_library(main SHARED
|
||||
main.c
|
||||
gopass_app.c
|
||||
pass_app.c
|
||||
android_bridge.c
|
||||
"${GOPASS_NATIVE_DIR}/gopass_core.c"
|
||||
"${GOPASS_EMBEDDED_ASSETS_C}"
|
||||
"${PASS_NATIVE_DIR}/pass_core.c"
|
||||
"${PASS_EMBEDDED_ASSETS_C}"
|
||||
${KRYON_SOURCES}
|
||||
"${NATIVE_APP_GLUE_DIR}/android_native_app_glue.c"
|
||||
)
|
||||
@@ -84,7 +86,7 @@ add_library(main SHARED
|
||||
target_include_directories(main PRIVATE
|
||||
"${KRYON_DIR}/include"
|
||||
"${KRYON_DIR}/src"
|
||||
"${GOPASS_NATIVE_DIR}"
|
||||
"${PASS_NATIVE_DIR}"
|
||||
"${NATIVE_APP_GLUE_DIR}"
|
||||
)
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* Minimal JNI bridge for the gopass Android app: safe-area insets, display
|
||||
/* Minimal JNI bridge for the pass Android app: safe-area insets, display
|
||||
* density, soft-keyboard visibility, and soft-keyboard text input. Modeled
|
||||
* on inbe's android_device.c / android_insets.c. */
|
||||
|
||||
@@ -7,12 +7,15 @@
|
||||
#if ANDROID_BUILD
|
||||
|
||||
#include "kryon.h"
|
||||
#include "theme.h"
|
||||
#include "ui_dpi.h"
|
||||
|
||||
#include <android/log.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#include <jni.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
extern struct android_app *GetAndroidApp(void);
|
||||
|
||||
@@ -20,7 +23,7 @@ extern struct android_app *GetAndroidApp(void);
|
||||
#define JNI_VERSION_1_6 0x10060000
|
||||
#endif
|
||||
|
||||
#define LOG_TAG "GOPASS_JNI"
|
||||
#define LOG_TAG "PASS_JNI"
|
||||
|
||||
static pthread_mutex_t bridge_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
static int insets_status_bar = 0;
|
||||
@@ -38,6 +41,42 @@ scaled_inset(int java_px, float density)
|
||||
return (int)(java_px / density + 0.5f);
|
||||
}
|
||||
|
||||
static int
|
||||
activity_env(JNIEnv **env_out, JavaVM **jvm_out, jobject *activity_out)
|
||||
{
|
||||
struct android_app *app = GetAndroidApp();
|
||||
JavaVM *jvm;
|
||||
JNIEnv *env = NULL;
|
||||
int attached = 0;
|
||||
|
||||
if(env_out == NULL || jvm_out == NULL || activity_out == NULL ||
|
||||
app == NULL || app->activity == NULL || app->activity->vm == NULL ||
|
||||
app->activity->clazz == NULL)
|
||||
return -1;
|
||||
|
||||
jvm = app->activity->vm;
|
||||
if((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) {
|
||||
if((*jvm)->AttachCurrentThread(jvm, &env, NULL) != JNI_OK || env == NULL)
|
||||
return -1;
|
||||
attached = 1;
|
||||
}
|
||||
*env_out = env;
|
||||
*jvm_out = jvm;
|
||||
*activity_out = app->activity->clazz;
|
||||
return attached;
|
||||
}
|
||||
|
||||
static void
|
||||
activity_env_done(JNIEnv *env, JavaVM *jvm, int attached)
|
||||
{
|
||||
if(env != NULL && (*env)->ExceptionCheck(env)) {
|
||||
(*env)->ExceptionDescribe(env);
|
||||
(*env)->ExceptionClear(env);
|
||||
}
|
||||
if(attached && jvm != NULL)
|
||||
(*jvm)->DetachCurrentThread(jvm);
|
||||
}
|
||||
|
||||
void
|
||||
android_bridge_init(void)
|
||||
{
|
||||
@@ -51,6 +90,69 @@ android_bridge_init(void)
|
||||
pthread_mutex_unlock(&bridge_mutex);
|
||||
}
|
||||
|
||||
static Color
|
||||
color_from_argb(jint argb)
|
||||
{
|
||||
Color color;
|
||||
|
||||
color.a = (unsigned char)((argb >> 24) & 0xff);
|
||||
color.r = (unsigned char)((argb >> 16) & 0xff);
|
||||
color.g = (unsigned char)((argb >> 8) & 0xff);
|
||||
color.b = (unsigned char)(argb & 0xff);
|
||||
if(color.a == 0)
|
||||
color.a = 0xff;
|
||||
return color;
|
||||
}
|
||||
|
||||
void
|
||||
android_bridge_apply_system_theme(void)
|
||||
{
|
||||
JavaVM *jvm;
|
||||
JNIEnv *env = NULL;
|
||||
jobject activity;
|
||||
jclass activity_class;
|
||||
jmethodID method;
|
||||
jintArray array;
|
||||
jint values[9];
|
||||
jsize len;
|
||||
int attached;
|
||||
|
||||
attached = activity_env(&env, &jvm, &activity);
|
||||
if(attached < 0)
|
||||
return;
|
||||
|
||||
memset(values, 0, sizeof(values));
|
||||
activity_class = (*env)->GetObjectClass(env, activity);
|
||||
if(activity_class == NULL)
|
||||
goto done;
|
||||
method = (*env)->GetMethodID(env, activity_class, "systemThemeColors", "()[I");
|
||||
if(method == NULL) {
|
||||
__android_log_write(ANDROID_LOG_ERROR, LOG_TAG, "systemThemeColors not found");
|
||||
goto done;
|
||||
}
|
||||
array = (jintArray)(*env)->CallObjectMethod(env, activity, method);
|
||||
if(array == NULL)
|
||||
goto done;
|
||||
len = (*env)->GetArrayLength(env, array);
|
||||
if(len < 9)
|
||||
goto done;
|
||||
(*env)->GetIntArrayRegion(env, array, 0, 9, values);
|
||||
SetSystemThemePalette("Android",
|
||||
color_from_argb(values[1]),
|
||||
color_from_argb(values[2]),
|
||||
color_from_argb(values[3]),
|
||||
color_from_argb(values[4]),
|
||||
color_from_argb(values[5]),
|
||||
color_from_argb(values[6]),
|
||||
color_from_argb(values[7]),
|
||||
color_from_argb(values[8]),
|
||||
values[0] != 0,
|
||||
1);
|
||||
|
||||
done:
|
||||
activity_env_done(env, jvm, attached);
|
||||
}
|
||||
|
||||
int
|
||||
android_bridge_top_reserved(void)
|
||||
{
|
||||
@@ -92,26 +194,17 @@ android_bridge_bottom_reserved(void)
|
||||
void
|
||||
android_bridge_set_soft_keyboard(int visible)
|
||||
{
|
||||
struct android_app *app = GetAndroidApp();
|
||||
JavaVM *jvm;
|
||||
JNIEnv *env = NULL;
|
||||
jobject activity;
|
||||
jclass activity_class;
|
||||
jmethodID method;
|
||||
int attached = 0;
|
||||
int attached;
|
||||
|
||||
if(app == NULL || app->activity == NULL || app->activity->vm == NULL ||
|
||||
app->activity->clazz == NULL)
|
||||
attached = activity_env(&env, &jvm, &activity);
|
||||
if(attached < 0)
|
||||
return;
|
||||
|
||||
jvm = app->activity->vm;
|
||||
activity = app->activity->clazz;
|
||||
if((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) {
|
||||
if((*jvm)->AttachCurrentThread(jvm, &env, NULL) != JNI_OK || env == NULL)
|
||||
return;
|
||||
attached = 1;
|
||||
}
|
||||
|
||||
activity_class = (*env)->GetObjectClass(env, activity);
|
||||
if(activity_class == NULL)
|
||||
goto done;
|
||||
@@ -125,12 +218,196 @@ android_bridge_set_soft_keyboard(int visible)
|
||||
(*env)->CallVoidMethod(env, activity, method, visible ? JNI_TRUE : JNI_FALSE);
|
||||
|
||||
done:
|
||||
if((*env)->ExceptionCheck(env)) {
|
||||
(*env)->ExceptionDescribe(env);
|
||||
(*env)->ExceptionClear(env);
|
||||
activity_env_done(env, jvm, attached);
|
||||
}
|
||||
|
||||
static int
|
||||
call_boolean_method(const char *name)
|
||||
{
|
||||
JavaVM *jvm;
|
||||
JNIEnv *env = NULL;
|
||||
jobject activity;
|
||||
jclass activity_class;
|
||||
jmethodID method;
|
||||
int attached;
|
||||
int result = 0;
|
||||
|
||||
attached = activity_env(&env, &jvm, &activity);
|
||||
if(attached < 0)
|
||||
return 0;
|
||||
activity_class = (*env)->GetObjectClass(env, activity);
|
||||
if(activity_class == NULL)
|
||||
goto done;
|
||||
method = (*env)->GetMethodID(env, activity_class, name, "()Z");
|
||||
if(method == NULL)
|
||||
goto done;
|
||||
result = (*env)->CallBooleanMethod(env, activity, method) ? 1 : 0;
|
||||
|
||||
done:
|
||||
activity_env_done(env, jvm, attached);
|
||||
return result;
|
||||
}
|
||||
|
||||
int
|
||||
android_bridge_biometric_available(void)
|
||||
{
|
||||
return call_boolean_method("isBiometricAvailable");
|
||||
}
|
||||
|
||||
int
|
||||
android_bridge_biometric_setup_required(void)
|
||||
{
|
||||
return call_boolean_method("isBiometricSetupRequired");
|
||||
}
|
||||
|
||||
int
|
||||
android_bridge_master_saved(void)
|
||||
{
|
||||
return call_boolean_method("hasStoredMasterPassword");
|
||||
}
|
||||
|
||||
int
|
||||
android_bridge_master_biometric(void)
|
||||
{
|
||||
return call_boolean_method("isStoredMasterBiometric");
|
||||
}
|
||||
|
||||
void
|
||||
android_bridge_save_master(const char *master, int require_biometric)
|
||||
{
|
||||
JavaVM *jvm;
|
||||
JNIEnv *env = NULL;
|
||||
jobject activity;
|
||||
jclass activity_class;
|
||||
jmethodID method;
|
||||
jstring jmaster;
|
||||
int attached;
|
||||
|
||||
attached = activity_env(&env, &jvm, &activity);
|
||||
if(attached < 0)
|
||||
return;
|
||||
activity_class = (*env)->GetObjectClass(env, activity);
|
||||
if(activity_class == NULL)
|
||||
goto done;
|
||||
method = (*env)->GetMethodID(env, activity_class, "saveMasterPassword", "(Ljava/lang/String;Z)V");
|
||||
if(method == NULL)
|
||||
goto done;
|
||||
jmaster = (*env)->NewStringUTF(env, master != NULL ? master : "");
|
||||
if(jmaster == NULL)
|
||||
goto done;
|
||||
(*env)->CallVoidMethod(env, activity, method, jmaster, require_biometric ? JNI_TRUE : JNI_FALSE);
|
||||
(*env)->DeleteLocalRef(env, jmaster);
|
||||
|
||||
done:
|
||||
activity_env_done(env, jvm, attached);
|
||||
}
|
||||
|
||||
static void
|
||||
call_void_method(const char *name)
|
||||
{
|
||||
JavaVM *jvm;
|
||||
JNIEnv *env = NULL;
|
||||
jobject activity;
|
||||
jclass activity_class;
|
||||
jmethodID method;
|
||||
int attached;
|
||||
|
||||
attached = activity_env(&env, &jvm, &activity);
|
||||
if(attached < 0)
|
||||
return;
|
||||
activity_class = (*env)->GetObjectClass(env, activity);
|
||||
if(activity_class == NULL)
|
||||
goto done;
|
||||
method = (*env)->GetMethodID(env, activity_class, name, "()V");
|
||||
if(method == NULL)
|
||||
goto done;
|
||||
(*env)->CallVoidMethod(env, activity, method);
|
||||
|
||||
done:
|
||||
activity_env_done(env, jvm, attached);
|
||||
}
|
||||
|
||||
void
|
||||
android_bridge_unlock_master(void)
|
||||
{
|
||||
call_void_method("unlockMasterPassword");
|
||||
}
|
||||
|
||||
void
|
||||
android_bridge_clear_master(void)
|
||||
{
|
||||
call_void_method("clearMasterPassword");
|
||||
}
|
||||
|
||||
int
|
||||
android_bridge_secure_status(void)
|
||||
{
|
||||
JavaVM *jvm;
|
||||
JNIEnv *env = NULL;
|
||||
jobject activity;
|
||||
jclass activity_class;
|
||||
jmethodID method;
|
||||
int attached;
|
||||
int result = 0;
|
||||
|
||||
attached = activity_env(&env, &jvm, &activity);
|
||||
if(attached < 0)
|
||||
return 0;
|
||||
activity_class = (*env)->GetObjectClass(env, activity);
|
||||
if(activity_class == NULL)
|
||||
goto done;
|
||||
method = (*env)->GetMethodID(env, activity_class, "secureMasterStatus", "()I");
|
||||
if(method == NULL)
|
||||
goto done;
|
||||
result = (int)(*env)->CallIntMethod(env, activity, method);
|
||||
|
||||
done:
|
||||
activity_env_done(env, jvm, attached);
|
||||
return result;
|
||||
}
|
||||
|
||||
int
|
||||
android_bridge_take_secure_result(char *out, int out_size)
|
||||
{
|
||||
JavaVM *jvm;
|
||||
JNIEnv *env = NULL;
|
||||
jobject activity;
|
||||
jclass activity_class;
|
||||
jmethodID method;
|
||||
jstring result;
|
||||
const char *chars;
|
||||
int attached;
|
||||
int status = 0;
|
||||
|
||||
if(out != NULL && out_size > 0)
|
||||
out[0] = '\0';
|
||||
attached = activity_env(&env, &jvm, &activity);
|
||||
if(attached < 0)
|
||||
return 0;
|
||||
activity_class = (*env)->GetObjectClass(env, activity);
|
||||
if(activity_class == NULL)
|
||||
goto done;
|
||||
method = (*env)->GetMethodID(env, activity_class, "secureMasterStatus", "()I");
|
||||
if(method == NULL)
|
||||
goto done;
|
||||
status = (int)(*env)->CallIntMethod(env, activity, method);
|
||||
method = (*env)->GetMethodID(env, activity_class, "takeSecureMasterResult", "()Ljava/lang/String;");
|
||||
if(method == NULL)
|
||||
goto done;
|
||||
result = (jstring)(*env)->CallObjectMethod(env, activity, method);
|
||||
if(result == NULL)
|
||||
goto done;
|
||||
chars = (*env)->GetStringUTFChars(env, result, NULL);
|
||||
if(chars != NULL) {
|
||||
if(out != NULL && out_size > 0)
|
||||
snprintf(out, (size_t)out_size, "%s", chars);
|
||||
(*env)->ReleaseStringUTFChars(env, result, chars);
|
||||
}
|
||||
if(attached)
|
||||
(*jvm)->DetachCurrentThread(jvm);
|
||||
(*env)->DeleteLocalRef(env, result);
|
||||
|
||||
done:
|
||||
activity_env_done(env, jvm, attached);
|
||||
return status;
|
||||
}
|
||||
|
||||
/* ---- Java -> C natives (exported JNI symbols; RegisterNatives from
|
||||
@@ -198,8 +475,18 @@ Java_xyz_waozi_pass_MainActivity_nativeTextInputEnter(JNIEnv *env, jobject thiz)
|
||||
#else /* !ANDROID_BUILD */
|
||||
|
||||
void android_bridge_init(void) {}
|
||||
void android_bridge_apply_system_theme(void) {}
|
||||
int android_bridge_top_reserved(void) { return 0; }
|
||||
int android_bridge_bottom_reserved(void) { return 0; }
|
||||
void android_bridge_set_soft_keyboard(int visible) { (void)visible; }
|
||||
int android_bridge_biometric_available(void) { return 0; }
|
||||
int android_bridge_biometric_setup_required(void) { return 0; }
|
||||
int android_bridge_master_saved(void) { return 0; }
|
||||
int android_bridge_master_biometric(void) { return 0; }
|
||||
void android_bridge_save_master(const char *master, int require_biometric) { (void)master; (void)require_biometric; }
|
||||
void android_bridge_unlock_master(void) {}
|
||||
void android_bridge_clear_master(void) {}
|
||||
int android_bridge_secure_status(void) { return 0; }
|
||||
int android_bridge_take_secure_result(char *out, int out_size) { if(out != NULL && out_size > 0) out[0] = '\0'; return 0; }
|
||||
|
||||
#endif
|
||||
@@ -1,5 +1,5 @@
|
||||
#ifndef GOPASS_ANDROID_BRIDGE_H
|
||||
#define GOPASS_ANDROID_BRIDGE_H
|
||||
#ifndef PASS_ANDROID_BRIDGE_H
|
||||
#define PASS_ANDROID_BRIDGE_H
|
||||
|
||||
#if defined(__cplusplus)
|
||||
extern "C" {
|
||||
@@ -7,6 +7,7 @@ extern "C" {
|
||||
|
||||
/* Call once before InitWindow. */
|
||||
void android_bridge_init(void);
|
||||
void android_bridge_apply_system_theme(void);
|
||||
|
||||
/* Safe-area insets converted to UI units (java px / density). Returns 0
|
||||
* until Java has reported real values; callers should treat 0 as "unknown"
|
||||
@@ -17,6 +18,16 @@ int android_bridge_bottom_reserved(void);
|
||||
/* Shows or hides the soft keyboard through the activity. */
|
||||
void android_bridge_set_soft_keyboard(int visible);
|
||||
|
||||
int android_bridge_biometric_available(void);
|
||||
int android_bridge_biometric_setup_required(void);
|
||||
int android_bridge_master_saved(void);
|
||||
int android_bridge_master_biometric(void);
|
||||
void android_bridge_save_master(const char *master, int require_biometric);
|
||||
void android_bridge_unlock_master(void);
|
||||
void android_bridge_clear_master(void);
|
||||
int android_bridge_secure_status(void);
|
||||
int android_bridge_take_secure_result(char *out, int out_size);
|
||||
|
||||
#if defined(__cplusplus)
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,521 +0,0 @@
|
||||
/* C port of the gopass desktop GUI (gui/main.go) for the Android build.
|
||||
* The desktop branch keeps the Go layout; this port adds a narrow-screen
|
||||
* layout for phones: single column, two-abreast rules, scrollable card. */
|
||||
|
||||
#include "gopass_app.h"
|
||||
#include "gopass_core.h"
|
||||
|
||||
#include "kryon.h"
|
||||
#include "embedded_assets.h"
|
||||
#include "ui_scroll.h"
|
||||
#include "ui_scaling.h"
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#define CLIPBOARD_LIFETIME_MS 20000
|
||||
|
||||
typedef struct {
|
||||
char buffer[1024];
|
||||
int cursor;
|
||||
int focused;
|
||||
int commit;
|
||||
int focus_id;
|
||||
int max_codepoints;
|
||||
int secure;
|
||||
} Field;
|
||||
|
||||
static void
|
||||
field_init(Field *f, int focus_id, int capacity_codepoints)
|
||||
{
|
||||
memset(f, 0, sizeof(*f));
|
||||
f->focus_id = focus_id;
|
||||
f->max_codepoints = capacity_codepoints;
|
||||
}
|
||||
|
||||
static const char *
|
||||
field_text(const Field *f)
|
||||
{
|
||||
return f->buffer;
|
||||
}
|
||||
|
||||
static void
|
||||
field_clear(Field *f)
|
||||
{
|
||||
memset(f->buffer, 0, sizeof(f->buffer));
|
||||
f->cursor = 0;
|
||||
}
|
||||
|
||||
struct GopassApp {
|
||||
Field site, login, master, exclude;
|
||||
int length, counter;
|
||||
int lower, upper, digits, symbols;
|
||||
int reveal;
|
||||
char generated[136];
|
||||
char message[160];
|
||||
/* clipboard lease */
|
||||
char clip_value[136];
|
||||
int64_t clip_expires_ms;
|
||||
int clip_has_value;
|
||||
int scroll_offset;
|
||||
};
|
||||
|
||||
static int64_t
|
||||
now_ms(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
|
||||
}
|
||||
|
||||
static void
|
||||
clipboard_copy(GopassApp *a, const char *value)
|
||||
{
|
||||
SetClipboardText(value);
|
||||
snprintf(a->clip_value, sizeof(a->clip_value), "%s", value);
|
||||
a->clip_expires_ms = now_ms() + CLIPBOARD_LIFETIME_MS;
|
||||
a->clip_has_value = 1;
|
||||
}
|
||||
|
||||
static void
|
||||
clipboard_tick(GopassApp *a)
|
||||
{
|
||||
const char *current;
|
||||
|
||||
if(!a->clip_has_value || now_ms() < a->clip_expires_ms)
|
||||
return;
|
||||
current = GetClipboardText();
|
||||
if(current != NULL && strcmp(current, a->clip_value) == 0)
|
||||
SetClipboardText("");
|
||||
a->clip_has_value = 0;
|
||||
a->clip_value[0] = '\0';
|
||||
}
|
||||
|
||||
static void
|
||||
clipboard_clear(GopassApp *a)
|
||||
{
|
||||
const char *current;
|
||||
|
||||
if(a->clip_has_value) {
|
||||
current = GetClipboardText();
|
||||
if(current != NULL && strcmp(current, a->clip_value) == 0)
|
||||
SetClipboardText("");
|
||||
}
|
||||
a->clip_has_value = 0;
|
||||
a->clip_value[0] = '\0';
|
||||
}
|
||||
|
||||
static void
|
||||
generate(GopassApp *a)
|
||||
{
|
||||
GopassOptions options;
|
||||
char err[160];
|
||||
|
||||
memset(&options, 0, sizeof(options));
|
||||
options.length = a->length;
|
||||
options.counter = (uint64_t)a->counter;
|
||||
options.lowercase = a->lower;
|
||||
options.uppercase = a->upper;
|
||||
options.digits = a->digits;
|
||||
options.symbols = a->symbols;
|
||||
options.exclude = a->exclude.buffer;
|
||||
|
||||
if(gopass_generate(field_text(&a->site), field_text(&a->login),
|
||||
field_text(&a->master), &options,
|
||||
a->generated, sizeof(a->generated),
|
||||
err, sizeof(err)) != 0) {
|
||||
a->generated[0] = '\0';
|
||||
snprintf(a->message, sizeof(a->message), "%s", err);
|
||||
return;
|
||||
}
|
||||
snprintf(a->message, sizeof(a->message), "%s", "Password generated locally");
|
||||
}
|
||||
|
||||
static UITextInputStyle
|
||||
input_style(void)
|
||||
{
|
||||
UIMaterialScheme s = GetUIMaterialScheme();
|
||||
UITextInputStyle style;
|
||||
|
||||
memset(&style, 0, sizeof(style));
|
||||
style.background = s.surface_container;
|
||||
style.border = s.outline;
|
||||
style.focus_border = s.primary;
|
||||
style.text = s.on_surface;
|
||||
style.cursor = s.primary;
|
||||
style.radius = 6.0f;
|
||||
style.padding_x = 10;
|
||||
style.padding_y = 8;
|
||||
return style;
|
||||
}
|
||||
|
||||
static int
|
||||
draw_field(Field *f, Rectangle bounds, int font, UITextInputStyle style)
|
||||
{
|
||||
TextFieldProps props;
|
||||
|
||||
memset(&props, 0, sizeof(props));
|
||||
props.bounds = bounds;
|
||||
props.text = f->buffer;
|
||||
props.text_size = sizeof(f->buffer);
|
||||
props.cursor_position = &f->cursor;
|
||||
props.focused = &f->focused;
|
||||
props.max_codepoints = f->max_codepoints;
|
||||
props.font = font;
|
||||
props.focus_id = f->focus_id;
|
||||
props.style = style;
|
||||
props.commit_pressed = &f->commit;
|
||||
props.secure = f->secure;
|
||||
return DrawUITextField(props);
|
||||
}
|
||||
|
||||
static int
|
||||
button(int x, int y, int w, int h, const char *label, UIButtonStyle style, int disabled)
|
||||
{
|
||||
int hover = 0;
|
||||
|
||||
return DrawUIGenericButton(x, y, w, h, label, style, disabled, &hover);
|
||||
}
|
||||
|
||||
static void
|
||||
checkbox(int x, int y, const char *label, int *value)
|
||||
{
|
||||
DrawUICheckboxToggle(x, y, label, value);
|
||||
}
|
||||
|
||||
static Rectangle
|
||||
scaled_rect(float x, float y, float w, float h)
|
||||
{
|
||||
Rectangle r;
|
||||
|
||||
r.x = (float)ScaleUIPx((int)x);
|
||||
r.y = (float)ScaleUIPx((int)y);
|
||||
r.width = (float)ScaleUIPx((int)w);
|
||||
r.height = (float)ScaleUIPx((int)h);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void
|
||||
label_text(const char *text, int x, int y, int font, Color color)
|
||||
{
|
||||
Text(text, ScaleUIPx(x), ScaleUIPx(y), font, color);
|
||||
}
|
||||
|
||||
GopassApp *
|
||||
gopass_app(void)
|
||||
{
|
||||
static GopassApp app;
|
||||
static int initialized;
|
||||
|
||||
if(!initialized) {
|
||||
initialized = 1;
|
||||
field_init(&app.site, 101, 256);
|
||||
field_init(&app.login, 102, 256);
|
||||
field_init(&app.master, 103, 1024);
|
||||
field_init(&app.exclude, 104, 128);
|
||||
app.length = 16;
|
||||
app.counter = 1;
|
||||
app.lower = app.upper = app.digits = app.symbols = 1;
|
||||
}
|
||||
return &app;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Wide layout: mirrors gui/main.go */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static void
|
||||
draw_wide(GopassApp *a, int width, int height, int top_reserved)
|
||||
{
|
||||
UIMaterialScheme scheme = GetUIMaterialScheme();
|
||||
Color text = GetThemeText();
|
||||
UITextInputStyle style = input_style();
|
||||
int content_w = width - 64;
|
||||
int x, y;
|
||||
|
||||
if(content_w > 720)
|
||||
content_w = 720;
|
||||
x = (width - content_w) / 2;
|
||||
y = 22 + top_reserved;
|
||||
|
||||
DrawRectangleRounded(scaled_rect((float)x, (float)y, 48, 48), 0.22f, 10, scheme.primary);
|
||||
label_text("g", x + 15, y + 7, 32, scheme.on_primary);
|
||||
label_text("gopass", x + 64, y + 2, 32, text);
|
||||
label_text("Private by design - generated on this device",
|
||||
x + 64, y + 38, 14, scheme.on_surface_variant);
|
||||
y += 70;
|
||||
DrawRectangleRounded(scaled_rect((float)x, (float)y, (float)content_w, 550), 0.035f, 10, scheme.surface);
|
||||
DrawRectangleLinesEx(scaled_rect((float)x, (float)y, (float)content_w, 550), 1.0f, scheme.outline);
|
||||
label_text("PASSWORD DETAILS", x + 24, y + 24, 12, scheme.primary);
|
||||
|
||||
y += 54;
|
||||
label_text("Site", x + 24, y, 14, text);
|
||||
draw_field(&a->site, scaled_rect((float)x + 24, (float)y + 24, (float)content_w - 48, 38), 16, style);
|
||||
y += 76;
|
||||
label_text("Login", x + 24, y, 14, text);
|
||||
draw_field(&a->login, scaled_rect((float)x + 24, (float)y + 24, (float)content_w - 48, 38), 16, style);
|
||||
y += 76;
|
||||
label_text("Master password", x + 24, y, 14, text);
|
||||
a->master.secure = !a->reveal;
|
||||
draw_field(&a->master, scaled_rect((float)x + 24, (float)y + 24, (float)content_w - 150, 38), 16, style);
|
||||
if(button(ScaleUIPx(x + content_w - 112), ScaleUIPx(y + 24), ScaleUIPx(88), ScaleUIPx(38),
|
||||
a->reveal ? "Hide" : "Reveal", UI_BUTTON_STYLE_SECONDARY, 0))
|
||||
a->reveal = !a->reveal;
|
||||
y += 76;
|
||||
|
||||
label_text("PASSWORD RULES", x + 24, y - 10, 12, scheme.primary);
|
||||
y += 14;
|
||||
label_text("Length", x + 24, y, 14, text);
|
||||
{
|
||||
SpinboxProps props;
|
||||
|
||||
memset(&props, 0, sizeof(props));
|
||||
props.bounds = scaled_rect((float)x + 24, (float)y + 24, 130, 38);
|
||||
props.id = 301;
|
||||
props.min = 1;
|
||||
props.max = 128;
|
||||
props.step = 1;
|
||||
props.value = &a->length;
|
||||
Spinbox(props);
|
||||
}
|
||||
label_text("Counter", x + 182, y, 14, text);
|
||||
{
|
||||
SpinboxProps props;
|
||||
|
||||
memset(&props, 0, sizeof(props));
|
||||
props.bounds = scaled_rect((float)x + 182, (float)y + 24, 130, 38);
|
||||
props.id = 302;
|
||||
props.min = 1;
|
||||
props.max = 999999;
|
||||
props.step = 1;
|
||||
props.value = &a->counter;
|
||||
Spinbox(props);
|
||||
}
|
||||
draw_field(&a->exclude, scaled_rect((float)x + 340, (float)y + 24, (float)content_w - 364, 38), 16, style);
|
||||
label_text("Excluded characters", x + 340, y, 14, text);
|
||||
y += 76;
|
||||
|
||||
checkbox(ScaleUIPx(x + 24), ScaleUIPx(y), "Lowercase", &a->lower);
|
||||
checkbox(ScaleUIPx(x + 174), ScaleUIPx(y), "Uppercase", &a->upper);
|
||||
checkbox(ScaleUIPx(x + 324), ScaleUIPx(y), "Digits", &a->digits);
|
||||
checkbox(ScaleUIPx(x + 444), ScaleUIPx(y), "Symbols", &a->symbols);
|
||||
y += 48;
|
||||
|
||||
if(button(ScaleUIPx(x + 24), ScaleUIPx(y), ScaleUIPx(150), ScaleUIPx(42),
|
||||
"Generate", UI_BUTTON_STYLE_PRIMARY, 0))
|
||||
generate(a);
|
||||
if(button(ScaleUIPx(x + 190), ScaleUIPx(y), ScaleUIPx(150), ScaleUIPx(42),
|
||||
"Copy for 20s", UI_BUTTON_STYLE_SECONDARY, a->generated[0] == '\0')) {
|
||||
clipboard_copy(a, a->generated);
|
||||
snprintf(a->message, sizeof(a->message), "%s", "Copied; clipboard clears in 20 seconds");
|
||||
}
|
||||
if(button(ScaleUIPx(x + 356), ScaleUIPx(y), ScaleUIPx(120), ScaleUIPx(42),
|
||||
"Clear", UI_BUTTON_STYLE_SECONDARY, 0)) {
|
||||
field_clear(&a->master);
|
||||
a->generated[0] = '\0';
|
||||
snprintf(a->message, sizeof(a->message), "%s", "Cleared");
|
||||
}
|
||||
y += 56;
|
||||
|
||||
DrawRectangleRounded(scaled_rect((float)x + 24, (float)y, (float)content_w - 48, 72), 0.08f, 10, scheme.surface_container);
|
||||
if(a->generated[0] != '\0')
|
||||
label_text(a->generated, x + 42, y + 15, 20, text);
|
||||
else
|
||||
label_text("Your generated password appears here", x + 42, y + 17, 16, scheme.on_surface_variant);
|
||||
if(a->message[0] != '\0')
|
||||
label_text(a->message, x + 42, y + 45, 12, scheme.on_surface_variant);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Narrow phone layout: single column inside a scrollable card */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static void
|
||||
draw_narrow(GopassApp *a, int width, int height, int top_reserved, int bottom_reserved)
|
||||
{
|
||||
UIMaterialScheme scheme = GetUIMaterialScheme();
|
||||
Color text = GetThemeText();
|
||||
UITextInputStyle style = input_style();
|
||||
UIScrollArea area;
|
||||
UIScrollView view;
|
||||
int margin = 12;
|
||||
int card_x = margin;
|
||||
int card_y = top_reserved + 62;
|
||||
int card_w = width - margin * 2;
|
||||
int card_h = height - bottom_reserved - margin - card_y;
|
||||
int pad = 18;
|
||||
int inner_x = card_x + pad;
|
||||
int inner_w = card_w - pad * 2;
|
||||
int half_w = (inner_w - 12) / 2;
|
||||
int content_h;
|
||||
int x, y, cx, cy;
|
||||
Rectangle card;
|
||||
|
||||
if(card_h < 200)
|
||||
card_h = 200;
|
||||
|
||||
/* compact header */
|
||||
DrawRectangleRounded(scaled_rect((float)margin, (float)top_reserved + 8, 40, 40), 0.22f, 10, scheme.primary);
|
||||
label_text("g", margin + 13, top_reserved + 15, 24, scheme.on_primary);
|
||||
label_text("gopass", margin + 52, top_reserved + 6, 24, text);
|
||||
label_text("Private by design \xc2\xb7 generated on this device",
|
||||
margin + 52, top_reserved + 36, 12, scheme.on_surface_variant);
|
||||
|
||||
/* content height (UI units): sections and rows below */
|
||||
content_h = 20 /* section label */
|
||||
+ 3 * 66 /* site, login, master rows */
|
||||
+ 20 + 62 /* rules label + spinbox row */
|
||||
+ 66 /* excluded characters */
|
||||
+ 2 * 36 /* checkbox rows */
|
||||
+ 50 /* generate */
|
||||
+ 50 /* copy/clear row */
|
||||
+ 78 /* result box */
|
||||
+ pad;
|
||||
|
||||
card = scaled_rect((float)card_x, (float)card_y, (float)card_w, (float)card_h);
|
||||
DrawRectangleRounded(card, 0.035f, 10, scheme.surface);
|
||||
DrawRectangleLinesEx(card, 1.0f, scheme.outline);
|
||||
|
||||
memset(&area, 0, sizeof(area));
|
||||
area.bounds = card;
|
||||
area.content_height = ScaleUIPx(content_h);
|
||||
area.content_x = ScaleUIPx(inner_x);
|
||||
area.content_width = ScaleUIPx(inner_w);
|
||||
area.scroll_offset = &a->scroll_offset;
|
||||
view = BeginUIScrollContainer(area);
|
||||
cx = view.content_x;
|
||||
cy = view.content_y;
|
||||
/* positions in UI units relative to content origin */
|
||||
x = 0;
|
||||
y = 0;
|
||||
|
||||
label_text("PASSWORD DETAILS", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 12, scheme.primary);
|
||||
y += 20;
|
||||
|
||||
label_text("Site", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
|
||||
draw_field(&a->site, (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 22)),
|
||||
(float)ScaleUIPx(inner_w), (float)ScaleUIPx(38)}, 16, style);
|
||||
y += 66;
|
||||
|
||||
label_text("Login", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
|
||||
draw_field(&a->login, (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 22)),
|
||||
(float)ScaleUIPx(inner_w), (float)ScaleUIPx(38)}, 16, style);
|
||||
y += 66;
|
||||
|
||||
label_text("Master password", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
|
||||
a->master.secure = !a->reveal;
|
||||
{
|
||||
int field_w = inner_w - 80;
|
||||
|
||||
draw_field(&a->master, (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 22)),
|
||||
(float)ScaleUIPx(field_w), (float)ScaleUIPx(38)}, 16, style);
|
||||
if(button(cx + ScaleUIPx(x + field_w + 8), cy + ScaleUIPx(y + 22), ScaleUIPx(72), ScaleUIPx(38),
|
||||
a->reveal ? "Hide" : "Reveal", UI_BUTTON_STYLE_SECONDARY, 0))
|
||||
a->reveal = !a->reveal;
|
||||
}
|
||||
y += 66;
|
||||
|
||||
label_text("PASSWORD RULES", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 12, scheme.primary);
|
||||
y += 18;
|
||||
label_text("Length", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
|
||||
{
|
||||
SpinboxProps props;
|
||||
|
||||
memset(&props, 0, sizeof(props));
|
||||
props.bounds = (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 20)),
|
||||
(float)ScaleUIPx(half_w), (float)ScaleUIPx(38)};
|
||||
props.id = 301;
|
||||
props.min = 1;
|
||||
props.max = 128;
|
||||
props.step = 1;
|
||||
props.value = &a->length;
|
||||
Spinbox(props);
|
||||
}
|
||||
label_text("Counter", cx + ScaleUIPx(x + half_w + 12), cy + ScaleUIPx(y), 14, text);
|
||||
{
|
||||
SpinboxProps props;
|
||||
|
||||
memset(&props, 0, sizeof(props));
|
||||
props.bounds = (Rectangle){(float)(cx + ScaleUIPx(x + half_w + 12)), (float)(cy + ScaleUIPx(y + 20)),
|
||||
(float)ScaleUIPx(half_w), (float)ScaleUIPx(38)};
|
||||
props.id = 302;
|
||||
props.min = 1;
|
||||
props.max = 999999;
|
||||
props.step = 1;
|
||||
props.value = &a->counter;
|
||||
Spinbox(props);
|
||||
}
|
||||
y += 62;
|
||||
|
||||
label_text("Excluded characters", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
|
||||
draw_field(&a->exclude, (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 22)),
|
||||
(float)ScaleUIPx(inner_w), (float)ScaleUIPx(38)}, 16, style);
|
||||
y += 66;
|
||||
|
||||
checkbox(cx + ScaleUIPx(x), cy + ScaleUIPx(y), "Lowercase", &a->lower);
|
||||
checkbox(cx + ScaleUIPx(x + half_w + 12), cy + ScaleUIPx(y), "Uppercase", &a->upper);
|
||||
y += 36;
|
||||
checkbox(cx + ScaleUIPx(x), cy + ScaleUIPx(y), "Digits", &a->digits);
|
||||
checkbox(cx + ScaleUIPx(x + half_w + 12), cy + ScaleUIPx(y), "Symbols", &a->symbols);
|
||||
y += 44;
|
||||
|
||||
if(button(cx + ScaleUIPx(x), cy + ScaleUIPx(y), ScaleUIPx(inner_w), ScaleUIPx(42),
|
||||
"Generate", UI_BUTTON_STYLE_PRIMARY, 0))
|
||||
generate(a);
|
||||
y += 50;
|
||||
if(button(cx + ScaleUIPx(x), cy + ScaleUIPx(y), ScaleUIPx(half_w), ScaleUIPx(42),
|
||||
"Copy for 20s", UI_BUTTON_STYLE_SECONDARY, a->generated[0] == '\0')) {
|
||||
clipboard_copy(a, a->generated);
|
||||
snprintf(a->message, sizeof(a->message), "%s", "Copied; clipboard clears in 20 seconds");
|
||||
}
|
||||
if(button(cx + ScaleUIPx(x + half_w + 12), cy + ScaleUIPx(y), ScaleUIPx(half_w), ScaleUIPx(42),
|
||||
"Clear", UI_BUTTON_STYLE_SECONDARY, 0)) {
|
||||
field_clear(&a->master);
|
||||
a->generated[0] = '\0';
|
||||
snprintf(a->message, sizeof(a->message), "%s", "Cleared");
|
||||
}
|
||||
y += 50;
|
||||
|
||||
DrawRectangleRounded((Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y)),
|
||||
(float)ScaleUIPx(inner_w), (float)ScaleUIPx(72)}, 0.08f, 10,
|
||||
scheme.surface_container);
|
||||
if(a->generated[0] != '\0')
|
||||
DrawUITextInRect(a->generated,
|
||||
(Rectangle){(float)(cx + ScaleUIPx(x + 14)), (float)(cy + ScaleUIPx(y + 8)),
|
||||
(float)ScaleUIPx(inner_w - 28), (float)ScaleUIPx(40)},
|
||||
16, text);
|
||||
else
|
||||
label_text("Your generated password appears here", x + 14, y + 14, 14, scheme.on_surface_variant);
|
||||
if(a->message[0] != '\0')
|
||||
label_text(a->message, x + 14, y + 50, 11, scheme.on_surface_variant);
|
||||
|
||||
EndUIScrollContainer(area, view);
|
||||
}
|
||||
|
||||
void
|
||||
gopass_app_draw(GopassApp *a, int surface_w, int surface_h, float dpi,
|
||||
int top_reserved, int bottom_reserved)
|
||||
{
|
||||
int ui_w = (int)(surface_w / (dpi > 0.0f ? dpi : 1.0f) + 0.5f);
|
||||
int ui_h = (int)(surface_h / (dpi > 0.0f ? dpi : 1.0f) + 0.5f);
|
||||
|
||||
(void)ui_h;
|
||||
Background(GetThemeBackground());
|
||||
clipboard_tick(a);
|
||||
if(ui_w >= 560)
|
||||
draw_wide(a, ui_w, ui_h, top_reserved);
|
||||
else
|
||||
draw_narrow(a, ui_w, ui_h, top_reserved, bottom_reserved);
|
||||
}
|
||||
|
||||
void
|
||||
gopass_app_shutdown(GopassApp *a)
|
||||
{
|
||||
if(a == NULL)
|
||||
return;
|
||||
field_clear(&a->master);
|
||||
clipboard_clear(a);
|
||||
a->generated[0] = '\0';
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
#ifndef GOPASS_APP_H
|
||||
#define GOPASS_APP_H
|
||||
|
||||
typedef struct GopassApp GopassApp;
|
||||
|
||||
GopassApp *gopass_app(void);
|
||||
|
||||
/* Draws one frame. Surface sizes are physical pixels; dpi is the display
|
||||
* scale. top/bottom_reserved are safe-area insets in UI units (dp). */
|
||||
void gopass_app_draw(GopassApp *app, int surface_w, int surface_h, float dpi,
|
||||
int top_reserved, int bottom_reserved);
|
||||
|
||||
/* Clears secrets held in memory. */
|
||||
void gopass_app_shutdown(GopassApp *app);
|
||||
|
||||
#endif
|
||||
@@ -1,4 +1,4 @@
|
||||
/* Android entry point for gopass. Raylib's Android backend provides
|
||||
/* Android entry point for pass. Raylib's Android backend provides
|
||||
* android_main and calls main(); this file owns window, theme, fonts, and
|
||||
* the frame loop. */
|
||||
|
||||
@@ -7,9 +7,10 @@
|
||||
#include "ui_dpi.h"
|
||||
#include "ui_core.h"
|
||||
#include "ui_scaling.h"
|
||||
#include "ui_text.h"
|
||||
|
||||
#include "android_bridge.h"
|
||||
#include "gopass_app.h"
|
||||
#include "pass_app.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
@@ -20,6 +21,7 @@
|
||||
#endif
|
||||
|
||||
static const char *const FONT_ASSET_PATH = "vendor/kryon/fonts/noto/NotoSans-Regular.ttf";
|
||||
static const char *const EMOJI_FONT_ASSET_PATH = "gui/assets/emoji.ttf";
|
||||
|
||||
/* Kryon's shape drawing rides on a 1x1 white texture so rectangles tint
|
||||
* cleanly on the GL ES surface (same setup inbe performs on Android). */
|
||||
@@ -42,16 +44,35 @@ setup_ui_font(void)
|
||||
const EmbeddedAsset *asset = GetEmbeddedAsset(FONT_ASSET_PATH);
|
||||
|
||||
if(asset == NULL || asset->data == NULL || asset->size == 0) {
|
||||
TraceLog(LOG_WARNING, "GOPASS: missing embedded font asset");
|
||||
TraceLog(LOG_WARNING, "PASS: missing embedded font asset");
|
||||
return 0;
|
||||
}
|
||||
if(!RegisterUIFontSource("ui", GetEmbeddedAssetExtension(FONT_ASSET_PATH),
|
||||
asset->data, asset->size, NULL, 0)) {
|
||||
TraceLog(LOG_WARNING, "GOPASS: RegisterUIFontSource failed");
|
||||
TraceLog(LOG_WARNING, "PASS: RegisterUIFontSource failed");
|
||||
return 0;
|
||||
}
|
||||
if(!UseUIFont("ui")) {
|
||||
TraceLog(LOG_WARNING, "GOPASS: UseUIFont failed");
|
||||
TraceLog(LOG_WARNING, "PASS: UseUIFont failed");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
setup_emoji_font(void)
|
||||
{
|
||||
const EmbeddedAsset *asset = GetEmbeddedAsset(EMOJI_FONT_ASSET_PATH);
|
||||
int codepoint_count = 0;
|
||||
const int *codepoints = pass_app_master_emoji_codepoints(&codepoint_count);
|
||||
|
||||
if(asset == NULL || asset->data == NULL || asset->size == 0) {
|
||||
TraceLog(LOG_WARNING, "PASS: missing embedded emoji font asset");
|
||||
return 0;
|
||||
}
|
||||
if(!RegisterUIFixedFontSource("pass-emoji", GetEmbeddedAssetExtension(EMOJI_FONT_ASSET_PATH),
|
||||
asset->data, asset->size, codepoints, codepoint_count)) {
|
||||
TraceLog(LOG_WARNING, "PASS: RegisterUIFixedFontSource failed for emoji");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
@@ -60,32 +81,36 @@ setup_ui_font(void)
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
GopassApp *app;
|
||||
PassApp *app;
|
||||
|
||||
(void)argc;
|
||||
(void)argv;
|
||||
|
||||
#if ANDROID_BUILD
|
||||
__android_log_write(ANDROID_LOG_INFO, "GOPASS_MAIN", "main start");
|
||||
__android_log_write(ANDROID_LOG_INFO, "PASS_MAIN", "main start");
|
||||
android_bridge_init();
|
||||
if(chdir("/data/user/0/xyz.waozi.pass/files") != 0)
|
||||
TraceLog(LOG_WARNING, "GOPASS: failed to switch to files directory");
|
||||
TraceLog(LOG_WARNING, "PASS: failed to switch to files directory");
|
||||
#endif
|
||||
|
||||
InitWindow(0, 0, "gopass");
|
||||
InitWindow(0, 0, "pass");
|
||||
if(!IsWindowReady()) {
|
||||
TraceLog(LOG_ERROR, "GOPASS: InitWindow failed");
|
||||
TraceLog(LOG_ERROR, "PASS: InitWindow failed");
|
||||
return 1;
|
||||
}
|
||||
InitUIDPI();
|
||||
SetThemeStyle(THEME_STYLE_MATERIAL);
|
||||
SetCurrentTheme(11, 1); /* Cobalt dark, same as the desktop GUI */
|
||||
SetCurrentTheme(GetDefaultThemeForThemeStyle(THEME_STYLE_MATERIAL), 0);
|
||||
android_bridge_apply_system_theme();
|
||||
SetThemeSource(THEME_SOURCE_SYSTEM);
|
||||
SetThemeMode(THEME_MODE_SYSTEM);
|
||||
setup_ui_font();
|
||||
setup_emoji_font();
|
||||
setup_shapes_texture();
|
||||
SetUITextInputPlatformCallback(android_bridge_set_soft_keyboard);
|
||||
SetTargetFPS(60);
|
||||
|
||||
app = gopass_app();
|
||||
app = pass_app();
|
||||
while(!WindowShouldClose()) {
|
||||
int width = GetScreenWidth();
|
||||
int height = GetScreenHeight();
|
||||
@@ -94,14 +119,14 @@ main(int argc, char **argv)
|
||||
|
||||
BeginDrawing();
|
||||
BeginUIFrame(width, height, dpi);
|
||||
gopass_app_draw(app, width, height, dpi,
|
||||
pass_app_draw(app, width, height, dpi,
|
||||
android_bridge_top_reserved(),
|
||||
android_bridge_bottom_reserved());
|
||||
EndUIFrame();
|
||||
EndDrawing();
|
||||
}
|
||||
|
||||
gopass_app_shutdown(app);
|
||||
pass_app_shutdown(app);
|
||||
CloseWindow();
|
||||
return 0;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,17 @@
|
||||
#ifndef PASS_APP_H
|
||||
#define PASS_APP_H
|
||||
|
||||
typedef struct PassApp PassApp;
|
||||
|
||||
PassApp *pass_app(void);
|
||||
const int *pass_app_master_emoji_codepoints(int *count);
|
||||
|
||||
/* Draws one frame. Surface sizes are physical pixels; dpi is the display
|
||||
* scale. top/bottom_reserved are safe-area insets in UI units (dp). */
|
||||
void pass_app_draw(PassApp *app, int surface_w, int surface_h, float dpi,
|
||||
int top_reserved, int bottom_reserved);
|
||||
|
||||
/* Clears secrets held in memory. */
|
||||
void pass_app_shutdown(PassApp *app);
|
||||
|
||||
#endif
|
||||
@@ -1,9 +1,19 @@
|
||||
package xyz.waozi.pass;
|
||||
|
||||
import android.app.NativeActivity;
|
||||
import android.app.KeyguardManager;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.content.res.Configuration;
|
||||
import android.graphics.Insets;
|
||||
import android.hardware.biometrics.BiometricPrompt;
|
||||
import android.hardware.fingerprint.FingerprintManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.CancellationSignal;
|
||||
import android.security.keystore.KeyGenParameterSpec;
|
||||
import android.security.keystore.KeyProperties;
|
||||
import android.util.TypedValue;
|
||||
import android.view.DisplayCutout;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.View;
|
||||
@@ -12,11 +22,30 @@ import android.view.WindowInsets;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.content.Context;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyStore;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
|
||||
/**
|
||||
* NativeActivity glue for the kryon UI: routes soft-keyboard input and
|
||||
* window insets to the native side. Modeled on inbe's MainActivity.
|
||||
*/
|
||||
public class MainActivity extends NativeActivity {
|
||||
private static final String SECURE_PREFS = "pass_secure";
|
||||
private static final String KEY_ALIAS = "pass_master_key";
|
||||
private static final String PREF_CIPHERTEXT = "master_ciphertext";
|
||||
private static final String PREF_IV = "master_iv";
|
||||
private static final String PREF_BIOMETRIC = "master_biometric";
|
||||
private static final int SECURE_IDLE = 0;
|
||||
private static final int SECURE_PENDING = 1;
|
||||
private static final int SECURE_OK = 2;
|
||||
private static final int SECURE_ERROR = 3;
|
||||
|
||||
static {
|
||||
// Associate libmain with this class's loader so ART can resolve the
|
||||
// native methods below (NativeActivity loads it via the boot loader).
|
||||
@@ -24,6 +53,9 @@ public class MainActivity extends NativeActivity {
|
||||
}
|
||||
|
||||
private int lastDeleteRepeatCount = -1;
|
||||
private final Object secureLock = new Object();
|
||||
private int secureStatus = SECURE_IDLE;
|
||||
private String secureResult = "";
|
||||
|
||||
private native void nativeSetInsets(int status, int nav,
|
||||
int cutoutLeft, int cutoutTop, int cutoutRight, int cutoutBottom);
|
||||
@@ -35,9 +67,305 @@ public class MainActivity extends NativeActivity {
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
applySystemBars();
|
||||
setupInsetsListener();
|
||||
}
|
||||
|
||||
public int[] systemThemeColors() {
|
||||
boolean dark = (getResources().getConfiguration().uiMode
|
||||
& Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
|
||||
int background = dark ? 0xFF141218 : 0xFFFFFBFE;
|
||||
int surface = dark ? 0xFF211F26 : 0xFFF7F2FA;
|
||||
int text = dark ? 0xFFE6E0E9 : 0xFF1D1B20;
|
||||
int accent = resolveThemeColor(android.R.attr.colorAccent,
|
||||
dark ? 0xFFD0BCFF : 0xFF6750A4);
|
||||
int control = dark ? 0xFFE6E0E9 : 0xFF1D1B20;
|
||||
int button = blend(accent, background, dark ? 65 : 80);
|
||||
int buttonHover = blend(accent, background, dark ? 45 : 60);
|
||||
|
||||
return new int[] {
|
||||
dark ? 1 : 0,
|
||||
background,
|
||||
surface,
|
||||
text,
|
||||
accent,
|
||||
button,
|
||||
buttonHover,
|
||||
control,
|
||||
accent
|
||||
};
|
||||
}
|
||||
|
||||
private void applySystemBars() {
|
||||
int[] colors = systemThemeColors();
|
||||
boolean dark = colors[0] != 0;
|
||||
getWindow().setStatusBarColor(colors[1]);
|
||||
getWindow().setNavigationBarColor(colors[1]);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
int flags = getWindow().getDecorView().getSystemUiVisibility();
|
||||
if (!dark) {
|
||||
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
|
||||
}
|
||||
} else {
|
||||
flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
flags &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
|
||||
}
|
||||
}
|
||||
getWindow().getDecorView().setSystemUiVisibility(flags);
|
||||
}
|
||||
}
|
||||
|
||||
private int resolveThemeColor(int attr, int fallback) {
|
||||
TypedValue value = new TypedValue();
|
||||
if (!getTheme().resolveAttribute(attr, value, true)) {
|
||||
return fallback;
|
||||
}
|
||||
if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
|
||||
&& value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
|
||||
return value.data;
|
||||
}
|
||||
if (value.resourceId != 0) {
|
||||
try {
|
||||
ColorStateList list;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
list = getResources().getColorStateList(value.resourceId, getTheme());
|
||||
} else {
|
||||
list = getResources().getColorStateList(value.resourceId);
|
||||
}
|
||||
if (list != null) {
|
||||
return list.getDefaultColor();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private static int blend(int from, int to, int percentTo) {
|
||||
int p = Math.max(0, Math.min(100, percentTo));
|
||||
int a = (((from >>> 24) & 0xff) * (100 - p) + ((to >>> 24) & 0xff) * p) / 100;
|
||||
int r = (((from >>> 16) & 0xff) * (100 - p) + ((to >>> 16) & 0xff) * p) / 100;
|
||||
int g = (((from >>> 8) & 0xff) * (100 - p) + ((to >>> 8) & 0xff) * p) / 100;
|
||||
int b = ((from & 0xff) * (100 - p) + (to & 0xff) * p) / 100;
|
||||
return (a << 24) | (r << 16) | (g << 8) | b;
|
||||
}
|
||||
|
||||
public boolean hasStoredMasterPassword() {
|
||||
SharedPreferences prefs = getSharedPreferences(SECURE_PREFS, MODE_PRIVATE);
|
||||
return prefs.contains(PREF_CIPHERTEXT) && prefs.contains(PREF_IV);
|
||||
}
|
||||
|
||||
public boolean isStoredMasterBiometric() {
|
||||
return getSharedPreferences(SECURE_PREFS, MODE_PRIVATE).getBoolean(PREF_BIOMETRIC, false);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public boolean isBiometricAvailable() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
|
||||
try {
|
||||
FingerprintManager fm = (FingerprintManager)getSystemService(Context.FINGERPRINT_SERVICE);
|
||||
if (fm != null && fm.isHardwareDetected() && fm.hasEnrolledFingerprints()) return true;
|
||||
} catch (SecurityException ignored) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public boolean isBiometricSetupRequired() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
|
||||
try {
|
||||
FingerprintManager fm = (FingerprintManager)getSystemService(Context.FINGERPRINT_SERVICE);
|
||||
if (fm == null || !fm.isHardwareDetected()) return false;
|
||||
KeyguardManager km = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
|
||||
return !fm.hasEnrolledFingerprints() || km == null || !km.isDeviceSecure();
|
||||
} catch (SecurityException ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String biometricUnavailableMessage() {
|
||||
if (isBiometricSetupRequired()) {
|
||||
return "Set up Android screen lock and fingerprint first";
|
||||
}
|
||||
return "Biometric unlock is not available on this device";
|
||||
}
|
||||
|
||||
public int secureMasterStatus() {
|
||||
synchronized (secureLock) {
|
||||
return secureStatus;
|
||||
}
|
||||
}
|
||||
|
||||
public String takeSecureMasterResult() {
|
||||
synchronized (secureLock) {
|
||||
String value = secureResult == null ? "" : secureResult;
|
||||
secureResult = "";
|
||||
secureStatus = SECURE_IDLE;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public void saveMasterPassword(final String master, final boolean requireBiometric) {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (master == null || master.length() == 0) {
|
||||
setSecureError("Enter a master password first");
|
||||
return;
|
||||
}
|
||||
if (requireBiometric && !isBiometricAvailable()) {
|
||||
setSecureError(biometricUnavailableMessage());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateMasterKey());
|
||||
byte[] encrypted = cipher.doFinal(master.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] iv = cipher.getIV();
|
||||
if (iv == null || iv.length == 0) {
|
||||
setSecureError("Save failed: missing encryption IV");
|
||||
return;
|
||||
}
|
||||
|
||||
SharedPreferences.Editor editor = getSharedPreferences(SECURE_PREFS, MODE_PRIVATE).edit();
|
||||
editor.putString(PREF_IV, b64(iv));
|
||||
editor.putString(PREF_CIPHERTEXT, b64(encrypted));
|
||||
editor.putBoolean(PREF_BIOMETRIC, requireBiometric);
|
||||
editor.apply();
|
||||
setSecureOk("Master password saved");
|
||||
} catch (Exception e) {
|
||||
setSecureError("Save failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void unlockMasterPassword() {
|
||||
if (!hasStoredMasterPassword()) {
|
||||
setSecureError("No saved master password");
|
||||
return;
|
||||
}
|
||||
if (isStoredMasterBiometric()) {
|
||||
authenticateThenDecrypt();
|
||||
return;
|
||||
}
|
||||
decryptStoredMaster();
|
||||
}
|
||||
|
||||
public void clearMasterPassword() {
|
||||
getSharedPreferences(SECURE_PREFS, MODE_PRIVATE).edit().clear().apply();
|
||||
setSecureOk("Saved master password removed");
|
||||
}
|
||||
|
||||
private void authenticateThenDecrypt() {
|
||||
if (!isBiometricAvailable()) {
|
||||
setSecureError(biometricUnavailableMessage());
|
||||
return;
|
||||
}
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
|
||||
setSecureError("Biometric prompt requires Android 9 or newer");
|
||||
return;
|
||||
}
|
||||
synchronized (secureLock) {
|
||||
secureStatus = SECURE_PENDING;
|
||||
secureResult = "Waiting for biometric unlock";
|
||||
}
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Executor executor = new Executor() {
|
||||
@Override
|
||||
public void execute(Runnable command) {
|
||||
runOnUiThread(command);
|
||||
}
|
||||
};
|
||||
BiometricPrompt prompt = new BiometricPrompt.Builder(MainActivity.this)
|
||||
.setTitle("Unlock master password")
|
||||
.setSubtitle("Use your fingerprint or device credential")
|
||||
.setDescription("pass will decrypt the saved master password after unlock")
|
||||
.setNegativeButton("Cancel", executor, (dialog, which) -> setSecureError("Unlock canceled"))
|
||||
.build();
|
||||
prompt.authenticate(new CancellationSignal(), executor,
|
||||
new BiometricPrompt.AuthenticationCallback() {
|
||||
@Override
|
||||
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
|
||||
decryptStoredMaster();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAuthenticationError(int errorCode, CharSequence errString) {
|
||||
setSecureError(errString == null ? "Unlock failed" : errString.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAuthenticationFailed() {
|
||||
setSecureError("Biometric unlock failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void decryptStoredMaster() {
|
||||
try {
|
||||
SharedPreferences prefs = getSharedPreferences(SECURE_PREFS, MODE_PRIVATE);
|
||||
String ivText = prefs.getString(PREF_IV, "");
|
||||
String encryptedText = prefs.getString(PREF_CIPHERTEXT, "");
|
||||
if (ivText.length() == 0 || encryptedText.length() == 0) {
|
||||
setSecureError("No saved master password");
|
||||
return;
|
||||
}
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, getOrCreateMasterKey(), new GCMParameterSpec(128, unb64(ivText)));
|
||||
byte[] decrypted = cipher.doFinal(unb64(encryptedText));
|
||||
setSecureOk(new String(decrypted, StandardCharsets.UTF_8));
|
||||
} catch (Exception e) {
|
||||
setSecureError("Unlock failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private SecretKey getOrCreateMasterKey() throws Exception {
|
||||
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
|
||||
keyStore.load(null);
|
||||
if (keyStore.containsAlias(KEY_ALIAS)) {
|
||||
return (SecretKey)keyStore.getKey(KEY_ALIAS, null);
|
||||
}
|
||||
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
|
||||
KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(
|
||||
KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setRandomizedEncryptionRequired(true)
|
||||
.build();
|
||||
generator.init(spec);
|
||||
return generator.generateKey();
|
||||
}
|
||||
|
||||
private void setSecureOk(String value) {
|
||||
synchronized (secureLock) {
|
||||
secureStatus = SECURE_OK;
|
||||
secureResult = value == null ? "" : value;
|
||||
}
|
||||
}
|
||||
|
||||
private void setSecureError(String value) {
|
||||
synchronized (secureLock) {
|
||||
secureStatus = SECURE_ERROR;
|
||||
secureResult = value == null ? "Secure storage failed" : value;
|
||||
}
|
||||
}
|
||||
|
||||
private static String b64(byte[] data) {
|
||||
return android.util.Base64.encodeToString(data, android.util.Base64.NO_WRAP);
|
||||
}
|
||||
|
||||
private static byte[] unb64(String text) {
|
||||
return android.util.Base64.decode(text, android.util.Base64.NO_WRAP);
|
||||
}
|
||||
|
||||
public void setSoftKeyboardVisible(final boolean visible) {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">gopass</string>
|
||||
<string name="app_name">pass</string>
|
||||
</resources>
|
||||
@@ -13,5 +13,5 @@ dependencyResolutionManagement {
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "gopass"
|
||||
rootProject.name = "pass"
|
||||
include ':app'
|
||||
@@ -1,3 +1,5 @@
|
||||
module github.com/waozixyz/gopass
|
||||
module github.com/waozixyz/pass
|
||||
|
||||
go 1.24
|
||||
|
||||
require github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc
|
||||
@@ -0,0 +1,2 @@
|
||||
github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc h1:7D+Bh06CRPCJO3gr2F7h1sriovOZ8BMhca2Rg85c2nk=
|
||||
github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
+5
-1
@@ -13,11 +13,15 @@ type clipboardLease struct {
|
||||
func (c *clipboardLease) copy(value string, lifetime time.Duration) {
|
||||
c.write(value)
|
||||
c.value = value
|
||||
if lifetime <= 0 {
|
||||
c.expires = time.Time{}
|
||||
return
|
||||
}
|
||||
c.expires = c.now().Add(lifetime)
|
||||
}
|
||||
|
||||
func (c *clipboardLease) tick() bool {
|
||||
if c.value == "" || c.now().Before(c.expires) {
|
||||
if c.value == "" || c.expires.IsZero() || c.now().Before(c.expires) {
|
||||
return false
|
||||
}
|
||||
if c.read() == c.value {
|
||||
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
module github.com/waozixyz/gopass/gui
|
||||
module github.com/waozixyz/pass/gui
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/waozixyz/gopass v0.0.0
|
||||
github.com/waozixyz/pass v0.0.0
|
||||
github.com/waozixyz/kryon/go/kryui v0.0.0
|
||||
)
|
||||
|
||||
replace github.com/waozixyz/gopass => ..
|
||||
replace github.com/waozixyz/pass => ..
|
||||
|
||||
replace github.com/waozixyz/kryon/go/kryui => ../vendor/kryon/go/kryui
|
||||
+310
-50
@@ -2,14 +2,24 @@ package main
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
password "github.com/waozixyz/gopass"
|
||||
"github.com/waozixyz/kryon/go/kryui"
|
||||
password "github.com/waozixyz/pass"
|
||||
)
|
||||
|
||||
const clipboardLifetime = 20 * time.Second
|
||||
|
||||
type appView int
|
||||
|
||||
const (
|
||||
viewGenerate appView = iota
|
||||
viewProfiles
|
||||
viewSettings
|
||||
)
|
||||
|
||||
//go:embed icon.png
|
||||
var appIconPNG []byte
|
||||
|
||||
@@ -18,114 +28,244 @@ var emojiFontTTF []byte
|
||||
|
||||
type app struct {
|
||||
site, login, master, exclude *kryui.TextFieldState
|
||||
profileName *kryui.TextFieldState
|
||||
length, counter int32
|
||||
lower, upper, digits, symbols bool
|
||||
reveal bool
|
||||
generated, message, fingerprint string
|
||||
clipboard clipboardLease
|
||||
clearAfter int32
|
||||
view appView
|
||||
settings guiSettings
|
||||
config guiConfig
|
||||
profiles []profileEntry
|
||||
selectedProfile int
|
||||
}
|
||||
|
||||
func newApp() *app {
|
||||
return &app{
|
||||
cfg, err := loadGUIConfig()
|
||||
a := &app{
|
||||
site: kryui.NewTextField(101, 256), login: kryui.NewTextField(102, 256),
|
||||
master: kryui.NewPasswordField(103, 1024), exclude: kryui.NewTextField(104, 128),
|
||||
length: 16, counter: 1, lower: true, upper: true, digits: true, symbols: true,
|
||||
clipboard: clipboardLease{read: kryui.GetClipboardText, write: kryui.SetClipboardText, now: time.Now},
|
||||
profileName: kryui.NewTextField(105, 64),
|
||||
length: 16, counter: 1, lower: true, upper: true, digits: true, symbols: true,
|
||||
clipboard: clipboardLease{read: kryui.GetClipboardText, write: kryui.SetClipboardText, now: time.Now},
|
||||
settings: cfg.Settings,
|
||||
config: cfg,
|
||||
profiles: sortedProfiles(cfg.Profiles),
|
||||
clearAfter: int32(cfg.Settings.ClearAfter),
|
||||
view: viewGenerate,
|
||||
selectedProfile: -1,
|
||||
}
|
||||
if err != nil {
|
||||
a.message = err.Error()
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func main() {
|
||||
kryui.SetConfigFlags(kryui.FlagWindowResizable)
|
||||
kryui.InitWindow(720, 690, "gopass")
|
||||
defer kryui.CloseWindow()
|
||||
kryui.InitWindow(720, 740, "pass")
|
||||
icon := kryui.LoadImageFromMemory(".png", appIconPNG)
|
||||
kryui.SetWindowIcon(icon)
|
||||
kryui.UnloadImage(icon)
|
||||
kryui.SetThemeStyle(kryui.ThemeStyleMaterial)
|
||||
kryui.SetCurrentTheme(11, true) // Cobalt dark
|
||||
kryui.SetCurrentTheme(11, true) // Cobalt dark (fallback palette)
|
||||
// Follow the system palette by default; Cobalt dark is the fallback when
|
||||
// no system theme can be read.
|
||||
kryui.SetThemeSource(kryui.ThemeSourceSystem)
|
||||
kryui.SetThemeMode(kryui.ThemeModeSystem)
|
||||
kryui.EnsureUIDefaultFont()
|
||||
// The emoji fingerprint font serves only the master-password emoji
|
||||
// codepoints; all other glyphs keep coming from the theme font.
|
||||
kryui.RegisterUIFixedFontData("gopass-emoji", ".ttf", emojiFontTTF, password.MasterEmojiCodepoints())
|
||||
kryui.RegisterUIFixedFontData("pass-emoji", ".ttf", emojiFontTTF, password.MasterEmojiCodepoints())
|
||||
kryui.SetWindowMinSize(560, 620)
|
||||
kryui.EnableEventWaiting()
|
||||
|
||||
a := newApp()
|
||||
defer func() { a.master.Clear(); a.clipboard.clear() }()
|
||||
for !kryui.WindowShouldClose() {
|
||||
updateCheckStart()
|
||||
for !kryui.WindowShouldClose() && !updateQuitRequested() {
|
||||
a.clipboard.tick()
|
||||
updatePoll()
|
||||
kryui.BeginDrawing()
|
||||
w := kryui.GetScreenWidth()
|
||||
kryui.BeginUI(kryui.Key("gopass/main"))
|
||||
kryui.BeginUI(kryui.Key("pass/main"))
|
||||
a.draw(w)
|
||||
kryui.EndUI()
|
||||
a.handleUIEvents()
|
||||
kryui.EndDrawing()
|
||||
}
|
||||
a.master.Clear()
|
||||
a.clipboard.clear()
|
||||
kryui.CloseWindow()
|
||||
// With the window down and secrets cleared, a pending update re-execs
|
||||
// the staged AppImage here.
|
||||
updateExecAfterUI()
|
||||
}
|
||||
|
||||
func (a *app) draw(width int32) {
|
||||
bg, text := kryui.GetThemeBackground(), kryui.GetThemeText()
|
||||
bg := kryui.GetThemeBackground()
|
||||
scheme := kryui.GetUIMaterialScheme()
|
||||
height := kryui.GetScreenHeight()
|
||||
kryui.ClearBackground(bg)
|
||||
contentW := width - 64
|
||||
if contentW > 720 {
|
||||
contentW = 720
|
||||
}
|
||||
x := (width - contentW) / 2
|
||||
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x), 22, 48, 48), .22, 10, scheme.Primary)
|
||||
kryui.DrawUIText("g", x+15, 29, kryui.UIText32, scheme.OnPrimary)
|
||||
kryui.DrawUIText("gopass", x+64, 24, kryui.UIText32, text)
|
||||
kryui.DrawUIText("Private by design · generated on this device", x+64, 60, kryui.UIText14, scheme.OnSurfaceVariant)
|
||||
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x), 92, float32(contentW), 550), .035, 10, scheme.Surface)
|
||||
kryui.DrawRectangleLinesEx(kryui.NewRectangle(float32(x), 92, float32(contentW), 550), 1, scheme.Outline)
|
||||
kryui.DrawUIText("PASSWORD DETAILS", x+24, 116, kryui.UIText12, scheme.Primary)
|
||||
cardH := height - 104
|
||||
if cardH < 520 {
|
||||
cardH = 520
|
||||
}
|
||||
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x), 22, float32(contentW), float32(cardH)), .035, 10, scheme.Surface)
|
||||
kryui.DrawRectangleLinesEx(kryui.NewRectangle(float32(x), 22, float32(contentW), float32(cardH)), 1, scheme.Outline)
|
||||
|
||||
style := inputStyle()
|
||||
y := int32(146)
|
||||
a.field("Site", a.site, x+24, y, contentW-48, style)
|
||||
y := int32(46)
|
||||
switch a.view {
|
||||
case viewProfiles:
|
||||
a.drawProfiles(x+24, y, contentW-48, style)
|
||||
case viewSettings:
|
||||
a.drawSettings(x+24, y, contentW-48)
|
||||
default:
|
||||
a.drawGenerate(x+24, y, contentW-48, style)
|
||||
}
|
||||
|
||||
a.drawBottomNav(width, height)
|
||||
a.updateDrawRow(x+24, 22+cardH+18, contentW-48)
|
||||
}
|
||||
|
||||
func (a *app) drawBottomNav(width, height int32) {
|
||||
result := kryui.BottomNav(kryui.BottomNavProps{
|
||||
ViewWidth: width,
|
||||
ViewHeight: height,
|
||||
Items: []kryui.BottomNavItem{
|
||||
{Route: int32(viewGenerate), Label: "Generate", Active: a.view == viewGenerate},
|
||||
{Route: int32(viewProfiles), Label: "Profiles", Active: a.view == viewProfiles},
|
||||
{Route: int32(viewSettings), Label: "Settings", Active: a.view == viewSettings},
|
||||
},
|
||||
})
|
||||
if result.ClickedRoute >= int32(viewGenerate) && result.ClickedRoute <= int32(viewSettings) {
|
||||
a.view = appView(result.ClickedRoute)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *app) drawGenerate(x, y, width int32, style kryui.UITextInputStyle) {
|
||||
text := kryui.GetThemeText()
|
||||
scheme := kryui.GetUIMaterialScheme()
|
||||
kryui.DrawUIText("PASSWORD DETAILS", x, y, kryui.UIText12, scheme.Primary)
|
||||
y += 30
|
||||
a.field("Site", a.site, x, y, width, style)
|
||||
y += 76
|
||||
a.field("Login", a.login, x+24, y, contentW-48, style)
|
||||
a.field("Login", a.login, x, y, width, style)
|
||||
y += 76
|
||||
kryui.DrawUIText("Master password", x+24, y, kryui.UIText14, text)
|
||||
kryui.DrawUIText("Master password", x, y, kryui.UIText14, text)
|
||||
a.master.SetSecure(!a.reveal)
|
||||
kryui.TextField(a.master, kryui.FieldProps{Bounds: kryui.NewRectangle(float32(x+24), float32(y+24), float32(contentW-150), 38), Font: kryui.UIText16, Style: style})
|
||||
if a.fingerprint != "" {
|
||||
fontToken := kryui.PushUIFont("gopass-emoji")
|
||||
width := kryui.MeasureText(a.fingerprint, kryui.UIText16)
|
||||
kryui.DrawUIText(a.fingerprint, x+contentW-24-width, y, kryui.UIText16, scheme.OnSurfaceVariant)
|
||||
kryui.TextField(a.master, kryui.FieldProps{Bounds: kryui.NewRectangle(float32(x), float32(y+24), float32(width-126), 38), Font: kryui.UIText16, Style: style})
|
||||
if a.settings.ShowFingerprint && a.fingerprint != "" {
|
||||
fontToken := kryui.PushUIFont("pass-emoji")
|
||||
fpWidth := kryui.MeasureText(a.fingerprint, kryui.UIText16)
|
||||
kryui.DrawUIText(a.fingerprint, x+width-fpWidth, y, kryui.UIText16, scheme.OnSurfaceVariant)
|
||||
kryui.PopUIFont(fontToken)
|
||||
}
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+contentW-112), float32(y+24), 88, 38), Label: map[bool]string{true: "Hide", false: "Reveal"}[a.reveal], Style: kryui.UIButtonStyleSecondary, ID: 205})
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+width-88), float32(y+24), 88, 38), Label: map[bool]string{true: "Hide", false: "Reveal"}[a.reveal], Style: kryui.UIButtonStyleSecondary, ID: 205})
|
||||
y += 76
|
||||
|
||||
kryui.DrawUIText("PASSWORD RULES", x+24, y-10, kryui.UIText12, scheme.Primary)
|
||||
kryui.DrawUIText("PASSWORD RULES", x, y-10, kryui.UIText12, scheme.Primary)
|
||||
y += 14
|
||||
kryui.DrawUIText("Length", x+24, y, kryui.UIText14, text)
|
||||
kryui.Spinbox(kryui.SpinboxProps{Bounds: kryui.NewRectangle(float32(x+24), float32(y+24), 130, 38), ID: 301, Min: 1, Max: 128, Step: 1, Value: &a.length})
|
||||
kryui.DrawUIText("Counter", x+182, y, kryui.UIText14, text)
|
||||
kryui.Spinbox(kryui.SpinboxProps{Bounds: kryui.NewRectangle(float32(x+182), float32(y+24), 130, 38), ID: 302, Min: 1, Max: 999999, Step: 1, Value: &a.counter})
|
||||
kryui.TextField(a.exclude, kryui.FieldProps{Bounds: kryui.NewRectangle(float32(x+340), float32(y+24), float32(contentW-364), 38), Font: kryui.UIText16, Style: style})
|
||||
kryui.DrawUIText("Excluded characters", x+340, y, kryui.UIText14, text)
|
||||
kryui.DrawUIText("Length", x, y, kryui.UIText14, text)
|
||||
kryui.Spinbox(kryui.SpinboxProps{Bounds: kryui.NewRectangle(float32(x), float32(y+24), 130, 38), ID: 301, Min: 1, Max: 128, Step: 1, Value: &a.length})
|
||||
kryui.DrawUIText("Counter", x+158, y, kryui.UIText14, text)
|
||||
kryui.Spinbox(kryui.SpinboxProps{Bounds: kryui.NewRectangle(float32(x+158), float32(y+24), 130, 38), ID: 302, Min: 1, Max: 999999, Step: 1, Value: &a.counter})
|
||||
kryui.TextField(a.exclude, kryui.FieldProps{Bounds: kryui.NewRectangle(float32(x+316), float32(y+24), float32(width-316), 38), Font: kryui.UIText16, Style: style})
|
||||
kryui.DrawUIText("Excluded characters", x+316, y, kryui.UIText14, text)
|
||||
y += 76
|
||||
|
||||
kryui.DrawUICheckboxToggle(x+24, y, "Lowercase", &a.lower)
|
||||
kryui.DrawUICheckboxToggle(x+174, y, "Uppercase", &a.upper)
|
||||
kryui.DrawUICheckboxToggle(x+324, y, "Digits", &a.digits)
|
||||
kryui.DrawUICheckboxToggle(x+444, y, "Symbols", &a.symbols)
|
||||
kryui.DrawUICheckboxToggle(x, y, "Lowercase", &a.lower)
|
||||
kryui.DrawUICheckboxToggle(x+150, y, "Uppercase", &a.upper)
|
||||
kryui.DrawUICheckboxToggle(x+300, y, "Digits", &a.digits)
|
||||
kryui.DrawUICheckboxToggle(x+420, y, "Symbols", &a.symbols)
|
||||
y += 48
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+24), float32(y), 150, 42), Label: "Generate", Style: kryui.UIButtonStylePrimary, ID: 401})
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+190), float32(y), 150, 42), Label: "Copy for 20s", Style: kryui.UIButtonStyleSecondary, ID: 402, Disabled: a.generated == ""})
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+356), float32(y), 120, 42), Label: "Clear", Style: kryui.UIButtonStyleSecondary, ID: 403})
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x), float32(y), 150, 42), Label: "Generate", Style: kryui.UIButtonStylePrimary, ID: 401})
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+166), float32(y), 150, 42), Label: "Copy", Style: kryui.UIButtonStyleSecondary, ID: 402, Disabled: a.generated == ""})
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+332), float32(y), 120, 42), Label: "Clear", Style: kryui.UIButtonStyleSecondary, ID: 403})
|
||||
y += 56
|
||||
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x+24), float32(y), float32(contentW-48), 72), .08, 10, scheme.SurfaceContainer)
|
||||
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x), float32(y), float32(width), 72), .08, 10, scheme.SurfaceContainer)
|
||||
if a.generated != "" {
|
||||
kryui.SelectableText(a.generated, x+42, y+15, kryui.UIText20, text)
|
||||
kryui.SelectableText(a.generated, x+18, y+15, kryui.UIText20, text)
|
||||
} else {
|
||||
kryui.DrawUIText("Your generated password appears here", x+42, y+17, kryui.UIText16, scheme.OnSurfaceVariant)
|
||||
kryui.DrawUIText("Your generated password appears here", x+18, y+17, kryui.UIText16, scheme.OnSurfaceVariant)
|
||||
}
|
||||
if a.message != "" {
|
||||
kryui.DrawUIText(a.message, x+42, y+45, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
kryui.DrawUIText(a.message, x+18, y+45, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *app) drawProfiles(x, y, width int32, style kryui.UITextInputStyle) {
|
||||
text := kryui.GetThemeText()
|
||||
scheme := kryui.GetUIMaterialScheme()
|
||||
|
||||
kryui.DrawUIText("PROFILE", x, y, kryui.UIText12, scheme.Primary)
|
||||
y += 30
|
||||
a.field("Name", a.profileName, x, y, width, style)
|
||||
y += 76
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x), float32(y), 154, 42), Label: "Save Current", Style: kryui.UIButtonStylePrimary, ID: 501})
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+170), float32(y), 120, 42), Label: "Delete", Style: kryui.UIButtonStyleSecondary, ID: 502, Disabled: a.selectedProfile < 0})
|
||||
y += 62
|
||||
|
||||
kryui.DrawUIText("SAVED PROFILES", x, y, kryui.UIText12, scheme.Primary)
|
||||
y += 28
|
||||
if len(a.profiles) == 0 {
|
||||
kryui.DrawUIText("No profiles saved yet", x, y, kryui.UIText14, scheme.OnSurfaceVariant)
|
||||
y += 34
|
||||
}
|
||||
for i, p := range a.profiles {
|
||||
if i >= 7 {
|
||||
kryui.DrawUIText(fmt.Sprintf("%d more profiles in settings file", len(a.profiles)-i), x, y+8, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
y += 32
|
||||
break
|
||||
}
|
||||
label := p.Name
|
||||
if p.Data.Site != "" {
|
||||
label = fmt.Sprintf("%s - %s", p.Name, p.Data.Site)
|
||||
}
|
||||
style := kryui.UIButtonStyleSecondary
|
||||
if i == a.selectedProfile {
|
||||
style = kryui.UIButtonStylePrimary
|
||||
}
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x), float32(y), float32(width), 40), Label: label, Style: style, ID: int32(600 + i)})
|
||||
y += 48
|
||||
}
|
||||
if a.message != "" {
|
||||
kryui.DrawUIText(a.message, x, y+8, kryui.UIText12, text)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *app) drawSettings(x, y, width int32) {
|
||||
text := kryui.GetThemeText()
|
||||
scheme := kryui.GetUIMaterialScheme()
|
||||
|
||||
kryui.DrawUIText("BEHAVIOR", x, y, kryui.UIText12, scheme.Primary)
|
||||
y += 32
|
||||
kryui.DrawUICheckboxToggle(x, y, "Auto-copy after Generate", &a.settings.AutoCopy)
|
||||
y += 42
|
||||
kryui.DrawUICheckboxToggle(x, y, "Show master fingerprint", &a.settings.ShowFingerprint)
|
||||
y += 48
|
||||
kryui.DrawUIText("Clipboard seconds", x, y, kryui.UIText14, text)
|
||||
kryui.Spinbox(kryui.SpinboxProps{Bounds: kryui.NewRectangle(float32(x), float32(y+24), 150, 38), ID: 701, Min: 0, Max: 3600, Step: 5, Value: &a.clearAfter})
|
||||
y += 82
|
||||
|
||||
kryui.DrawUIText("MASTER PASSWORD", x, y, kryui.UIText12, scheme.Primary)
|
||||
y += 30
|
||||
kryui.DrawUIText("Android can save and unlock the master password with system biometrics.", x, y, kryui.UIText14, scheme.OnSurfaceVariant)
|
||||
y += 34
|
||||
kryui.DrawUIText("Desktop keeps the master password only in memory for this session.", x, y, kryui.UIText14, scheme.OnSurfaceVariant)
|
||||
y += 54
|
||||
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x), float32(y), 140, 42), Label: "Save Settings", Style: kryui.UIButtonStylePrimary, ID: 503})
|
||||
y += 58
|
||||
if a.message != "" {
|
||||
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x), float32(y), float32(width), 56), .08, 10, scheme.SurfaceContainer)
|
||||
kryui.DrawUIText(a.message, x+16, y+20, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,14 +293,26 @@ func (a *app) handleUIEvents() {
|
||||
a.generate()
|
||||
case 402:
|
||||
if a.generated != "" {
|
||||
a.clipboard.copy(a.generated, clipboardLifetime)
|
||||
a.message = "Copied; clipboard clears in 20 seconds"
|
||||
a.copyGenerated()
|
||||
}
|
||||
case 403:
|
||||
a.master.Clear()
|
||||
a.fingerprint = ""
|
||||
a.generated = ""
|
||||
a.message = "Cleared"
|
||||
case 501:
|
||||
a.saveCurrentProfile()
|
||||
case 502:
|
||||
a.deleteSelectedProfile()
|
||||
case 503:
|
||||
a.saveSettings()
|
||||
default:
|
||||
if event.Key >= 600 && event.Key < kryui.UIKey(600+len(a.profiles)) {
|
||||
idx := int(event.Key - 600)
|
||||
a.selectedProfile = idx
|
||||
a.applyProfile(a.profiles[idx])
|
||||
a.view = viewGenerate
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,7 +325,115 @@ func (a *app) generate() {
|
||||
a.message = err.Error()
|
||||
return
|
||||
}
|
||||
a.generated, a.message = result, "Password generated locally"
|
||||
a.generated = result
|
||||
if a.settings.AutoCopy {
|
||||
a.copyGenerated()
|
||||
return
|
||||
}
|
||||
a.message = "Password generated locally"
|
||||
}
|
||||
|
||||
func (a *app) copyGenerated() {
|
||||
seconds := int(a.clearAfter)
|
||||
if seconds < 0 {
|
||||
seconds = 0
|
||||
}
|
||||
a.clipboard.copy(a.generated, clipboardDuration(seconds))
|
||||
if seconds > 0 {
|
||||
a.message = fmt.Sprintf("Copied; clipboard clears in %d seconds", seconds)
|
||||
} else {
|
||||
a.message = "Copied"
|
||||
}
|
||||
}
|
||||
|
||||
func clipboardDuration(seconds int) time.Duration {
|
||||
if seconds <= 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
func (a *app) saveSettings() {
|
||||
if a.clearAfter < 0 {
|
||||
a.clearAfter = 0
|
||||
}
|
||||
a.settings.ClearAfter = int(a.clearAfter)
|
||||
a.config.Settings = a.settings
|
||||
if err := saveGUIConfig(a.config); err != nil {
|
||||
a.message = err.Error()
|
||||
return
|
||||
}
|
||||
a.message = "Settings saved"
|
||||
}
|
||||
|
||||
func (a *app) saveCurrentProfile() {
|
||||
name := strings.TrimSpace(a.profileName.Text())
|
||||
if name == "" {
|
||||
a.message = "Enter a profile name"
|
||||
return
|
||||
}
|
||||
if a.config.Profiles == nil {
|
||||
a.config.Profiles = map[string]storedProfile{}
|
||||
}
|
||||
a.config.Profiles[name] = storedProfile{
|
||||
Site: a.site.Text(),
|
||||
Login: a.login.Text(),
|
||||
Counter: uint64(a.counter),
|
||||
Length: int(a.length),
|
||||
Lowercase: a.lower,
|
||||
Uppercase: a.upper,
|
||||
Digits: a.digits,
|
||||
Symbols: a.symbols,
|
||||
Exclude: a.exclude.Text(),
|
||||
}
|
||||
a.config.Settings = a.settings
|
||||
if err := saveGUIConfig(a.config); err != nil {
|
||||
a.message = err.Error()
|
||||
return
|
||||
}
|
||||
a.profiles = sortedProfiles(a.config.Profiles)
|
||||
a.selectedProfile = -1
|
||||
for i, p := range a.profiles {
|
||||
if p.Name == name {
|
||||
a.selectedProfile = i
|
||||
break
|
||||
}
|
||||
}
|
||||
a.message = "Profile saved"
|
||||
}
|
||||
|
||||
func (a *app) deleteSelectedProfile() {
|
||||
if a.selectedProfile < 0 || a.selectedProfile >= len(a.profiles) {
|
||||
return
|
||||
}
|
||||
name := a.profiles[a.selectedProfile].Name
|
||||
delete(a.config.Profiles, name)
|
||||
if err := saveGUIConfig(a.config); err != nil {
|
||||
a.message = err.Error()
|
||||
return
|
||||
}
|
||||
a.profiles = sortedProfiles(a.config.Profiles)
|
||||
a.selectedProfile = -1
|
||||
a.profileName.SetText("")
|
||||
a.message = "Profile deleted"
|
||||
}
|
||||
|
||||
func (a *app) applyProfile(p profileEntry) {
|
||||
a.profileName.SetText(p.Name)
|
||||
a.site.SetText(p.Data.Site)
|
||||
a.login.SetText(p.Data.Login)
|
||||
if p.Data.Counter > 0 {
|
||||
a.counter = int32(p.Data.Counter)
|
||||
}
|
||||
if p.Data.Length > 0 {
|
||||
a.length = int32(p.Data.Length)
|
||||
}
|
||||
a.lower = p.Data.Lowercase
|
||||
a.upper = p.Data.Uppercase
|
||||
a.digits = p.Data.Digits
|
||||
a.symbols = p.Data.Symbols
|
||||
a.exclude.SetText(p.Data.Exclude)
|
||||
a.message = "Profile loaded"
|
||||
}
|
||||
|
||||
func inputStyle() kryui.UITextInputStyle {
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type storedProfile struct {
|
||||
Site string `json:"site,omitempty"`
|
||||
Login string `json:"login"`
|
||||
Counter uint64 `json:"counter,omitempty"`
|
||||
Length int `json:"length,omitempty"`
|
||||
Lowercase bool `json:"lowercase"`
|
||||
Uppercase bool `json:"uppercase"`
|
||||
Digits bool `json:"digits"`
|
||||
Symbols bool `json:"symbols"`
|
||||
Exclude string `json:"exclude,omitempty"`
|
||||
}
|
||||
|
||||
type guiSettings struct {
|
||||
AutoCopy bool `json:"auto_copy"`
|
||||
ClearAfter int `json:"clear_after_seconds"`
|
||||
ShowFingerprint bool `json:"show_fingerprint"`
|
||||
}
|
||||
|
||||
type guiConfig struct {
|
||||
Settings guiSettings `json:"settings"`
|
||||
Profiles map[string]storedProfile `json:"profiles"`
|
||||
}
|
||||
|
||||
type profileEntry struct {
|
||||
Name string
|
||||
Data storedProfile
|
||||
}
|
||||
|
||||
func defaultGUISettings() guiSettings {
|
||||
return guiSettings{ClearAfter: 20, ShowFingerprint: true}
|
||||
}
|
||||
|
||||
func configFilePath() string {
|
||||
if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" {
|
||||
return filepath.Join(dir, "pass", "profiles.json")
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, ".config", "pass", "profiles.json")
|
||||
}
|
||||
|
||||
func loadGUIConfig() (guiConfig, error) {
|
||||
cfg := guiConfig{Settings: defaultGUISettings(), Profiles: map[string]storedProfile{}}
|
||||
path := configFilePath()
|
||||
if path == "" {
|
||||
return cfg, nil
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return cfg, nil
|
||||
}
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return cfg, nil
|
||||
}
|
||||
if err := json.Unmarshal(raw, &cfg); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if cfg.Profiles == nil {
|
||||
cfg.Profiles = map[string]storedProfile{}
|
||||
}
|
||||
if cfg.Settings.ClearAfter < 0 {
|
||||
cfg.Settings.ClearAfter = 0
|
||||
}
|
||||
if cfg.Settings.ClearAfter == 0 && !cfg.Settings.AutoCopy {
|
||||
cfg.Settings.ClearAfter = 20
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func saveGUIConfig(cfg guiConfig) error {
|
||||
path := configFilePath()
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(raw, '\n'), 0o600)
|
||||
}
|
||||
|
||||
func sortedProfiles(profiles map[string]storedProfile) []profileEntry {
|
||||
names := make([]string, 0, len(profiles))
|
||||
for name := range profiles {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
out := make([]profileEntry, 0, len(names))
|
||||
for _, name := range names {
|
||||
out = append(out, profileEntry{Name: name, Data: profiles[name]})
|
||||
}
|
||||
return out
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package main
|
||||
|
||||
// Desktop update flow over kryon's kry_update_flow: check the release
|
||||
// appcast once per session, toast when a newer pass exists, and offer
|
||||
// download + restart in a small row under the main card. AppImage builds
|
||||
// self-update (verified download, atomic swap, re-exec); tarball, deb and
|
||||
// source installs stay on the release link.
|
||||
|
||||
import (
|
||||
"github.com/waozixyz/kryon/go/kryui"
|
||||
password "github.com/waozixyz/pass"
|
||||
)
|
||||
|
||||
const appcastURL = "https://github.com/waozixyz/pass/releases/latest/download/appcast.json"
|
||||
|
||||
const updateButtonID = 510
|
||||
|
||||
var (
|
||||
updater *kryui.UpdateFlow
|
||||
updateNoticed bool
|
||||
restartPending bool
|
||||
)
|
||||
|
||||
func updateCheckStart() {
|
||||
updater = kryui.StartUpdateFlow("pass", password.Version, appcastURL)
|
||||
}
|
||||
|
||||
func updatePoll() {
|
||||
if updater == nil {
|
||||
return
|
||||
}
|
||||
updater.Poll()
|
||||
if !updateNoticed && updater.State() == kryui.UpdateFlowAvailable {
|
||||
updateNoticed = true
|
||||
if updater.HasArtifact() {
|
||||
kryui.ShowToast("pass " + updater.NewVersion() + " available — update below")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func updateQuitRequested() bool {
|
||||
return restartPending
|
||||
}
|
||||
|
||||
// updateExecAfterUI re-execs the staged AppImage; call once the window is
|
||||
// closed and secrets are cleared. Does nothing when no restart is pending.
|
||||
func updateExecAfterUI() {
|
||||
if updater != nil && restartPending {
|
||||
updater.ExecPending()
|
||||
}
|
||||
}
|
||||
|
||||
// updateDrawRow renders the update row under the main card. Returns true
|
||||
// when it drew (the layout reserves the space unconditionally once an
|
||||
// update was seen, so the card doesn't jump while states change).
|
||||
func (a *app) updateDrawRow(x, y, width int32) bool {
|
||||
if updater == nil {
|
||||
return false
|
||||
}
|
||||
scheme := kryui.GetUIMaterialScheme()
|
||||
switch updater.State() {
|
||||
case kryui.UpdateFlowAvailable:
|
||||
if !updater.HasArtifact() {
|
||||
// system-managed or source install: one quiet link-out line
|
||||
if updater.ReleaseURL() == "" {
|
||||
return false
|
||||
}
|
||||
kryui.DrawUIText("pass "+updater.NewVersion()+" available", x, y, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
return true
|
||||
}
|
||||
kryui.DrawUIText("pass "+updater.NewVersion()+" available", x, y, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
if kryui.Button(kryui.ButtonProps{
|
||||
Bounds: kryui.NewRectangle(float32(x+width-96), float32(y-14), 96, 32),
|
||||
Label: "Download", Style: kryui.UIButtonStyleSecondary, ID: updateButtonID,
|
||||
}) {
|
||||
updater.Download()
|
||||
}
|
||||
case kryui.UpdateFlowDownloading:
|
||||
pct := int(updater.Progress()*100 + 0.5)
|
||||
if pct < 0 {
|
||||
pct = 0
|
||||
}
|
||||
kryui.DrawUIText("Downloading… "+itoa(pct)+"%", x, y, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
case kryui.UpdateFlowReady:
|
||||
kryui.DrawUIText("pass "+updater.NewVersion()+" ready to install", x, y, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
if kryui.Button(kryui.ButtonProps{
|
||||
Bounds: kryui.NewRectangle(float32(x+width-150), float32(y-14), 150, 32),
|
||||
Label: "Restart to update", Style: kryui.UIButtonStylePrimary, ID: updateButtonID,
|
||||
}) {
|
||||
if updater.Apply() {
|
||||
restartPending = true
|
||||
}
|
||||
}
|
||||
case kryui.UpdateFlowFailed:
|
||||
kryui.DrawUIText("Update failed: "+updater.Error(), x, y, kryui.UIText12, scheme.OnSurfaceVariant)
|
||||
if kryui.Button(kryui.ButtonProps{
|
||||
Bounds: kryui.NewRectangle(float32(x+width-96), float32(y-14), 96, 32),
|
||||
Label: "Retry", Style: kryui.UIButtonStyleSecondary, ID: updateButtonID,
|
||||
}) {
|
||||
updater.Download()
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
var buf [8]byte
|
||||
i := len(buf)
|
||||
for n > 0 {
|
||||
i--
|
||||
buf[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
}
|
||||
return string(buf[i:])
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package gopass
|
||||
package pass
|
||||
|
||||
import "crypto/sha256"
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package gopass
|
||||
package pass
|
||||
|
||||
import "testing"
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/* C port of the gopass Go generator (gopass.go, pbkdf2.go). The output is
|
||||
* byte-identical to the Go implementation; native/gopass_core_test.c checks
|
||||
/* C port of the pass Go generator (pass.go, pbkdf2.go). The output is
|
||||
* byte-identical to the Go implementation; native/pass_core_test.c checks
|
||||
* the same fixed vectors the Go tests use. */
|
||||
|
||||
#include "gopass_core.h"
|
||||
#include "pass_core.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
@@ -175,6 +175,12 @@ sha256(const void *data, size_t len, uint8_t out[32])
|
||||
sha256_final(&ctx, out);
|
||||
}
|
||||
|
||||
void
|
||||
pass_sha256(const void *data, size_t len, uint8_t out[32])
|
||||
{
|
||||
sha256(data, len, out);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* HMAC-SHA256 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -217,7 +223,7 @@ hmac_sha256(const void *key, size_t key_len,
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
void
|
||||
gopass_derive_key(const char *password, size_t password_len,
|
||||
pass_derive_key(const char *password, size_t password_len,
|
||||
const char *salt, size_t salt_len,
|
||||
uint8_t out[32])
|
||||
{
|
||||
@@ -241,7 +247,7 @@ gopass_derive_key(const char *password, size_t password_len,
|
||||
hmac_sha256(password, password_len, block_input, input_len, previous);
|
||||
memcpy(out, previous, 32);
|
||||
|
||||
for(round = 1; round < GOPASS_DERIVATION_ROUNDS; round++) {
|
||||
for(round = 1; round < PASS_DERIVATION_ROUNDS; round++) {
|
||||
hmac_sha256(password, password_len, previous, 32, previous);
|
||||
for(int i = 0; i < 32; i++)
|
||||
out[i] ^= previous[i];
|
||||
@@ -303,8 +309,8 @@ class_filtered(const char *characters, const char *exclude, char *out, int out_s
|
||||
}
|
||||
|
||||
int
|
||||
gopass_generate(const char *site, const char *login, const char *master,
|
||||
const GopassOptions *options,
|
||||
pass_generate(const char *site, const char *login, const char *master,
|
||||
const PassOptions *options,
|
||||
char *out, size_t out_size,
|
||||
char *err, size_t err_size)
|
||||
{
|
||||
@@ -380,7 +386,7 @@ gopass_generate(const char *site, const char *login, const char *master,
|
||||
salt_len += (size_t)snprintf(salt + salt_len, sizeof(salt) - salt_len,
|
||||
"%llu", (unsigned long long)options->counter);
|
||||
|
||||
gopass_derive_key(master != NULL ? master : "", master != NULL ? strlen(master) : 0,
|
||||
pass_derive_key(master != NULL ? master : "", master != NULL ? strlen(master) : 0,
|
||||
salt, salt_len, entropy);
|
||||
|
||||
password_length = options->length - class_count;
|
||||
@@ -1,10 +1,10 @@
|
||||
#ifndef GOPASS_CORE_H
|
||||
#define GOPASS_CORE_H
|
||||
#ifndef PASS_CORE_H
|
||||
#define PASS_CORE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define GOPASS_DERIVATION_ROUNDS 100000
|
||||
#define PASS_DERIVATION_ROUNDS 100000
|
||||
|
||||
typedef struct {
|
||||
int length;
|
||||
@@ -14,19 +14,23 @@ typedef struct {
|
||||
int digits;
|
||||
int symbols;
|
||||
const char *exclude; /* NUL-terminated; may be NULL or empty */
|
||||
} GopassOptions;
|
||||
} PassOptions;
|
||||
|
||||
/* Derives the 32-byte PBKDF2-HMAC-SHA256 key (one block, 100000 rounds),
|
||||
* the byte-exact counterpart of the Go package's deriveKey. */
|
||||
void gopass_derive_key(const char *password, size_t password_len,
|
||||
void pass_derive_key(const char *password, size_t password_len,
|
||||
const char *salt, size_t salt_len,
|
||||
uint8_t out[32]);
|
||||
|
||||
/* Computes SHA-256. Shared with UI code that must match the Go package's
|
||||
* master-password fingerprint derivation. */
|
||||
void pass_sha256(const void *data, size_t len, uint8_t out[32]);
|
||||
|
||||
/* Generates a LessPass-compatible password. Returns 0 on success and writes
|
||||
* the NUL-terminated password into out. Returns nonzero on invalid options
|
||||
* and writes the reason into err (English, matches the Go error strings). */
|
||||
int gopass_generate(const char *site, const char *login, const char *master,
|
||||
const GopassOptions *options,
|
||||
int pass_generate(const char *site, const char *login, const char *master,
|
||||
const PassOptions *options,
|
||||
char *out, size_t out_size,
|
||||
char *err, size_t err_size);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* Host-buildable vector test for gopass_core.c. The vectors are copied from
|
||||
* the Go tests (gopass_test.go) so the C generator stays byte-compatible. */
|
||||
/* Host-buildable vector test for pass_core.c. The vectors are copied from
|
||||
* the Go tests (pass_test.go) so the C generator stays byte-compatible. */
|
||||
|
||||
#include "gopass_core.h"
|
||||
#include "pass_core.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -11,7 +11,7 @@ static int failures = 0;
|
||||
|
||||
static void
|
||||
check_generate(int index, const char *site, const char *login, const char *master,
|
||||
GopassOptions options, const char *want, int want_error)
|
||||
PassOptions options, const char *want, int want_error)
|
||||
{
|
||||
char out[256];
|
||||
char err[256];
|
||||
@@ -19,7 +19,7 @@ check_generate(int index, const char *site, const char *login, const char *maste
|
||||
|
||||
memset(out, 0, sizeof(out));
|
||||
memset(err, 0, sizeof(err));
|
||||
result = gopass_generate(site, login, master, &options, out, sizeof(out), err, sizeof(err));
|
||||
result = pass_generate(site, login, master, &options, out, sizeof(out), err, sizeof(err));
|
||||
|
||||
if(want_error) {
|
||||
if(result == 0) {
|
||||
@@ -52,7 +52,7 @@ check_derive(int index, const char *password, const char *salt, const char *want
|
||||
char hex[65];
|
||||
int i;
|
||||
|
||||
gopass_derive_key(password, strlen(password), salt, strlen(salt), out);
|
||||
pass_derive_key(password, strlen(password), salt, strlen(salt), out);
|
||||
for(i = 0; i < 32; i++)
|
||||
sprintf(hex + i * 2, "%02x", out[i]);
|
||||
hex[64] = '\0';
|
||||
@@ -65,10 +65,30 @@ check_derive(int index, const char *password, const char *salt, const char *want
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
check_sha256(void)
|
||||
{
|
||||
uint8_t out[32];
|
||||
char hex[65];
|
||||
int i;
|
||||
|
||||
pass_sha256("correct horse battery staple", strlen("correct horse battery staple"), out);
|
||||
for(i = 0; i < 32; i++)
|
||||
sprintf(hex + i * 2, "%02x", out[i]);
|
||||
hex[64] = '\0';
|
||||
|
||||
if(strcmp(hex, "c4bbcb1fbec99d65bf59d85c8cb62ee2db963f0fe106f483d9afa73bd4e39a8a") != 0) {
|
||||
printf("FAIL sha256: got %s\n", hex);
|
||||
failures++;
|
||||
} else {
|
||||
printf("ok sha256: %s\n", hex);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
check_shape(void)
|
||||
{
|
||||
GopassOptions options;
|
||||
PassOptions options;
|
||||
char out[256];
|
||||
char err[256];
|
||||
static const char *exclude = "abcXYZ019!@";
|
||||
@@ -87,7 +107,7 @@ check_shape(void)
|
||||
options.symbols = 1;
|
||||
options.exclude = exclude;
|
||||
|
||||
if(gopass_generate("host", "account", "secret", &options, out, sizeof(out), err, sizeof(err)) != 0) {
|
||||
if(pass_generate("host", "account", "secret", &options, out, sizeof(out), err, sizeof(err)) != 0) {
|
||||
printf("FAIL shape: %s\n", err);
|
||||
failures++;
|
||||
return;
|
||||
@@ -129,12 +149,13 @@ check_shape(void)
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
GopassOptions defaults;
|
||||
PassOptions defaults;
|
||||
|
||||
check_derive(1, "password", "salt",
|
||||
"0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5");
|
||||
check_derive(2, "", "examplealice1",
|
||||
"caa46554f5a676b76c15b368c655b0b24eaaad8595ef919999785c68e60fd5f5");
|
||||
check_sha256();
|
||||
|
||||
memset(&defaults, 0, sizeof(defaults));
|
||||
defaults.length = 16;
|
||||
@@ -149,7 +170,7 @@ main(void)
|
||||
defaults, "&vLf44D'/cSkP-_8", 0);
|
||||
|
||||
{
|
||||
GopassOptions o = defaults;
|
||||
PassOptions o = defaults;
|
||||
|
||||
o.length = 20;
|
||||
o.counter = 2;
|
||||
@@ -158,7 +179,7 @@ main(void)
|
||||
}
|
||||
|
||||
{
|
||||
GopassOptions o;
|
||||
PassOptions o;
|
||||
|
||||
memset(&o, 0, sizeof(o));
|
||||
o.length = 12;
|
||||
@@ -171,7 +192,7 @@ main(void)
|
||||
}
|
||||
|
||||
{
|
||||
GopassOptions o = defaults;
|
||||
PassOptions o = defaults;
|
||||
|
||||
o.length = 24;
|
||||
o.exclude = "0Ool1I!|";
|
||||
@@ -180,7 +201,7 @@ main(void)
|
||||
}
|
||||
|
||||
{
|
||||
GopassOptions o;
|
||||
PassOptions o;
|
||||
|
||||
memset(&o, 0, sizeof(o));
|
||||
o.length = 4;
|
||||
@@ -191,7 +212,7 @@ main(void)
|
||||
}
|
||||
|
||||
{
|
||||
GopassOptions o;
|
||||
PassOptions o;
|
||||
|
||||
memset(&o, 0, sizeof(o));
|
||||
o.length = 0;
|
||||
@@ -200,7 +221,7 @@ main(void)
|
||||
}
|
||||
|
||||
{
|
||||
GopassOptions o;
|
||||
PassOptions o;
|
||||
|
||||
memset(&o, 0, sizeof(o));
|
||||
o.length = 8;
|
||||
@@ -208,7 +229,7 @@ main(void)
|
||||
}
|
||||
|
||||
{
|
||||
GopassOptions o;
|
||||
PassOptions o;
|
||||
|
||||
memset(&o, 0, sizeof(o));
|
||||
o.length = 2;
|
||||
@@ -219,7 +240,7 @@ main(void)
|
||||
}
|
||||
|
||||
{
|
||||
GopassOptions o;
|
||||
PassOptions o;
|
||||
|
||||
memset(&o, 0, sizeof(o));
|
||||
o.length = 8;
|
||||
@@ -1,15 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<component type="desktop-application">
|
||||
<id>xyz.waozi.pass</id>
|
||||
<name>gopass</name>
|
||||
<name>pass</name>
|
||||
<summary>Generate deterministic passwords locally</summary>
|
||||
<metadata_license>CC0-1.0</metadata_license>
|
||||
<project_license>BSD-3-Clause</project_license>
|
||||
<description>
|
||||
<p>gopass derives repeatable passwords from a site, login, master password, and generation settings without storing a password database.</p>
|
||||
<p>pass derives repeatable passwords from a site, login, master password, and generation settings without storing a password database.</p>
|
||||
</description>
|
||||
<launchable type="desktop-id">xyz.waozi.pass.desktop</launchable>
|
||||
<url type="homepage">https://github.com/waozixyz/gopass</url>
|
||||
<provides><binary>gopass-gui</binary></provides>
|
||||
<releases><release version="0.1.2" date="2026-08-17"/><release version="0.1.1" date="2026-08-17"/><release version="0.1.0" date="2026-08-17"/></releases>
|
||||
<url type="homepage">https://github.com/waozixyz/pass</url>
|
||||
<provides><binary>pass-gui</binary></provides>
|
||||
<releases><release version="0.2.2" date="2026-08-20"/><release version="0.2.1" date="2026-08-19"/><release version="0.2.0" date="2026-08-18"/><release version="0.1.3" date="2026-08-17"/><release version="0.1.2" date="2026-08-17"/><release version="0.1.1" date="2026-08-17"/><release version="0.1.0" date="2026-08-17"/></releases>
|
||||
</component>
|
||||
@@ -1,9 +1,9 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=gopass
|
||||
Name=pass
|
||||
Comment=Generate deterministic passwords locally
|
||||
Exec=gopass-gui
|
||||
Icon=gopass
|
||||
Exec=pass-gui
|
||||
Icon=pass
|
||||
Terminal=false
|
||||
Categories=System;Security;
|
||||
StartupNotify=true
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
// Package gopass derives site-specific passwords without storing them.
|
||||
package gopass
|
||||
// Package pass derives site-specific passwords without storing them.
|
||||
package pass
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -1,4 +1,4 @@
|
||||
package gopass
|
||||
package pass
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
name "gopass"
|
||||
name "pass"
|
||||
generated "build/kryon/generated"
|
||||
default_target "Run"
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package gopass
|
||||
package pass
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
|
||||
@@ -5,17 +5,17 @@ root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
version=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' "$root/version.go")
|
||||
arch=${APPIMAGE_ARCH:-$(uname -m)}
|
||||
linuxdeploy=${LINUXDEPLOY:-linuxdeploy}
|
||||
appdir="$root/build/package/appimage/gopass.AppDir"
|
||||
out="$root/build/release/gopass-${version}-${arch}.AppImage"
|
||||
appdir="$root/build/package/appimage/pass.AppDir"
|
||||
out="$root/build/release/pass-${version}-${arch}.AppImage"
|
||||
|
||||
test -n "$version"
|
||||
rm -rf "$appdir"
|
||||
mkdir -p "$appdir/usr/bin" "$appdir/usr/share/applications" "$appdir/usr/share/metainfo" "$appdir/usr/share/icons/hicolor/512x512/apps" "$(dirname "$out")"
|
||||
cp "$root/build/gopass-gui" "$appdir/usr/bin/gopass-gui"
|
||||
cp "$root/build/pass-gui" "$appdir/usr/bin/pass-gui"
|
||||
cp "$root/packaging/linux/xyz.waozi.pass.desktop" "$appdir/usr/share/applications/xyz.waozi.pass.desktop"
|
||||
cp "$root/packaging/linux/xyz.waozi.pass.appdata.xml" "$appdir/usr/share/metainfo/xyz.waozi.pass.appdata.xml"
|
||||
cp "$root/assets/app/icon.png" "$appdir/usr/share/icons/hicolor/512x512/apps/gopass.png"
|
||||
rm -f "$root"/gopass-*.AppImage
|
||||
cp "$root/assets/app/icon.png" "$appdir/usr/share/icons/hicolor/512x512/apps/pass.png"
|
||||
rm -f "$root"/pass-*.AppImage
|
||||
ARCH="$arch" "$linuxdeploy" --appdir "$appdir" --desktop-file "$root/packaging/linux/xyz.waozi.pass.desktop" --icon-file "$root/assets/app/icon.png" --output appimage
|
||||
image=$(find "$root" -maxdepth 1 -type f -name '*.AppImage' -print | head -n 1)
|
||||
test -n "$image"
|
||||
|
||||
@@ -4,23 +4,23 @@ set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
version=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' "$root/version.go")
|
||||
arch=${DEB_ARCH:-$(dpkg --print-architecture)}
|
||||
stage="$root/build/package/deb/gopass"
|
||||
stage="$root/build/package/deb/pass"
|
||||
out="$root/build/release"
|
||||
|
||||
test -n "$version"
|
||||
rm -rf "$stage"
|
||||
mkdir -p "$stage/DEBIAN" "$stage/usr/bin" "$stage/usr/share/applications" "$stage/usr/share/metainfo" "$stage/usr/share/icons/hicolor/512x512/apps" "$stage/usr/share/doc/gopass" "$out"
|
||||
cp "$root/build/gopass-gui" "$stage/usr/bin/gopass-gui"
|
||||
mkdir -p "$stage/DEBIAN" "$stage/usr/bin" "$stage/usr/share/applications" "$stage/usr/share/metainfo" "$stage/usr/share/icons/hicolor/512x512/apps" "$stage/usr/share/doc/pass" "$out"
|
||||
cp "$root/build/pass-gui" "$stage/usr/bin/pass-gui"
|
||||
cp "$root/packaging/linux/xyz.waozi.pass.desktop" "$stage/usr/share/applications/xyz.waozi.pass.desktop"
|
||||
cp "$root/packaging/linux/xyz.waozi.pass.appdata.xml" "$stage/usr/share/metainfo/xyz.waozi.pass.appdata.xml"
|
||||
cp "$root/assets/app/icon.png" "$stage/usr/share/icons/hicolor/512x512/apps/gopass.png"
|
||||
cp "$root/LICENSE" "$root/README.md" "$stage/usr/share/doc/gopass/"
|
||||
cp "$root/assets/app/icon.png" "$stage/usr/share/icons/hicolor/512x512/apps/pass.png"
|
||||
cp "$root/LICENSE" "$root/README.md" "$stage/usr/share/doc/pass/"
|
||||
find "$stage" -type d -exec chmod 0755 {} \;
|
||||
chmod 0755 "$stage/usr/bin/gopass-gui"
|
||||
chmod 0755 "$stage/usr/bin/pass-gui"
|
||||
find "$stage/usr/share" -type f -exec chmod 0644 {} \;
|
||||
installed=$(du -sk "$stage" | awk '{print $1}')
|
||||
cat > "$stage/DEBIAN/control" <<EOF
|
||||
Package: gopass
|
||||
Package: pass
|
||||
Version: $version
|
||||
Architecture: $arch
|
||||
Maintainer: Waozi <[email protected]>
|
||||
@@ -32,4 +32,4 @@ Homepage: https://pass.waozi.xyz/
|
||||
Description: deterministic local password generator
|
||||
Generate repeatable passwords locally without a password database.
|
||||
EOF
|
||||
dpkg-deb --root-owner-group --build "$stage" "$out/gopass_${version}_${arch}.deb"
|
||||
dpkg-deb --root-owner-group --build "$stage" "$out/pass_${version}_${arch}.deb"
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/bin/sh
|
||||
# privacy_scan.sh — refuse to ship private terms.
|
||||
#
|
||||
# Scans a git tree (contents and file paths) or a directory for the
|
||||
# fixed-string terms listed in TERMS_FILE. The terms file lives outside
|
||||
# every repository — ~/.config/git/private-terms.txt for the local
|
||||
# pre-push hook, the PRIVATE_TERMS Actions secret in CI — so this script,
|
||||
# its workflow, and its self-test never contain or reveal the private
|
||||
# values. Reports redact every term before printing.
|
||||
#
|
||||
# Usage: privacy_scan.sh TERMS_FILE TREE-ISH|DIRECTORY [TREE-ISH...]
|
||||
# Exit: 0 clean, 1 a term was found, 2 bad usage / unusable terms file.
|
||||
|
||||
set -u
|
||||
|
||||
if [ "$#" -lt 2 ]; then
|
||||
echo "usage: $0 TERMS_FILE TREE-ISH|DIRECTORY..." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
terms_file=$1
|
||||
shift
|
||||
|
||||
if [ ! -f "$terms_file" ]; then
|
||||
echo "privacy: terms file $terms_file not found" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Drop comments and blank lines; require at least one term.
|
||||
tmp_terms=$(mktemp) || exit 2
|
||||
trap 'rm -f "$tmp_terms"' EXIT
|
||||
chmod 600 "$tmp_terms"
|
||||
sed -e 's/#.*$//' -e '/^[[:space:]]*$/d' "$terms_file" > "$tmp_terms"
|
||||
if [ ! -s "$tmp_terms" ]; then
|
||||
echo "privacy: terms file $terms_file has no terms" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
redact() {
|
||||
awk -v terms_file="$tmp_terms" '
|
||||
BEGIN { while ((getline t < terms_file) > 0) terms[++nt] = tolower(t) }
|
||||
{
|
||||
line = $0
|
||||
for (i = 1; i <= nt; i++) {
|
||||
low = tolower(line)
|
||||
while ((p = index(low, terms[i])) > 0) {
|
||||
line = substr(line, 1, p - 1) "***" substr(line, p + length(terms[i]))
|
||||
low = tolower(line)
|
||||
}
|
||||
}
|
||||
print line
|
||||
}'
|
||||
}
|
||||
|
||||
found=0
|
||||
for target in "$@"; do
|
||||
if git rev-parse -q --verify "$target^{tree}" >/dev/null 2>&1; then
|
||||
# A git tree: search contents and file paths at that revision.
|
||||
hits=$(git grep -I -iF -f "$tmp_terms" "$target" -- . 2>/dev/null || true)
|
||||
paths=$(git ls-tree -r --name-only "$target" 2>/dev/null | grep -iF -f "$tmp_terms" || true)
|
||||
elif [ -d "$target" ]; then
|
||||
# A directory: search contents and file paths on disk.
|
||||
hits=$(grep -rI -iF -f "$tmp_terms" --exclude-dir=.git "$target" 2>/dev/null || true)
|
||||
paths=$(cd "$target" && find . -name .git -prune -o -print 2>/dev/null | grep -iF -f "$tmp_terms" || true)
|
||||
else
|
||||
echo "privacy: cannot scan $target (not a tree-ish or directory)" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [ -n "$hits" ]; then
|
||||
found=1
|
||||
# git grep and grep -r output already carries the tree/path prefix.
|
||||
printf '%s\n' "$hits" | redact >&2
|
||||
fi
|
||||
if [ -n "$paths" ]; then
|
||||
found=1
|
||||
printf '%s\n' "$paths" | sed 's|^|path name match: |' | redact >&2
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$found" -ne 0 ]; then
|
||||
echo "privacy: PRIVATE DATA DETECTED — refusing to ship" >&2
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
+20
-2
@@ -13,11 +13,29 @@ if [ -z "$release_date" ]; then
|
||||
fi
|
||||
|
||||
sed -E -i "s/^const Version = \"[^\"]+\"$/const Version = \"$release_version\"/" version.go
|
||||
sed -E -i "s/versionName \"[^\"]+\"/versionName \"$release_version\"/" droid/app/build.gradle
|
||||
|
||||
# Android versionName and versionCode: bump the code only when preparing a
|
||||
# different release, so rerunning this script for the same version is
|
||||
# idempotent.
|
||||
gradle_file=droid/app/build.gradle
|
||||
current_name=$(sed -n 's/.*versionName "\([^"]*\)".*/\1/p' "$gradle_file" | head -n 1)
|
||||
current_code=$(sed -n 's/^[[:space:]]*versionCode \([0-9][0-9]*\).*/\1/p' "$gradle_file" | head -n 1)
|
||||
if [ -z "$current_code" ]; then
|
||||
echo "Could not read versionCode from $gradle_file" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$current_name" = "$release_version" ]; then
|
||||
release_code=$current_code
|
||||
else
|
||||
release_code=$((current_code + 1))
|
||||
fi
|
||||
sed -E -i "s/versionName \"[^\"]+\"/versionName \"$release_version\"/" "$gradle_file"
|
||||
sed -E -i "s/^([[:space:]]*)versionCode [0-9]+/\1versionCode $release_code/" "$gradle_file"
|
||||
metainfo=packaging/linux/xyz.waozi.pass.appdata.xml
|
||||
if ! grep -F "<release version=\"$release_version\"" "$metainfo" >/dev/null; then
|
||||
sed -E -i "s#<releases>#<releases><release version=\"$release_version\" date=\"$release_date\"/>#" "$metainfo"
|
||||
fi
|
||||
grep -F "const Version = \"$release_version\"" version.go >/dev/null
|
||||
grep -F "versionName \"$release_version\"" droid/app/build.gradle >/dev/null
|
||||
grep -F "versionName \"$release_version\"" "$gradle_file" >/dev/null
|
||||
grep -E "^[[:space:]]*versionCode $release_code$" "$gradle_file" >/dev/null
|
||||
grep -F "<release version=\"$release_version\" date=\"$release_date\"" "$metainfo" >/dev/null
|
||||
@@ -0,0 +1,94 @@
|
||||
// Package vault decrypts OpenSSL-encrypted secret files so they can be used
|
||||
// as master passwords without storing them anywhere.
|
||||
package vault
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/pbkdf2"
|
||||
"crypto/sha512"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrFormat = errors.New("vault is not in OpenSSL salted base64 format")
|
||||
ErrDecrypt = errors.New("wrong vault passphrase or corrupted vault")
|
||||
)
|
||||
|
||||
// Decrypt decrypts a file produced by:
|
||||
//
|
||||
// openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt \
|
||||
// -pass pass:... > vault
|
||||
//
|
||||
// File format: base64("Salted__" + 8-byte salt + AES-256-CBC ciphertext).
|
||||
// Key/IV are derived with PBKDF2-HMAC-SHA512(passphrase, salt, 100000, 48):
|
||||
// first 32 bytes are the AES key, the next 16 are the CBC IV.
|
||||
// Trailing newlines are stripped, matching the $(...) substitution of the
|
||||
// shell scripts this replaces.
|
||||
func Decrypt(path, passphrase string) (string, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// The base64 body may contain newlines; strip all whitespace first.
|
||||
var b strings.Builder
|
||||
for _, c := range raw {
|
||||
switch c {
|
||||
case '\n', '\r', ' ', '\t':
|
||||
default:
|
||||
b.WriteByte(c)
|
||||
}
|
||||
}
|
||||
data, err := base64.StdEncoding.DecodeString(b.String())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrFormat, err)
|
||||
}
|
||||
if len(data) < aes.BlockSize*2 || string(data[:8]) != "Salted__" {
|
||||
return "", ErrFormat
|
||||
}
|
||||
salt := data[8:16]
|
||||
ciphertext := data[16:]
|
||||
if len(ciphertext) == 0 || len(ciphertext)%aes.BlockSize != 0 {
|
||||
return "", ErrFormat
|
||||
}
|
||||
|
||||
keyIV, err := pbkdf2.Key(sha512.New, passphrase, salt, 100000, aes.BlockSize*3)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
key, iv := keyIV[:32], keyIV[32:48]
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
plaintext := make([]byte, len(ciphertext))
|
||||
cipher.NewCBCDecrypter(block, iv).CryptBlocks(plaintext, ciphertext)
|
||||
|
||||
// Strip PKCS#7 padding; a bad pad almost always means a wrong passphrase.
|
||||
pad := int(plaintext[len(plaintext)-1])
|
||||
if pad == 0 || pad > aes.BlockSize || pad > len(plaintext) {
|
||||
return "", ErrDecrypt
|
||||
}
|
||||
for _, p := range plaintext[len(plaintext)-pad:] {
|
||||
if int(p) != pad {
|
||||
return "", ErrDecrypt
|
||||
}
|
||||
}
|
||||
plaintext = plaintext[:len(plaintext)-pad]
|
||||
|
||||
secret := strings.TrimRight(string(plaintext), "\n")
|
||||
clear(plaintext) // best effort: wipe the decrypted bytes
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
func clear(buf []byte) {
|
||||
for i := range buf {
|
||||
buf[i] = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package vault
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Round-trip against the real openssl binary using the exact command line of
|
||||
// the original pass shell script.
|
||||
func TestDecryptAgainstOpenSSL(t *testing.T) {
|
||||
if _, err := exec.LookPath("openssl"); err != nil {
|
||||
t.Skip("openssl not available")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, ".vault")
|
||||
|
||||
encrypt := `printf 'my-top-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + file
|
||||
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
|
||||
got, err := Decrypt(file, "masterpw")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
if got != "my-top-secret" {
|
||||
t.Errorf("got %q, want %q", got, "my-top-secret")
|
||||
}
|
||||
|
||||
// Trailing newlines in the plaintext must be stripped ($(...) parity).
|
||||
encryptNL := `printf 'secret-with-newline\n\n' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + file
|
||||
if out, err := exec.Command("sh", "-c", encryptNL).CombinedOutput(); err != nil {
|
||||
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
|
||||
}
|
||||
got, err = Decrypt(file, "masterpw")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
if got != "secret-with-newline" {
|
||||
t.Errorf("got %q, want %q (trailing newlines stripped)", got, "secret-with-newline")
|
||||
}
|
||||
|
||||
if _, err := Decrypt(file, "wrong-passphrase"); err == nil {
|
||||
t.Error("expected error with wrong passphrase")
|
||||
}
|
||||
|
||||
if err := os.WriteFile(file, []byte("not-base64-$$$!!!"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Decrypt(file, "masterpw"); err == nil {
|
||||
t.Error("expected error for non-OpenSSL file")
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
// Copyright (c) 2009 The XGB Authors. All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// Subject to the terms and conditions of this License, Google hereby
|
||||
// grants to You a perpetual, worldwide, non-exclusive, no-charge,
|
||||
// royalty-free, irrevocable (except as stated in this section) patent
|
||||
// license to make, have made, use, offer to sell, sell, import, and
|
||||
// otherwise transfer this implementation of XGB, where such license
|
||||
// applies only to those patent claims licensable by Google that are
|
||||
// necessarily infringed by use of this implementation of XGB. If You
|
||||
// institute patent litigation against any entity (including a
|
||||
// cross-claim or counterclaim in a lawsuit) alleging that this
|
||||
// implementation of XGB or a Contribution incorporated within this
|
||||
// implementation of XGB constitutes direct or contributory patent
|
||||
// infringement, then any patent licenses granted to You under this
|
||||
// License for this implementation of XGB shall terminate as of the date
|
||||
// such litigation is filed.
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package xgb
|
||||
|
||||
/*
|
||||
auth.go contains functions to facilitate the parsing of .Xauthority files.
|
||||
|
||||
It is largely unmodified from the original XGB package that I forked.
|
||||
*/
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// readAuthority reads the X authority file for the DISPLAY.
|
||||
// If hostname == "" or hostname == "localhost",
|
||||
// then use the system's hostname (as returned by os.Hostname) instead.
|
||||
func readAuthority(hostname, display string) (
|
||||
name string, data []byte, err error) {
|
||||
|
||||
// b is a scratch buffer to use and should be at least 256 bytes long
|
||||
// (i.e. it should be able to hold a hostname).
|
||||
b := make([]byte, 256)
|
||||
|
||||
// As per /usr/include/X11/Xauth.h.
|
||||
const familyLocal = 256
|
||||
const familyWild = 65535
|
||||
|
||||
if len(hostname) == 0 || hostname == "localhost" {
|
||||
hostname, err = os.Hostname()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
|
||||
fname := os.Getenv("XAUTHORITY")
|
||||
if len(fname) == 0 {
|
||||
home := os.Getenv("HOME")
|
||||
if len(home) == 0 {
|
||||
err = errors.New("Xauthority not found: $XAUTHORITY, $HOME not set")
|
||||
return "", nil, err
|
||||
}
|
||||
fname = home + "/.Xauthority"
|
||||
}
|
||||
|
||||
r, err := os.Open(fname)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
for {
|
||||
var family uint16
|
||||
if err := binary.Read(r, binary.BigEndian, &family); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
addr, err := getString(r, b)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
disp, err := getString(r, b)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
name0, err := getString(r, b)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
data0, err := getBytes(r, b)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
addrmatch := (family == familyWild) ||
|
||||
(family == familyLocal && addr == hostname)
|
||||
dispmatch := (disp == "") || (disp == display)
|
||||
|
||||
if addrmatch && dispmatch {
|
||||
return name0, data0, nil
|
||||
}
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
func getBytes(r io.Reader, b []byte) ([]byte, error) {
|
||||
var n uint16
|
||||
if err := binary.Read(r, binary.BigEndian, &n); err != nil {
|
||||
return nil, err
|
||||
} else if n > uint16(len(b)) {
|
||||
return nil, errors.New("bytes too long for buffer")
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(r, b[0:n]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b[0:n], nil
|
||||
}
|
||||
|
||||
func getString(r io.Reader, b []byte) (string, error) {
|
||||
b, err := getBytes(r, b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package xgb
|
||||
|
||||
/*
|
||||
conn.go contains a couple of functions that do some real dirty work related
|
||||
to the initial connection handshake with X.
|
||||
|
||||
This code is largely unmodified from the original XGB package that I forked.
|
||||
*/
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// connect connects to the X server given in the 'display' string,
|
||||
// and does all the necessary setup handshaking.
|
||||
// If 'display' is empty it will be taken from os.Getenv("DISPLAY").
|
||||
// Note that you should read and understand the "Connection Setup" of the
|
||||
// X Protocol Reference Manual before changing this function:
|
||||
// http://goo.gl/4zGQg
|
||||
func (c *Conn) connect(display string) error {
|
||||
err := c.dial(display)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.postConnect()
|
||||
}
|
||||
|
||||
// connect init from to the net.Conn,
|
||||
func (c *Conn) connectNet(netConn net.Conn) error {
|
||||
c.conn = netConn
|
||||
return c.postConnect()
|
||||
}
|
||||
|
||||
// do the postConnect action after Conn get it's underly net.Conn
|
||||
func (c *Conn) postConnect() error {
|
||||
// Get authentication data
|
||||
authName, authData, err := readAuthority(c.host, c.display)
|
||||
noauth := false
|
||||
if err != nil {
|
||||
Logger.Printf("Could not get authority info: %v", err)
|
||||
Logger.Println("Trying connection without authority info...")
|
||||
authName = ""
|
||||
authData = []byte{}
|
||||
noauth = true
|
||||
}
|
||||
|
||||
// Assume that the authentication protocol is "MIT-MAGIC-COOKIE-1".
|
||||
if !noauth && (authName != "MIT-MAGIC-COOKIE-1" || len(authData) != 16) {
|
||||
return errors.New("unsupported auth protocol " + authName)
|
||||
}
|
||||
|
||||
buf := make([]byte, 12+Pad(len(authName))+Pad(len(authData)))
|
||||
buf[0] = 0x6c
|
||||
buf[1] = 0
|
||||
Put16(buf[2:], 11)
|
||||
Put16(buf[4:], 0)
|
||||
Put16(buf[6:], uint16(len(authName)))
|
||||
Put16(buf[8:], uint16(len(authData)))
|
||||
Put16(buf[10:], 0)
|
||||
copy(buf[12:], []byte(authName))
|
||||
copy(buf[12+Pad(len(authName)):], authData)
|
||||
if _, err = c.conn.Write(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
head := make([]byte, 8)
|
||||
if _, err = io.ReadFull(c.conn, head[0:8]); err != nil {
|
||||
return err
|
||||
}
|
||||
code := head[0]
|
||||
reasonLen := head[1]
|
||||
major := Get16(head[2:])
|
||||
minor := Get16(head[4:])
|
||||
dataLen := Get16(head[6:])
|
||||
|
||||
if major != 11 || minor != 0 {
|
||||
return fmt.Errorf("x protocol version mismatch: %d.%d", major, minor)
|
||||
}
|
||||
|
||||
buf = make([]byte, int(dataLen)*4+8, int(dataLen)*4+8)
|
||||
copy(buf, head)
|
||||
if _, err = io.ReadFull(c.conn, buf[8:]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if code == 0 {
|
||||
reason := buf[8 : 8+reasonLen]
|
||||
return fmt.Errorf("x protocol authentication refused: %s",
|
||||
string(reason))
|
||||
}
|
||||
|
||||
// Unfortunately, it isn't really feasible to read the setup bytes here,
|
||||
// since the code to do so is in a different package.
|
||||
// Users must call 'xproto.Setup(X)' to get the setup info.
|
||||
c.SetupBytes = buf
|
||||
|
||||
// But also read stuff that we *need* to get started.
|
||||
c.setupResourceIdBase = Get32(buf[12:])
|
||||
c.setupResourceIdMask = Get32(buf[16:])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// dial initializes the actual net connection with X.
|
||||
func (c *Conn) dial(display string) error {
|
||||
if len(display) == 0 {
|
||||
display = os.Getenv("DISPLAY")
|
||||
}
|
||||
|
||||
display0 := display
|
||||
if len(display) == 0 {
|
||||
return errors.New("empty display string")
|
||||
}
|
||||
|
||||
colonIdx := strings.LastIndex(display, ":")
|
||||
if colonIdx < 0 {
|
||||
return errors.New("bad display string: " + display0)
|
||||
}
|
||||
|
||||
var protocol, socket string
|
||||
|
||||
if display[0] == '/' {
|
||||
socket = display[0:colonIdx]
|
||||
} else {
|
||||
slashIdx := strings.LastIndex(display, "/")
|
||||
if slashIdx >= 0 {
|
||||
protocol = display[0:slashIdx]
|
||||
c.host = display[slashIdx+1 : colonIdx]
|
||||
} else {
|
||||
c.host = display[0:colonIdx]
|
||||
}
|
||||
}
|
||||
|
||||
display = display[colonIdx+1 : len(display)]
|
||||
if len(display) == 0 {
|
||||
return errors.New("bad display string: " + display0)
|
||||
}
|
||||
|
||||
var scr string
|
||||
dotIdx := strings.LastIndex(display, ".")
|
||||
if dotIdx < 0 {
|
||||
c.display = display[0:]
|
||||
} else {
|
||||
c.display = display[0:dotIdx]
|
||||
scr = display[dotIdx+1:]
|
||||
}
|
||||
|
||||
var err error
|
||||
c.DisplayNumber, err = strconv.Atoi(c.display)
|
||||
if err != nil || c.DisplayNumber < 0 {
|
||||
return errors.New("bad display string: " + display0)
|
||||
}
|
||||
|
||||
if len(scr) != 0 {
|
||||
c.DefaultScreen, err = strconv.Atoi(scr)
|
||||
if err != nil {
|
||||
return errors.New("bad display string: " + display0)
|
||||
}
|
||||
}
|
||||
|
||||
// Connect to server
|
||||
if len(socket) != 0 {
|
||||
c.conn, err = net.Dial("unix", socket+":"+c.display)
|
||||
} else if len(c.host) != 0 && c.host != "unix" {
|
||||
if protocol == "" {
|
||||
protocol = "tcp"
|
||||
}
|
||||
c.conn, err = net.Dial(protocol,
|
||||
c.host+":"+strconv.Itoa(6000+c.DisplayNumber))
|
||||
} else {
|
||||
c.host = ""
|
||||
c.conn, err = net.Dial("unix", "/tmp/.X11-unix/X"+c.display)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.New("cannot connect to " + display0 + ": " + err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package xgb
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Cookie is the internal representation of a cookie, where one is generated
|
||||
// for *every* request sent by XGB.
|
||||
// 'cookie' is most frequently used by embedding it into a more specific
|
||||
// kind of cookie, i.e., 'GetInputFocusCookie'.
|
||||
type Cookie struct {
|
||||
conn *Conn
|
||||
Sequence uint16
|
||||
replyChan chan []byte
|
||||
errorChan chan error
|
||||
pingChan chan bool
|
||||
}
|
||||
|
||||
// NewCookie creates a new cookie with the correct channels initialized
|
||||
// depending upon the values of 'checked' and 'reply'. Together, there are
|
||||
// four different kinds of cookies. (See more detailed comments in the
|
||||
// function for more info on those.)
|
||||
// Note that a sequence number is not set until just before the request
|
||||
// corresponding to this cookie is sent over the wire.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c *Conn) NewCookie(checked, reply bool) *Cookie {
|
||||
cookie := &Cookie{
|
||||
conn: c,
|
||||
Sequence: 0, // we add the sequence id just before sending a request
|
||||
replyChan: nil,
|
||||
errorChan: nil,
|
||||
pingChan: nil,
|
||||
}
|
||||
|
||||
// There are four different kinds of cookies:
|
||||
// Checked requests with replies get a reply channel and an error channel.
|
||||
// Unchecked requests with replies get a reply channel and a ping channel.
|
||||
// Checked requests w/o replies get a ping channel and an error channel.
|
||||
// Unchecked requests w/o replies get no channels.
|
||||
// The reply channel is used to send reply data.
|
||||
// The error channel is used to send error data.
|
||||
// The ping channel is used when one of the 'reply' or 'error' channels
|
||||
// is missing but the other is present. The ping channel is way to force
|
||||
// the blocking to stop and basically say "the error has been received
|
||||
// in the main event loop" (when the ping channel is coupled with a reply
|
||||
// channel) or "the request you made that has no reply was successful"
|
||||
// (when the ping channel is coupled with an error channel).
|
||||
if checked {
|
||||
cookie.errorChan = make(chan error, 1)
|
||||
if !reply {
|
||||
cookie.pingChan = make(chan bool, 1)
|
||||
}
|
||||
}
|
||||
if reply {
|
||||
cookie.replyChan = make(chan []byte, 1)
|
||||
if !checked {
|
||||
cookie.pingChan = make(chan bool, 1)
|
||||
}
|
||||
}
|
||||
|
||||
return cookie
|
||||
}
|
||||
|
||||
// Reply detects whether this is a checked or unchecked cookie, and calls
|
||||
// 'replyChecked' or 'replyUnchecked' appropriately.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c Cookie) Reply() ([]byte, error) {
|
||||
// checked
|
||||
if c.errorChan != nil {
|
||||
return c.replyChecked()
|
||||
}
|
||||
return c.replyUnchecked()
|
||||
}
|
||||
|
||||
// replyChecked waits for a response on either the replyChan or errorChan
|
||||
// channels. If the former arrives, the bytes are returned with a nil error.
|
||||
// If the latter arrives, no bytes are returned (nil) and the error received
|
||||
// is returned.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c Cookie) replyChecked() ([]byte, error) {
|
||||
if c.replyChan == nil {
|
||||
return nil, errors.New("Cannot call 'replyChecked' on a cookie that " +
|
||||
"is not expecting a *reply* or an error.")
|
||||
}
|
||||
if c.errorChan == nil {
|
||||
return nil, errors.New("Cannot call 'replyChecked' on a cookie that " +
|
||||
"is not expecting a reply or an *error*.")
|
||||
}
|
||||
|
||||
select {
|
||||
case reply := <-c.replyChan:
|
||||
return reply, nil
|
||||
case err := <-c.errorChan:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// replyUnchecked waits for a response on either the replyChan or pingChan
|
||||
// channels. If the former arrives, the bytes are returned with a nil error.
|
||||
// If the latter arrives, no bytes are returned (nil) and a nil error
|
||||
// is returned. (In the latter case, the corresponding error can be retrieved
|
||||
// from (Wait|Poll)ForEvent asynchronously.)
|
||||
// In all honesty, you *probably* don't want to use this method.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c Cookie) replyUnchecked() ([]byte, error) {
|
||||
if c.replyChan == nil {
|
||||
return nil, errors.New("Cannot call 'replyUnchecked' on a cookie " +
|
||||
"that is not expecting a *reply*.")
|
||||
}
|
||||
|
||||
select {
|
||||
case reply := <-c.replyChan:
|
||||
return reply, nil
|
||||
case <-c.pingChan:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Check is used for checked requests that have no replies. It is a mechanism
|
||||
// by which to report "success" or "error" in a synchronous fashion. (Therefore,
|
||||
// unchecked requests without replies cannot use this method.)
|
||||
// If the request causes an error, it is sent to this cookie's errorChan.
|
||||
// If the request was successful, there is no response from the server.
|
||||
// Thus, pingChan is sent a value when the *next* reply is read.
|
||||
// If no more replies are being processed, we force a round trip request with
|
||||
// GetInputFocus.
|
||||
//
|
||||
// Unless you're building requests from bytes by hand, this method should
|
||||
// not be used.
|
||||
func (c Cookie) Check() error {
|
||||
if c.replyChan != nil {
|
||||
return errors.New("Cannot call 'Check' on a cookie that is " +
|
||||
"expecting a *reply*. Use 'Reply' instead.")
|
||||
}
|
||||
if c.errorChan == nil {
|
||||
return errors.New("Cannot call 'Check' on a cookie that is " +
|
||||
"not expecting a possible *error*.")
|
||||
}
|
||||
|
||||
// First do a quick non-blocking check to see if we've been pinged.
|
||||
select {
|
||||
case err := <-c.errorChan:
|
||||
return err
|
||||
case <-c.pingChan:
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
|
||||
// Now force a round trip and try again, but block this time.
|
||||
c.conn.Sync()
|
||||
select {
|
||||
case err := <-c.errorChan:
|
||||
return err
|
||||
case <-c.pingChan:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
Package XGB provides the X Go Binding, which is a low-level API to communicate
|
||||
with the core X protocol and many of the X extensions.
|
||||
|
||||
It is *very* closely modeled on XCB, so that experience with XCB (or xpyb) is
|
||||
easily translatable to XGB. That is, it uses the same cookie/reply model
|
||||
and is thread safe. There are otherwise no major differences (in the API).
|
||||
|
||||
Most uses of XGB typically fall under the realm of window manager and GUI kit
|
||||
development, but other applications (like pagers, panels, tilers, etc.) may
|
||||
also require XGB. Moreover, it is a near certainty that if you need to work
|
||||
with X, xgbutil will be of great use to you as well:
|
||||
https://github.com/BurntSushi/xgbutil
|
||||
|
||||
Example
|
||||
|
||||
This is an extremely terse example that demonstrates how to connect to X,
|
||||
create a window, listen to StructureNotify events and Key{Press,Release}
|
||||
events, map the window, and print out all events received. An example with
|
||||
accompanying documentation can be found in examples/create-window.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/BurntSushi/xgb"
|
||||
"github.com/BurntSushi/xgb/xproto"
|
||||
)
|
||||
|
||||
func main() {
|
||||
X, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
wid, _ := xproto.NewWindowId(X)
|
||||
screen := xproto.Setup(X).DefaultScreen(X)
|
||||
xproto.CreateWindow(X, screen.RootDepth, wid, screen.Root,
|
||||
0, 0, 500, 500, 0,
|
||||
xproto.WindowClassInputOutput, screen.RootVisual,
|
||||
xproto.CwBackPixel | xproto.CwEventMask,
|
||||
[]uint32{ // values must be in the order defined by the protocol
|
||||
0xffffffff,
|
||||
xproto.EventMaskStructureNotify |
|
||||
xproto.EventMaskKeyPress |
|
||||
xproto.EventMaskKeyRelease})
|
||||
|
||||
xproto.MapWindow(X, wid)
|
||||
for {
|
||||
ev, xerr := X.WaitForEvent()
|
||||
if ev == nil && xerr == nil {
|
||||
fmt.Println("Both event and error are nil. Exiting...")
|
||||
return
|
||||
}
|
||||
|
||||
if ev != nil {
|
||||
fmt.Printf("Event: %s\n", ev)
|
||||
}
|
||||
if xerr != nil {
|
||||
fmt.Printf("Error: %s\n", xerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Xinerama Example
|
||||
|
||||
This is another small example that shows how to query Xinerama for geometry
|
||||
information of each active head. Accompanying documentation for this example
|
||||
can be found in examples/xinerama.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"github.com/BurntSushi/xgb"
|
||||
"github.com/BurntSushi/xgb/xinerama"
|
||||
)
|
||||
|
||||
func main() {
|
||||
X, err := xgb.NewConn()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Initialize the Xinerama extension.
|
||||
// The appropriate 'Init' function must be run for *every*
|
||||
// extension before any of its requests can be used.
|
||||
err = xinerama.Init(X)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
reply, err := xinerama.QueryScreens(X).Reply()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Printf("Number of heads: %d\n", reply.Number)
|
||||
for i, screen := range reply.ScreenInfo {
|
||||
fmt.Printf("%d :: X: %d, Y: %d, Width: %d, Height: %d\n",
|
||||
i, screen.XOrg, screen.YOrg, screen.Width, screen.Height)
|
||||
}
|
||||
}
|
||||
|
||||
Parallelism
|
||||
|
||||
XGB can benefit greatly from parallelism due to its concurrent design. For
|
||||
evidence of this claim, please see the benchmarks in xproto/xproto_test.go.
|
||||
|
||||
Tests
|
||||
|
||||
xproto/xproto_test.go contains a number of contrived tests that stress
|
||||
particular corners of XGB that I presume could be problem areas. Namely:
|
||||
requests with no replies, requests with replies, checked errors, unchecked
|
||||
errors, sequence number wrapping, cookie buffer flushing (i.e., forcing a round
|
||||
trip every N requests made that don't have a reply), getting/setting properties
|
||||
and creating a window and listening to StructureNotify events.
|
||||
|
||||
Code Generator
|
||||
|
||||
Both XCB and xpyb use the same Python module (xcbgen) for a code generator. XGB
|
||||
(before this fork) used the same code generator as well, but in my attempt to
|
||||
add support for more extensions, I found the code generator extremely difficult
|
||||
to work with. Therefore, I re-wrote the code generator in Go. It can be found
|
||||
in its own sub-package, xgbgen, of xgb. My design of xgbgen includes a rough
|
||||
consideration that it could be used for other languages.
|
||||
|
||||
What works
|
||||
|
||||
I am reasonably confident that the core X protocol is in full working form. I've
|
||||
also tested the Xinerama and RandR extensions sparingly. Many of the other
|
||||
existing extensions have Go source generated (and are compilable) and are
|
||||
included in this package, but I am currently unsure of their status. They
|
||||
*should* work.
|
||||
|
||||
What does not work
|
||||
|
||||
XKB is the only extension that intentionally does not work, although I suspect
|
||||
that GLX also does not work (however, there is Go source code for GLX that
|
||||
compiles, unlike XKB). I don't currently have any intention of getting XKB
|
||||
working, due to its complexity and my current mental incapacity to test it.
|
||||
|
||||
*/
|
||||
package xgb
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package xgb
|
||||
|
||||
/*
|
||||
help.go is meant to contain a rough hodge podge of functions that are mainly
|
||||
used in the auto generated code. Indeed, several functions here are simple
|
||||
wrappers so that the sub-packages don't need to be smart about which stdlib
|
||||
packages to import.
|
||||
|
||||
Also, the 'Get..' and 'Put..' functions are used through the core xgb package
|
||||
too. (xgbutil uses them too.)
|
||||
*/
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// StringsJoin is an alias to strings.Join. It allows us to avoid having to
|
||||
// import 'strings' in each of the generated Go files.
|
||||
func StringsJoin(ss []string, sep string) string {
|
||||
return strings.Join(ss, sep)
|
||||
}
|
||||
|
||||
// Sprintf is so we don't need to import 'fmt' in the generated Go files.
|
||||
func Sprintf(format string, v ...interface{}) string {
|
||||
return fmt.Sprintf(format, v...)
|
||||
}
|
||||
|
||||
// Errorf is just a wrapper for fmt.Errorf. Exists for the same reason
|
||||
// that 'stringsJoin' and 'sprintf' exists.
|
||||
func Errorf(format string, v ...interface{}) error {
|
||||
return fmt.Errorf(format, v...)
|
||||
}
|
||||
|
||||
// Pad a length to align on 4 bytes.
|
||||
func Pad(n int) int {
|
||||
return (n + 3) & ^3
|
||||
}
|
||||
|
||||
// PopCount counts the number of bits set in a value list mask.
|
||||
func PopCount(mask0 int) int {
|
||||
mask := uint32(mask0)
|
||||
n := 0
|
||||
for i := uint32(0); i < 32; i++ {
|
||||
if mask&(1<<i) != 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Put16 takes a 16 bit integer and copies it into a byte slice.
|
||||
func Put16(buf []byte, v uint16) {
|
||||
buf[0] = byte(v)
|
||||
buf[1] = byte(v >> 8)
|
||||
}
|
||||
|
||||
// Put32 takes a 32 bit integer and copies it into a byte slice.
|
||||
func Put32(buf []byte, v uint32) {
|
||||
buf[0] = byte(v)
|
||||
buf[1] = byte(v >> 8)
|
||||
buf[2] = byte(v >> 16)
|
||||
buf[3] = byte(v >> 24)
|
||||
}
|
||||
|
||||
// Put64 takes a 64 bit integer and copies it into a byte slice.
|
||||
func Put64(buf []byte, v uint64) {
|
||||
buf[0] = byte(v)
|
||||
buf[1] = byte(v >> 8)
|
||||
buf[2] = byte(v >> 16)
|
||||
buf[3] = byte(v >> 24)
|
||||
buf[4] = byte(v >> 32)
|
||||
buf[5] = byte(v >> 40)
|
||||
buf[6] = byte(v >> 48)
|
||||
buf[7] = byte(v >> 56)
|
||||
}
|
||||
|
||||
// Get16 constructs a 16 bit integer from the beginning of a byte slice.
|
||||
func Get16(buf []byte) uint16 {
|
||||
v := uint16(buf[0])
|
||||
v |= uint16(buf[1]) << 8
|
||||
return v
|
||||
}
|
||||
|
||||
// Get32 constructs a 32 bit integer from the beginning of a byte slice.
|
||||
func Get32(buf []byte) uint32 {
|
||||
v := uint32(buf[0])
|
||||
v |= uint32(buf[1]) << 8
|
||||
v |= uint32(buf[2]) << 16
|
||||
v |= uint32(buf[3]) << 24
|
||||
return v
|
||||
}
|
||||
|
||||
// Get64 constructs a 64 bit integer from the beginning of a byte slice.
|
||||
func Get64(buf []byte) uint64 {
|
||||
v := uint64(buf[0])
|
||||
v |= uint64(buf[1]) << 8
|
||||
v |= uint64(buf[2]) << 16
|
||||
v |= uint64(buf[3]) << 24
|
||||
v |= uint64(buf[4]) << 32
|
||||
v |= uint64(buf[5]) << 40
|
||||
v |= uint64(buf[6]) << 48
|
||||
v |= uint64(buf[7]) << 56
|
||||
return v
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package xgb
|
||||
|
||||
// Sync sends a round trip request and waits for the response.
|
||||
// This forces all pending cookies to be dealt with.
|
||||
// You actually shouldn't need to use this like you might with Xlib. Namely,
|
||||
// buffers are automatically flushed using Go's channels and round trip requests
|
||||
// are forced where appropriate automatically.
|
||||
func (c *Conn) Sync() {
|
||||
cookie := c.NewCookie(true, true)
|
||||
c.NewRequest(c.getInputFocusRequest(), cookie)
|
||||
cookie.Reply() // wait for the buffer to clear
|
||||
}
|
||||
|
||||
// getInputFocusRequest writes the raw bytes to a buffer.
|
||||
// It is duplicated from xproto/xproto.go.
|
||||
func (c *Conn) getInputFocusRequest() []byte {
|
||||
size := 4
|
||||
b := 0
|
||||
buf := make([]byte, size)
|
||||
|
||||
buf[b] = 43 // request opcode
|
||||
b += 1
|
||||
|
||||
b += 1 // padding
|
||||
Put16(buf[b:], uint16(size/4)) // write request size in 4-byte units
|
||||
b += 2
|
||||
|
||||
return buf
|
||||
}
|
||||
+554
@@ -0,0 +1,554 @@
|
||||
package xgb
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
// Where to log error-messages. Defaults to stderr.
|
||||
// To disable logging, just set this to log.New(ioutil.Discard, "", 0)
|
||||
Logger = log.New(os.Stderr, "XGB: ", log.Lshortfile)
|
||||
)
|
||||
|
||||
const (
|
||||
// cookieBuffer represents the queue size of cookies existing at any
|
||||
// point in time. The size of the buffer is really only important when
|
||||
// there are many requests without replies made in sequence. Once the
|
||||
// buffer fills, a round trip request is made to clear the buffer.
|
||||
cookieBuffer = 1000
|
||||
|
||||
// xidBuffer represents the queue size of the xid channel.
|
||||
// I don't think this value matters much, since xid generation is not
|
||||
// that expensive.
|
||||
xidBuffer = 5
|
||||
|
||||
// seqBuffer represents the queue size of the sequence number channel.
|
||||
// I don't think this value matters much, since sequence number generation
|
||||
// is not that expensive.
|
||||
seqBuffer = 5
|
||||
|
||||
// reqBuffer represents the queue size of the number of requests that
|
||||
// can be made until new ones block. This value seems OK.
|
||||
reqBuffer = 100
|
||||
|
||||
// eventBuffer represents the queue size of the number of events or errors
|
||||
// that can be loaded off the wire and not grabbed with WaitForEvent
|
||||
// until reading an event blocks. This value should be big enough to handle
|
||||
// bursts of events.
|
||||
eventBuffer = 5000
|
||||
)
|
||||
|
||||
// A Conn represents a connection to an X server.
|
||||
type Conn struct {
|
||||
host string
|
||||
conn net.Conn
|
||||
display string
|
||||
DisplayNumber int
|
||||
DefaultScreen int
|
||||
SetupBytes []byte
|
||||
|
||||
setupResourceIdBase uint32
|
||||
setupResourceIdMask uint32
|
||||
|
||||
eventChan chan eventOrError
|
||||
cookieChan chan *Cookie
|
||||
xidChan chan xid
|
||||
seqChan chan uint16
|
||||
reqChan chan *request
|
||||
closing chan chan struct{}
|
||||
|
||||
// ExtLock is a lock used whenever new extensions are initialized.
|
||||
// It should not be used. It is exported for use in the extension
|
||||
// sub-packages.
|
||||
ExtLock sync.RWMutex
|
||||
|
||||
// Extensions is a map from extension name to major opcode. It should
|
||||
// not be used. It is exported for use in the extension sub-packages.
|
||||
Extensions map[string]byte
|
||||
}
|
||||
|
||||
// NewConn creates a new connection instance. It initializes locks, data
|
||||
// structures, and performs the initial handshake. (The code for the handshake
|
||||
// has been relegated to conn.go.)
|
||||
func NewConn() (*Conn, error) {
|
||||
return NewConnDisplay("")
|
||||
}
|
||||
|
||||
// NewConnDisplay is just like NewConn, but allows a specific DISPLAY
|
||||
// string to be used.
|
||||
// If 'display' is empty it will be taken from os.Getenv("DISPLAY").
|
||||
//
|
||||
// Examples:
|
||||
// NewConn(":1") -> net.Dial("unix", "", "/tmp/.X11-unix/X1")
|
||||
// NewConn("/tmp/launch-12/:0") -> net.Dial("unix", "", "/tmp/launch-12/:0")
|
||||
// NewConn("hostname:2.1") -> net.Dial("tcp", "", "hostname:6002")
|
||||
// NewConn("tcp/hostname:1.0") -> net.Dial("tcp", "", "hostname:6001")
|
||||
func NewConnDisplay(display string) (*Conn, error) {
|
||||
conn := &Conn{}
|
||||
|
||||
// First connect. This reads authority, checks DISPLAY environment
|
||||
// variable, and loads the initial Setup info.
|
||||
err := conn.connect(display)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return postNewConn(conn)
|
||||
}
|
||||
|
||||
// NewConnDisplay is just like NewConn, but allows a specific net.Conn
|
||||
// to be used.
|
||||
func NewConnNet(netConn net.Conn) (*Conn, error) {
|
||||
conn := &Conn{}
|
||||
|
||||
// First connect. This reads authority, checks DISPLAY environment
|
||||
// variable, and loads the initial Setup info.
|
||||
err := conn.connectNet(netConn)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return postNewConn(conn)
|
||||
}
|
||||
|
||||
func postNewConn(conn *Conn) (*Conn, error) {
|
||||
conn.Extensions = make(map[string]byte)
|
||||
|
||||
conn.cookieChan = make(chan *Cookie, cookieBuffer)
|
||||
conn.xidChan = make(chan xid, xidBuffer)
|
||||
conn.seqChan = make(chan uint16, seqBuffer)
|
||||
conn.reqChan = make(chan *request, reqBuffer)
|
||||
conn.eventChan = make(chan eventOrError, eventBuffer)
|
||||
conn.closing = make(chan chan struct{}, 1)
|
||||
|
||||
go conn.generateXIds()
|
||||
go conn.generateSeqIds()
|
||||
go conn.sendRequests()
|
||||
go conn.readResponses()
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// Close gracefully closes the connection to the X server.
|
||||
func (c *Conn) Close() {
|
||||
close(c.reqChan)
|
||||
}
|
||||
|
||||
// Event is an interface that can contain any of the events returned by the
|
||||
// server. Use a type assertion switch to extract the Event structs.
|
||||
type Event interface {
|
||||
Bytes() []byte
|
||||
String() string
|
||||
}
|
||||
|
||||
// NewEventFun is the type of function use to construct events from raw bytes.
|
||||
// It should not be used. It is exported for use in the extension sub-packages.
|
||||
type NewEventFun func(buf []byte) Event
|
||||
|
||||
// NewEventFuncs is a map from event numbers to functions that create
|
||||
// the corresponding event. It should not be used. It is exported for use
|
||||
// in the extension sub-packages.
|
||||
var NewEventFuncs = make(map[int]NewEventFun)
|
||||
|
||||
// NewExtEventFuncs is a temporary map that stores event constructor functions
|
||||
// for each extension. When an extension is initialized, each event for that
|
||||
// extension is added to the 'NewEventFuncs' map. It should not be used. It is
|
||||
// exported for use in the extension sub-packages.
|
||||
var NewExtEventFuncs = make(map[string]map[int]NewEventFun)
|
||||
|
||||
// Error is an interface that can contain any of the errors returned by
|
||||
// the server. Use a type assertion switch to extract the Error structs.
|
||||
type Error interface {
|
||||
SequenceId() uint16
|
||||
BadId() uint32
|
||||
Error() string
|
||||
}
|
||||
|
||||
// NewErrorFun is the type of function use to construct errors from raw bytes.
|
||||
// It should not be used. It is exported for use in the extension sub-packages.
|
||||
type NewErrorFun func(buf []byte) Error
|
||||
|
||||
// NewErrorFuncs is a map from error numbers to functions that create
|
||||
// the corresponding error. It should not be used. It is exported for use in
|
||||
// the extension sub-packages.
|
||||
var NewErrorFuncs = make(map[int]NewErrorFun)
|
||||
|
||||
// NewExtErrorFuncs is a temporary map that stores error constructor functions
|
||||
// for each extension. When an extension is initialized, each error for that
|
||||
// extension is added to the 'NewErrorFuncs' map. It should not be used. It is
|
||||
// exported for use in the extension sub-packages.
|
||||
var NewExtErrorFuncs = make(map[string]map[int]NewErrorFun)
|
||||
|
||||
// eventOrError corresponds to values that can be either an event or an
|
||||
// error.
|
||||
type eventOrError interface{}
|
||||
|
||||
// NewId generates a new unused ID for use with requests like CreateWindow.
|
||||
// If no new ids can be generated, the id returned is 0 and error is non-nil.
|
||||
// This shouldn't be used directly, and is exported for use in the extension
|
||||
// sub-packages.
|
||||
// If you need identifiers, use the appropriate constructor.
|
||||
// e.g., For a window id, use xproto.NewWindowId. For
|
||||
// a new pixmap id, use xproto.NewPixmapId. And so on.
|
||||
func (c *Conn) NewId() (uint32, error) {
|
||||
xid := <-c.xidChan
|
||||
if xid.err != nil {
|
||||
return 0, xid.err
|
||||
}
|
||||
return xid.id, nil
|
||||
}
|
||||
|
||||
// xid encapsulates a resource identifier being sent over the Conn.xidChan
|
||||
// channel. If no new resource id can be generated, id is set to 0 and a
|
||||
// non-nil error is set in xid.err.
|
||||
type xid struct {
|
||||
id uint32
|
||||
err error
|
||||
}
|
||||
|
||||
// generateXids sends new Ids down the channel for NewId to use.
|
||||
// generateXids should be run in its own goroutine.
|
||||
// This needs to be updated to use the XC Misc extension once we run out of
|
||||
// new ids.
|
||||
// Thanks to libxcb/src/xcb_xid.c. This code is greatly inspired by it.
|
||||
func (conn *Conn) generateXIds() {
|
||||
defer close(conn.xidChan)
|
||||
|
||||
// This requires some explanation. From the horse's mouth:
|
||||
// "The resource-id-mask contains a single contiguous set of bits (at least
|
||||
// 18). The client allocates resource IDs for types WINDOW, PIXMAP,
|
||||
// CURSOR, FONT, GCONTEXT, and COLORMAP by choosing a value with only some
|
||||
// subset of these bits set and ORing it with resource-id-base. Only values
|
||||
// constructed in this way can be used to name newly created resources over
|
||||
// this connection."
|
||||
// So for example (using 8 bit integers), the mask might look like:
|
||||
// 00111000
|
||||
// So that valid values would be 00101000, 00110000, 00001000, and so on.
|
||||
// Thus, the idea is to increment it by the place of the last least
|
||||
// significant '1'. In this case, that value would be 00001000. To get
|
||||
// that value, we can AND the original mask with its two's complement:
|
||||
// 00111000 & 11001000 = 00001000.
|
||||
// And we use that value to increment the last resource id to get a new one.
|
||||
// (And then, of course, we OR it with resource-id-base.)
|
||||
inc := conn.setupResourceIdMask & -conn.setupResourceIdMask
|
||||
max := conn.setupResourceIdMask
|
||||
last := uint32(0)
|
||||
for {
|
||||
// TODO: Use the XC Misc extension to look for released ids.
|
||||
if last > 0 && last >= max-inc+1 {
|
||||
conn.xidChan <- xid{
|
||||
id: 0,
|
||||
err: errors.New("There are no more available resource" +
|
||||
"identifiers."),
|
||||
}
|
||||
}
|
||||
|
||||
last += inc
|
||||
conn.xidChan <- xid{
|
||||
id: last | conn.setupResourceIdBase,
|
||||
err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newSeqId fetches the next sequence id from the Conn.seqChan channel.
|
||||
func (c *Conn) newSequenceId() uint16 {
|
||||
return <-c.seqChan
|
||||
}
|
||||
|
||||
// generateSeqIds returns new sequence ids. It is meant to be run in its
|
||||
// own goroutine.
|
||||
// A sequence id is generated for *every* request. It's the identifier used
|
||||
// to match up replies with requests.
|
||||
// Since sequence ids can only be 16 bit integers we start over at zero when it
|
||||
// comes time to wrap.
|
||||
// N.B. As long as the cookie buffer is less than 2^16, there are no limitations
|
||||
// on the number (or kind) of requests made in sequence.
|
||||
func (c *Conn) generateSeqIds() {
|
||||
defer close(c.seqChan)
|
||||
|
||||
seqid := uint16(1)
|
||||
for {
|
||||
c.seqChan <- seqid
|
||||
if seqid == uint16((1<<16)-1) {
|
||||
seqid = 0
|
||||
} else {
|
||||
seqid++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// request encapsulates a buffer of raw bytes (containing the request data)
|
||||
// and a cookie, which when combined represents a single request.
|
||||
// The cookie is used to match up the reply/error.
|
||||
type request struct {
|
||||
buf []byte
|
||||
cookie *Cookie
|
||||
|
||||
// seq is closed when the request (cookie) has been sequenced by the Conn.
|
||||
seq chan struct{}
|
||||
}
|
||||
|
||||
// NewRequest takes the bytes and a cookie of a particular request, constructs
|
||||
// a request type, and sends it over the Conn.reqChan channel.
|
||||
// Note that the sequence number is added to the cookie after it is sent
|
||||
// over the request channel, but before it is sent to X.
|
||||
//
|
||||
// Note that you may safely use NewRequest to send arbitrary byte requests
|
||||
// to X. The resulting cookie can be used just like any normal cookie and
|
||||
// abides by the same rules, except that for replies, you'll get back the
|
||||
// raw byte data. This may be useful for performance critical sections where
|
||||
// every allocation counts, since all X requests in XGB allocate a new byte
|
||||
// slice. In contrast, NewRequest allocates one small request struct and
|
||||
// nothing else. (Except when the cookie buffer is full and has to be flushed.)
|
||||
//
|
||||
// If you're using NewRequest manually, you'll need to use NewCookie to create
|
||||
// a new cookie.
|
||||
//
|
||||
// In all likelihood, you should be able to copy and paste with some minor
|
||||
// edits the generated code for the request you want to issue.
|
||||
func (c *Conn) NewRequest(buf []byte, cookie *Cookie) {
|
||||
seq := make(chan struct{})
|
||||
c.reqChan <- &request{buf: buf, cookie: cookie, seq: seq}
|
||||
<-seq
|
||||
}
|
||||
|
||||
// sendRequests is run as a single goroutine that takes requests and writes
|
||||
// the bytes to the wire and adds the cookie to the cookie queue.
|
||||
// It is meant to be run as its own goroutine.
|
||||
func (c *Conn) sendRequests() {
|
||||
defer close(c.cookieChan)
|
||||
|
||||
for req := range c.reqChan {
|
||||
// ho there! if the cookie channel is nearly full, force a round
|
||||
// trip to clear out the cookie buffer.
|
||||
// Note that we circumvent the request channel, because we're *in*
|
||||
// the request channel.
|
||||
if len(c.cookieChan) == cookieBuffer-1 {
|
||||
if err := c.noop(); err != nil {
|
||||
// Shut everything down.
|
||||
break
|
||||
}
|
||||
}
|
||||
req.cookie.Sequence = c.newSequenceId()
|
||||
c.cookieChan <- req.cookie
|
||||
c.writeBuffer(req.buf)
|
||||
close(req.seq)
|
||||
}
|
||||
response := make(chan struct{})
|
||||
c.closing <- response
|
||||
c.noop() // Flush the response reading goroutine, ignore error.
|
||||
<-response
|
||||
c.conn.Close()
|
||||
}
|
||||
|
||||
// noop circumvents the usual request sending goroutines and forces a round
|
||||
// trip request manually.
|
||||
func (c *Conn) noop() error {
|
||||
cookie := c.NewCookie(true, true)
|
||||
cookie.Sequence = c.newSequenceId()
|
||||
c.cookieChan <- cookie
|
||||
if err := c.writeBuffer(c.getInputFocusRequest()); err != nil {
|
||||
return err
|
||||
}
|
||||
cookie.Reply() // wait for the buffer to clear
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeBuffer is a convenience function for writing a byte slice to the wire.
|
||||
func (c *Conn) writeBuffer(buf []byte) error {
|
||||
if _, err := c.conn.Write(buf); err != nil {
|
||||
Logger.Printf("A write error is unrecoverable: %s", err)
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// readResponses is a goroutine that reads events, errors and
|
||||
// replies off the wire.
|
||||
// When an event is read, it is always added to the event channel.
|
||||
// When an error is read, if it corresponds to an existing checked cookie,
|
||||
// it is sent to that cookie's error channel. Otherwise it is added to the
|
||||
// event channel.
|
||||
// When a reply is read, it is added to the corresponding cookie's reply
|
||||
// channel. (It is an error if no such cookie exists in this case.)
|
||||
// Finally, cookies that came "before" this reply are always cleaned up.
|
||||
func (c *Conn) readResponses() {
|
||||
defer close(c.eventChan)
|
||||
|
||||
var (
|
||||
err Error
|
||||
seq uint16
|
||||
replyBytes []byte
|
||||
)
|
||||
|
||||
for {
|
||||
select {
|
||||
case respond := <-c.closing:
|
||||
respond <- struct{}{}
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
buf := make([]byte, 32)
|
||||
err, seq = nil, 0
|
||||
if _, err := io.ReadFull(c.conn, buf); err != nil {
|
||||
Logger.Printf("A read error is unrecoverable: %s", err)
|
||||
c.eventChan <- err
|
||||
c.Close()
|
||||
continue
|
||||
}
|
||||
switch buf[0] {
|
||||
case 0: // This is an error
|
||||
// Use the constructor function for this error (that is auto
|
||||
// generated) by looking it up by the error number.
|
||||
newErrFun, ok := NewErrorFuncs[int(buf[1])]
|
||||
if !ok {
|
||||
Logger.Printf("BUG: Could not find error constructor function "+
|
||||
"for error with number %d.", buf[1])
|
||||
continue
|
||||
}
|
||||
err = newErrFun(buf)
|
||||
seq = err.SequenceId()
|
||||
|
||||
// This error is either sent to the event channel or a specific
|
||||
// cookie's error channel below.
|
||||
case 1: // This is a reply
|
||||
seq = Get16(buf[2:])
|
||||
|
||||
// check to see if this reply has more bytes to be read
|
||||
size := Get32(buf[4:])
|
||||
if size > 0 {
|
||||
byteCount := 32 + size*4
|
||||
biggerBuf := make([]byte, byteCount)
|
||||
copy(biggerBuf[:32], buf)
|
||||
if _, err := io.ReadFull(c.conn, biggerBuf[32:]); err != nil {
|
||||
Logger.Printf("A read error is unrecoverable: %s", err)
|
||||
c.eventChan <- err
|
||||
c.Close()
|
||||
continue
|
||||
}
|
||||
replyBytes = biggerBuf
|
||||
} else {
|
||||
replyBytes = buf
|
||||
}
|
||||
|
||||
// This reply is sent to its corresponding cookie below.
|
||||
default: // This is an event
|
||||
// Use the constructor function for this event (like for errors,
|
||||
// and is also auto generated) by looking it up by the event number.
|
||||
// Note that we AND the event number with 127 so that we ignore
|
||||
// the most significant bit (which is set when it was sent from
|
||||
// a SendEvent request).
|
||||
evNum := int(buf[0] & 127)
|
||||
newEventFun, ok := NewEventFuncs[evNum]
|
||||
if !ok {
|
||||
Logger.Printf("BUG: Could not find event construct function "+
|
||||
"for event with number %d.", evNum)
|
||||
continue
|
||||
}
|
||||
c.eventChan <- newEventFun(buf)
|
||||
continue
|
||||
}
|
||||
|
||||
// At this point, we have a sequence number and we're either
|
||||
// processing an error or a reply, which are both responses to
|
||||
// requests. So all we have to do is find the cookie corresponding
|
||||
// to this error/reply, and send the appropriate data to it.
|
||||
// In doing so, we make sure that any cookies that came before it
|
||||
// are marked as successful if they are void and checked.
|
||||
// If there's a cookie that requires a reply that is before this
|
||||
// reply, then something is wrong.
|
||||
for cookie := range c.cookieChan {
|
||||
// This is the cookie we're looking for. Process and break.
|
||||
if cookie.Sequence == seq {
|
||||
if err != nil { // this is an error to a request
|
||||
// synchronous processing
|
||||
if cookie.errorChan != nil {
|
||||
cookie.errorChan <- err
|
||||
} else { // asynchronous processing
|
||||
c.eventChan <- err
|
||||
// if this is an unchecked reply, ping the cookie too
|
||||
if cookie.pingChan != nil {
|
||||
cookie.pingChan <- true
|
||||
}
|
||||
}
|
||||
} else { // this is a reply
|
||||
if cookie.replyChan == nil {
|
||||
Logger.Printf("Reply with sequence id %d does not "+
|
||||
"have a cookie with a valid reply channel.", seq)
|
||||
continue
|
||||
} else {
|
||||
cookie.replyChan <- replyBytes
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
switch {
|
||||
// Checked requests with replies
|
||||
case cookie.replyChan != nil && cookie.errorChan != nil:
|
||||
Logger.Printf("Found cookie with sequence id %d that is "+
|
||||
"expecting a reply but will never get it. Currently "+
|
||||
"on sequence number %d", cookie.Sequence, seq)
|
||||
// Unchecked requests with replies
|
||||
case cookie.replyChan != nil && cookie.pingChan != nil:
|
||||
Logger.Printf("Found cookie with sequence id %d that is "+
|
||||
"expecting a reply (and not an error) but will never "+
|
||||
"get it. Currently on sequence number %d",
|
||||
cookie.Sequence, seq)
|
||||
// Checked requests without replies
|
||||
case cookie.pingChan != nil && cookie.errorChan != nil:
|
||||
cookie.pingChan <- true
|
||||
// Unchecked requests without replies don't have any channels,
|
||||
// so we can't do anything with them except let them pass by.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// processEventOrError takes an eventOrError, type switches on it,
|
||||
// and returns it in Go idiomatic style.
|
||||
func processEventOrError(everr eventOrError) (Event, Error) {
|
||||
switch ee := everr.(type) {
|
||||
case Event:
|
||||
return ee, nil
|
||||
case Error:
|
||||
return nil, ee
|
||||
default:
|
||||
Logger.Printf("Invalid event/error type: %T", everr)
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// WaitForEvent returns the next event from the server.
|
||||
// It will block until an event is available.
|
||||
// WaitForEvent returns either an Event or an Error. (Returning both
|
||||
// is a bug.) Note than an Error here is an X error and not an XGB error. That
|
||||
// is, X errors are sometimes completely expected (and you may want to ignore
|
||||
// them in some cases).
|
||||
//
|
||||
// If both the event and error are nil, then the connection has been closed.
|
||||
func (c *Conn) WaitForEvent() (Event, Error) {
|
||||
return processEventOrError(<-c.eventChan)
|
||||
}
|
||||
|
||||
// PollForEvent returns the next event from the server if one is available in
|
||||
// the internal queue without blocking. Note that unlike WaitForEvent, both
|
||||
// Event and Error could be nil. Indeed, they are both nil when the event queue
|
||||
// is empty.
|
||||
func (c *Conn) PollForEvent() (Event, Error) {
|
||||
select {
|
||||
case everr := <-c.eventChan:
|
||||
return processEventOrError(everr)
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
+14910
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
Submodule vendor/kryon updated: 4fa7f1f0c4...2ddeeecbdd.
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
# github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc
|
||||
## explicit; go 1.16
|
||||
github.com/BurntSushi/xgb
|
||||
github.com/BurntSushi/xgb/xproto
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
package gopass
|
||||
package pass
|
||||
|
||||
// Version is the current application version.
|
||||
const Version = "0.1.2"
|
||||
const Version = "0.2.2"
|
||||
+4
-2
@@ -9,6 +9,7 @@ rm -rf "$out_dir"
|
||||
mkdir -p "$out_dir/app"
|
||||
cp "$root_dir/web/site/index.html" "$out_dir/index.html"
|
||||
cp "$root_dir/web/site/styles.css" "$out_dir/styles.css"
|
||||
cp "$root_dir/web/site/home.js" "$out_dir/home.js"
|
||||
cp "$root_dir/web/site/app/index.html" "$out_dir/app/index.html"
|
||||
cp "$root_dir/web/site/app/app.js" "$out_dir/app/app.js"
|
||||
cp "$root_dir/web/site/CNAME" "$out_dir/CNAME"
|
||||
@@ -21,7 +22,8 @@ cp -R "$root_dir/web/site/app/icons" "$out_dir/app/icons"
|
||||
cp "$root_dir/web/site/app/sw.js" "$out_dir/app/sw.js"
|
||||
cp "$goroot/lib/wasm/wasm_exec.js" "$out_dir/app/wasm_exec.js" 2>/dev/null || \
|
||||
cp "$goroot/misc/wasm/wasm_exec.js" "$out_dir/app/wasm_exec.js"
|
||||
(cd "$root_dir/web/wasm" && GOOS=js GOARCH=wasm go build -o "$out_dir/app/gopass.wasm" .)
|
||||
(cd "$root_dir/web/wasm" && GOOS=js GOARCH=wasm go build -o "$out_dir/app/pass.wasm" .)
|
||||
|
||||
test -s "$out_dir/app/gopass.wasm"
|
||||
test -s "$out_dir/app/pass.wasm"
|
||||
test -s "$out_dir/home.js"
|
||||
printf 'built site at %s\n' "$out_dir"
|
||||
+9
-8
@@ -1,8 +1,9 @@
|
||||
/downloads/gopass-cli-linux-amd64.tar.gz https://github.com/waozixyz/gopass/releases/latest/download/gopass-cli-linux-amd64.tar.gz 302
|
||||
/downloads/gopass-cli-linux-arm64.tar.gz https://github.com/waozixyz/gopass/releases/latest/download/gopass-cli-linux-arm64.tar.gz 302
|
||||
/downloads/gopass-cli-darwin-amd64.tar.gz https://github.com/waozixyz/gopass/releases/latest/download/gopass-cli-darwin-amd64.tar.gz 302
|
||||
/downloads/gopass-cli-darwin-arm64.tar.gz https://github.com/waozixyz/gopass/releases/latest/download/gopass-cli-darwin-arm64.tar.gz 302
|
||||
/downloads/gopass-cli-windows-amd64.zip https://github.com/waozixyz/gopass/releases/latest/download/gopass-cli-windows-amd64.zip 302
|
||||
/downloads/gopass-cli-windows-arm64.zip https://github.com/waozixyz/gopass/releases/latest/download/gopass-cli-windows-arm64.zip 302
|
||||
/downloads/gopass-gui-linux-amd64.tar.gz https://github.com/waozixyz/gopass/releases/latest/download/gopass-gui-linux-amd64.tar.gz 302
|
||||
/downloads/gopass-gui-linux-arm64.tar.gz https://github.com/waozixyz/gopass/releases/latest/download/gopass-gui-linux-arm64.tar.gz 302
|
||||
/downloads/pass-cli-linux-amd64.tar.gz https://github.com/waozixyz/pass/releases/latest/download/pass-cli-linux-amd64.tar.gz 302
|
||||
/downloads/pass-cli-linux-arm64.tar.gz https://github.com/waozixyz/pass/releases/latest/download/pass-cli-linux-arm64.tar.gz 302
|
||||
/downloads/pass-cli-darwin-amd64.tar.gz https://github.com/waozixyz/pass/releases/latest/download/pass-cli-darwin-amd64.tar.gz 302
|
||||
/downloads/pass-cli-darwin-arm64.tar.gz https://github.com/waozixyz/pass/releases/latest/download/pass-cli-darwin-arm64.tar.gz 302
|
||||
/downloads/pass-cli-windows-amd64.zip https://github.com/waozixyz/pass/releases/latest/download/pass-cli-windows-amd64.zip 302
|
||||
/downloads/pass-cli-windows-arm64.zip https://github.com/waozixyz/pass/releases/latest/download/pass-cli-windows-arm64.zip 302
|
||||
/downloads/pass-gui-linux-amd64.tar.gz https://github.com/waozixyz/pass/releases/latest/download/pass-gui-linux-amd64.tar.gz 302
|
||||
/downloads/pass-gui-linux-arm64.tar.gz https://github.com/waozixyz/pass/releases/latest/download/pass-gui-linux-arm64.tar.gz 302
|
||||
/downloads/pass-android.apk https://github.com/waozixyz/pass/releases/latest/download/pass-android.apk 302
|
||||
+3
-3
@@ -3,12 +3,12 @@
|
||||
const byId = id => document.getElementById(id);
|
||||
const generate = byId('generate'), copy = byId('copy'), result = byId('result'), message = byId('message');
|
||||
let copied = '', clearTimer = 0;
|
||||
document.addEventListener('gopass-ready', () => { byId('runtime-status').textContent = 'Ready · runs locally'; generate.disabled = false; });
|
||||
document.addEventListener('pass-ready', () => { byId('runtime-status').textContent = 'Ready · runs locally'; generate.disabled = false; });
|
||||
const go = new Go();
|
||||
WebAssembly.instantiateStreaming(fetch('gopass.wasm'), go.importObject).then(instance => go.run(instance.instance)).catch(error => { byId('runtime-status').textContent = 'Generator failed to load'; message.textContent = error; });
|
||||
WebAssembly.instantiateStreaming(fetch('pass.wasm'), go.importObject).then(instance => go.run(instance.instance)).catch(error => { byId('runtime-status').textContent = 'Generator failed to load'; message.textContent = error; });
|
||||
byId('reveal').addEventListener('click', () => { const master = byId('master'); master.type = master.type === 'password' ? 'text' : 'password'; byId('reveal').textContent = master.type === 'password' ? 'Reveal' : 'Hide'; });
|
||||
generate.addEventListener('click', () => {
|
||||
const response = window.gopassGenerate(byId('site').value, byId('login').value, byId('master').value, Number(byId('length').value), Number(byId('counter').value), byId('lower').checked, byId('upper').checked, byId('digits').checked, byId('symbols').checked, byId('exclude').value);
|
||||
const response = window.passGenerate(byId('site').value, byId('login').value, byId('master').value, Number(byId('length').value), Number(byId('counter').value), byId('lower').checked, byId('upper').checked, byId('digits').checked, byId('symbols').checked, byId('exclude').value);
|
||||
if (response.error) { result.textContent = 'Unable to generate'; message.textContent = response.error; copy.disabled = true; return; }
|
||||
result.textContent = response.password; message.textContent = 'Generated locally in this tab'; copy.disabled = false;
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f3f1ea"><title>Generate — gopass</title><meta name="description" content="Generate a deterministic password locally in your browser."><link rel="manifest" href="/manifest.webmanifest"><link rel="icon" type="image/png" sizes="32x32" href="/icons/favicon-32.png"><link rel="apple-touch-icon" href="/icons/apple-touch-icon.png"><link rel="stylesheet" href="/styles.css"></head>
|
||||
<body class="app-page"><header class="site-header"><div class="site-header-inner"><a class="brand" href="/"><img src="/icons/icon-192.png" alt="">GOPASS</a><nav class="header-nav"><a href="/">Home</a><span id="runtime-status">Loading secure generator…</span></nav></div></header>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f3f1ea"><title>Generate — pass</title><meta name="description" content="Generate a deterministic password locally in your browser."><link rel="manifest" href="/manifest.webmanifest"><link rel="icon" type="image/png" sizes="32x32" href="/icons/favicon-32.png"><link rel="apple-touch-icon" href="/icons/apple-touch-icon.png"><link rel="stylesheet" href="/styles.css"></head>
|
||||
<body class="app-page"><header class="site-header"><div class="site-header-inner"><a class="brand" href="/"><img src="/icons/icon-192.png" alt="">PASS</a><nav class="header-nav"><a href="/">Home</a><span id="runtime-status">Loading secure generator…</span></nav></div></header>
|
||||
<main class="generator-shell"><section class="generator-card"><p class="eyebrow">LOCAL PASSWORD GENERATOR</p><h1>Generate a password</h1><div class="form-grid">
|
||||
<label>Site<input id="site" autocomplete="off" placeholder="example.org"></label><label>Login<input id="login" autocomplete="username" placeholder="[email protected]"></label>
|
||||
<label class="wide">Master password<span class="password-wrap"><input id="master" type="password" autocomplete="current-password"><button id="reveal" type="button" class="inline">Reveal</button></span></label>
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
const cacheName = 'gopass-app-v2';
|
||||
const appFiles = ['/app/', '/app/app.js', '/app/wasm_exec.js', '/app/gopass.wasm', '/styles.css', '/manifest.webmanifest', '/icons/icon-192.png', '/icons/icon-512.png'];
|
||||
const cacheName = 'pass-app-v2';
|
||||
const appFiles = ['/app/', '/app/app.js', '/app/wasm_exec.js', '/app/pass.wasm', '/styles.css', '/manifest.webmanifest', '/icons/icon-192.png', '/icons/icon-512.png'];
|
||||
self.addEventListener('install', event => {
|
||||
self.skipWaiting();
|
||||
event.waitUntil(caches.open(cacheName).then(cache => cache.addAll(appFiles)));
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
(() => {
|
||||
const byId = id => document.getElementById(id);
|
||||
const card = byId('generator');
|
||||
const generate = byId('generate'), copy = byId('copy'), result = byId('result'), message = byId('message');
|
||||
let copied = '', clearTimer = 0, started = false, ready = false, pending = false;
|
||||
|
||||
function runGenerate() {
|
||||
const response = window.passGenerate(byId('site').value, byId('login').value, byId('master').value, Number(byId('length').value), Number(byId('counter').value), byId('lower').checked, byId('upper').checked, byId('digits').checked, byId('symbols').checked, byId('exclude').value);
|
||||
if (response.error) { result.textContent = 'Unable to generate'; message.textContent = response.error; copy.disabled = true; return; }
|
||||
result.textContent = response.password; message.textContent = 'Generated locally in this tab'; copy.disabled = false;
|
||||
}
|
||||
|
||||
function startLoad() {
|
||||
if (started) return;
|
||||
started = true;
|
||||
const script = document.createElement('script');
|
||||
script.src = '/app/wasm_exec.js';
|
||||
script.onload = () => {
|
||||
const go = new Go();
|
||||
WebAssembly.instantiateStreaming(fetch('/app/pass.wasm'), go.importObject).then(instance => go.run(instance.instance)).catch(error => { message.textContent = 'Generator failed to load'; generate.textContent = error; });
|
||||
};
|
||||
script.onerror = () => { message.textContent = 'Generator failed to load'; };
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
|
||||
['focusin', 'input', 'click'].forEach(type => card.addEventListener(type, startLoad, {passive: true, capture: true}));
|
||||
document.addEventListener('pass-ready', () => { ready = true; generate.disabled = false; if (pending) { pending = false; runGenerate(); } });
|
||||
|
||||
byId('reveal').addEventListener('click', () => { const master = byId('master'); master.type = master.type === 'password' ? 'text' : 'password'; byId('reveal').textContent = master.type === 'password' ? 'Reveal' : 'Hide'; });
|
||||
generate.addEventListener('click', () => { if (!ready) { pending = true; message.textContent = 'Loading secure generator…'; return; } runGenerate(); });
|
||||
copy.addEventListener('click', async () => { await navigator.clipboard.writeText(result.textContent); copied = result.textContent; message.textContent = 'Copied; clipboard clears in 20 seconds'; clearTimeout(clearTimer); clearTimer = setTimeout(async () => { try { const current = await navigator.clipboard.readText(); if (current === copied) await navigator.clipboard.writeText(''); } catch (_) {} copied = ''; }, 20000); });
|
||||
byId('clear').addEventListener('click', () => { ['site','login','master','exclude'].forEach(id => byId(id).value = ''); result.textContent = 'Your generated password appears here'; message.textContent = 'Cleared'; copy.disabled = true; byId('site').focus(); });
|
||||
})();
|
||||
+17
-8
@@ -3,8 +3,8 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>gopass — deterministic passwords</title>
|
||||
<meta name="description" content="Generate deterministic passwords locally with the BSD-licensed gopass CLI, desktop app, or browser app.">
|
||||
<title>pass — deterministic passwords</title>
|
||||
<meta name="description" content="Generate deterministic passwords locally with the BSD-licensed pass CLI, desktop app, or browser app.">
|
||||
<link rel="canonical" href="https://pass.waozi.xyz/">
|
||||
<meta name="theme-color" content="#f3f1ea">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
@@ -13,19 +13,28 @@
|
||||
<link rel="stylesheet" href="/styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header"><div class="site-header-inner"><a class="brand" href="/"><img src="/icons/icon-192.png" alt="">GOPASS</a><nav class="header-nav"><a href="#downloads">Downloads</a><a href="#privacy">Privacy</a><a href="https://waozi.xyz">Waozi ↗</a><a class="button small" href="/app/">Run Web</a></nav></div></header>
|
||||
<header class="site-header"><div class="site-header-inner"><a class="brand" href="/"><img src="/icons/icon-192.png" alt="">PASS</a><nav class="header-nav"><a href="#downloads">Downloads</a><a href="#privacy">Privacy</a><a href="https://waozi.xyz">Waozi ↗</a><a class="button small" href="/app/">Run Web</a></nav></div></header>
|
||||
<main>
|
||||
<section class="hero">
|
||||
<div><p class="eyebrow">Stateless · local · open source</p><img class="hero-icon" src="/icons/icon-192.png" alt="gopass"><h1>One master password.<br><span>Every site covered.</span></h1><p class="lede">gopass derives strong, repeatable passwords on your device. Nothing is stored, uploaded, or tracked.</p><div class="actions"><a class="button primary" href="/app/">Run Web</a><a class="button" href="#downloads">Download apps</a></div></div>
|
||||
<div class="preview"><div class="preview-head"><i></i><i></i><i></i><span>generated locally</span></div><div class="preview-body"><label>Site</label><div class="fake-input">example.org</div><label>Generated password</label><div class="password">••••••••••••••••</div><div class="privacy-line">No network requests. No password database.</div></div></div>
|
||||
<div><p class="eyebrow">Stateless · local · open source</p><img class="hero-icon" src="/icons/icon-192.png" alt="pass"><h1>One master password.<br><span>Every site covered.</span></h1><p class="lede">pass derives strong, repeatable passwords on your device. Nothing is stored, uploaded, or tracked.</p><div class="actions"><a class="button primary" href="/app/">Run Web</a><a class="button" href="#downloads">Download apps</a></div></div>
|
||||
<div class="preview" id="generator"><div class="preview-head"><i></i><i></i><i></i><span>generated locally</span></div><div class="preview-body"><div class="form-grid">
|
||||
<label>Site<input id="site" autocomplete="off" placeholder="example.org"></label><label>Login<input id="login" autocomplete="username" placeholder="[email protected]"></label>
|
||||
<label class="wide">Master password<span class="password-wrap"><input id="master" type="password" autocomplete="current-password"><button id="reveal" type="button" class="inline">Reveal</button></span></label>
|
||||
<label>Length<input id="length" type="number" min="1" max="128" value="16"></label><label>Counter<input id="counter" type="number" min="1" value="1"></label><label class="wide">Excluded characters<input id="exclude" autocomplete="off"></label>
|
||||
<fieldset class="wide"><legend>Character classes</legend><label><input id="lower" type="checkbox" checked> Lowercase</label><label><input id="upper" type="checkbox" checked> Uppercase</label><label><input id="digits" type="checkbox" checked> Digits</label><label><input id="symbols" type="checkbox" checked> Symbols</label></fieldset>
|
||||
<div class="wide actions"><button id="generate" class="button" disabled>Generate</button><button id="copy" class="button secondary" disabled>Copy</button><button id="clear" class="button ghost">Clear</button></div>
|
||||
<output id="result" class="wide" aria-live="polite">Your generated password appears here</output><p id="message" class="wide status"></p>
|
||||
</div><div class="privacy-line">No network requests. No password database.</div></div></div>
|
||||
</section>
|
||||
<section id="downloads"><p class="eyebrow">DOWNLOADS</p><h2>Choose your interface</h2><div class="cards">
|
||||
<article><span class="tag">DESKTOP</span><h3>Kryon GUI</h3><p>Visual controls, secure masked input, and clipboard clearing.</p><div class="links"><a href="/downloads/gopass-gui-linux-amd64.tar.gz">Linux x86_64</a><a href="/downloads/gopass-gui-linux-arm64.tar.gz">Linux ARM64</a></div></article>
|
||||
<article><span class="tag">TERMINAL</span><h3>CLI</h3><p>Small, scriptable binaries for servers and workstations.</p><div class="links"><a href="/downloads/gopass-cli-linux-amd64.tar.gz">Linux</a><a href="/downloads/gopass-cli-darwin-arm64.tar.gz">macOS</a><a href="/downloads/gopass-cli-windows-amd64.zip">Windows</a></div></article>
|
||||
<article><span class="tag">ANDROID</span><h3>APK</h3><p>Native Android app with the same generator and biometric-protected master password storage.</p><div class="links"><a href="/downloads/pass-android.apk">Download APK</a></div></article>
|
||||
<article><span class="tag">DESKTOP</span><h3>GUI</h3><p>Visual controls, secure masked input, and clipboard clearing.</p><div class="links"><a href="/downloads/pass-gui-linux-amd64.tar.gz">Linux x86_64</a><a href="/downloads/pass-gui-linux-arm64.tar.gz">Linux ARM64</a></div></article>
|
||||
<article><span class="tag">TERMINAL</span><h3>CLI</h3><p>Small, scriptable binaries for servers and workstations.</p><div class="links"><a href="/downloads/pass-cli-linux-amd64.tar.gz">Linux</a><a href="/downloads/pass-cli-darwin-arm64.tar.gz">macOS</a><a href="/downloads/pass-cli-windows-amd64.zip">Windows</a></div></article>
|
||||
<article><span class="tag">BROWSER</span><h3>Web app</h3><p>The same Go generator compiled to WebAssembly. Runs entirely in your tab.</p><div class="links"><a href="/app/">Open web app</a></div></article>
|
||||
</div></section>
|
||||
<section class="privacy" id="privacy"><p class="eyebrow">PRIVACY</p><h2>Your master password stays yours.</h2><p>The desktop and browser apps derive passwords locally. The website has no analytics, accounts, cookies, or backend API. Source and releases remain available under BSD-3-Clause.</p></section>
|
||||
</main>
|
||||
<footer><span>© 2026 Waozi</span><a href="https://waozi.xyz">waozi.xyz</a></footer>
|
||||
<footer><span>© 2026 <a href="https://waozi.xyz">Waozi</a></span></footer>
|
||||
<script src="home.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gopass",
|
||||
"short_name": "gopass",
|
||||
"name": "pass",
|
||||
"short_name": "pass",
|
||||
"description": "Generate deterministic passwords locally.",
|
||||
"start_url": "/app/",
|
||||
"scope": "/app/",
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
:root{--bg:#f3f1ea;--surface:#fdfcf8;--control:#eae6da;--control-hi:#fff;--ink:#2a3b40;--muted:#5d6f74;--line:rgba(42,59,64,.20);--line-strong:rgba(42,59,64,.30);--accent:#65558f;--accent-deep:#433668;--accent-soft:rgba(101,85,143,.10);--card:#f7f4ec;--radius:10px;--radius-sm:6px;--maxw:1080px;--font:ui-monospace,"SFMono-Regular",Menlo,Consolas,monospace;--bevel:0 1px 0 var(--control-hi),inset 1px 1px 0 var(--control-hi),0 2px 10px rgba(0,0,0,.04)}
|
||||
*{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:72px}body{margin:0;min-height:100vh;background:var(--bg);color:var(--ink);font:15px/1.6 var(--font);-webkit-font-smoothing:antialiased}body:before{content:"";position:fixed;inset:0;z-index:-1;background-image:linear-gradient(45deg,rgba(42,59,64,.028) 25%,transparent 25%),linear-gradient(-45deg,rgba(42,59,64,.028) 25%,transparent 25%),linear-gradient(45deg,transparent 75%,rgba(42,59,64,.028) 75%),linear-gradient(-45deg,transparent 75%,rgba(42,59,64,.028) 75%);background-position:0 0,0 16px,16px -16px,-16px 0;background-size:32px 32px;opacity:.18}a{color:var(--accent);font-weight:700;text-decoration:none}a:hover{color:var(--accent-deep)}a:active,.button:active{position:relative;top:1px;left:1px}.site-header{position:sticky;top:0;z-index:50;background:rgba(243,241,234,.92);backdrop-filter:blur(8px);border-bottom:1px solid var(--line)}.site-header-inner{max-width:var(--maxw);margin:auto;padding:10px 20px;display:flex;align-items:center;gap:16px}.brand{display:flex;align-items:center;gap:8px;color:var(--ink);font-size:15px;letter-spacing:.04em}.brand img{width:22px;height:22px;border-radius:5px;image-rendering:pixelated}.header-nav{display:flex;align-items:center;gap:18px;margin-left:auto}.header-nav>a,.header-nav span{color:var(--muted);font-size:13px}.header-nav .button{color:#fffdf8}.button,button.button{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:8px 14px;border:1px solid var(--line);border-radius:var(--radius-sm);background:var(--control);box-shadow:var(--bevel);color:var(--ink);font:700 13px var(--font);cursor:pointer}.button:hover{background:var(--surface);color:var(--accent)}.button.primary,.header-nav .button{background:var(--accent);border-color:var(--accent-deep);color:#fff}.button.secondary{background:var(--control)}.button.ghost{background:transparent}.button.small{padding:7px 12px}button:disabled{opacity:.45;cursor:not-allowed}
|
||||
.hero{max-width:var(--maxw);min-height:calc(100vh - 64px);margin:auto;padding:48px 20px 40px;display:grid;grid-template-columns:minmax(0,.9fr) minmax(360px,.8fr);gap:44px;align-items:center}.hero-icon{width:96px;height:96px;margin:4px 0 0;border:1px solid var(--line-strong);border-radius:8px;box-shadow:var(--bevel);image-rendering:pixelated}.eyebrow{display:flex;align-items:center;gap:8px;margin:0 0 12px;color:var(--accent);font-size:13px;font-weight:700;letter-spacing:.04em;text-transform:uppercase}.eyebrow:before{content:"";width:8px;height:8px;background:var(--accent);border:1px solid var(--accent-deep);border-radius:2px;box-shadow:1px 1px 0 rgba(0,0,0,.12)}h1,h2,h3{margin:0;color:var(--ink);line-height:1.15}h1{margin:14px 0 16px;font-size:clamp(42px,7vw,74px);line-height:.98}h1 span{color:var(--accent)}h2{margin-bottom:16px;font-size:clamp(26px,4vw,40px)}h3{font-size:16px}.lede{max-width:700px;color:var(--muted);font-size:17px}.actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:24px}.preview,.generator-card{overflow:hidden;background:var(--surface);border:1px solid var(--line-strong);border-radius:var(--radius);box-shadow:0 1px 0 var(--control-hi),inset 1px 1px 0 var(--control-hi),0 18px 46px rgba(0,0,0,.10)}.preview-head{display:flex;align-items:center;gap:8px;padding:10px 12px;background:var(--control);border-bottom:1px solid var(--line)}.preview-head i{width:10px;height:10px;background:var(--accent);border:1px solid var(--accent-deep);border-radius:3px}.preview-head span{margin-left:6px;color:var(--muted);font-size:12px}.preview-body{padding:16px}.preview label,.generator-card>label{display:block;margin:12px 0 6px;color:var(--muted);font-size:13px}.fake-input,.password,output{padding:12px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);box-shadow:var(--bevel)}.password{color:var(--accent);font-size:18px;letter-spacing:.12em}.privacy-line{margin-top:16px;color:var(--muted);font-size:12px}
|
||||
main>section:not(.hero){max-width:var(--maxw);margin:0 auto;padding:56px 20px}.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.cards article,.privacy{padding:16px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);box-shadow:var(--bevel)}.cards h3{margin:8px 0}.cards p,.privacy p{color:var(--muted);font-size:14px}.tag{color:var(--accent);font-size:12px;font-weight:700}.links{display:flex;flex-wrap:wrap;gap:12px;margin-top:18px}footer{max-width:var(--maxw);margin:auto;padding:16px 20px 28px;text-align:center;color:var(--muted);font-size:13px}.generator-shell{max-width:820px;margin:48px auto;padding:0 20px}.generator-card{padding:24px}.generator-card h1{font-size:clamp(34px,6vw,52px)}.form-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.form-grid label,fieldset legend{color:var(--muted);font-size:13px}.form-grid input:not([type=checkbox]){display:block;width:100%;margin-top:7px;padding:11px 12px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);color:var(--ink);font:inherit;outline:none}.form-grid input:focus{border-color:var(--accent)}.wide{grid-column:1/-1}.password-wrap{display:flex;gap:8px}.password-wrap input{flex:1}.inline{margin-top:7px;border:1px solid var(--line);background:var(--control);border-radius:var(--radius-sm);color:var(--ink);font:inherit;padding:0 12px}fieldset{display:flex;gap:20px;border:0;padding:0}fieldset legend{margin-bottom:10px}fieldset label{color:var(--ink)!important}output{display:block;min-height:68px;font-size:17px;overflow-wrap:anywhere}.status{min-height:20px;margin:0;color:var(--muted)}#runtime-status{font-size:12px}
|
||||
@media(max-width:760px){.header-nav>a:not(.button){display:none}.hero{grid-template-columns:1fr;min-height:0;gap:36px}.cards{grid-template-columns:1fr}.form-grid{grid-template-columns:1fr 1fr}}@media(max-width:520px){.site-header-inner{padding:10px 14px}.hero,.generator-shell{padding-left:14px;padding-right:14px}.form-grid{grid-template-columns:1fr}.wide{grid-column:1}fieldset{display:grid;grid-template-columns:1fr 1fr}.actions .button{flex:1}.generator-card{padding:18px}}
|
||||
.hero{max-width:var(--maxw);min-height:calc(100vh - 64px);margin:auto;padding:48px 20px 40px;display:grid;grid-template-columns:minmax(0,.9fr) minmax(360px,.8fr);gap:44px;align-items:center}.hero-icon{width:96px;height:96px;margin:4px 0 0;border:1px solid var(--line-strong);border-radius:8px;box-shadow:var(--bevel);image-rendering:pixelated}.eyebrow{display:flex;align-items:center;gap:8px;margin:0 0 12px;color:var(--accent);font-size:13px;font-weight:700;letter-spacing:.04em;text-transform:uppercase}.eyebrow:before{content:"";width:8px;height:8px;background:var(--accent);border:1px solid var(--accent-deep);border-radius:2px;box-shadow:1px 1px 0 rgba(0,0,0,.12)}h1,h2,h3{margin:0;color:var(--ink);line-height:1.15}h1{margin:14px 0 16px;font-size:clamp(42px,7vw,74px);line-height:.98}h1 span{color:var(--accent)}h2{margin-bottom:16px;font-size:clamp(26px,4vw,40px)}h3{font-size:16px}.lede{max-width:700px;color:var(--muted);font-size:17px}.actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:24px}.preview,.generator-card{overflow:hidden;background:var(--surface);border:1px solid var(--line-strong);border-radius:var(--radius);box-shadow:0 1px 0 var(--control-hi),inset 1px 1px 0 var(--control-hi),0 18px 46px rgba(0,0,0,.10)}.preview-head{display:flex;align-items:center;gap:8px;padding:10px 12px;background:var(--control);border-bottom:1px solid var(--line)}.preview-head i{width:10px;height:10px;background:var(--accent);border:1px solid var(--accent-deep);border-radius:3px}.preview-head span{margin-left:6px;color:var(--muted);font-size:12px}.preview-body{padding:16px}.generator-card>label{display:block;margin:12px 0 6px;color:var(--muted);font-size:13px}output{padding:12px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);box-shadow:var(--bevel)}.privacy-line{margin-top:16px;color:var(--muted);font-size:12px}
|
||||
main>section:not(.hero){max-width:var(--maxw);margin:0 auto;padding:56px 20px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:14px}.cards article,.privacy{padding:16px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);box-shadow:var(--bevel)}.cards h3{margin:8px 0}.cards p,.privacy p{color:var(--muted);font-size:14px}.tag{color:var(--accent);font-size:12px;font-weight:700}.links{display:flex;flex-wrap:wrap;gap:12px;margin-top:18px}footer{max-width:var(--maxw);margin:auto;padding:16px 20px 28px;text-align:center;color:var(--muted);font-size:13px}.generator-shell{max-width:820px;margin:48px auto;padding:0 20px}.generator-card{padding:24px}.generator-card h1{font-size:clamp(34px,6vw,52px)}.form-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.form-grid label,fieldset legend{color:var(--muted);font-size:13px}.form-grid input:not([type=checkbox]){display:block;width:100%;margin-top:7px;padding:11px 12px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius-sm);color:var(--ink);font:inherit;outline:none}.form-grid input:focus{border-color:var(--accent)}.wide{grid-column:1/-1}.password-wrap{display:flex;gap:8px}.password-wrap input{flex:1}.inline{margin-top:7px;border:1px solid var(--line);background:var(--control);border-radius:var(--radius-sm);color:var(--ink);font:inherit;padding:0 12px}fieldset{display:flex;gap:20px;border:0;padding:0}fieldset legend{margin-bottom:10px}fieldset label{color:var(--ink)!important}output{display:block;min-height:68px;font-size:17px;overflow-wrap:anywhere}.status{min-height:20px;margin:0;color:var(--muted)}#runtime-status{font-size:12px}
|
||||
.preview .form-grid{grid-template-columns:1fr 1fr;gap:14px}.preview fieldset{display:grid;grid-template-columns:1fr 1fr;gap:8px 16px}.preview fieldset legend{grid-column:1/-1;margin-bottom:2px}.preview .actions{margin-top:0;gap:10px}.preview .actions .button{flex:1}.preview output{min-height:52px;font-size:15px}
|
||||
@media(max-width:760px){.header-nav>a:not(.button){display:none}.hero{grid-template-columns:1fr;min-height:0;gap:36px}.cards{grid-template-columns:1fr}.form-grid{grid-template-columns:1fr 1fr}}@media(max-width:520px){.site-header-inner{padding:10px 14px}.hero,.generator-shell{padding-left:14px;padding-right:14px}.form-grid,.preview .form-grid{grid-template-columns:1fr}.wide{grid-column:1}fieldset{display:grid;grid-template-columns:1fr 1fr}.actions .button{flex:1}.generator-card{padding:18px}}
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
module github.com/waozixyz/gopass/web
|
||||
module github.com/waozixyz/pass/web
|
||||
|
||||
go 1.24
|
||||
|
||||
require github.com/waozixyz/gopass v0.0.0
|
||||
require github.com/waozixyz/pass v0.0.0
|
||||
|
||||
replace github.com/waozixyz/gopass => ../..
|
||||
replace github.com/waozixyz/pass => ../..
|
||||
+3
-3
@@ -5,7 +5,7 @@ package main
|
||||
import (
|
||||
"syscall/js"
|
||||
|
||||
password "github.com/waozixyz/gopass"
|
||||
password "github.com/waozixyz/pass"
|
||||
)
|
||||
|
||||
func generate(_ js.Value, args []js.Value) any {
|
||||
@@ -25,7 +25,7 @@ func generate(_ js.Value, args []js.Value) any {
|
||||
|
||||
func main() {
|
||||
fn := js.FuncOf(generate)
|
||||
js.Global().Set("gopassGenerate", fn)
|
||||
js.Global().Get("document").Call("dispatchEvent", js.Global().Get("CustomEvent").New("gopass-ready"))
|
||||
js.Global().Set("passGenerate", fn)
|
||||
js.Global().Get("document").Call("dispatchEvent", js.Global().Get("CustomEvent").New("pass-ready"))
|
||||
select {}
|
||||
}
|
||||
Reference in new issue
Block a user