51 Commits
Author SHA1 Message Date
waozi 9f4f12f68a Release Pass 0.2.6 2026-08-24 16:14:56 -03:00
waozi 1497ecee17 Release Pass 0.2.5 2026-08-24 15:33:42 -03:00
waozi 3f4b8e43d5 Update desktop showcase banner 2026-08-23 23:26:13 -03:00
waozi a68e9fa3ee Bump Kryon submodule 2026-08-23 23:17:45 -03:00
waozi f70ade6adc Adopt Kryon #ui hierarchy syntax 2026-08-23 23:17:20 -03:00
waozi e636813590 Fix Android safe-area layout rotation 2026-08-23 22:46:36 -03:00
waozi 92ee741298 Add Kryon app smoke and Android rotation fixes 2026-08-23 22:30:28 -03:00
waozi 5c60cf8226 Optimize showcase banner 2026-08-23 22:29:53 -03:00
waozi 8f4121d921 Update showcase banner 2026-08-23 22:27:53 -03:00
waozi b0c7b2079a Update Kryon and expand E2E coverage 2026-08-22 20:03:28 -03:00
waozi 055d130bc3 android: tighten release changelog 2026-08-22 02:01:27 -03:00
waozi 57d52c6658 android: autosave generator defaults 2026-08-22 01:58:42 -03:00
waozi 8a601d6366 android: clear displayed secrets after timeout 2026-08-22 01:55:34 -03:00
waozi cc77006502 ci: install emscripten for release web app 2026-08-22 01:47:13 -03:00
waozi cb82a38b6a release: prepare pass 0.2.4 2026-08-22 01:45:45 -03:00
waozi d19d6edf7d Update pass logo assets 2026-08-22 01:10:18 -03:00
waozi f2eaed3c86 Add Kryon showcase metadata 2026-08-22 01:02:04 -03:00
waozi b6cdc32d52 site: full download channels with per-platform links
The Android card now offers the direct APK and the F-Droid package
page like the inbe site, the desktop card links the AppImage and
deb packages that releases already ship, and the CLI card covers
every platform. AppImage and deb asset names carry the version, so
build.sh templates it from version.go at build time. A SHA256SUMS
note closes the section now that releases publish checksums.
2026-08-21 09:12:16 -03:00
waozi 5047ce86b0 release: prepare pass 0.2.3 2026-08-21 09:04:01 -03:00
waozi 45f3f8dbc0 release: publish SHA256SUMS with the downloads
Every release now carries a SHA256SUMS file covering all published
artifacts, so the CLI, desktop, Android, and browser downloads can be
verified before use. The appcast already embedded digests for the
desktop update channels; this extends verification to every file.
2026-08-21 09:03:47 -03:00
waozi a52a4b6462 docs: describe installing the Android app
The APK has shipped since 0.2.2 but the README never mentioned it.
Document where to get it, the minimum Android version, and that the
app declares no Internet permission.
2026-08-21 09:03:47 -03:00
waozi b8bed150d0 release: push the tag only after the artifacts are ready
The tag used to be pushed before the appcast step ran, so any failure
there (v0.2.1 lost its release to a missing vendored script) orphaned
the version: later runs saw the tag and skipped publishing forever.
Publishing now happens in the safe order: build artifacts, appcast,
tag, release.
2026-08-21 09:03:33 -03:00
waozi 56be19e3a9 packaging: move the fdroiddata recipe to the fdroiddata fork
The F-Droid build recipe lives in fdroiddata, not in the app repository; the fastlane listing metadata stays because F-Droid reads it from the default branch.
2026-08-20 19:55:43 -03:00
waozi b256e9b9fd packaging: fix fdroiddata recipe from a local fdroidserver build
Point the 0.2.2 build at b4be990: the v0.2.2 tag does not survive fdroidserver signing-config stripping, and the binary scanner needs scandelete entries for unused vendored binaries in kryon submodules.
2026-08-20 19:44:04 -03:00
waozi b4be99002d droid: require the keystore password before signing release builds 2026-08-20 19:28:12 -03:00
waozi 9447c3a75c packaging: draft fdroiddata recipe for the F-Droid inclusion request 2026-08-20 19:17:34 -03:00
waozi 3deda78d54 fastlane: Android store listing metadata, changelogs, and screenshots 2026-08-20 19:17:34 -03:00
waozi c76f76ffb7 droid: build unsigned release APKs when no keystore is present 2026-08-20 19:17:34 -03:00
waozi c57006672a release: prepare pass 0.2.2 2026-08-20 18:48:29 -03:00
waozi 881a7336ec site: offer the Android APK download 2026-08-20 18:48:29 -03:00
waozi 11d0908325 ci: build and publish the Android APK 2026-08-20 18:48:29 -03:00
waozi b4d09eb632 droid: sign release builds and bump the version code 2026-08-20 18:48:29 -03:00
waozi d60269ca3d Restore pass CLI profile shorthand 2026-08-19 21:08:20 -03:00
waozi 7a40ebcce4 Clarify biometric setup requirement 2026-08-19 21:01:13 -03:00
waozi 9eeba9fe82 Fix Android master fingerprint and secure storage 2026-08-19 20:52:31 -03:00
waozi 7f06063bf5 Rename gopass to pass 2026-08-19 20:16:57 -03:00
waozi 664d981cb5 CI: gate on public-HTTPS submodule URLs
A guard job with a plain checkout fails the run when any .gitmodules
URL is not https:// — SSH URLs work only with a developer key and
break fresh clones and CI instead. The test job needs the guard.
2026-08-19 15:28:53 -03:00
waozi 03345a6304 Add desktop update checks and self-update to the GUI (0.2.1)
The GUI rides kryon's kry_update_flow through new kryui bindings: a
session-start appcast check, a toast plus an update row under the main
card, and for AppImage installs a verified download with one-click
restart (atomic swap + re-exec after secrets are cleared). Tarball and
deb installs show the release link. The release workflow publishes
appcast.json per arch (appimage-amd64/arm64) via kryon's
make_appcast.py.
2026-08-19 14:18:45 -03:00
waozi a237ff9a15 Follow the system theme by default
The GUI now uses the system palette and system light/dark mode by default, keeping Cobalt dark as the fallback palette when no system theme can be read. Includes the kryon bump that adds SetThemeSource/SetThemeMode bindings and defaults the platform theme source to SYSTEM everywhere.
2026-08-19 12:14:33 -03:00
waozi 57e229c13f ci: fix inverted polarity in the scanner self-test 2026-08-18 13:16:01 -03:00
waozi fb1188ac37 ci: privacy scan guard with a secret-fed deny-list
scripts/privacy_scan.sh scans git trees (or directories) for fixed-string
terms and redacts them from its own output; the deny-list never lives in
this repository — locally it is read from ~/.config/git/private-terms.txt
by the pre-push hook, in CI from the encrypted PRIVATE_TERMS secret. The
workflow self-test uses only a synthetic canary term.
2026-08-18 13:12:02 -03:00
waozi 9f3ea43414 privacy: scrub the vault filename from docs and tests
Docs and tests used the real vault filename as an example; replace it with
a generic name so published code says nothing about the private setup, and
isolate the CLI tests from the developer's real profiles file so local
configuration can never leak into test behavior.
2026-08-18 13:12:02 -03:00
waozi ba8cd2d7a1 release: prepare gopass 0.2.0 2026-08-18 12:55:14 -03:00
waozi 02fd716314 cli: built-in X11 clipboard, profiles, and the pass shorthand
- --copy uses a pure-Go X11 selection server on Linux (detached daemon,
  auto-clear with --clear-after, --read-clipboard) and falls back to the
  external clipboard tools elsewhere or when no X server is reachable.
- Optional profiles.json maps named profiles (login plus default settings)
  to --profile; flags always win and the file holds no secrets.
- Symlinked as 'pass', the binary accepts 'pass PROFILE SITE' with copy and
  a 90-second auto-clear by default.
2026-08-18 12:55:14 -03:00
waozi 846879f62d cli: read master passwords from an OpenSSL vault
Decrypts standard 'openssl enc' files (AES-256-CBC, PBKDF2-SHA512) so the
master password can live in an encrypted file instead of argv or the
environment.
2026-08-18 12:55:14 -03:00
waozi d67a05a01d vendor: add BurntSushi/xgb for the built-in X11 clipboard 2026-08-18 12:55:14 -03:00
waozi 127b16cafa site: embed the web generator in the home page
Replace the static "generated locally" mock with the real WebAssembly
generator: the full option form now runs directly in the front-page hero
card. The generator and its ~2.9 MB wasm module load lazily on first
interaction with the card, so the landing page stays light for visitors
who do not use it. The standalone /app/ page is unchanged.

Release: 0.1.3.
2026-08-17 23:09:07 -03:00
waozi d6423b9d15 build: rebuild Kryon after source updates 2026-08-17 22:42:43 -03:00
waozi 00e20a0147 site: simplify desktop download copy 2026-08-17 22:40:22 -03:00
waozi e0454798b4 build: update Kryon input diagnostics 2026-08-17 22:32:10 -03:00
waozi 4adb352172 build: update Kryon text selection 2026-08-17 22:14:46 -03:00
122 changed files with 20915 additions and 2262 deletions

No files matched your search

+136 -17
View File
@@ -15,30 +15,68 @@ 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 validates URLs before allowing
# recursive submodule checkout to continue.
- name: Checkout Repository
uses: actions/checkout@v4
- name: Reject non-HTTPS submodule URLs
run: scripts/check_submodule_urls.sh
test:
runs-on: ubuntu-latest
needs: guard-submodule-urls
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: 1.25.x
cache: false
- name: Test CLI and generator
run: go test ./...
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Test C CLI, core, and Kry generator
run: make test
- name: Build browser app
run: make site
- name: Verify generated site
run: |
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/gopass.wasm
- name: Check formatting
run: test -z "$(find . -path ./vendor -prune -o -name '*.go' -type f -print | xargs gofmt -l)"
test -s build/site/app/index.wasm
- name: Check fastlane metadata
run: |
set -eu
meta=fastlane/metadata/android/en-US
limit() {
n=$(wc -m < "$1")
if [ "$n" -gt "$2" ]; then
echo "::error::$1 is $n characters (max $2)"
exit 1
fi
}
limit "$meta/title.txt" 30
limit "$meta/short_description.txt" 80
limit "$meta/full_description.txt" 4000
for f in "$meta"/changelogs/*.txt; do
limit "$f" 500
done
code=$(sed -n 's/^[[:space:]]*versionCode \([0-9][0-9]*\)$/\1/p' droid/app/build.gradle | head -n 1)
test -n "$code"
test -s "$meta/changelogs/$code.txt"
test -s "$meta/images/icon.png"
echo "fastlane metadata ok (versionCode $code)"
build-gui:
name: GUI (${{ matrix.arch }})
needs: guard-submodule-urls
strategy:
matrix:
include:
@@ -51,10 +89,6 @@ jobs:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: 1.25.x
cache: false
- name: Install native dependencies
run: |
mapfile -t packages < .github/apt/gui-packages.txt
@@ -62,12 +96,97 @@ jobs:
sudo apt-get install -y "${packages[@]}"
- name: Build GUI
run: make gui
- name: Test GUI logic
run: cd gui && go test ./...
- name: Build Debian package
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('app/*.kry', '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
android-input-test:
name: Android input instrumentation
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: 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: Run Android input tests
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 35
arch: x86_64
target: google_apis
script: |
bash <<'EOF'
set -euo pipefail
chmod +x droid/gradlew
make android-input-test
EOF
- uses: actions/upload-artifact@v4
if: failure()
with:
name: android-input-test-reports
path: |
droid/app/build/reports/androidTests/
droid/app/build/outputs/androidTest-results/
if-no-files-found: ignore
+165 -38
View File
@@ -13,44 +13,46 @@ concurrency:
cancel-in-progress: false
jobs:
cli:
name: CLI (${{ matrix.os }}-${{ matrix.arch }})
guard-submodule-urls:
name: Submodule URLs are public HTTPS
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Reject non-HTTPS submodule URLs
run: scripts/check_submodule_urls.sh
cli:
name: CLI (${{ matrix.arch }})
needs: guard-submodule-urls
strategy:
matrix:
os: [linux, darwin, windows, freebsd]
arch: [amd64, arm64]
include:
- runner: ubuntu-22.04
arch: amd64
- runner: ubuntu-24.04-arm
arch: arm64
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.24.x
cache: false
- name: Build archive
env:
TARGET_OS: ${{ matrix.os }}
TARGET_ARCH: ${{ matrix.arch }}
run: |
set -euo pipefail
name="gopass-cli-${TARGET_OS}-${TARGET_ARCH}"
make cli
name="pass-cli-linux-${{ matrix.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
cp LICENSE README.md "build/release/$name/"
if [ "$TARGET_OS" = windows ]; then
(cd build/release && zip -qr "$name.zip" "$name")
else
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
fi
cp pass LICENSE README.md "build/release/$name/"
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
- uses: actions/upload-artifact@v4
with:
name: cli-${{ matrix.os }}-${{ matrix.arch }}
path: build/release/gopass-cli-${{ matrix.os }}-${{ matrix.arch }}.*
name: cli-linux-${{ matrix.arch }}
path: build/release/pass-cli-linux-${{ matrix.arch }}.tar.gz
if-no-files-found: error
gui:
name: GUI (${{ matrix.arch }})
needs: guard-submodule-urls
strategy:
matrix:
include:
@@ -63,10 +65,6 @@ jobs:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: 1.25.x
cache: false
- name: Install native dependencies
run: |
mapfile -t packages < .github/apt/gui-packages.txt
@@ -75,9 +73,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,29 +92,113 @@ 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
web:
android:
name: Android
runs-on: ubuntu-latest
timeout-minutes: 60
needs: guard-submodule-urls
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.24.x
cache: false
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 APKs
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
make kry-c
./droid/gradlew -p droid assembleRelease \
-PsplitApks=true \
-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-universal-release.apk build/release/pass-android.apk
cp droid/app/build/outputs/apk/release/app-arm64-v8a-release.apk build/release/pass-android-arm64-v8a.apk
cp droid/app/build/outputs/apk/release/app-armeabi-v7a-release.apk build/release/pass-android-armeabi-v7a.apk
test -s build/release/pass-android.apk
test -s build/release/pass-android-arm64-v8a.apk
test -s build/release/pass-android-armeabi-v7a.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
needs: guard-submodule-urls
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- 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 +206,7 @@ jobs:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: recursive
- uses: actions/download-artifact@v4
with:
path: build/artifacts
@@ -132,7 +215,7 @@ jobs:
name: Resolve release version
run: |
set -euo pipefail
version=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' version.go)
version=$(sed -n '1p' VERSION)
test -n "$version"
tag="v$version"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
@@ -141,6 +224,50 @@ jobs:
else
echo "released=true" >> "$GITHUB_OUTPUT"
fi
- name: Generate Update Appcast
if: steps.version.outputs.released == 'true'
run: |
set -euo pipefail
VERSION=$(sed -n '1p' VERSION)
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 checksums
if: steps.version.outputs.released == 'true'
run: |
set -euo pipefail
cd build/artifacts
# The glob expands before the redirect creates SHA256SUMS itself.
sha256sum -- * > SHA256SUMS
- name: Create release tag
if: steps.version.outputs.released == 'true'
run: |
+59
View File
@@ -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
+27 -10
View File
@@ -14,24 +14,41 @@ concurrency:
cancel-in-progress: true
jobs:
guard-submodule-urls:
name: Submodule URLs are public HTTPS
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Reject non-HTTPS submodule URLs
run: scripts/check_submodule_urls.sh
build:
needs: guard-submodule-urls
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.24.x
cache: false
submodules: recursive
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Build Site
run: |
set -euo pipefail
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/index.wasm
- uses: actions/upload-artifact@v4
with:
name: gopass-site
name: pass-site
path: build/site
if-no-files-found: error
@@ -43,7 +60,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 +88,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 +109,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"
+1 -2
View File
@@ -1,3 +1,2 @@
/build/
/gopass
/gui/gopass-gui
/pass
+73 -1
View File
@@ -1,10 +1,82 @@
# Changelog
## [0.2.6] - 2026-08-24
- Keep Android source builds self-contained so F-Droid and other source builds
generate the Kry app sources automatically.
## [0.2.5] - 2026-08-24
- Add Android appearance settings for following device colors, choosing
light or dark mode, selecting a color palette, and switching widget style.
- Use Android system Material colors for the app theme, with a stable Material
fallback instead of the bright pink accent some devices report.
- Recalculate the Android layout cleanly when rotating between portrait and
landscape, keeping controls clear of system bars and navigation insets.
## [0.2.4] - 2026-08-22
- Save and reuse Android master-password defaults, with fingerprint unlock
available from the generator and settings screens.
- Clear unlocked master-password text and generated passwords from the Android
screen after a short timeout.
- Autosave Android generator defaults when length, counter, character classes,
excluded characters, or biometric display settings change.
- Keep Android form fields visible while the keyboard is open, with better
spacing around settings and excluded-character controls.
- Run the real Pass app at pass.waozi.xyz/app through the Kryon canvas UI,
replacing the standalone browser form.
- Publish Android releases as a universal APK plus per-ABI APKs.
## [0.2.3] - 2026-08-21
- Verify every download: releases now ship a SHA256SUMS file covering the
command-line, desktop, Android, and browser downloads.
- The Android app now builds entirely from source with no developer signing
key, clearing the way for F-Droid distribution.
## [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.
+122 -20
View File
@@ -1,60 +1,162 @@
.PHONY: all cli gui native run test native-test web site install-gui uninstall-gui package-deb package-appimage android-debug
.PHONY: all cli kry-c gui native run test native-test cli-test check-submodule-urls kry-smoke web web-canvas site web-smoke android-debug android-smoke android-input-test e2e install install-cli uninstall-cli install-gui uninstall-gui package-deb package-appimage
BIN_DIR ?= $(HOME)/bin
DATA_DIR ?= $(if $(XDG_DATA_HOME),$(XDG_DATA_HOME),$(HOME)/.local/share)
CC ?= cc
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)
K2C_SOURCES := $(shell find vendor/kryon/cmd/k2c vendor/kryon/cmd/kir -type f)
KRY_APP_SRCS := $(shell find app -type f -name '*.kry' | LC_ALL=C sort)
KRY_C_GENERATED_DIR := build/krygen/c
KRY_C_STAMP := $(KRY_C_GENERATED_DIR)/.stamp
KRY_C_APP_SRCS := $(KRY_C_GENERATED_DIR)/app/nav.c $(KRY_C_GENERATED_DIR)/app/pass.c $(KRY_C_GENERATED_DIR)/app/profiles.c $(KRY_C_GENERATED_DIR)/app/settings.c
K2C := $(KRYON_BUILD_DIR)/bin/k2c
PASS_VERSION := $(shell sed -n '1p' VERSION)
WEB_EMSDK_BIN ?= $(HOME)/emsdk/upstream/emscripten
WEB_CC ?= $(if $(wildcard $(WEB_EMSDK_BIN)/emcc),$(WEB_EMSDK_BIN)/emcc,emcc)
ifneq ($(wildcard $(WEB_EMSDK_BIN)/emcc),)
export PATH := $(WEB_EMSDK_BIN):$(PATH)
endif
WEB_APP_BUILD_DIR := build/web-app
WEB_APP_TARGET := $(WEB_APP_BUILD_DIR)/index.html
WEB_APP_EMBEDDED_ASSETS_C := build/web/pass_embedded_assets.c
WEB_APP_ASSETS := vendor/kryon/fonts/noto/NotoSans-Regular.ttf assets/fonts/emoji.ttf
KRYON_ICON_ASSETS_C := vendor/kryon/src/ui/ui_icon_assets.c
KRYON_WEB_SRCS_ALL := $(filter-out $(KRYON_ICON_ASSETS_C),$(shell find vendor/kryon/src -type f -name '*.c' | LC_ALL=C sort)) $(KRYON_ICON_ASSETS_C)
KRYON_WEB_SRCS := $(filter-out vendor/kryon/src/backend/libdraw_% vendor/kryon/src/file_dialog/file_dialog.c vendor/kryon/src/ksync/% vendor/kryon/src/runtime_assets/% vendor/kryon/src/notification/% vendor/kryon/src/platform/plan9/% vendor/kryon/src/scene/physics_world.c vendor/kryon/src/scene/node_body2d.c vendor/kryon/src/scene/node_area2d.c vendor/kryon/src/scene/node_collision_shape2d.c,$(KRYON_WEB_SRCS_ALL))
PASS_WEB_SRCS := droid/app/src/main/cpp/main.c droid/app/src/main/cpp/android_bridge.c native/pass_core.c native/pass_runtime.c $(KRY_C_APP_SRCS) $(WEB_APP_EMBEDDED_ASSETS_C)
WEB_CFLAGS := -Wall -Wextra -std=gnu99 -Os -DPLATFORM_WEB -DGRAPHICS_API_OPENGL_ES2 -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -DUI_EMBEDDED_ONLY=1 -DKRYON_WITH_PHYSICS=0 -Ivendor/kryon/include -Ivendor/kryon/src -I$(KRY_C_GENERATED_DIR) -Inative -Idroid/app/src/main/cpp
WEB_LDFLAGS := -sASYNCIFY -sASYNCIFY_STACK_SIZE=1048576 -sFORCE_FILESYSTEM=1 -sFETCH=1 -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=134217728 -sSTACK_SIZE=16777216 -lidbfs.js -lm
GUI_CFLAGS := -Wall -Wextra -std=gnu99 -O2 -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -DUI_EMBEDDED_ONLY=1 -DKRYON_WITH_PHYSICS=0 -Ivendor/kryon/include -Ivendor/kryon/src -I$(KRY_C_GENERATED_DIR) -Inative -Idroid/app/src/main/cpp $(shell pkg-config --cflags sdl2 gtk+-3.0 2>/dev/null)
GUI_LDLIBS := $(shell pkg-config --libs sdl2 2>/dev/null) $(shell pkg-config --libs libdrm gbm egl glesv2 2>/dev/null) $(shell pkg-config --libs gtk+-3.0 gio-2.0 glib-2.0 2>/dev/null) -ldl -lpthread -lm
KRYON_STATIC_LIBS := $(KRYON_BUILD_DIR)/libkryon.a $(KRYON_BUILD_DIR)/raylib/libraylib.a
all: cli gui
cli:
go build -o gopass ./cmd/gopass
cli: build/pass
cp build/pass pass
$(KRYON_BUILD_DIR)/libkryon.a:
build/pass: native/pass_cli.c native/pass_core.c native/pass_core.h | build
$(CC) -Wall -Wextra -O2 -std=gnu99 -Inative -DPASS_VERSION=\"$(PASS_VERSION)\" native/pass_cli.c native/pass_core.c -o $@
build build/gui:
mkdir -p $@
$(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 .
$(K2C): $(K2C_SOURCES) vendor/kryon/Makefile
$(MAKE) -C vendor/kryon -f Makefile k2c
kry-c: $(KRY_C_STAMP)
$(KRY_C_STAMP): $(K2C) $(KRY_APP_SRCS) | build
rm -rf $(KRY_C_GENERATED_DIR)
mkdir -p $(KRY_C_GENERATED_DIR)
$(K2C) --no-main --root . -o $(KRY_C_GENERATED_DIR) $(KRY_APP_SRCS)
touch $@
gui: build/pass-gui
build/pass-gui: $(KRYON_BUILD_DIR)/libkryon.a $(KRY_C_STAMP) droid/app/src/main/cpp/main.c droid/app/src/main/cpp/android_bridge.c native/pass_core.c native/pass_runtime.c native/pass_runtime.h | build
$(CC) $(GUI_CFLAGS) -o $@ \
droid/app/src/main/cpp/main.c \
droid/app/src/main/cpp/android_bridge.c \
native/pass_core.c \
native/pass_runtime.c \
$(KRY_C_APP_SRCS) \
-Wl,-export-dynamic \
$(KRYON_STATIC_LIBS) \
$(GUI_LDLIBS)
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 ./...
cd gui && go test ./...
$(MAKE) native-test cli-test kry-smoke
# Checks the C generator (used by the Android app) against the same fixed
# vectors as the Go tests.
# Checks the C generator used by the CLI and every Kry app target.
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
mkdir -p build
cc -Wall -Wextra -O2 -Inative native/pass_core.c native/pass_core_test.c -o build/pass_core_test
./build/pass_core_test
cli-test: cli
test "$$(./pass example.com alice 'correct horse battery staple')" = "&vLf44D'/cSkP-_8"
test "$$(./pass --length 20 --counter 2 service.test [email protected] master)" = "j:x_Lo5X_jL0w%ez\`1be"
check-submodule-urls:
bash scripts/check_submodule_urls.sh
kry-smoke:
sh scripts/kry_smoke.sh
ANDROID_DIR := droid
ANDROID_ABIS ?= armeabi-v7a,arm64-v8a
android-debug:
cd $(ANDROID_DIR) && ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS)
android-debug: kry-c
cd $(ANDROID_DIR) && ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true
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-universal-debug.apk build/pass-android-debug.apk
cp $(ANDROID_DIR)/app/build/outputs/apk/debug/app-arm64-v8a-debug.apk build/pass-android-arm64-v8a-debug.apk
cp $(ANDROID_DIR)/app/build/outputs/apk/debug/app-armeabi-v7a-debug.apk build/pass-android-armeabi-v7a-debug.apk
android-smoke: android-debug
bash scripts/android_smoke.sh
android-input-test: kry-c
cd $(ANDROID_DIR) && ./gradlew connectedDebugAndroidTest -Pabi=x86_64 -PsplitApks=false
web:
./web/build.sh
web-canvas: $(WEB_APP_TARGET)
$(WEB_APP_BUILD_DIR) build/web:
mkdir -p $@
$(WEB_APP_EMBEDDED_ASSETS_C): $(WEB_APP_ASSETS) vendor/kryon/scripts/embed-assets.sh | build/web
sh vendor/kryon/scripts/embed-assets.sh $@ $(WEB_APP_ASSETS)
$(WEB_APP_TARGET): Makefile $(KRY_C_STAMP) $(PASS_WEB_SRCS) $(KRYON_WEB_SRCS) web/site/app/index.html web/site/app/app.js | $(WEB_APP_BUILD_DIR)
$(WEB_CC) $(WEB_CFLAGS) \
-o $(WEB_APP_BUILD_DIR)/index.js \
$(PASS_WEB_SRCS) \
$(KRYON_WEB_SRCS) \
$(WEB_LDFLAGS)
cp web/site/app/index.html $(WEB_APP_TARGET)
cp web/site/app/app.js $(WEB_APP_BUILD_DIR)/app.js
site: web
test -f build/site/index.html
test -f build/site/app/gopass.wasm
test -f build/site/app/index.wasm
web-smoke: site
bash scripts/web_smoke.sh
e2e: check-submodule-urls test native-test gui web-canvas site web-smoke android-debug android-smoke
package-deb: gui
./scripts/package-deb.sh
+38 -39
View File
@@ -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
@@ -11,73 +11,72 @@ LessPass project.
## Install
Prebuilt CLI and desktop downloads are available from
[pass.waozi.xyz](https://pass.waozi.xyz/#downloads).
With Go 1.24 or newer:
[pass.waozi.xyz](https://pass.waozi.xyz/#downloads). To build from a checkout:
```sh
go install github.com/waozixyz/gopass/cmd/gopass@latest
```
Or build the command from a checkout:
```sh
go build ./cmd/gopass
git submodule update --init --recursive
make cli
```
## 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
`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:
and shell history. Omitting it is safer: `pass` first checks
`LESSPASS_MASTER_PASSWORD`, then reads one line from standard input. Use
`--prompt` to bypass the environment and read from standard input. 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.
Clipboard copying, profile storage, settings, and Android fingerprint unlock
live in the Kry app runtime. The C CLI stays stateless and prints the generated
password.
Run `gopass --help` for all flags.
Run `pass --help` for all flags.
## Desktop app
The optional desktop app is written in Go with Kryon and calls the same
generator package directly. It keeps the master password in process memory,
masks the master-password field, and clears copied passwords after 20 seconds
unless the clipboard has since been replaced.
The desktop, Android, and browser apps are written in Kry and compiled with
Kryon's `k2c` compiler to C. They share `native/pass_core.c` for password
generation and `native/pass_runtime.c` for app storage, clipboard, and platform
hooks.
```sh
git submodule update --init --recursive
make gui
./build/gopass-gui
./build/pass-gui
```
## Library
## Android
```go
settings := gopass.DefaultOptions()
result, err := gopass.Generate("example.com", "alice", master, settings)
The Android app runs on Android 5.0 (API 21) and newer. Install the signed
APK (`pass-android.apk`) from [pass.waozi.xyz](https://pass.waozi.xyz/#downloads)
or the [releases page](https://github.com/waozixyz/pass/releases/latest). It
uses the same generation algorithm as the desktop app, computes everything
locally, and declares no Internet permission at all. The only permissions it
requests are for the optional fingerprint unlock.
## Source Layout
The app has one UI implementation:
```text
app/*.kry -> k2c -> generated C -> desktop / Android / web
native/pass_core.c -> password derivation
native/pass_runtime.c -> app-facing runtime externs
native/pass_cli.c -> command-line frontend
```
All inputs are interpreted as UTF-8 strings. Excluded characters are removed
from every enabled character class; generation fails if a class becomes empty,
all classes are disabled, or the requested length cannot include one character
from each class.
## License
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
+1
View File
@@ -0,0 +1 @@
0.2.6
+59
View File
@@ -0,0 +1,59 @@
#import "kryon.h"
state {
nav_icons_loaded: int = 0
nav_generate_icon: Texture2D
nav_profiles_icon: Texture2D
nav_settings_icon: Texture2D
}
nav_load_icons :: () #private {
if nav_icons_loaded == 1 {
return
}
nav_generate_icon = LoadUIIconTexture(UI_ICON_TYPE_HOME)
nav_profiles_icon = LoadUIIconTexture(UI_ICON_TYPE_PROFILE)
nav_settings_icon = LoadUIIconTexture(UI_ICON_TYPE_GEAR)
nav_icons_loaded = 1
}
nav_draw :: (x: int, y: int, width: int, height: int, view: int*) {
nav_load_icons()
generate_active: int = 0
profiles_active: int = 0
settings_active: int = 0
if *view == 0 {
generate_active = 1
}
if *view == 1 {
profiles_active = 1
}
if *view == 2 {
settings_active = 1
}
items: [3] BottomNavItem = {
{0, "Generate", nav_generate_icon, generate_active, 0},
{1, "Profiles", nav_profiles_icon, profiles_active, 0},
{2, "Settings", nav_settings_icon, settings_active, 0}
}
result := BottomNav((BottomNavProps){
.view_width = GetScreenWidth(),
.view_height = GetScreenHeight(),
.count = 3,
.items = items,
.height = height,
.icon_size = ScaleUIPx(22),
.icon_padding = ScaleUIPx(8),
.side_margin = x,
.bottom_margin = GetScreenHeight() - y - height,
.max_button_width = width / 3
})
if result.clicked_route >= 0 {
*view = result.clicked_route
}
}
+362
View File
@@ -0,0 +1,362 @@
#import "kryon.h"
#import "app/nav"
#import "app/profiles"
#import "app/settings"
pass_generate :: (site: const char*, login: const char*, master: const char*, length: int, counter: int, lower: int, upper: int, digits: int, symbols: int, exclude: const char*) -> int #extern "pass_generate"
pass_generated :: () -> char* #extern "pass_generated"
pass_status :: () -> char* #extern "pass_status"
pass_copy :: () -> int #extern "pass_copy"
pass_master_emoji :: (master: const char*) -> char* #extern "pass_master_emoji"
pass_save_profile :: (name: const char*, site: const char*, login: const char*, length: int, counter: int, lower: int, upper: int, digits: int, symbols: int, exclude: const char*) -> int #extern "pass_save_profile"
pass_safe_left :: () -> int #extern "pass_safe_left"
pass_safe_top :: () -> int #extern "pass_safe_top"
pass_safe_right :: () -> int #extern "pass_safe_right"
pass_safe_bottom :: () -> int #extern "pass_safe_bottom"
pass_can_unlock_master :: () -> int #extern "pass_can_unlock_master"
pass_take_unlocked_master :: (out: char*) -> int #extern "pass_take_unlocked_master"
pass_unlock_master :: () -> int #extern "pass_unlock_master"
pass_load_settings :: (auto_copy: int*, clear_seconds: int*, show_fingerprint: int*, length: int*, counter: int*, lower: int*, upper: int*, digits: int*, symbols: int*, exclude: char*, exclude_size: int, theme_source: int*, theme_mode: int*, theme_id: int*, theme_style: int*) -> int #extern "pass_load_settings"
ViewMode :: enum {
VIEW_GENERATE = 0,
VIEW_PROFILES,
VIEW_SETTINGS
}
state {
view: int = VIEW_GENERATE
site: [256] char = ""
site_cursor: int = 0
login: [256] char = ""
login_cursor: int = 0
master: [1024] char = ""
master_cursor: int = 0
exclude: [128] char = ""
exclude_cursor: int = 0
profile_name: [64] char = ""
profile_name_cursor: int = 0
length: int = 16
counter: int = 1
lower: int = 1
upper: int = 1
digits: int = 1
symbols: int = 1
reveal_master: int = 0
auto_copy: int = 0
clear_seconds: int = 20
show_fingerprint: int = 1
theme_source: int = THEME_SOURCE_SYSTEM
theme_mode: int = THEME_MODE_SYSTEM
theme_id: int = THEME_MINT
theme_style: int = THEME_STYLE_MATERIAL
theme_menu_state: UIThemeSettingsState
pass_icons_loaded: int = 0
pass_settings_loaded: int = 0
pass_fingerprint_icon: Texture2D
pass_eye_icon: Texture2D
pass_eye_off_icon: Texture2D
generate_scroll: int = 0
profiles_scroll: int = 0
settings_scroll: int = 0
pass_focused_rect_valid: int = 0
pass_focused_rect: Rectangle
pass_visible_focus_id: int = 0
pass_scroll_to_generated: int = 0
}
app "Pass" {
size 390 740
fps 60
}
pass_apply_theme :: () #private {
if theme_source < THEME_SOURCE_APP {
theme_source = THEME_SOURCE_APP
}
if theme_source > THEME_SOURCE_SYSTEM {
theme_source = THEME_SOURCE_SYSTEM
}
if theme_mode < THEME_MODE_SYSTEM {
theme_mode = THEME_MODE_SYSTEM
}
if theme_mode > THEME_MODE_DARK {
theme_mode = THEME_MODE_DARK
}
if theme_style < THEME_STYLE_SYSTEM {
theme_style = THEME_STYLE_SYSTEM
}
if theme_style > THEME_STYLE_MATERIAL {
theme_style = THEME_STYLE_MATERIAL
}
if theme_id < 0 {
theme_id = 0
}
if theme_id >= THEME_COUNT {
theme_id = THEME_COUNT - 1
}
dark: int = 0
if theme_mode == THEME_MODE_DARK {
dark = 1
} else if theme_mode == THEME_MODE_SYSTEM {
if SystemThemePrefersDark() {
dark = 1
}
}
SetThemeSource((ThemeSource)theme_source)
SetThemeMode((ThemeMode)theme_mode)
SetThemeStyle((ThemeStyle)theme_style)
SetCurrentTheme(theme_id, dark)
}
pass_load_icons :: () #private {
if pass_icons_loaded == 1 {
return
}
pass_fingerprint_icon = LoadUIIconTexture(UI_ICON_TYPE_FINGERPRINT)
pass_eye_icon = LoadUIIconTexture(UI_ICON_TYPE_EYE)
pass_eye_off_icon = LoadUIIconTexture(UI_ICON_TYPE_EYE_OFF)
pass_icons_loaded = 1
}
pass_load_saved_settings :: () #private {
if pass_settings_loaded == 1 {
return
}
pass_load_settings(&auto_copy, &clear_seconds, &show_fingerprint, &length, &counter, &lower, &upper, &digits, &symbols, exclude, sizeof(exclude), &theme_source, &theme_mode, &theme_id, &theme_style)
pass_settings_loaded = 1
}
pass_generate_content_height :: () -> int #private {
return ScaleUIPx(820)
}
pass_draw_master_emoji :: (x: int, y: int, master_text: [1024] char, enabled: int) -> int #private {
if enabled == 0 {
return 0
}
if master_text[0] == 0 {
return 0
}
font_token: int = PushUIFont("pass-emoji")
Text(pass_master_emoji(master_text), x, y, Text20, GetThemeIcon())
PopUIFont(font_token)
return ScaleUIPx(32)
}
pass_request_focused_input_visible :: (focus_id: int, bounds: Rectangle) #private {
if IsUIFocusActive(focus_id) == 0 {
if pass_visible_focus_id == focus_id {
pass_visible_focus_id = 0
}
return
}
if pass_visible_focus_id == focus_id {
return
}
pass_visible_focus_id = focus_id
pass_request_rect_visible(bounds)
}
pass_request_rect_visible :: (bounds: Rectangle) #private {
pass_focused_rect = bounds
pass_focused_rect_valid = 1
}
pass_ensure_focused_input_visible :: (area: UIScrollArea) #private {
if pass_focused_rect_valid == 0 {
return
}
EnsureUIScrollRectVisible(area, pass_focused_rect, ScaleUIPx(24))
pass_focused_rect_valid = 0
}
pass_draw_generate :: (pad: int, y: int, content_w: int) -> int #private {
Text("Site", pad, y, Text14, GetThemeText())
TextField((TextFieldProps){.bounds = {pad, y + ScaleUIPx(22), content_w, ScaleUIPx(38)}, .text = site, .text_size = sizeof(site), .cursor_position = &site_cursor, .max_codepoints = 255, .font = Text16, .focus_id = 101})
pass_request_focused_input_visible(101, (Rectangle){pad, y, content_w, ScaleUIPx(62)})
y += ScaleUIPx(72)
Text("Login", pad, y, Text14, GetThemeText())
TextField((TextFieldProps){.bounds = {pad, y + ScaleUIPx(22), content_w, ScaleUIPx(38)}, .text = login, .text_size = sizeof(login), .cursor_position = &login_cursor, .max_codepoints = 255, .font = Text16, .focus_id = 102})
pass_request_focused_input_visible(102, (Rectangle){pad, y, content_w, ScaleUIPx(62)})
y += ScaleUIPx(72)
Text("Master password", pad, y, Text14, GetThemeText())
show_unlock: int = 0
if show_fingerprint == 1 && pass_can_unlock_master() == 1 {
show_unlock = 1
}
action_size: int = ScaleUIPx(42)
action_gap: int = ScaleUIPx(8)
reveal_x: int = pad + content_w - action_size
unlock_x: int = reveal_x - action_gap - action_size
master_field_w: int = content_w - action_size - action_gap
if show_unlock == 1 {
master_field_w = content_w - action_size * 2 - action_gap * 2
}
if master_field_w < ScaleUIPx(120) {
master_field_w = ScaleUIPx(120)
}
if reveal_master == 0 {
TextField((TextFieldProps){.bounds = {pad, y + ScaleUIPx(22), master_field_w, ScaleUIPx(38)}, .text = master, .text_size = sizeof(master), .cursor_position = &master_cursor, .max_codepoints = 1023, .font = Text16, .focus_id = 103, .secure = 1})
} else {
TextField((TextFieldProps){.bounds = {pad, y + ScaleUIPx(22), master_field_w, ScaleUIPx(38)}, .text = master, .text_size = sizeof(master), .cursor_position = &master_cursor, .max_codepoints = 1023, .font = Text16, .focus_id = 103, .secure = 0})
}
pass_request_focused_input_visible(103, (Rectangle){pad, y, content_w, ScaleUIPx(62)})
if show_unlock == 1 {
if IconButton((IconButtonProps){.bounds = {unlock_x, y + ScaleUIPx(22), action_size, ScaleUIPx(38)}, .icon = pass_fingerprint_icon, .icon_size = ScaleUIPx(22), .icon_padding = ScaleUIPx(8), .focus_id = 14, .background = GetThemeButton(), .hover_background = GetThemeButtonHover(), .icon_color = WHITE, .border = Fade(GetThemeIcon(), 0.35f), .radius = 0.10f}) {
ClearUIFocus()
SetUIFocusTextInputActive(0)
pass_unlock_master()
}
}
reveal_icon: Texture2D = pass_eye_icon
if reveal_master == 1 {
reveal_icon = pass_eye_off_icon
}
if IconButton((IconButtonProps){.bounds = {reveal_x, y + ScaleUIPx(22), action_size, ScaleUIPx(38)}, .icon = reveal_icon, .icon_size = ScaleUIPx(22), .icon_padding = ScaleUIPx(8), .focus_id = 13, .background = GetThemeButton(), .hover_background = GetThemeButtonHover(), .icon_color = WHITE, .border = Fade(GetThemeIcon(), 0.35f), .radius = 0.10f}) {
reveal_master = 1 - reveal_master
}
y += ScaleUIPx(64)
y += pass_draw_master_emoji(pad, y, master, show_fingerprint)
y += ScaleUIPx(12)
Text("Length", pad, y + ScaleUIPx(10), Text16, GetThemeText())
Spinbox((SpinboxProps){.bounds = {pad + content_w - ScaleUIPx(156), y, ScaleUIPx(156), ScaleUIPx(40)}, .id = 20, .min = 4, .max = 128, .step = 1, .value = &length, .disabled = 0, .wrap = 0})
y += ScaleUIPx(54)
Text("Counter", pad, y + ScaleUIPx(10), Text16, GetThemeText())
Spinbox((SpinboxProps){.bounds = {pad + content_w - ScaleUIPx(156), y, ScaleUIPx(156), ScaleUIPx(40)}, .id = 21, .min = 1, .max = 999999, .step = 1, .value = &counter, .disabled = 0, .wrap = 0})
y += ScaleUIPx(58)
Checkbox(31, pad, y, "a-z", &lower)
Checkbox(32, pad + content_w / 4, y, "A-Z", &upper)
Checkbox(33, pad + content_w / 2, y, "0-9", &digits)
Checkbox(34, pad + (content_w / 4) * 3, y, "#", &symbols)
y += ScaleUIPx(72)
Text("Exclude", pad, y, Text14, GetThemeText())
TextField((TextFieldProps){.bounds = {pad, y + ScaleUIPx(22), content_w, ScaleUIPx(38)}, .text = exclude, .text_size = sizeof(exclude), .cursor_position = &exclude_cursor, .max_codepoints = 127, .font = Text16, .focus_id = 104})
pass_request_focused_input_visible(104, (Rectangle){pad, y, content_w, ScaleUIPx(62)})
y += ScaleUIPx(76)
if Button((ButtonProps){.bounds = {pad, y, content_w, ScaleUIPx(44)}, .label = "Generate", .style = ButtonStylePrimary, .font = Text16, .id = 40}) {
pass_generate(site, login, master, length, counter, lower, upper, digits, symbols, exclude)
pass_scroll_to_generated = 1
if auto_copy == 1 {
pass_copy()
}
}
y += ScaleUIPx(60)
Text("Generated password", pad, y, Text14, GetThemeText())
TextInRect(pass_generated(), (Rectangle){pad, y + ScaleUIPx(22), content_w, ScaleUIPx(48)}, Text16, GetThemeText())
if pass_scroll_to_generated == 1 {
pass_request_rect_visible((Rectangle){pad, y, content_w, ScaleUIPx(76)})
pass_scroll_to_generated = 0
}
y += ScaleUIPx(82)
if Button((ButtonProps){.bounds = {pad, y, content_w, ScaleUIPx(40)}, .label = "Copy", .style = ButtonStyleSecondary, .font = Text16, .id = 41}) {
pass_copy()
}
return y + ScaleUIPx(54)
}
pass_draw_profiles :: (pad: int, y: int, content_w: int) -> int #private {
Text("Profile name", pad, y, Text14, GetThemeText())
TextField((TextFieldProps){.bounds = {pad, y + ScaleUIPx(22), content_w, ScaleUIPx(38)}, .text = profile_name, .text_size = sizeof(profile_name), .cursor_position = &profile_name_cursor, .max_codepoints = 63, .font = Text16, .focus_id = 201})
pass_request_focused_input_visible(201, (Rectangle){pad, y, content_w, ScaleUIPx(62)})
y += ScaleUIPx(76)
if Button((ButtonProps){.bounds = {pad, y, content_w, ScaleUIPx(42)}, .label = "Save Current Profile", .style = ButtonStylePrimary, .font = Text16, .id = 210}) {
pass_save_profile(profile_name, site, login, length, counter, lower, upper, digits, symbols, exclude)
}
y += ScaleUIPx(58)
return profiles_draw_list(pad, y, content_w, master)
}
pass_frame :: () #ui {
if pass_take_unlocked_master(master) == 1 {
master_cursor = 0
}
pass_load_saved_settings()
pass_apply_theme()
pass_load_icons()
Background(GetThemeBackground())
screen_w: int = GetScreenWidth()
screen_h: int = GetScreenHeight()
pad: int = ScaleUIPx(18)
top: int = ScaleUIPx(16) + ScaleUIPx(pass_safe_top())
left: int = pad + ScaleUIPx(pass_safe_left())
right: int = pad + ScaleUIPx(pass_safe_right())
bottom: int = ScaleUIPx(pass_safe_bottom())
content_w: int = screen_w - left - right
if content_w < ScaleUIPx(280) {
content_w = ScaleUIPx(280)
}
nav_h: int = ScaleUIPx(66)
nav_y: int = screen_h - bottom - nav_h
y: int = top
view_h: int = nav_y - y
if view_h < ScaleUIPx(180) {
view_h = ScaleUIPx(180)
}
pass_focused_rect_valid = 0
if view == VIEW_GENERATE {
area := (UIScrollArea){
.bounds = {left, y, content_w, view_h},
.content_height = pass_generate_content_height(),
.scroll_offset = &generate_scroll
}
scroll := BeginUIScrollContainer(area)
pass_draw_generate(scroll.content_x, scroll.content_y, scroll.content_w)
pass_ensure_focused_input_visible(area)
EndUIScrollContainer(area, scroll)
} else if view == VIEW_PROFILES {
area := (UIScrollArea){
.bounds = {left, y, content_w, view_h},
.content_height = profiles_content_height(),
.scroll_offset = &profiles_scroll
}
scroll := BeginUIScrollContainer(area)
pass_draw_profiles(scroll.content_x, scroll.content_y, scroll.content_w)
pass_ensure_focused_input_visible(area)
EndUIScrollContainer(area, scroll)
} else {
area := (UIScrollArea){
.bounds = {left, y, content_w, view_h},
.content_height = settings_content_height(),
.scroll_offset = &settings_scroll
}
scroll := BeginUIScrollContainer(area)
settings_draw(scroll.content_x, scroll.content_y, scroll.content_w, master, &master_cursor, &reveal_master, &auto_copy, &clear_seconds, &show_fingerprint, &length, &counter, &lower, &upper, &digits, &symbols, exclude, &exclude_cursor, &theme_source, &theme_mode, &theme_id, &theme_style)
pass_request_focused_input_visible(512, (Rectangle){scroll.content_x, scroll.content_y + ScaleUIPx(364), scroll.content_w, ScaleUIPx(62)})
pass_request_focused_input_visible(530, (Rectangle){scroll.content_x, scroll.content_y + ScaleUIPx(534), scroll.content_w, ScaleUIPx(62)})
pass_ensure_focused_input_visible(area)
EndUIScrollContainer(area, scroll)
}
DrawRectangleRec((Rectangle){0, nav_y, screen_w, screen_h - nav_y}, GetThemeSurface())
Line(0, nav_y, screen_w, nav_y, Fade(GetThemeIcon(), 0.24f))
nav_draw(left, nav_y, content_w, nav_h, &view)
if view == VIEW_SETTINGS {
settings_draw_theme_modal(&auto_copy, &clear_seconds, &show_fingerprint, &length, &counter, &lower, &upper, &digits, &symbols, exclude, &theme_source, &theme_mode, &theme_id, &theme_style, &theme_menu_state)
}
}
+38
View File
@@ -0,0 +1,38 @@
#import "kryon.h"
pass_profile_count :: () -> int #extern "pass_profile_count"
pass_profile_label :: (index: int) -> char* #extern "pass_profile_label"
pass_generate_profile :: (index: int, master: const char*) -> int #extern "pass_generate_profile"
pass_delete_profile :: (index: int) -> int #extern "pass_delete_profile"
profiles_draw_list :: (x: int, y: int, width: int, master: [1024] char) -> int {
count: int = pass_profile_count()
if count == 0 {
Text("No saved profiles", x, y, Text16, GetThemeIcon())
return y + ScaleUIPx(48)
}
for int i = 0; i < count; i++ {
row_y: int = y + i * ScaleUIPx(48)
Text(pass_profile_label(i), x, row_y + ScaleUIPx(10), Text16, GetThemeText())
if Button((ButtonProps){.bounds = {x + width - ScaleUIPx(170), row_y, ScaleUIPx(88), ScaleUIPx(36)}, .label = "Generate", .style = ButtonStyleSecondary, .font = Text14, .id = 300 + i}) {
pass_generate_profile(i, master)
}
if Button((ButtonProps){.bounds = {x + width - ScaleUIPx(74), row_y, ScaleUIPx(74), ScaleUIPx(36)}, .label = "Delete", .style = ButtonStyleSecondary, .font = Text14, .id = 400 + i}) {
pass_delete_profile(i)
}
}
return y + count * ScaleUIPx(48)
}
profiles_content_height :: () -> int {
count: int = pass_profile_count()
list_h: int = ScaleUIPx(48)
if count > 0 {
list_h = count * ScaleUIPx(48)
}
return ScaleUIPx(76) + ScaleUIPx(58) + list_h + ScaleUIPx(110)
}
+204
View File
@@ -0,0 +1,204 @@
#import "kryon.h"
pass_save_settings :: (auto_copy: int, clear_seconds: int, show_fingerprint: int, length: int, counter: int, lower: int, upper: int, digits: int, symbols: int, exclude: const char*, theme_source: int, theme_mode: int, theme_id: int, theme_style: int) -> int #extern "pass_save_settings"
pass_save_master :: (master: const char*, require_biometric: int) -> int #extern "pass_save_master"
pass_clear_master :: () -> int #extern "pass_clear_master"
pass_biometric_available :: () -> int #extern "pass_biometric_available"
pass_master_saved :: () -> int #extern "pass_master_saved"
pass_fingerprint_status :: () -> char* #extern "pass_fingerprint_status"
pass_master_emoji :: (master: const char*) -> char* #extern "pass_master_emoji"
state {
settings_theme_modal_open: int = 0
settings_icons_loaded: int = 0
settings_close_icon: Texture2D
settings_eye_icon: Texture2D
settings_eye_off_icon: Texture2D
}
settings_load_icons :: () #private {
if settings_icons_loaded == 1 {
return
}
settings_close_icon = LoadUIIconTexture(UI_ICON_TYPE_X)
settings_eye_icon = LoadUIIconTexture(UI_ICON_TYPE_EYE)
settings_eye_off_icon = LoadUIIconTexture(UI_ICON_TYPE_EYE_OFF)
settings_icons_loaded = 1
}
settings_draw_master_emoji :: (x: int, y: int, master_text: [1024] char) -> int #private {
if master_text[0] == 0 {
return 0
}
font_token: int = PushUIFont("pass-emoji")
Text(pass_master_emoji(master_text), x, y, Text20, GetThemeIcon())
PopUIFont(font_token)
return ScaleUIPx(32)
}
settings_draw :: (
x: int,
y: int,
width: int,
master: [1024] char,
master_cursor: int*,
reveal_master: int*,
auto_copy: int*,
clear_seconds: int*,
show_fingerprint: int*,
length: int*,
counter: int*,
lower: int*,
upper: int*,
digits: int*,
symbols: int*,
exclude: [128] char,
exclude_cursor: int*,
theme_source: int*,
theme_mode: int*,
theme_id: int*,
theme_style: int*
) -> int {
settings_load_icons()
Checkbox(501, x, y, "Auto-copy after Generate", auto_copy)
y += ScaleUIPx(42)
Slider(502, x, y, width, "Clipboard seconds", 0, 3600, clear_seconds, "", nil)
y += ScaleUIPx(52)
Checkbox(503, x, y, "Show master fingerprint", show_fingerprint)
y += ScaleUIPx(52)
Text("Generation defaults", x, y, Text16, GetThemeText())
y += ScaleUIPx(34)
Text("Length", x, y + ScaleUIPx(10), Text16, GetThemeText())
Spinbox((SpinboxProps){.bounds = {x + width - ScaleUIPx(156), y, ScaleUIPx(156), ScaleUIPx(40)}, .id = 504, .min = 4, .max = 128, .step = 1, .value = length, .disabled = 0, .wrap = 0})
y += ScaleUIPx(54)
Text("Counter", x, y + ScaleUIPx(10), Text16, GetThemeText())
Spinbox((SpinboxProps){.bounds = {x + width - ScaleUIPx(156), y, ScaleUIPx(156), ScaleUIPx(40)}, .id = 505, .min = 1, .max = 999999, .step = 1, .value = counter, .disabled = 0, .wrap = 0})
y += ScaleUIPx(58)
Checkbox(506, x, y, "a-z", lower)
Checkbox(507, x + width / 4, y, "A-Z", upper)
Checkbox(508, x + width / 2, y, "0-9", digits)
Checkbox(509, x + (width / 4) * 3, y, "#", symbols)
y += ScaleUIPx(72)
Text("Exclude", x, y, Text14, GetThemeText())
TextField((TextFieldProps){.bounds = {x, y + ScaleUIPx(22), width, ScaleUIPx(38)}, .text = exclude, .text_size = 128, .cursor_position = exclude_cursor, .max_codepoints = 127, .font = Text16, .focus_id = 512})
y += ScaleUIPx(76)
if Button((ButtonProps){.bounds = {x, y, width, ScaleUIPx(42)}, .label = "Save Settings", .style = ButtonStylePrimary, .font = Text16, .id = 510}) {
pass_save_settings(*auto_copy, *clear_seconds, *show_fingerprint, *length, *counter, *lower, *upper, *digits, *symbols, exclude, *theme_source, *theme_mode, *theme_id, *theme_style)
}
y += ScaleUIPx(60)
Text("Secure master password", x, y, Text16, GetThemeText())
y += ScaleUIPx(34)
Text("Master password", x, y, Text14, GetThemeText())
action_size: int = ScaleUIPx(42)
action_gap: int = ScaleUIPx(8)
field_w: int = width - action_size - action_gap
if field_w < ScaleUIPx(120) {
field_w = ScaleUIPx(120)
}
if *reveal_master == 0 {
TextField((TextFieldProps){.bounds = {x, y + ScaleUIPx(22), field_w, ScaleUIPx(38)}, .text = master, .text_size = 1024, .cursor_position = master_cursor, .max_codepoints = 1023, .font = Text16, .focus_id = 530, .secure = 1})
} else {
TextField((TextFieldProps){.bounds = {x, y + ScaleUIPx(22), field_w, ScaleUIPx(38)}, .text = master, .text_size = 1024, .cursor_position = master_cursor, .max_codepoints = 1023, .font = Text16, .focus_id = 530, .secure = 0})
}
reveal_icon: Texture2D = settings_eye_icon
if *reveal_master == 1 {
reveal_icon = settings_eye_off_icon
}
if IconButton((IconButtonProps){.bounds = {x + width - action_size, y + ScaleUIPx(22), action_size, ScaleUIPx(38)}, .icon = reveal_icon, .icon_size = ScaleUIPx(22), .icon_padding = ScaleUIPx(8), .focus_id = 531, .background = GetThemeButton(), .hover_background = GetThemeButtonHover(), .icon_color = WHITE, .border = Fade(GetThemeIcon(), 0.35f), .radius = 0.10f}) {
*reveal_master = 1 - *reveal_master
}
y += ScaleUIPx(64)
y += settings_draw_master_emoji(x, y, master)
y += ScaleUIPx(12)
Text(pass_fingerprint_status(), x, y, Text12, GetThemeIcon())
y += ScaleUIPx(30)
if Button((ButtonProps){.bounds = {x, y, width / 2 - ScaleUIPx(6), ScaleUIPx(42)}, .label = "Save", .style = ButtonStylePrimary, .font = Text16, .id = 520, .disabled = pass_biometric_available() == 0}) {
pass_save_master(master, 1)
}
if Button((ButtonProps){.bounds = {x + width / 2 + ScaleUIPx(6), y, width / 2 - ScaleUIPx(6), ScaleUIPx(42)}, .label = "Forget", .style = ButtonStyleSecondary, .font = Text16, .id = 522, .disabled = pass_master_saved() == 0}) {
pass_clear_master()
}
y += ScaleUIPx(60)
if Button((ButtonProps){.bounds = {x, y, width, ScaleUIPx(42)}, .label = "Theme Settings", .style = ButtonStyleSecondary, .font = Text16, .id = 500}) {
settings_theme_modal_open = 1
}
return y + ScaleUIPx(52)
}
settings_theme_modal_is_open :: () -> int {
return settings_theme_modal_open
}
settings_content_height :: () -> int {
return ScaleUIPx(940)
}
settings_draw_theme_modal :: (
auto_copy: int*,
clear_seconds: int*,
show_fingerprint: int*,
length: int*,
counter: int*,
lower: int*,
upper: int*,
digits: int*,
symbols: int*,
exclude: [128] char,
theme_source: int*,
theme_mode: int*,
theme_id: int*,
theme_style: int*,
theme_menu_state: UIThemeSettingsState*
) {
if settings_theme_modal_open == 0 {
return
}
settings_load_icons()
empty_icon: Texture2D = {0}
modal_w: int = GetScreenWidth() - ScaleUIPx(32)
modal_h: int = ScaleUIPx(380)
frame := ModalFrame(modal_w, modal_h, "Theme Settings", empty_icon, settings_close_icon)
if frame.right_clicked == 1 {
settings_theme_modal_open = 0
}
settings := (ThemeSettingsProps){
.id_base = 600,
.x = frame.content_x,
.y = frame.content_y,
.w = frame.content_w,
.theme_source = theme_source,
.theme_mode = theme_mode,
.theme_id = theme_id,
.theme_style = theme_style,
.allow_system_source = 1,
.allow_system_mode = 1,
.palette_label = "Color palette",
.source_system_label = "System colors",
.style_label = "Widget style",
.style_system_label = "System style"
}
ThemeSettings(settings, theme_menu_state, nil)
save_y: int = frame.content_y + frame.content_h - ScaleUIPx(44)
if Button((ButtonProps){.bounds = {frame.content_x, save_y, frame.content_w, ScaleUIPx(40)}, .label = "Save Theme", .style = ButtonStylePrimary, .font = Text16, .id = 511}) {
pass_save_settings(*auto_copy, *clear_seconds, *show_fingerprint, *length, *counter, *lower, *upper, *digits, *symbols, exclude, *theme_source, *theme_mode, *theme_id, *theme_style)
settings_theme_modal_open = 0
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

+39
View File
@@ -0,0 +1,39 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="512" height="512" shape-rendering="crispEdges">
<rect width="64" height="64" fill="none"/>
<rect x="10" y="8" width="44" height="48" fill="#1b3942"/>
<rect x="8" y="10" width="48" height="44" fill="#1b3942"/>
<rect x="12" y="12" width="40" height="40" fill="#8fcfc8"/>
<rect x="12" y="12" width="40" height="8" fill="#b9e5dc"/>
<rect x="12" y="44" width="40" height="8" fill="#5aa59f"/>
<rect x="16" y="16" width="32" height="32" fill="#6ebdb6"/>
<rect x="22" y="24" width="20" height="22" fill="#14262d"/>
<rect x="20" y="26" width="24" height="18" fill="#14262d"/>
<rect x="24" y="26" width="18" height="16" fill="#f3e7c0"/>
<rect x="22" y="28" width="20" height="16" fill="#d6c48d"/>
<rect x="24" y="28" width="16" height="12" fill="#f7edcf"/>
<rect x="28" y="32" width="8" height="4" fill="#17303a"/>
<rect x="30" y="36" width="4" height="6" fill="#17303a"/>
<rect x="24" y="16" width="16" height="4" fill="#14262d"/>
<rect x="22" y="20" width="4" height="8" fill="#14262d"/>
<rect x="38" y="20" width="4" height="8" fill="#14262d"/>
<rect x="26" y="18" width="12" height="4" fill="#e9f2ed"/>
<rect x="24" y="22" width="4" height="6" fill="#e9f2ed"/>
<rect x="36" y="22" width="4" height="6" fill="#b8c5bf"/>
<rect x="38" y="38" width="16" height="4" fill="#14262d"/>
<rect x="50" y="34" width="6" height="6" fill="#14262d"/>
<rect x="52" y="32" width="4" height="4" fill="#14262d"/>
<rect x="40" y="40" width="14" height="4" fill="#f0bd52"/>
<rect x="52" y="36" width="4" height="4" fill="#f0bd52"/>
<rect x="44" y="44" width="4" height="4" fill="#f0bd52"/>
<rect x="48" y="44" width="4" height="4" fill="#f0bd52"/>
<rect x="42" y="38" width="10" height="2" fill="#ffe28a"/>
<rect x="54" y="34" width="2" height="2" fill="#ffe28a"/>
<rect x="14" y="14" width="6" height="4" fill="#e4f2e9"/>
<rect x="14" y="46" width="10" height="2" fill="#407f7b"/>
<rect x="44" y="18" width="4" height="4" fill="#4a918c"/>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

File renamed without changes.
File renamed without changes.
-53
View File
@@ -1,53 +0,0 @@
package main
import (
"errors"
"fmt"
"os/exec"
"runtime"
"strings"
)
type clipboardCommand struct {
program string
args []string
}
func copyToClipboard(value string) error {
commands := clipboardCommands()
var failures []error
for _, candidate := range commands {
path, err := exec.LookPath(candidate.program)
if err != nil {
continue
}
command := exec.Command(path, candidate.args...)
command.Stdin = strings.NewReader(value)
if output, err := command.CombinedOutput(); err == nil {
return nil
} else if len(output) > 0 {
failures = append(failures, fmt.Errorf("%s: %w: %s", candidate.program, err, output))
} else {
failures = append(failures, fmt.Errorf("%s: %w", candidate.program, err))
}
}
if len(failures) > 0 {
return fmt.Errorf("clipboard command failed: %w", errors.Join(failures...))
}
return errors.New("clipboard unavailable: install wl-copy, xclip, xsel, pbcopy, or clip.exe")
}
func clipboardCommands() []clipboardCommand {
switch runtime.GOOS {
case "darwin":
return []clipboardCommand{{program: "pbcopy"}}
case "windows":
return []clipboardCommand{{program: "clip.exe"}}
default:
return []clipboardCommand{
{program: "wl-copy"},
{program: "xclip", args: []string{"-selection", "clipboard", "-in"}},
{program: "xsel", args: []string{"--clipboard", "--input"}},
}
}
}
-172
View File
@@ -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(&copyPassword, "c", false, "copy the password to the clipboard")
flags.BoolVar(&copyPassword, "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`)
}
-89
View File
@@ -1,89 +0,0 @@
package main
import (
"bytes"
"strings"
"testing"
password "github.com/waozixyz/gopass"
)
func TestRunWithArgument(t *testing.T) {
var output, diagnostics bytes.Buffer
err := run([]string{"example.com", "alice", "correct horse battery staple"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got, want := output.String(), "&vLf44D'/cSkP-_8\n"; got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestRunUsesEnvironmentAndFlags(t *testing.T) {
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"--length", "10", "--no-symbols", "--exclude", "aA0", "example.com", "alice"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(output.String())
if len(got) != 10 {
t.Fatalf("output length = %d, want 10", len(got))
}
if strings.ContainsAny(got, "aA0"+"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
t.Fatalf("output %q contains a disabled character", got)
}
}
func TestRunAcceptsFlagsAfterSiteAndLogin(t *testing.T) {
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"example.com", "alice", "-C", "9", "-L", "23", "--no-symbols"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); len(got) != 23 {
t.Fatalf("output length = %d, want 23", len(got))
}
}
func TestRunInformationOptions(t *testing.T) {
for _, test := range []struct {
argument string
want string
}{
{"--version", "gopass " + password.Version},
{"--help", "Usage: gopass"},
} {
var output, diagnostics bytes.Buffer
if err := run([]string{test.argument}, &output, &diagnostics); err != nil {
t.Errorf("run(%s): %v", test.argument, err)
}
combined := output.String() + diagnostics.String()
if !strings.Contains(combined, test.want) {
t.Errorf("run(%s) output %q does not contain %q", test.argument, combined, test.want)
}
}
}
func TestRunRejectsConflictingPasswordSources(t *testing.T) {
var output, diagnostics bytes.Buffer
err := run([]string{"--prompt", "example.com", "alice", "master"}, &output, &diagnostics)
if err == nil || !strings.Contains(err.Error(), "cannot be supplied") {
t.Fatalf("error = %v, want source conflict", err)
}
}
func TestClipboardCommandsDoNotCarryPasswordData(t *testing.T) {
secret := "this must travel only over standard input"
for _, command := range clipboardCommands() {
if command.program == secret {
t.Fatal("secret appeared as clipboard executable")
}
for _, argument := range command.args {
if strings.Contains(argument, secret) {
t.Fatal("secret appeared in clipboard command arguments")
}
}
}
}
-53
View File
@@ -1,53 +0,0 @@
//go:build linux
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
)
func readPassword(label string) (string, error) {
terminal, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a controlling terminal: %w", err)
}
defer terminal.Close()
state, err := terminalState(terminal.Fd(), syscall.TCGETS, nil)
if err != nil {
return "", fmt.Errorf("cannot read terminal settings: %w", err)
}
noEcho := *state
noEcho.Lflag &^= syscall.ECHO
if _, err := terminalState(terminal.Fd(), syscall.TCSETS, &noEcho); err != nil {
return "", fmt.Errorf("cannot disable terminal echo: %w", err)
}
defer func() { _, _ = terminalState(terminal.Fd(), syscall.TCSETS, state) }()
if _, err := fmt.Fprint(terminal, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(terminal).ReadString('\n')
fmt.Fprintln(terminal)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func terminalState(fd uintptr, request uintptr, replacement *syscall.Termios) (*syscall.Termios, error) {
state := replacement
if state == nil {
state = new(syscall.Termios)
}
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, request, uintptr(unsafe.Pointer(state)))
if errno != 0 {
return nil, errno
}
return state, nil
}
-9
View File
@@ -1,9 +0,0 @@
//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !windows
package main
import "errors"
func readPassword(_ string) (string, error) {
return "", errors.New("secure terminal prompting is not supported on this operating system; use LESSPASS_MASTER_PASSWORD")
}
-50
View File
@@ -1,50 +0,0 @@
//go:build darwin || dragonfly || freebsd || netbsd || openbsd || solaris
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
)
func readPassword(label string) (string, error) {
terminal, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a controlling terminal: %w", err)
}
defer terminal.Close()
stty, err := exec.LookPath("stty")
if err != nil {
return "", fmt.Errorf("cannot securely prompt because stty is unavailable: %w", err)
}
original, err := runStty(stty, terminal, "-g")
if err != nil {
return "", fmt.Errorf("cannot read terminal settings: %w", err)
}
if _, err := runStty(stty, terminal, "-echo"); err != nil {
return "", fmt.Errorf("cannot disable terminal echo: %w", err)
}
defer func() { _, _ = runStty(stty, terminal, strings.TrimSpace(original)) }()
if _, err := fmt.Fprint(terminal, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(terminal).ReadString('\n')
fmt.Fprintln(terminal)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func runStty(path string, terminal *os.File, argument string) (string, error) {
command := exec.Command(path, argument)
command.Stdin = terminal
command.Stderr = terminal
output, err := command.Output()
return string(output), err
}
-63
View File
@@ -1,63 +0,0 @@
//go:build windows
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
)
const enableEchoInput = 0x0004
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
getConsoleMode = kernel32.NewProc("GetConsoleMode")
setConsoleMode = kernel32.NewProc("SetConsoleMode")
)
func readPassword(label string) (string, error) {
input, err := os.OpenFile("CONIN$", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a console: %w", err)
}
defer input.Close()
output, err := os.OpenFile("CONOUT$", os.O_WRONLY, 0)
if err != nil {
return "", fmt.Errorf("cannot open the console for prompting: %w", err)
}
defer output.Close()
var original uint32
if err := windowsCall(getConsoleMode, input.Fd(), uintptr(unsafe.Pointer(&original))); err != nil {
return "", fmt.Errorf("cannot read console settings: %w", err)
}
if err := windowsCall(setConsoleMode, input.Fd(), uintptr(original&^enableEchoInput)); err != nil {
return "", fmt.Errorf("cannot disable console echo: %w", err)
}
defer func() { _ = windowsCall(setConsoleMode, input.Fd(), uintptr(original)) }()
if _, err := fmt.Fprint(output, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(input).ReadString('\n')
fmt.Fprintln(output)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func windowsCall(procedure *syscall.LazyProc, arguments ...uintptr) error {
result, _, callErr := procedure.Call(arguments...)
if result != 0 {
return nil
}
if callErr != nil && callErr != syscall.Errno(0) {
return callErr
}
return syscall.EINVAL
}
+50 -2
View File
@@ -12,12 +12,44 @@ 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') ?: ""
def releaseKeystorePath = getKeystorePath()
def releaseKeystore = releaseKeystorePath ? file(releaseKeystorePath) : null
// Sign release builds only when a keystore is actually available: CI and
// local release builds pass -Pkeystore.* properties, while clean checkouts
// (for example an F-Droid builder) produce an unsigned APK instead.
def signRelease = !project.hasProperty('fDroidBuild') \
&& releaseKeystore != null && releaseKeystore.exists() \
&& releasePassword != ""
signingConfigs {
release {
if (signRelease) {
storeFile releaseKeystore
storePassword releasePassword
keyAlias getKeystoreAlias()
keyPassword releasePassword
}
}
}
defaultConfig {
applicationId 'xyz.waozi.pass'
minSdk 21
targetSdk 36
versionCode 2
versionName "0.1.2"
versionCode 7
versionName "0.2.6"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// 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'
@@ -26,8 +58,18 @@ android {
}
}
splits {
abi {
enable = (project.findProperty('splitApks') ?: 'false').toString().toBoolean()
reset()
include 'armeabi-v7a', 'arm64-v8a'
universalApk true
}
}
buildTypes {
release {
signingConfig signRelease ? signingConfigs.release : null
minifyEnabled false
}
debug {
@@ -51,3 +93,9 @@ android {
}
}
}
dependencies {
androidTestImplementation 'androidx.test:runner:1.6.2'
androidTestImplementation 'androidx.test:rules:1.6.1'
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
}
@@ -0,0 +1,62 @@
package xyz.waozi.pass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class MainActivityImeTest {
@Rule
public ActivityScenarioRule<TextInputBridgeHarnessActivity> activityRule =
new ActivityScenarioRule<>(TextInputBridgeHarnessActivity.class);
@Test
public void keyboardBridgeCanHideAndReopen() {
activityRule.getScenario().onActivity(activity -> {
int startShows = activity.getShowRequests();
int startHides = activity.getHideRequests();
activity.setTextInputVisible(true);
assertTrue(activity.isTextInputFocused());
activity.setTextInputVisible(false);
activity.setTextInputVisible(true);
assertTrue(activity.isTextInputFocused());
assertTrue(activity.getShowRequests() >= startShows + 2);
assertTrue(activity.getHideRequests() >= startHides + 1);
});
}
@Test
public void inputConnectionForwardsTextEditingOnce() {
activityRule.getScenario().onActivity(activity -> {
activity.setTextInputVisible(true);
activity.takeCommittedText();
activity.takeBackspaceCount();
activity.takeEnterCount();
EditorInfo info = new EditorInfo();
InputConnection connection = activity.createInputConnection(info);
assertNotNull(connection);
connection.commitText("site", 1);
connection.deleteSurroundingText(1, 0);
connection.performEditorAction(EditorInfo.IME_ACTION_DONE);
assertEquals("site", activity.takeCommittedText());
assertEquals(1, activity.takeBackspaceCount());
assertEquals(1, activity.takeEnterCount());
});
}
}
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity
android:name="xyz.waozi.pass.TextInputBridgeHarnessActivity"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar" />
</application>
</manifest>
@@ -0,0 +1,74 @@
package xyz.waozi.pass;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
public final class TextInputBridgeHarnessActivity extends Activity {
private TextInputBridge bridge;
private StringBuilder committedText = new StringBuilder();
private int backspaceCount = 0;
private int enterCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bridge = new TextInputBridge(this, new TextInputBridge.Callbacks() {
@Override
public void commitText(int codepoint) {
committedText.appendCodePoint(codepoint);
}
@Override
public void backspace() {
backspaceCount++;
}
@Override
public void enter() {
enterCount++;
}
});
addContentView(bridge.getView(), new ViewGroup.LayoutParams(1, 1));
}
void setTextInputVisible(boolean visible) {
bridge.setVisible(visible);
}
int getShowRequests() {
return bridge.showRequestsForTest();
}
int getHideRequests() {
return bridge.hideRequestsForTest();
}
boolean isTextInputFocused() {
return bridge.hasFocusForTest();
}
InputConnection createInputConnection(EditorInfo info) {
return bridge.createInputConnectionForTest(info);
}
String takeCommittedText() {
String value = committedText.toString();
committedText.setLength(0);
return value;
}
int takeBackspaceCount() {
int value = backspaceCount;
backspaceCount = 0;
return value;
}
int takeEnterCount() {
int value = enterCount;
enterCount = 0;
return value;
}
}
+3 -1
View File
@@ -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"
+39 -14
View File
@@ -1,35 +1,56 @@
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(KRY_GENERATED_DIR "${CMAKE_BINARY_DIR}/krygen/c")
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")
include("${KRYON_DIR}/cmake/KryonKrySources.cmake")
file(GLOB_RECURSE KRYON_SOURCES CONFIGURE_DEPENDS "${KRYON_DIR}/src/*.c")
# The src/backend/ software renderer implements raylib-named functions for
# 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")
# Keep Android builds off platform implementations for other targets. These
# directories can contain host SDK headers or symbols unavailable to the NDK.
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/platform/desktop/.*")
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/platform/desktop_tray/.*")
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/platform/plan9/.*")
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/platform/web/.*")
set(GOPASS_FONT_ASSET "vendor/kryon/fonts/noto/NotoSans-Regular.ttf")
set(GOPASS_EMBEDDED_ASSETS_C "${CMAKE_BINARY_DIR}/gopass_embedded_assets.c")
file(GLOB_RECURSE PASS_KRY_SOURCES CONFIGURE_DEPENDS "${REPO_ROOT}/app/*.kry")
list(SORT PASS_KRY_SOURCES)
kryon_generate_kry_sources(PASS_KRY_GENERATED_SOURCES PASS_KRY_INCLUDE_DIR
TARGET pass_kry_generated
KRYON_DIR "${KRYON_DIR}"
ROOT "${REPO_ROOT}"
OUT_DIR "${KRY_GENERATED_DIR}"
NO_MAIN
SOURCES ${PASS_KRY_SOURCES}
)
set(PASS_FONT_ASSET "vendor/kryon/fonts/noto/NotoSans-Regular.ttf")
set(PASS_EMOJI_FONT_ASSET "assets/fonts/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,18 +94,22 @@ target_include_directories(raylib PUBLIC
add_library(main SHARED
main.c
gopass_app.c
android_bridge.c
"${GOPASS_NATIVE_DIR}/gopass_core.c"
"${GOPASS_EMBEDDED_ASSETS_C}"
"${PASS_NATIVE_DIR}/pass_core.c"
"${PASS_NATIVE_DIR}/pass_runtime.c"
${PASS_KRY_GENERATED_SOURCES}
"${PASS_EMBEDDED_ASSETS_C}"
${KRYON_SOURCES}
"${NATIVE_APP_GLUE_DIR}/android_native_app_glue.c"
)
add_dependencies(main pass_kry_generated)
target_include_directories(main PRIVATE
"${KRYON_DIR}/include"
"${KRYON_DIR}/src"
"${GOPASS_NATIVE_DIR}"
"${PASS_KRY_INCLUDE_DIR}"
"${PASS_NATIVE_DIR}"
"${CMAKE_CURRENT_LIST_DIR}"
"${NATIVE_APP_GLUE_DIR}"
)
+392 -39
View File
@@ -1,18 +1,23 @@
/* 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. */
#include "android_bridge.h"
#include <stddef.h>
#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,12 +25,17 @@ 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;
static int insets_nav_bar = 0;
static int insets_system_left = 0;
static int insets_system_top = 0;
static int insets_system_right = 0;
static int insets_system_bottom = 0;
static int insets_ime_bottom = 0;
static int insets_cutout_left = 0;
static int insets_cutout_top = 0;
static int insets_cutout_right = 0;
static int insets_cutout_bottom = 0;
static int insets_ready = 0;
static float device_density = 0.0f;
@@ -38,27 +48,149 @@ 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)
{
pthread_mutex_lock(&bridge_mutex);
insets_status_bar = 0;
insets_nav_bar = 0;
insets_system_left = 0;
insets_system_top = 0;
insets_system_right = 0;
insets_system_bottom = 0;
insets_ime_bottom = 0;
insets_cutout_left = 0;
insets_cutout_top = 0;
insets_cutout_right = 0;
insets_cutout_bottom = 0;
insets_ready = 0;
device_density = 0.0f;
pthread_mutex_unlock(&bridge_mutex);
}
int
android_bridge_top_reserved(void)
static Color
color_from_argb(jint argb)
{
int status, cutout, top, ready;
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_left_reserved(void)
{
int system, cutout, ready;
float density;
pthread_mutex_lock(&bridge_mutex);
status = insets_status_bar;
system = insets_system_left;
cutout = insets_cutout_left;
density = device_density;
ready = insets_ready;
pthread_mutex_unlock(&bridge_mutex);
if(!ready)
return 0;
return scaled_inset(system > cutout ? system : cutout, density);
}
int
android_bridge_top_reserved(void)
{
int system, cutout, top, ready;
float density;
pthread_mutex_lock(&bridge_mutex);
system = insets_system_top;
cutout = insets_cutout_top;
density = device_density;
ready = insets_ready;
@@ -66,18 +198,37 @@ android_bridge_top_reserved(void)
if(!ready)
return 28; /* conservative status-bar guess until Java reports */
top = status > cutout ? status : cutout;
top = system > cutout ? system : cutout;
return scaled_inset(top, density);
}
int
android_bridge_right_reserved(void)
{
int system, cutout, ready;
float density;
pthread_mutex_lock(&bridge_mutex);
system = insets_system_right;
cutout = insets_cutout_right;
density = device_density;
ready = insets_ready;
pthread_mutex_unlock(&bridge_mutex);
if(!ready)
return 0;
return scaled_inset(system > cutout ? system : cutout, density);
}
int
android_bridge_bottom_reserved(void)
{
int nav, cutout, bottom, ready;
int system, ime, cutout, bottom, ready;
float density;
pthread_mutex_lock(&bridge_mutex);
nav = insets_nav_bar;
system = insets_system_bottom;
ime = insets_ime_bottom;
cutout = insets_cutout_bottom;
density = device_density;
ready = insets_ready;
@@ -85,36 +236,35 @@ android_bridge_bottom_reserved(void)
if(!ready)
return 48; /* conservative nav-bar guess until Java reports */
bottom = nav > cutout ? nav : cutout;
bottom = system > cutout ? system : cutout;
if(ime > bottom)
bottom = ime;
return scaled_inset(bottom, density);
}
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) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG,
"soft keyboard %d: no activity env", visible);
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)
if(activity_class == NULL) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG,
"soft keyboard %d: no activity class", visible);
goto done;
}
method = (*env)->GetMethodID(env, activity_class, "setSoftKeyboardVisible", "(Z)V");
if(method == NULL) {
@@ -125,12 +275,198 @@ 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);
if(status != 2 && status != 3)
goto done;
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
@@ -139,19 +475,24 @@ done:
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeSetInsets(JNIEnv *env, jobject thiz,
jint status_bar, jint nav_bar,
jint system_left, jint system_top,
jint system_right, jint system_bottom,
jint ime_bottom,
jint cutout_left, jint cutout_top,
jint cutout_right, jint cutout_bottom)
{
(void)env;
(void)thiz;
(void)cutout_left;
(void)cutout_right;
pthread_mutex_lock(&bridge_mutex);
insets_status_bar = status_bar;
insets_nav_bar = nav_bar;
insets_system_left = system_left;
insets_system_top = system_top;
insets_system_right = system_right;
insets_system_bottom = system_bottom;
insets_ime_bottom = ime_bottom;
insets_cutout_left = cutout_left;
insets_cutout_top = cutout_top;
insets_cutout_right = cutout_right;
insets_cutout_bottom = cutout_bottom;
insets_ready = 1;
pthread_mutex_unlock(&bridge_mutex);
@@ -176,7 +517,7 @@ Java_xyz_waozi_pass_MainActivity_nativeTextInputCommit(JNIEnv *env, jobject thiz
{
(void)env;
(void)thiz;
QueueUITextInputCodepoint((int)codepoint);
QueueTextInputCodepoint((int)codepoint);
}
JNIEXPORT void JNICALL
@@ -184,7 +525,7 @@ Java_xyz_waozi_pass_MainActivity_nativeTextInputBackspace(JNIEnv *env, jobject t
{
(void)env;
(void)thiz;
QueueUITextInputBackspace();
QueueTextInputBackspace();
}
JNIEXPORT void JNICALL
@@ -192,14 +533,26 @@ Java_xyz_waozi_pass_MainActivity_nativeTextInputEnter(JNIEnv *env, jobject thiz)
{
(void)env;
(void)thiz;
QueueUITextInputEnter();
QueueTextInputEnter();
}
#else /* !ANDROID_BUILD */
void android_bridge_init(void) {}
void android_bridge_apply_system_theme(void) {}
int android_bridge_left_reserved(void) { return 0; }
int android_bridge_top_reserved(void) { return 0; }
int android_bridge_right_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
+16 -5
View File
@@ -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,16 +7,27 @@ 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"
* and keep a conservative margin. */
/* Safe-area insets converted to UI units (java px / density). */
int android_bridge_left_reserved(void);
int android_bridge_top_reserved(void);
int android_bridge_right_reserved(void);
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
-521
View File
@@ -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';
}
-16
View File
@@ -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
+62 -17
View File
@@ -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,11 @@
#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 "app/pass.h"
#include "pass_runtime.h"
#include <stdio.h>
#include <string.h>
@@ -20,6 +22,7 @@
#endif
static const char *const FONT_ASSET_PATH = "vendor/kryon/fonts/noto/NotoSans-Regular.ttf";
static const char *const EMOJI_FONT_ASSET_PATH = "assets/fonts/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 +45,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_runtime_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,48 +82,71 @@ setup_ui_font(void)
int
main(int argc, char **argv)
{
GopassApp *app;
int window_width = 720;
int window_height = 740;
(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");
window_width = 0;
window_height = 0;
#elif defined(PLATFORM_WEB)
SetConfigFlags(GetWebWindowFlags());
GetWebViewportSize(window_width, window_height, &window_width, &window_height);
#endif
InitWindow(0, 0, "gopass");
InitWindow(window_width, window_height, "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();
SetThemeMode(THEME_MODE_SYSTEM);
SetThemeSource(THEME_SOURCE_SYSTEM);
ApplyCurrentUITheme();
setup_ui_font();
setup_emoji_font();
setup_shapes_texture();
SetUITextInputPlatformCallback(android_bridge_set_soft_keyboard);
SetTextInputPlatformCallback(android_bridge_set_soft_keyboard);
SetTargetFPS(60);
app = gopass_app();
pass_runtime_init();
TraceLog(LOG_INFO, "PASS: app ready");
while(!WindowShouldClose()) {
int width = GetScreenWidth();
int height = GetScreenHeight();
Vector2 scale = GetWindowScaleDPI();
float dpi = scale.x > 0.0f ? scale.x : 1.0f;
#if ANDROID_BUILD
SyncAndroidSurfaceSize(&width, &height);
#endif
#if defined(PLATFORM_WEB)
SyncWebWindowSize();
width = GetScreenWidth();
height = GetScreenHeight();
#endif
BeginDrawing();
#if ANDROID_BUILD
SyncAndroidSurfaceSize(&width, &height);
#endif
BeginUIFrame(width, height, dpi);
gopass_app_draw(app, width, height, dpi,
android_bridge_top_reserved(),
android_bridge_bottom_reserved());
pass_runtime_tick();
pass_frame();
EndUIFrame();
EndDrawing();
}
gopass_app_shutdown(app);
pass_runtime_shutdown();
CloseWindow();
return 0;
}
@@ -1,32 +1,66 @@
package xyz.waozi.pass;
import android.app.NativeActivity;
import android.app.KeyguardManager;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Insets;
import android.graphics.Rect;
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.UserNotAuthenticatedException;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.view.DisplayCutout;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
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_LEGACY = "pass_master_key";
private static final String KEY_ALIAS_PLAIN = "pass_master_key_plain";
private static final String KEY_ALIAS_AUTH = "pass_master_key_auth";
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 String PREF_KEY_ALIAS = "master_key_alias";
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).
System.loadLibrary("main");
}
private int lastDeleteRepeatCount = -1;
private final Object secureLock = new Object();
private int secureStatus = SECURE_IDLE;
private String secureResult = "";
private TextInputBridge textInputBridge;
private native void nativeSetInsets(int status, int nav,
int cutoutLeft, int cutoutTop, int cutoutRight, int cutoutBottom);
private native void nativeSetInsets(int left, int top, int right, int bottom,
int ime, int cutoutLeft, int cutoutTop, int cutoutRight, int cutoutBottom);
private native void nativeSetDeviceDensity(float density);
private native void nativeTextInputCommit(int codepoint);
private native void nativeTextInputBackspace();
@@ -35,71 +69,371 @@ public class MainActivity extends NativeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applySystemBars();
setupInsetsListener();
setupTextInputBridge();
}
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 = 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 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;
}
if (requireBiometric) {
authenticateThenSave(master);
} else {
encryptAndStoreMaster(master, false);
}
}
});
}
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() {
promptForBiometric("Unlock master password",
"Use your fingerprint",
"pass will decrypt the saved master password after unlock",
new Runnable() {
@Override
public void run() {
decryptStoredMaster();
}
});
}
private void authenticateThenSave(final String master) {
promptForBiometric("Save master password",
"Use your fingerprint",
"pass will require fingerprint unlock for the saved master password",
new Runnable() {
@Override
public void run() {
encryptAndStoreMaster(master, true);
}
});
}
private void promptForBiometric(String title, String subtitle, String description,
final Runnable onSuccess) {
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 = "";
}
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(title)
.setSubtitle(subtitle)
.setDescription(description)
.setNegativeButton("Cancel", executor, (dialog, which) -> setSecureError("Canceled"))
.build();
prompt.authenticate(new CancellationSignal(), executor,
new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
onSuccess.run();
}
@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 encryptAndStoreMaster(String master, boolean requireBiometric) {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateMasterKey(requireBiometric));
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.putString(PREF_KEY_ALIAS, requireBiometric ? KEY_ALIAS_AUTH : KEY_ALIAS_PLAIN);
editor.apply();
setSecureOk("Master password saved");
} catch (UserNotAuthenticatedException e) {
setSecureError("Unlock with fingerprint first");
} catch (Exception e) {
setSecureError("Save failed: " + e.getMessage());
}
}
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, getStoredMasterKey(), new GCMParameterSpec(128, unb64(ivText)));
byte[] decrypted = cipher.doFinal(unb64(encryptedText));
setSecureOk(new String(decrypted, StandardCharsets.UTF_8));
} catch (UserNotAuthenticatedException e) {
setSecureError("Unlock with fingerprint first");
} catch (Exception e) {
setSecureError("Unlock failed: " + e.getMessage());
}
}
private SecretKey getStoredMasterKey() throws Exception {
SharedPreferences prefs = getSharedPreferences(SECURE_PREFS, MODE_PRIVATE);
String alias = prefs.getString(PREF_KEY_ALIAS, KEY_ALIAS_LEGACY);
boolean requireAuth = KEY_ALIAS_AUTH.equals(alias);
return getOrCreateMasterKey(alias, requireAuth);
}
private SecretKey getOrCreateMasterKey(boolean requireAuth) throws Exception {
return getOrCreateMasterKey(requireAuth ? KEY_ALIAS_AUTH : KEY_ALIAS_PLAIN, requireAuth);
}
private SecretKey getOrCreateMasterKey(String alias, boolean requireAuth) throws Exception {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
if (keyStore.containsAlias(alias)) {
return (SecretKey)keyStore.getKey(alias, null);
}
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
KeyGenParameterSpec.Builder spec = new KeyGenParameterSpec.Builder(
alias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setRandomizedEncryptionRequired(true);
if (requireAuth) {
spec.setUserAuthenticationRequired(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
spec.setUserAuthenticationParameters(30,
KeyProperties.AUTH_BIOMETRIC_STRONG | KeyProperties.AUTH_DEVICE_CREDENTIAL);
} else {
spec.setUserAuthenticationValidityDurationSeconds(30);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
spec.setInvalidatedByBiometricEnrollment(true);
}
}
KeyGenParameterSpec builtSpec = spec.build();
generator.init(builtSpec);
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);
}
private void setupTextInputBridge() {
textInputBridge = new TextInputBridge(this, new TextInputBridge.Callbacks() {
@Override
public void commitText(int codepoint) {
nativeTextInputCommit(codepoint);
}
@Override
public void backspace() {
nativeTextInputBackspace();
}
@Override
public void enter() {
nativeTextInputEnter();
}
});
addContentView(textInputBridge.getView(), new ViewGroup.LayoutParams(1, 1));
}
public void setSoftKeyboardVisible(final boolean visible) {
runOnUiThread(new Runnable() {
@Override
public void run() {
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
View view = getWindow() != null ? getWindow().getDecorView() : null;
if (imm == null || view == null) return;
if (visible) {
view.requestFocus();
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
} else {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
if (textInputBridge != null) {
textInputBridge.setVisible(visible);
}
}
});
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_DEL) {
int repeatCount = event.getRepeatCount();
int deleteCount = lastDeleteRepeatCount < 0
? 1
: Math.max(1, repeatCount - lastDeleteRepeatCount);
lastDeleteRepeatCount = repeatCount;
for (int i = 0; i < deleteCount; i++) {
nativeTextInputBackspace();
}
} else if (keyCode == KeyEvent.KEYCODE_ENTER ||
keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) {
lastDeleteRepeatCount = -1;
nativeTextInputEnter();
} else {
lastDeleteRepeatCount = -1;
int unicode = event.getUnicodeChar();
if (unicode >= 32) {
nativeTextInputCommit(unicode);
}
}
} else if (event != null && event.getAction() == KeyEvent.ACTION_UP) {
if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
lastDeleteRepeatCount = -1;
}
} else if (event != null && event.getAction() == KeyEvent.ACTION_MULTIPLE &&
event.getCharacters() != null) {
lastDeleteRepeatCount = -1;
String chars = event.getCharacters();
for (int i = 0; i < chars.length();) {
int codepoint = chars.codePointAt(i);
if (codepoint >= 32) {
nativeTextInputCommit(codepoint);
}
i += Character.charCount(codepoint);
}
}
return super.dispatchKeyEvent(event);
}
private void setupInsetsListener() {
final View decorView = getWindow().getDecorView();
@@ -113,7 +447,8 @@ public class MainActivity extends NativeActivity {
}
});
// Startup safety net: catch the initial layout pass.
// Keep the native UI updated when the soft keyboard changes the
// visible frame on API levels where IME insets are not reported.
decorView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
@@ -124,7 +459,6 @@ public class MainActivity extends NativeActivity {
updateInsets(insets);
}
}
decorView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
@@ -141,18 +475,28 @@ public class MainActivity extends NativeActivity {
nativeSetDeviceDensity(getResources().getDisplayMetrics().density);
int statusBar = 0;
int navBar = 0;
int systemLeft = 0;
int systemTop = 0;
int systemRight = 0;
int systemBottom = 0;
int imeBottom = 0;
int cLeft = 0, cTop = 0, cRight = 0, cBottom = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Insets systemBars = insets.getInsetsIgnoringVisibility(
WindowInsets.Type.systemBars());
statusBar = systemBars.top;
navBar = systemBars.bottom;
Insets ime = insets.getInsets(WindowInsets.Type.ime());
systemLeft = systemBars.left;
systemTop = systemBars.top;
systemRight = systemBars.right;
systemBottom = systemBars.bottom;
imeBottom = ime.bottom;
} else {
statusBar = insets.getSystemWindowInsetTop();
navBar = insets.getSystemWindowInsetBottom();
systemLeft = insets.getSystemWindowInsetLeft();
systemTop = insets.getSystemWindowInsetTop();
systemRight = insets.getSystemWindowInsetRight();
systemBottom = insets.getSystemWindowInsetBottom();
imeBottom = inferImeBottom(systemBottom);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
@@ -165,6 +509,18 @@ public class MainActivity extends NativeActivity {
}
}
nativeSetInsets(statusBar, navBar, cLeft, cTop, cRight, cBottom);
nativeSetInsets(systemLeft, systemTop, systemRight, systemBottom,
imeBottom, cLeft, cTop, cRight, cBottom);
}
private int inferImeBottom(int navBar) {
View decorView = getWindow().getDecorView();
Rect visible = new Rect();
decorView.getWindowVisibleDisplayFrame(visible);
int rootHeight = decorView.getRootView().getHeight();
int hiddenBottom = rootHeight - visible.bottom;
if (hiddenBottom <= navBar) return 0;
return hiddenBottom;
}
}
@@ -0,0 +1,214 @@
package xyz.waozi.pass;
import android.content.Context;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
final class TextInputBridge {
interface Callbacks {
void commitText(int codepoint);
void backspace();
void enter();
}
private final BridgeView view;
private final InputMethodManager inputMethodManager;
private final Callbacks callbacks;
private boolean active = false;
private int showRequests = 0;
private int hideRequests = 0;
private int pendingShowAttempts = 0;
private final Runnable showKeyboardRunnable = new Runnable() {
@Override
public void run() {
showKeyboardNow();
}
};
TextInputBridge(Context context, Callbacks callbacks) {
this.callbacks = callbacks;
this.view = new BridgeView(context);
this.view.setAlpha(0.0f);
this.view.setBackgroundColor(0x00000000);
this.inputMethodManager =
(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
}
View getView() {
return view;
}
void setVisible(boolean visible) {
if (inputMethodManager == null) {
return;
}
if (visible) {
active = true;
showRequests++;
pendingShowAttempts = 3;
showKeyboardNow();
} else {
active = false;
hideRequests++;
pendingShowAttempts = 0;
view.removeCallbacks(showKeyboardRunnable);
view.clearFocus();
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
int showRequestsForTest() {
return showRequests;
}
int hideRequestsForTest() {
return hideRequests;
}
boolean hasFocusForTest() {
return view.hasFocus();
}
InputConnection createInputConnectionForTest(EditorInfo info) {
return view.onCreateInputConnection(info);
}
private void showKeyboardNow() {
if (!active) {
return;
}
if (!view.isAttachedToWindow()) {
view.post(showKeyboardRunnable);
return;
}
view.requestFocus();
inputMethodManager.restartInput(view);
boolean shown = inputMethodManager.showSoftInput(
view, InputMethodManager.SHOW_IMPLICIT);
if (!shown) {
shown = inputMethodManager.showSoftInput(
view, InputMethodManager.SHOW_FORCED);
}
pendingShowAttempts--;
if (!shown && pendingShowAttempts > 0) {
view.postDelayed(showKeyboardRunnable, 80);
}
}
private void commitText(CharSequence text) {
if (!active || text == null) {
return;
}
for (int i = 0; i < text.length();) {
int codepoint = Character.codePointAt(text, i);
if (codepoint >= 32) {
callbacks.commitText(codepoint);
}
i += Character.charCount(codepoint);
}
}
private void commitBackspace() {
if (active) {
callbacks.backspace();
}
}
private void commitEnter() {
if (active) {
callbacks.enter();
}
}
private boolean handleKeyEvent(KeyEvent event) {
if (event == null || event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_DEL) {
commitBackspace();
return true;
}
if (keyCode == KeyEvent.KEYCODE_ENTER ||
keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) {
commitEnter();
return true;
}
int unicode = event.getUnicodeChar();
if (unicode >= 32) {
commitText(new String(Character.toChars(unicode)));
return true;
}
return false;
}
private final class BridgeView extends View {
BridgeView(Context context) {
super(context);
setLayoutParams(new ViewGroup.LayoutParams(1, 1));
setFocusable(true);
setFocusableInTouchMode(true);
}
@Override
public boolean onCheckIsTextEditor() {
return true;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
outAttrs.inputType = InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD |
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE |
EditorInfo.IME_FLAG_NO_EXTRACT_UI;
return new BaseInputConnection(this, false) {
@Override
public boolean commitText(CharSequence text, int newCursorPosition) {
TextInputBridge.this.commitText(text);
return true;
}
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
if (beforeLength > 0) {
commitBackspace();
}
return true;
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
return handleKeyEvent(event) || super.sendKeyEvent(event);
}
@Override
public boolean performEditorAction(int editorAction) {
if (editorAction == EditorInfo.IME_ACTION_DONE) {
commitEnter();
return true;
}
return super.performEditorAction(editorAction);
}
};
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return handleKeyEvent(event) || super.onKeyDown(keyCode, event);
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 614 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 598 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 627 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 681 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 746 B

+1 -1
View File
@@ -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>
+1 -1
View File
@@ -13,5 +13,5 @@ dependencyResolutionManagement {
}
}
rootProject.name = "gopass"
rootProject.name = "pass"
include ':app'
@@ -0,0 +1 @@
Initial release: deterministic, LessPass-compatible password generation with configurable length, counter, character classes, and excluded characters. Everything is computed locally; nothing is stored or uploaded.
@@ -0,0 +1 @@
New clipboard handling, vault support, and named profiles in the CLI, plus self-update checks in the desktop app. Android keeps the same local, stateless generator.
@@ -0,0 +1,2 @@
- 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,0 +1,2 @@
- Verify every download: releases now ship a SHA256SUMS file covering the command-line, desktop, Android, and browser downloads.
- The Android app now builds entirely from source with no developer signing key, clearing the way for F-Droid distribution.
@@ -0,0 +1,6 @@
- Save and reuse Android master-password defaults with fingerprint unlock.
- Clear unlocked master text and generated passwords after a timeout.
- Autosave length, counter, character classes, excluded characters, and biometric display settings.
- Keep Android fields visible while the keyboard is open.
- Run the real Pass app at pass.waozi.xyz/app.
- Publish universal and per-ABI Android APKs.
@@ -0,0 +1,3 @@
- Add Android appearance settings for following device colors, choosing light or dark mode, selecting a color palette, and switching widget style.
- Use Android system Material colors for the app theme, with a stable Material fallback instead of the bright pink accent some devices report.
- Recalculate the Android layout cleanly when rotating between portrait and landscape, keeping controls clear of system bars and navigation insets.
@@ -0,0 +1 @@
- Keep Android source builds self-contained so F-Droid and other source builds generate the Kry app sources automatically.
@@ -0,0 +1,17 @@
pass derives strong, repeatable passwords on your device. The same site, login, master password, and settings always produce the same result, so there is no password database to back up, sync, or lose.
Everything is computed locally. The app makes no network requests, keeps no accounts, and tracks nothing.
Features:
• Deterministic, LessPass-compatible password generation
• Configurable length, counter, character classes, and excluded characters
• Optional fingerprint unlock with the master password held in secure storage
• No analytics, no tracking, no network access
pass is an independent implementation of the LessPass algorithm. Compatibility does not imply endorsement by or affiliation with the LessPass project.
Source code: https://github.com/waozixyz/pass
Website: https://pass.waozi.xyz
Licensed under BSD-3-Clause.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

@@ -0,0 +1 @@
Deterministic passwords from site, login, and one master password.
@@ -0,0 +1 @@
pass
-3
View File
@@ -1,3 +0,0 @@
module github.com/waozixyz/gopass
go 1.24
-125
View File
@@ -1,125 +0,0 @@
// Package gopass derives site-specific passwords without storing them.
package gopass
import (
"errors"
"fmt"
"math/big"
"strconv"
)
const (
LowercaseCharacters = "abcdefghijklmnopqrstuvwxyz"
UppercaseCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DigitCharacters = "0123456789"
SymbolCharacters = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
)
// Options controls the shape of a generated password.
type Options struct {
Length int
Counter uint64
Lowercase bool
Uppercase bool
Digits bool
Symbols bool
Exclude string
}
// DefaultOptions returns the standard generator settings.
func DefaultOptions() Options {
return Options{
Length: 16,
Counter: 1,
Lowercase: true,
Uppercase: true,
Digits: true,
Symbols: true,
}
}
// Generate derives a password from site, login, master password, and options.
func Generate(site, login, master string, options Options) (string, error) {
classes, alphabet, err := availableCharacters(options)
if err != nil {
return "", err
}
if options.Length < len(classes) {
return "", fmt.Errorf("password length %d is smaller than the %d enabled character classes", options.Length, len(classes))
}
salt := []byte(site + login + strconv.FormatUint(options.Counter, 10))
entropy := new(big.Int).SetBytes(deriveKey([]byte(master), salt))
password := make([]byte, 0, options.Length)
for range options.Length - len(classes) {
password = append(password, alphabet[takeRemainder(entropy, len(alphabet))])
}
required := make([]byte, len(classes))
for i, class := range classes {
required[i] = class[takeRemainder(entropy, len(class))]
}
for _, character := range required {
position := takeRemainder(entropy, len(password)+1)
password = append(password, 0)
copy(password[position+1:], password[position:])
password[position] = character
}
return string(password), nil
}
func availableCharacters(options Options) ([][]byte, []byte, error) {
if options.Length < 1 {
return nil, nil, errors.New("password length must be positive")
}
excluded := make(map[byte]bool, len(options.Exclude))
for _, character := range []byte(options.Exclude) {
excluded[character] = true
}
configured := []struct {
enabled bool
name string
value string
}{
{options.Lowercase, "lowercase", LowercaseCharacters},
{options.Uppercase, "uppercase", UppercaseCharacters},
{options.Digits, "digits", DigitCharacters},
{options.Symbols, "symbols", SymbolCharacters},
}
var classes [][]byte
var alphabet []byte
for _, candidate := range configured {
if !candidate.enabled {
continue
}
filtered := make([]byte, 0, len(candidate.value))
for i := range len(candidate.value) {
if !excluded[candidate.value[i]] {
filtered = append(filtered, candidate.value[i])
}
}
if len(filtered) == 0 {
return nil, nil, fmt.Errorf("enabled %s character class is empty after exclusions", candidate.name)
}
classes = append(classes, filtered)
alphabet = append(alphabet, filtered...)
}
if len(classes) == 0 {
return nil, nil, errors.New("at least one character class must be enabled")
}
return classes, alphabet, nil
}
func takeRemainder(entropy *big.Int, divisor int) int {
quotient := new(big.Int)
remainder := new(big.Int)
quotient.QuoRem(entropy, big.NewInt(int64(divisor)), remainder)
entropy.Set(quotient)
return int(remainder.Int64())
}
-141
View File
@@ -1,141 +0,0 @@
package gopass
import (
"encoding/hex"
"strings"
"testing"
)
func TestDeriveKeyKnownResults(t *testing.T) {
tests := []struct {
password string
salt string
want string
}{
{"password", "salt", "0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5"},
{"", "examplealice1", "caa46554f5a676b76c15b368c655b0b24eaaad8595ef919999785c68e60fd5f5"},
}
for _, test := range tests {
got := hex.EncodeToString(deriveKey([]byte(test.password), []byte(test.salt)))
if got != test.want {
t.Errorf("deriveKey(%q, %q) = %s, want %s", test.password, test.salt, got, test.want)
}
}
}
func TestGenerateKnownResults(t *testing.T) {
tests := []struct {
name string
site, login, key string
options Options
want string
}{
{
name: "defaults",
site: "example.com", login: "alice", key: "correct horse battery staple",
options: DefaultOptions(), want: "&vLf44D'/cSkP-_8",
},
{
name: "counter and length",
site: "service.test", login: "[email protected]", key: "master",
options: Options{Length: 20, Counter: 2, Lowercase: true, Uppercase: true, Digits: true, Symbols: true},
want: "j:x_Lo5X_jL0w%ez`1be",
},
{
name: "utf8 inputs and two classes",
site: "δοκιμή.example", login: "ユーザー", key: "pässword",
options: Options{Length: 12, Counter: 7, Lowercase: true, Digits: true},
want: "ioh5o2mhyghv",
},
{
name: "excluded characters",
site: "example.com", login: "alice", key: "correct horse battery staple",
options: Options{Length: 24, Counter: 1, Lowercase: true, Uppercase: true, Digits: true, Symbols: true, Exclude: "0Ool1I!|"},
want: "7,a.Cp}YnF'ee7HqbX#PQhgH",
},
{
name: "empty master and zero counter",
site: "x", login: "y", key: "",
options: Options{Length: 4, Counter: 0, Uppercase: true, Digits: true},
want: "9O7C",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := Generate(test.site, test.login, test.key, test.options)
if err != nil {
t.Fatal(err)
}
if got != test.want {
t.Fatalf("Generate() = %q, want %q", got, test.want)
}
independent := referenceGenerate(test.site, test.login, test.key, test.options)
if got != independent {
t.Fatalf("Generate() = %q, separate reference = %q", got, independent)
}
})
}
}
func TestGeneratedPasswordMeetsRequestedShape(t *testing.T) {
options := Options{
Length: 40,
Counter: 3,
Lowercase: true,
Uppercase: true,
Digits: true,
Symbols: true,
Exclude: "abcXYZ019!@",
}
got, err := Generate("host", "account", "secret", options)
if err != nil {
t.Fatal(err)
}
if len(got) != options.Length {
t.Fatalf("length = %d, want %d", len(got), options.Length)
}
for _, excluded := range options.Exclude {
if strings.ContainsRune(got, excluded) {
t.Errorf("result contains excluded character %q", excluded)
}
}
for name, set := range map[string]string{
"lowercase": removeCharacters(LowercaseCharacters, options.Exclude),
"uppercase": removeCharacters(UppercaseCharacters, options.Exclude),
"digits": removeCharacters(DigitCharacters, options.Exclude),
"symbols": removeCharacters(SymbolCharacters, options.Exclude),
} {
if !strings.ContainsAny(got, set) {
t.Errorf("result has no %s character", name)
}
}
}
func removeCharacters(value, excluded string) string {
return strings.Map(func(character rune) rune {
if strings.ContainsRune(excluded, character) {
return -1
}
return character
}, value)
}
func TestRejectsInvalidOptions(t *testing.T) {
tests := []struct {
name string
options Options
}{
{"nonpositive length", Options{Length: 0, Lowercase: true}},
{"no class", Options{Length: 8}},
{"too few positions", Options{Length: 2, Lowercase: true, Uppercase: true, Digits: true}},
{"emptied class", Options{Length: 8, Digits: true, Exclude: DigitCharacters}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := Generate("site", "login", "master", test.options); err == nil {
t.Fatal("Generate() succeeded for invalid options")
}
})
}
}
-37
View File
@@ -1,37 +0,0 @@
package main
import "time"
type clipboardLease struct {
read func() string
write func(string)
now func() time.Time
value string
expires time.Time
}
func (c *clipboardLease) copy(value string, lifetime time.Duration) {
c.write(value)
c.value = value
c.expires = c.now().Add(lifetime)
}
func (c *clipboardLease) tick() bool {
if c.value == "" || c.now().Before(c.expires) {
return false
}
if c.read() == c.value {
c.write("")
}
c.value = ""
c.expires = time.Time{}
return true
}
func (c *clipboardLease) clear() {
if c.value != "" && c.read() == c.value {
c.write("")
}
c.value = ""
c.expires = time.Time{}
}
-44
View File
@@ -1,44 +0,0 @@
package main
import (
"testing"
"time"
)
func TestClipboardLeaseClearsOnlyItsOwnExpiredValue(t *testing.T) {
now := time.Unix(100, 0)
clipboard := ""
lease := clipboardLease{
read: func() string { return clipboard },
write: func(value string) { clipboard = value },
now: func() time.Time { return now },
}
lease.copy("generated", 20*time.Second)
if clipboard != "generated" {
t.Fatalf("clipboard = %q", clipboard)
}
now = now.Add(19 * time.Second)
if lease.tick() || clipboard == "" {
t.Fatal("lease cleared too early")
}
clipboard = "user replacement"
now = now.Add(2 * time.Second)
if !lease.tick() || clipboard != "user replacement" {
t.Fatal("lease overwrote newer clipboard content")
}
}
func TestClipboardLeaseClearsExpiredValue(t *testing.T) {
now := time.Unix(100, 0)
clipboard := ""
lease := clipboardLease{
read: func() string { return clipboard },
write: func(value string) { clipboard = value },
now: func() time.Time { return now },
}
lease.copy("generated", time.Second)
now = now.Add(time.Second)
if !lease.tick() || clipboard != "" {
t.Fatal("expired generated password was not cleared")
}
}
-12
View File
@@ -1,12 +0,0 @@
module github.com/waozixyz/gopass/gui
go 1.25.0
require (
github.com/waozixyz/gopass v0.0.0
github.com/waozixyz/kryon/go/kryui v0.0.0
)
replace github.com/waozixyz/gopass => ..
replace github.com/waozixyz/kryon/go/kryui => ../vendor/kryon/go/kryui
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

-182
View File
@@ -1,182 +0,0 @@
package main
import (
_ "embed"
"time"
password "github.com/waozixyz/gopass"
"github.com/waozixyz/kryon/go/kryui"
)
const clipboardLifetime = 20 * time.Second
//go:embed icon.png
var appIconPNG []byte
//go:embed assets/emoji.ttf
var emojiFontTTF []byte
type app struct {
site, login, master, exclude *kryui.TextFieldState
length, counter int32
lower, upper, digits, symbols bool
reveal bool
generated, message, fingerprint string
clipboard clipboardLease
}
func newApp() *app {
return &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},
}
}
func main() {
kryui.SetConfigFlags(kryui.FlagWindowResizable)
kryui.InitWindow(720, 690, "gopass")
defer kryui.CloseWindow()
icon := kryui.LoadImageFromMemory(".png", appIconPNG)
kryui.SetWindowIcon(icon)
kryui.UnloadImage(icon)
kryui.SetThemeStyle(kryui.ThemeStyleMaterial)
kryui.SetCurrentTheme(11, true) // Cobalt dark
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.SetWindowMinSize(560, 620)
kryui.EnableEventWaiting()
a := newApp()
defer func() { a.master.Clear(); a.clipboard.clear() }()
for !kryui.WindowShouldClose() {
a.clipboard.tick()
kryui.BeginDrawing()
w := kryui.GetScreenWidth()
kryui.BeginUI(kryui.Key("gopass/main"))
a.draw(w)
kryui.EndUI()
a.handleUIEvents()
kryui.EndDrawing()
}
}
func (a *app) draw(width int32) {
bg, text := kryui.GetThemeBackground(), kryui.GetThemeText()
scheme := kryui.GetUIMaterialScheme()
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)
style := inputStyle()
y := int32(146)
a.field("Site", a.site, x+24, y, contentW-48, style)
y += 76
a.field("Login", a.login, x+24, y, contentW-48, style)
y += 76
kryui.DrawUIText("Master password", x+24, 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.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})
y += 76
kryui.DrawUIText("PASSWORD RULES", x+24, 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)
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)
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})
y += 56
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x+24), float32(y), float32(contentW-48), 72), .08, 10, scheme.SurfaceContainer)
if a.generated != "" {
kryui.SelectableText(a.generated, x+42, y+15, kryui.UIText20, text)
} else {
kryui.DrawUIText("Your generated password appears here", x+42, y+17, kryui.UIText16, scheme.OnSurfaceVariant)
}
if a.message != "" {
kryui.DrawUIText(a.message, x+42, y+45, kryui.UIText12, scheme.OnSurfaceVariant)
}
}
func (a *app) field(label string, field *kryui.TextFieldState, x, y, width int32, style kryui.UITextInputStyle) {
kryui.DrawUIText(label, x, y, kryui.UIText14, kryui.GetThemeText())
kryui.TextField(field, kryui.FieldProps{Bounds: kryui.NewRectangle(float32(x), float32(y+24), float32(width), 38), Font: kryui.UIText16, Style: style})
}
func (a *app) handleUIEvents() {
for event, ok := kryui.NextUIEvent(); ok; event, ok = kryui.NextUIEvent() {
switch event.Kind {
case kryui.EventTextChanged:
if event.Key == 103 {
if master := a.master.Text(); master != "" {
a.fingerprint = password.MasterPasswordEmojiString(master)
} else {
a.fingerprint = ""
}
}
case kryui.EventClick:
switch event.Key {
case 205:
a.reveal = !a.reveal
case 401:
a.generate()
case 402:
if a.generated != "" {
a.clipboard.copy(a.generated, clipboardLifetime)
a.message = "Copied; clipboard clears in 20 seconds"
}
case 403:
a.master.Clear()
a.fingerprint = ""
a.generated = ""
a.message = "Cleared"
}
}
}
}
func (a *app) generate() {
result, err := password.Generate(a.site.Text(), a.login.Text(), a.master.Text(), password.Options{Length: int(a.length), Counter: uint64(a.counter), Lowercase: a.lower, Uppercase: a.upper, Digits: a.digits, Symbols: a.symbols, Exclude: a.exclude.Text()})
if err != nil {
a.generated = ""
a.message = err.Error()
return
}
a.generated, a.message = result, "Password generated locally"
}
func inputStyle() kryui.UITextInputStyle {
s := kryui.GetUIMaterialScheme()
return kryui.UITextInputStyle{Background: s.SurfaceContainer, Border: s.Outline, FocusBorder: s.Primary, Text: s.OnSurface, Cursor: s.Primary, Radius: 6, PaddingX: 10, PaddingY: 8}
}
-54
View File
@@ -1,54 +0,0 @@
package gopass
import "crypto/sha256"
// masterEmojiTable is the fixed alphabet for the master-password fingerprint.
// Entries are single-codepoint emoji with distinct silhouettes so a wrong
// master password is obvious at a glance. The order is part of the public
// derivation: never reorder or extend without treating it as a format change.
var masterEmojiTable = []rune{
// animals
'🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼',
'🐨', '🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🐔',
'🐧', '🦉', '🐺', '🐴', '🦄', '🐝', '🦋', '🐢',
// food
'🍎', '🍊', '🍋', '🍉', '🍇', '🍓', '🍒', '🍑',
'🥑', '🌽', '🍕', '🍔', '🍟', '🍩',
// nature
'🌵', '🌲', '🌳', '🌴', '🌱', '🌻', '🌸', '🌈',
'⭐', '🌙',
// objects
'🔥', '💧', '⛄', '🎉', '🎸', '🎯', '🎲', '🎁',
'🚀', '🚗', '⚓', '🎨', '🔑', '💡', '📚', '🎧',
}
// MasterEmojiCount is the number of emoji shown for one master password.
const MasterEmojiCount = 4
// MasterPasswordEmoji derives a short emoji fingerprint from a master
// password: the first bytes of its SHA-256 select MasterEmojiCount emoji from
// masterEmojiTable. The same master password always produces the same emoji,
// so a user can recognise a correctly typed master password across sessions
// without the password ever being stored or displayed. The fingerprint leaks
// only 24 bits of the hash, which does not help recover a strong master.
func MasterPasswordEmoji(master string) []rune {
sum := sha256.Sum256([]byte(master))
emoji := make([]rune, MasterEmojiCount)
for i := range emoji {
emoji[i] = masterEmojiTable[int(sum[i])%len(masterEmojiTable)]
}
return emoji
}
// MasterPasswordEmojiString is MasterPasswordEmoji as a display string.
func MasterPasswordEmojiString(master string) string {
return string(MasterPasswordEmoji(master))
}
// MasterEmojiCodepoints lists the table's codepoints. Registration with a
// font subset needs exactly these glyphs.
func MasterEmojiCodepoints() []rune {
codepoints := make([]rune, len(masterEmojiTable))
copy(codepoints, masterEmojiTable)
return codepoints
}
-63
View File
@@ -1,63 +0,0 @@
package gopass
import "testing"
func TestMasterPasswordEmojiIsDeterministic(t *testing.T) {
first := MasterPasswordEmojiString("correct horse battery staple")
for i := 0; i < 8; i++ {
if got := MasterPasswordEmojiString("correct horse battery staple"); got != first {
t.Fatalf("fingerprint changed between calls: %q vs %q", got, first)
}
}
if got := MasterPasswordEmojiString(""); got == "" || len([]rune(got)) != MasterEmojiCount {
t.Fatalf("empty master fingerprint = %q, want %d emoji", got, MasterEmojiCount)
}
}
func TestMasterPasswordEmojiDiffersForDifferentMasters(t *testing.T) {
seen := map[string]string{
MasterPasswordEmojiString("test"): "test",
MasterPasswordEmojiString("test2"): "test2",
MasterPasswordEmojiString("tset"): "tset",
MasterPasswordEmojiString("hunter2"): "hunter2",
MasterPasswordEmojiString("correct horse battery staple"): "correct horse battery staple",
}
// Five distinct short masters colliding on a 24-bit space would be
// itself a sha256 anomaly; a single collision here means a table bug.
if len(seen) != 5 {
t.Fatalf("expected distinct fingerprints, got %d unique for 5 masters", len(seen))
}
}
func TestMasterPasswordEmojiUsesTableAlphabet(t *testing.T) {
inTable := func(r rune) bool {
for _, candidate := range masterEmojiTable {
if candidate == r {
return true
}
}
return false
}
if len(masterEmojiTable) != 64 {
t.Fatalf("table has %d emoji, want 64", len(masterEmojiTable))
}
for _, master := range []string{"a", "b", "ab", "🔐", "фыв"} {
for _, r := range MasterPasswordEmoji(master) {
if !inTable(r) {
t.Fatalf("master %q produced rune %U outside the table", master, r)
}
}
}
}
func TestMasterEmojiCodepointsMatchTable(t *testing.T) {
codepoints := MasterEmojiCodepoints()
if len(codepoints) != len(masterEmojiTable) {
t.Fatalf("got %d codepoints, want %d", len(codepoints), len(masterEmojiTable))
}
for i := range codepoints {
if codepoints[i] != masterEmojiTable[i] {
t.Fatalf("codepoint %d = %U, want %U", i, codepoints[i], masterEmojiTable[i])
}
}
}
-33
View File
@@ -1,33 +0,0 @@
#ifndef GOPASS_CORE_H
#define GOPASS_CORE_H
#include <stddef.h>
#include <stdint.h>
#define GOPASS_DERIVATION_ROUNDS 100000
typedef struct {
int length;
uint64_t counter;
int lowercase;
int uppercase;
int digits;
int symbols;
const char *exclude; /* NUL-terminated; may be NULL or empty */
} GopassOptions;
/* 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,
const char *salt, size_t salt_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,
char *out, size_t out_size,
char *err, size_t err_size);
#endif
+225
View File
@@ -0,0 +1,225 @@
#include "pass_core.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef PASS_VERSION
#define PASS_VERSION "dev"
#endif
#define MASTER_ENV "LESSPASS_MASTER_PASSWORD"
typedef struct {
PassOptions options;
int prompt;
int copy;
int no_copy;
int show_version;
const char *site;
const char *login;
const char *master;
} Cli;
static void
usage(FILE *out)
{
fputs(
"Usage: pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]\n"
"\n"
"Derive a site-specific password.\n"
"\n"
"Options:\n"
" -L, --length N password length (default 16)\n"
" -C, --counter N generation counter (default 1)\n"
" -l, --lowercase include lowercase letters\n"
" -u, --uppercase include uppercase letters\n"
" -d, --digits include digits\n"
" -s, --symbols include symbols\n"
" --no-lowercase exclude lowercase letters\n"
" --no-uppercase exclude uppercase letters\n"
" --no-digits exclude digits\n"
" --no-symbols exclude symbols\n"
" --exclude CHARS remove characters from all enabled classes\n"
" -p, --prompt read the master password from stdin\n"
" -c, --copy reserved for GUI/runtime clipboard support\n"
" --no-copy print instead of copying\n"
" -v, --version show version\n"
" -h, --help show this help\n",
out);
}
static int
parse_int(const char *value, int *out)
{
char *end = NULL;
long parsed;
if(value == NULL || value[0] == '\0')
return 0;
parsed = strtol(value, &end, 10);
if(end == NULL || *end != '\0')
return 0;
*out = (int)parsed;
return 1;
}
static int
read_line(char *out, size_t out_size)
{
size_t len;
if(out == NULL || out_size == 0)
return 0;
if(fgets(out, (int)out_size, stdin) == NULL)
return 0;
len = strlen(out);
while(len > 0 && (out[len - 1] == '\n' || out[len - 1] == '\r')) {
out[len - 1] = '\0';
len--;
}
return 1;
}
static int
take_value(int argc, char **argv, int *i, const char **value, const char *name)
{
if(*i + 1 >= argc) {
fprintf(stderr, "pass: %s requires a value\n", name);
return 0;
}
*i += 1;
*value = argv[*i];
return 1;
}
static int
parse_args(int argc, char **argv, Cli *cli)
{
int positional = 0;
for(int i = 1; i < argc; i++) {
const char *arg = argv[i];
const char *value = NULL;
if(strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0) {
usage(stdout);
exit(0);
} else if(strcmp(arg, "-v") == 0 || strcmp(arg, "--version") == 0) {
cli->show_version = 1;
} else if(strcmp(arg, "-L") == 0 || strcmp(arg, "--length") == 0) {
if(!take_value(argc, argv, &i, &value, arg) ||
!parse_int(value, &cli->options.length))
return 0;
} else if(strcmp(arg, "-C") == 0 || strcmp(arg, "--counter") == 0) {
int counter;
if(!take_value(argc, argv, &i, &value, arg) ||
!parse_int(value, &counter))
return 0;
cli->options.counter = (unsigned long long)(counter < 0 ? 0 : counter);
} else if(strcmp(arg, "-l") == 0 || strcmp(arg, "--lowercase") == 0) {
cli->options.lowercase = 1;
} else if(strcmp(arg, "-u") == 0 || strcmp(arg, "--uppercase") == 0) {
cli->options.uppercase = 1;
} else if(strcmp(arg, "-d") == 0 || strcmp(arg, "--digits") == 0) {
cli->options.digits = 1;
} else if(strcmp(arg, "-s") == 0 || strcmp(arg, "--symbols") == 0) {
cli->options.symbols = 1;
} else if(strcmp(arg, "--no-lowercase") == 0) {
cli->options.lowercase = 0;
} else if(strcmp(arg, "--no-uppercase") == 0) {
cli->options.uppercase = 0;
} else if(strcmp(arg, "--no-digits") == 0) {
cli->options.digits = 0;
} else if(strcmp(arg, "--no-symbols") == 0) {
cli->options.symbols = 0;
} else if(strcmp(arg, "--exclude") == 0) {
if(!take_value(argc, argv, &i, &value, arg))
return 0;
cli->options.exclude = value;
} else if(strcmp(arg, "-p") == 0 || strcmp(arg, "--prompt") == 0) {
cli->prompt = 1;
} else if(strcmp(arg, "-c") == 0 || strcmp(arg, "--copy") == 0) {
cli->copy = 1;
} else if(strcmp(arg, "--no-copy") == 0) {
cli->no_copy = 1;
} else if(arg[0] == '-') {
fprintf(stderr, "pass: unknown option %s\n", arg);
return 0;
} else if(positional == 0) {
cli->site = arg;
positional++;
} else if(positional == 1) {
cli->login = arg;
positional++;
} else if(positional == 2) {
cli->master = arg;
positional++;
} else {
fprintf(stderr, "pass: too many positional arguments\n");
return 0;
}
}
return 1;
}
int
main(int argc, char **argv)
{
Cli cli;
char master[1024];
char out[256];
char err[256];
const char *env_master;
memset(&cli, 0, sizeof(cli));
cli.options.length = 16;
cli.options.counter = 1;
cli.options.lowercase = 1;
cli.options.uppercase = 1;
cli.options.digits = 1;
cli.options.symbols = 1;
cli.options.exclude = "";
if(!parse_args(argc, argv, &cli)) {
usage(stderr);
return 2;
}
if(cli.show_version) {
printf("pass %s\n", PASS_VERSION);
return 0;
}
if(cli.site == NULL || cli.login == NULL) {
usage(stderr);
return 2;
}
if(cli.copy && !cli.no_copy) {
fprintf(stderr, "pass: --copy is not available in the C CLI yet\n");
return 2;
}
memset(master, 0, sizeof(master));
if(cli.master != NULL) {
snprintf(master, sizeof(master), "%s", cli.master);
} else if(!cli.prompt && (env_master = getenv(MASTER_ENV)) != NULL) {
snprintf(master, sizeof(master), "%s", env_master);
} else {
if(!read_line(master, sizeof(master))) {
fprintf(stderr, "pass: missing master password\n");
return 2;
}
}
memset(out, 0, sizeof(out));
memset(err, 0, sizeof(err));
if(pass_core_generate(cli.site, cli.login, master, &cli.options,
out, sizeof(out), err, sizeof(err)) != 0) {
fprintf(stderr, "pass: %s\n", err);
return 1;
}
printf("%s\n", out);
memset(master, 0, sizeof(master));
memset(out, 0, sizeof(out));
return 0;
}
+96 -14
View File
@@ -1,8 +1,7 @@
/* 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
* the same fixed vectors the Go tests use. */
/* LessPass-compatible generator used by the CLI and every Kry app target.
* native/pass_core_test.c checks fixed vectors for byte stability. */
#include "gopass_core.h"
#include "pass_core.h"
#include <stdio.h>
#include <string.h>
@@ -175,6 +174,89 @@ sha256(const void *data, size_t len, uint8_t out[32])
sha256_final(&ctx, out);
}
void
pass_core_sha256(const void *data, size_t len, uint8_t out[32])
{
sha256(data, len, out);
}
static const int MASTER_EMOJI_CODEPOINTS[] = {
0x1F436, 0x1F431, 0x1F42D, 0x1F439, 0x1F430, 0x1F98A, 0x1F43B, 0x1F43C,
0x1F428, 0x1F42F, 0x1F981, 0x1F42E, 0x1F437, 0x1F438, 0x1F435, 0x1F414,
0x1F427, 0x1F989, 0x1F43A, 0x1F434, 0x1F984, 0x1F41D, 0x1F98B, 0x1F422,
0x1F34E, 0x1F34A, 0x1F34B, 0x1F349, 0x1F347, 0x1F353, 0x1F352, 0x1F351,
0x1F951, 0x1F33D, 0x1F355, 0x1F354, 0x1F35F, 0x1F369, 0x1F335, 0x1F332,
0x1F333, 0x1F334, 0x1F331, 0x1F33B, 0x1F338, 0x1F308, 0x2B50, 0x1F319,
0x1F525, 0x1F4A7, 0x26C4, 0x1F389, 0x1F3B8, 0x1F3AF, 0x1F3B2, 0x1F381,
0x1F680, 0x1F697, 0x2693, 0x1F3A8, 0x1F511, 0x1F4A1, 0x1F4DA, 0x1F3A7,
};
const int *
pass_core_master_emoji_codepoints(int *count)
{
if(count != NULL)
*count = (int)(sizeof(MASTER_EMOJI_CODEPOINTS) /
sizeof(MASTER_EMOJI_CODEPOINTS[0]));
return MASTER_EMOJI_CODEPOINTS;
}
static size_t
append_utf8(char *out, size_t used, size_t out_size, uint32_t codepoint)
{
unsigned char bytes[4];
int len = 0;
if(out == NULL || out_size == 0)
return 0;
if(codepoint <= 0x7Fu) {
bytes[0] = (unsigned char)codepoint;
len = 1;
} else if(codepoint <= 0x7FFu) {
bytes[0] = (unsigned char)(0xC0u | (codepoint >> 6));
bytes[1] = (unsigned char)(0x80u | (codepoint & 0x3Fu));
len = 2;
} else if(codepoint <= 0xFFFFu) {
bytes[0] = (unsigned char)(0xE0u | (codepoint >> 12));
bytes[1] = (unsigned char)(0x80u | ((codepoint >> 6) & 0x3Fu));
bytes[2] = (unsigned char)(0x80u | (codepoint & 0x3Fu));
len = 3;
} else if(codepoint <= 0x10FFFFu) {
bytes[0] = (unsigned char)(0xF0u | (codepoint >> 18));
bytes[1] = (unsigned char)(0x80u | ((codepoint >> 12) & 0x3Fu));
bytes[2] = (unsigned char)(0x80u | ((codepoint >> 6) & 0x3Fu));
bytes[3] = (unsigned char)(0x80u | (codepoint & 0x3Fu));
len = 4;
}
if(len <= 0 || used + (size_t)len >= out_size) {
out[used < out_size ? used : out_size - 1] = '\0';
return used;
}
memcpy(out + used, bytes, (size_t)len);
used += (size_t)len;
out[used] = '\0';
return used;
}
void
pass_core_master_emoji(const char *master, char *out, size_t out_size)
{
uint8_t sum[32];
size_t used = 0;
int table_count = 0;
const int *table = pass_core_master_emoji_codepoints(&table_count);
if(out == NULL || out_size == 0)
return;
out[0] = '\0';
if(master == NULL)
master = "";
pass_core_sha256(master, strlen(master), sum);
for(int i = 0; i < PASS_MASTER_EMOJI_COUNT && table_count > 0; i++)
used = append_utf8(out, used, out_size,
(uint32_t)table[sum[i] % table_count]);
}
/* ------------------------------------------------------------------ */
/* HMAC-SHA256 */
/* ------------------------------------------------------------------ */
@@ -217,9 +299,9 @@ hmac_sha256(const void *key, size_t key_len,
/* ------------------------------------------------------------------ */
void
gopass_derive_key(const char *password, size_t password_len,
const char *salt, size_t salt_len,
uint8_t out[32])
pass_core_derive_key(const char *password, size_t password_len,
const char *salt, size_t salt_len,
uint8_t out[32])
{
uint8_t block_input[512];
uint8_t previous[32];
@@ -241,7 +323,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,10 +385,10 @@ 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,
char *out, size_t out_size,
char *err, size_t err_size)
pass_core_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)
{
static const char *class_names[4] = {"lowercase", "uppercase", "digits", "symbols"};
static const char *class_sets[4] = {
@@ -380,8 +462,8 @@ 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,
salt, salt_len, entropy);
pass_core_derive_key(master != NULL ? master : "", master != NULL ? strlen(master) : 0,
salt, salt_len, entropy);
password_length = options->length - class_count;
for(i = 0; i < password_length; i++)
+41
View File
@@ -0,0 +1,41 @@
#ifndef PASS_CORE_H
#define PASS_CORE_H
#include <stddef.h>
#include <stdint.h>
#define PASS_DERIVATION_ROUNDS 100000
#define PASS_MASTER_EMOJI_COUNT 4
typedef struct {
int length;
uint64_t counter;
int lowercase;
int uppercase;
int digits;
int symbols;
const char *exclude; /* NUL-terminated; may be NULL or empty */
} PassOptions;
/* Derives the 32-byte PBKDF2-HMAC-SHA256 key (one block, 100000 rounds),
* the byte-exact counterpart of the Go package's deriveKey. */
void pass_core_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_core_sha256(const void *data, size_t len, uint8_t out[32]);
const int *pass_core_master_emoji_codepoints(int *count);
void pass_core_master_emoji(const char *master, char *out, size_t out_size);
/* 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 pass_core_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);
#endif
@@ -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 lock the generator
* output so CLI, desktop, Android, and web stay 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_core_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_core_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,98 @@ 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_core_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 int
utf8_codepoint_count(const char *text)
{
int count = 0;
if(text == NULL)
return 0;
for(int i = 0; text[i] != '\0'; i++) {
unsigned char c = (unsigned char)text[i];
if((c & 0xC0u) != 0x80u)
count++;
}
return count;
}
static void
check_master_emoji(void)
{
char first[64];
char again[64];
char empty[64];
char values[5][64];
int table_count = 0;
const int *table = pass_core_master_emoji_codepoints(&table_count);
if(table == NULL || table_count != 64) {
printf("FAIL master emoji: table count %d, want 64\n", table_count);
failures++;
return;
}
pass_core_master_emoji("correct horse battery staple", first, sizeof(first));
pass_core_master_emoji("correct horse battery staple", again, sizeof(again));
if(strcmp(first, again) != 0 ||
utf8_codepoint_count(first) != PASS_MASTER_EMOJI_COUNT) {
printf("FAIL master emoji: deterministic=%d count=%d value=%s\n",
strcmp(first, again) == 0,
utf8_codepoint_count(first), first);
failures++;
return;
}
pass_core_master_emoji("", empty, sizeof(empty));
if(utf8_codepoint_count(empty) != PASS_MASTER_EMOJI_COUNT) {
printf("FAIL master emoji: empty count=%d value=%s\n",
utf8_codepoint_count(empty), empty);
failures++;
return;
}
pass_core_master_emoji("test", values[0], sizeof(values[0]));
pass_core_master_emoji("test2", values[1], sizeof(values[1]));
pass_core_master_emoji("tset", values[2], sizeof(values[2]));
pass_core_master_emoji("hunter2", values[3], sizeof(values[3]));
pass_core_master_emoji("correct horse battery staple", values[4], sizeof(values[4]));
for(int i = 0; i < 5; i++) {
for(int j = i + 1; j < 5; j++) {
if(strcmp(values[i], values[j]) == 0) {
printf("FAIL master emoji: collision %d/%d = %s\n", i, j, values[i]);
failures++;
return;
}
}
}
printf("ok master emoji: %s\n", first);
}
static void
check_shape(void)
{
GopassOptions options;
PassOptions options;
char out[256];
char err[256];
static const char *exclude = "abcXYZ019!@";
@@ -87,7 +175,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_core_generate("host", "account", "secret", &options, out, sizeof(out), err, sizeof(err)) != 0) {
printf("FAIL shape: %s\n", err);
failures++;
return;
@@ -129,12 +217,14 @@ check_shape(void)
int
main(void)
{
GopassOptions defaults;
PassOptions defaults;
check_derive(1, "password", "salt",
"0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5");
check_derive(2, "", "examplealice1",
"caa46554f5a676b76c15b368c655b0b24eaaad8595ef919999785c68e60fd5f5");
check_sha256();
check_master_emoji();
memset(&defaults, 0, sizeof(defaults));
defaults.length = 16;
@@ -149,7 +239,7 @@ main(void)
defaults, "&vLf44D'/cSkP-_8", 0);
{
GopassOptions o = defaults;
PassOptions o = defaults;
o.length = 20;
o.counter = 2;
@@ -158,7 +248,7 @@ main(void)
}
{
GopassOptions o;
PassOptions o;
memset(&o, 0, sizeof(o));
o.length = 12;
@@ -171,7 +261,7 @@ main(void)
}
{
GopassOptions o = defaults;
PassOptions o = defaults;
o.length = 24;
o.exclude = "0Ool1I!|";
@@ -180,7 +270,7 @@ main(void)
}
{
GopassOptions o;
PassOptions o;
memset(&o, 0, sizeof(o));
o.length = 4;
@@ -191,7 +281,7 @@ main(void)
}
{
GopassOptions o;
PassOptions o;
memset(&o, 0, sizeof(o));
o.length = 0;
@@ -200,7 +290,7 @@ main(void)
}
{
GopassOptions o;
PassOptions o;
memset(&o, 0, sizeof(o));
o.length = 8;
@@ -208,7 +298,7 @@ main(void)
}
{
GopassOptions o;
PassOptions o;
memset(&o, 0, sizeof(o));
o.length = 2;
@@ -219,7 +309,7 @@ main(void)
}
{
GopassOptions o;
PassOptions o;
memset(&o, 0, sizeof(o));
o.length = 8;
+684
View File
@@ -0,0 +1,684 @@
#include "pass_runtime.h"
#include "pass_core.h"
#include "android_bridge.h"
#include "kryon.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PASS_MAX_PROFILES 64
#define PASS_NAME_SIZE 64
#define PASS_SITE_SIZE 256
#define PASS_LOGIN_SIZE 256
#define PASS_EXCLUDE_SIZE 128
#define PASS_PASSWORD_SIZE 256
#define PASS_STATUS_SIZE 256
typedef struct {
char name[PASS_NAME_SIZE];
char site[PASS_SITE_SIZE];
char login[PASS_LOGIN_SIZE];
int length;
int counter;
int lower;
int upper;
int digits;
int symbols;
char exclude[PASS_EXCLUDE_SIZE];
} PassProfile;
typedef struct {
int auto_copy;
int clear_seconds;
int show_fingerprint;
int length;
int counter;
int lower;
int upper;
int digits;
int symbols;
char exclude[PASS_EXCLUDE_SIZE];
int theme_source;
int theme_mode;
int theme_id;
int theme_style;
} PassRuntimeSettings;
typedef struct {
PassRuntimeSettings settings;
PassProfile profiles[PASS_MAX_PROFILES];
int profile_count;
char generated[PASS_PASSWORD_SIZE];
char status[PASS_STATUS_SIZE];
char fingerprint_status[PASS_STATUS_SIZE];
char master_emoji[32];
char profile_label[PASS_SITE_SIZE + PASS_LOGIN_SIZE + PASS_NAME_SIZE + 16];
char unlocked_master[1024];
int has_unlocked_master;
int secure_action;
double clipboard_clear_at;
} PassRuntime;
enum {
PASS_SECURE_ACTION_NONE = 0,
PASS_SECURE_ACTION_SAVE,
PASS_SECURE_ACTION_UNLOCK
};
static PassRuntime runtime;
static void
copy_text(char *dst, size_t dst_size, const char *src)
{
size_t len;
if(dst == NULL || dst_size == 0)
return;
if(src == NULL)
src = "";
len = strlen(src);
if(len >= dst_size)
len = dst_size - 1;
memcpy(dst, src, len);
dst[len] = '\0';
}
static void
runtime_defaults(void)
{
memset(&runtime, 0, sizeof(runtime));
runtime.settings.auto_copy = 0;
runtime.settings.clear_seconds = 20;
runtime.settings.show_fingerprint = 1;
runtime.settings.length = 16;
runtime.settings.counter = 1;
runtime.settings.lower = 1;
runtime.settings.upper = 1;
runtime.settings.digits = 1;
runtime.settings.symbols = 1;
runtime.settings.exclude[0] = '\0';
runtime.settings.theme_source = THEME_SOURCE_SYSTEM;
runtime.settings.theme_mode = THEME_MODE_SYSTEM;
runtime.settings.theme_id = THEME_MINT;
runtime.settings.theme_style = THEME_STYLE_MATERIAL;
copy_text(runtime.status, sizeof(runtime.status), "Ready");
copy_text(runtime.fingerprint_status, sizeof(runtime.fingerprint_status), "No saved master password");
}
static void
trim_newline(char *s)
{
size_t len;
if(s == NULL)
return;
len = strlen(s);
while(len > 0 && (s[len - 1] == '\n' || s[len - 1] == '\r')) {
s[len - 1] = '\0';
len--;
}
}
static void
load_settings(void)
{
FILE *f = fopen("settings.cfg", "r");
char line[256];
if(f == NULL)
return;
while(fgets(line, sizeof(line), f) != NULL) {
char *value;
trim_newline(line);
value = strchr(line, '=');
if(value == NULL)
continue;
*value++ = '\0';
if(strcmp(line, "auto_copy") == 0)
runtime.settings.auto_copy = atoi(value) != 0;
else if(strcmp(line, "clear_after_seconds") == 0)
runtime.settings.clear_seconds = atoi(value);
else if(strcmp(line, "show_fingerprint") == 0)
runtime.settings.show_fingerprint = atoi(value) != 0;
else if(strcmp(line, "length") == 0)
runtime.settings.length = atoi(value);
else if(strcmp(line, "counter") == 0)
runtime.settings.counter = atoi(value);
else if(strcmp(line, "lower") == 0)
runtime.settings.lower = atoi(value) != 0;
else if(strcmp(line, "upper") == 0)
runtime.settings.upper = atoi(value) != 0;
else if(strcmp(line, "digits") == 0)
runtime.settings.digits = atoi(value) != 0;
else if(strcmp(line, "symbols") == 0)
runtime.settings.symbols = atoi(value) != 0;
else if(strcmp(line, "exclude") == 0)
copy_text(runtime.settings.exclude, sizeof(runtime.settings.exclude), value);
else if(strcmp(line, "theme_source") == 0)
runtime.settings.theme_source = atoi(value);
else if(strcmp(line, "theme_mode") == 0)
runtime.settings.theme_mode = atoi(value);
else if(strcmp(line, "theme_id") == 0)
runtime.settings.theme_id = atoi(value);
else if(strcmp(line, "theme_style") == 0)
runtime.settings.theme_style = atoi(value);
}
fclose(f);
}
static int
write_settings(void)
{
FILE *f = fopen("settings.cfg", "w");
if(f == NULL) {
copy_text(runtime.status, sizeof(runtime.status), "Could not save settings");
return 1;
}
fprintf(f, "auto_copy=%d\n", runtime.settings.auto_copy ? 1 : 0);
fprintf(f, "clear_after_seconds=%d\n", runtime.settings.clear_seconds);
fprintf(f, "show_fingerprint=%d\n", runtime.settings.show_fingerprint ? 1 : 0);
fprintf(f, "length=%d\n", runtime.settings.length);
fprintf(f, "counter=%d\n", runtime.settings.counter);
fprintf(f, "lower=%d\n", runtime.settings.lower ? 1 : 0);
fprintf(f, "upper=%d\n", runtime.settings.upper ? 1 : 0);
fprintf(f, "digits=%d\n", runtime.settings.digits ? 1 : 0);
fprintf(f, "symbols=%d\n", runtime.settings.symbols ? 1 : 0);
fprintf(f, "exclude=%s\n", runtime.settings.exclude);
fprintf(f, "theme_source=%d\n", runtime.settings.theme_source);
fprintf(f, "theme_mode=%d\n", runtime.settings.theme_mode);
fprintf(f, "theme_id=%d\n", runtime.settings.theme_id);
fprintf(f, "theme_style=%d\n", runtime.settings.theme_style);
fclose(f);
copy_text(runtime.status, sizeof(runtime.status), "Settings saved");
return 0;
}
static int
read_field(char **cursor, char *dst, size_t dst_size)
{
char *start;
char *tab;
if(cursor == NULL || *cursor == NULL)
return 0;
start = *cursor;
tab = strchr(start, '\t');
if(tab != NULL) {
*tab = '\0';
*cursor = tab + 1;
} else {
*cursor = NULL;
}
copy_text(dst, dst_size, start);
return 1;
}
static void
load_profiles(void)
{
FILE *f = fopen("profiles.tsv", "r");
char line[1024];
runtime.profile_count = 0;
if(f == NULL)
return;
while(runtime.profile_count < PASS_MAX_PROFILES &&
fgets(line, sizeof(line), f) != NULL) {
PassProfile *p = &runtime.profiles[runtime.profile_count];
char *cursor = line;
char scratch[64];
trim_newline(line);
memset(p, 0, sizeof(*p));
if(!read_field(&cursor, p->name, sizeof(p->name)) ||
!read_field(&cursor, p->site, sizeof(p->site)) ||
!read_field(&cursor, p->login, sizeof(p->login)) ||
!read_field(&cursor, scratch, sizeof(scratch)))
continue;
p->length = atoi(scratch);
if(!read_field(&cursor, scratch, sizeof(scratch)))
continue;
p->counter = atoi(scratch);
if(!read_field(&cursor, scratch, sizeof(scratch)))
continue;
p->lower = atoi(scratch) != 0;
if(!read_field(&cursor, scratch, sizeof(scratch)))
continue;
p->upper = atoi(scratch) != 0;
if(!read_field(&cursor, scratch, sizeof(scratch)))
continue;
p->digits = atoi(scratch) != 0;
if(!read_field(&cursor, scratch, sizeof(scratch)))
continue;
p->symbols = atoi(scratch) != 0;
if(cursor != NULL)
copy_text(p->exclude, sizeof(p->exclude), cursor);
runtime.profile_count++;
}
fclose(f);
}
static int
write_profiles(void)
{
FILE *f = fopen("profiles.tsv", "w");
int i;
if(f == NULL) {
copy_text(runtime.status, sizeof(runtime.status), "Could not save profiles");
return 1;
}
for(i = 0; i < runtime.profile_count; i++) {
PassProfile *p = &runtime.profiles[i];
fprintf(f, "%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%s\n",
p->name, p->site, p->login, p->length, p->counter,
p->lower ? 1 : 0, p->upper ? 1 : 0,
p->digits ? 1 : 0, p->symbols ? 1 : 0, p->exclude);
}
fclose(f);
return 0;
}
static int
find_profile(const char *name)
{
int i;
for(i = 0; i < runtime.profile_count; i++) {
if(strcmp(runtime.profiles[i].name, name) == 0)
return i;
}
return -1;
}
void
pass_runtime_init(void)
{
runtime_defaults();
load_settings();
load_profiles();
}
void
pass_runtime_tick(void)
{
char result[1024];
int status = android_bridge_take_secure_result(result, sizeof(result));
if(status == 2) {
if(runtime.secure_action == PASS_SECURE_ACTION_UNLOCK) {
copy_text(runtime.unlocked_master, sizeof(runtime.unlocked_master), result);
runtime.has_unlocked_master = result[0] != '\0';
copy_text(runtime.status, sizeof(runtime.status), "Master unlocked");
} else {
copy_text(runtime.status, sizeof(runtime.status),
result[0] ? result : "Master password saved");
}
runtime.secure_action = PASS_SECURE_ACTION_NONE;
} else if(status == 3) {
copy_text(runtime.status, sizeof(runtime.status), result[0] ? result : "Secure master failed");
runtime.secure_action = PASS_SECURE_ACTION_NONE;
}
if(runtime.clipboard_clear_at > 0.0 && GetTime() >= runtime.clipboard_clear_at) {
SetClipboardText("");
runtime.clipboard_clear_at = 0.0;
copy_text(runtime.status, sizeof(runtime.status), "Clipboard cleared");
}
}
void
pass_runtime_shutdown(void)
{
memset(runtime.generated, 0, sizeof(runtime.generated));
memset(runtime.unlocked_master, 0, sizeof(runtime.unlocked_master));
runtime.has_unlocked_master = 0;
}
const int *
pass_runtime_master_emoji_codepoints(int *count)
{
return pass_core_master_emoji_codepoints(count);
}
int pass_safe_left(void) { return android_bridge_left_reserved(); }
int pass_safe_top(void) { return android_bridge_top_reserved(); }
int pass_safe_right(void) { return android_bridge_right_reserved(); }
int pass_safe_bottom(void) { return android_bridge_bottom_reserved(); }
int
pass_generate(const char *site, const char *login, const char *master,
int length, int counter,
int lower, int upper, int digits, int symbols,
const char *exclude)
{
PassOptions options;
char err[PASS_STATUS_SIZE];
memset(&options, 0, sizeof(options));
options.length = length;
options.counter = (unsigned long long)(counter < 0 ? 0 : counter);
options.lowercase = lower != 0;
options.uppercase = upper != 0;
options.digits = digits != 0;
options.symbols = symbols != 0;
options.exclude = exclude != NULL ? exclude : "";
memset(err, 0, sizeof(err));
if(pass_core_generate(site, login, master, &options,
runtime.generated, sizeof(runtime.generated),
err, sizeof(err)) != 0) {
memset(runtime.generated, 0, sizeof(runtime.generated));
copy_text(runtime.status, sizeof(runtime.status), err);
return 1;
}
if(runtime.settings.auto_copy)
pass_copy();
else
copy_text(runtime.status, sizeof(runtime.status), "Password generated locally");
return 0;
}
char *
pass_generated(void)
{
return runtime.generated;
}
char *
pass_master_emoji(const char *master)
{
if(master == NULL || master[0] == '\0') {
runtime.master_emoji[0] = '\0';
return runtime.master_emoji;
}
pass_core_master_emoji(master, runtime.master_emoji,
sizeof(runtime.master_emoji));
return runtime.master_emoji;
}
char *
pass_status(void)
{
return runtime.status;
}
int
pass_copy(void)
{
if(runtime.generated[0] == '\0') {
copy_text(runtime.status, sizeof(runtime.status), "Generate a password first");
return 1;
}
SetClipboardText(runtime.generated);
if(runtime.settings.clear_seconds > 0) {
runtime.clipboard_clear_at = GetTime() + runtime.settings.clear_seconds;
snprintf(runtime.status, sizeof(runtime.status),
"Copied for %d seconds", runtime.settings.clear_seconds);
} else {
runtime.clipboard_clear_at = 0.0;
copy_text(runtime.status, sizeof(runtime.status), "Copied");
}
return 0;
}
int
pass_save_profile(const char *name, const char *site, const char *login,
int length, int counter,
int lower, int upper, int digits, int symbols,
const char *exclude)
{
int index;
PassProfile *p;
if(name == NULL || name[0] == '\0') {
copy_text(runtime.status, sizeof(runtime.status), "Profile name required");
return 1;
}
index = find_profile(name);
if(index < 0) {
if(runtime.profile_count >= PASS_MAX_PROFILES) {
copy_text(runtime.status, sizeof(runtime.status), "Profile limit reached");
return 1;
}
index = runtime.profile_count++;
}
p = &runtime.profiles[index];
copy_text(p->name, sizeof(p->name), name);
copy_text(p->site, sizeof(p->site), site);
copy_text(p->login, sizeof(p->login), login);
p->length = length;
p->counter = counter;
p->lower = lower != 0;
p->upper = upper != 0;
p->digits = digits != 0;
p->symbols = symbols != 0;
copy_text(p->exclude, sizeof(p->exclude), exclude);
if(write_profiles() != 0)
return 1;
copy_text(runtime.status, sizeof(runtime.status), "Profile saved");
return 0;
}
int
pass_profile_count(void)
{
return runtime.profile_count;
}
char *
pass_profile_label(int index)
{
PassProfile *p;
if(index < 0 || index >= runtime.profile_count) {
runtime.profile_label[0] = '\0';
return runtime.profile_label;
}
p = &runtime.profiles[index];
snprintf(runtime.profile_label, sizeof(runtime.profile_label),
"%s %s / %s", p->name, p->site, p->login);
return runtime.profile_label;
}
int
pass_generate_profile(int index, const char *master)
{
PassProfile *p;
if(index < 0 || index >= runtime.profile_count) {
copy_text(runtime.status, sizeof(runtime.status), "Profile not found");
return 1;
}
p = &runtime.profiles[index];
return pass_generate(p->site, p->login, master, p->length, p->counter,
p->lower, p->upper, p->digits, p->symbols, p->exclude);
}
int
pass_delete_profile(int index)
{
int i;
if(index < 0 || index >= runtime.profile_count) {
copy_text(runtime.status, sizeof(runtime.status), "Profile not found");
return 1;
}
for(i = index; i + 1 < runtime.profile_count; i++)
runtime.profiles[i] = runtime.profiles[i + 1];
runtime.profile_count--;
if(write_profiles() != 0)
return 1;
copy_text(runtime.status, sizeof(runtime.status), "Profile deleted");
return 0;
}
int
pass_save_settings(int auto_copy, int clear_seconds, int show_fingerprint,
int length, int counter,
int lower, int upper, int digits, int symbols,
const char *exclude,
int theme_source, int theme_mode,
int theme_id, int theme_style)
{
runtime.settings.auto_copy = auto_copy != 0;
runtime.settings.clear_seconds = clear_seconds < 0 ? 0 : clear_seconds;
runtime.settings.show_fingerprint = show_fingerprint != 0;
runtime.settings.length = length < 4 ? 4 : length;
runtime.settings.counter = counter < 1 ? 1 : counter;
runtime.settings.lower = lower != 0;
runtime.settings.upper = upper != 0;
runtime.settings.digits = digits != 0;
runtime.settings.symbols = symbols != 0;
copy_text(runtime.settings.exclude, sizeof(runtime.settings.exclude), exclude);
runtime.settings.theme_source = theme_source;
runtime.settings.theme_mode = theme_mode;
runtime.settings.theme_id = theme_id;
runtime.settings.theme_style = theme_style;
return write_settings();
}
int
pass_load_settings(int *auto_copy, int *clear_seconds, int *show_fingerprint,
int *length, int *counter,
int *lower, int *upper, int *digits, int *symbols,
char *exclude, int exclude_size,
int *theme_source, int *theme_mode,
int *theme_id, int *theme_style)
{
if(auto_copy != NULL)
*auto_copy = runtime.settings.auto_copy;
if(clear_seconds != NULL)
*clear_seconds = runtime.settings.clear_seconds;
if(show_fingerprint != NULL)
*show_fingerprint = runtime.settings.show_fingerprint;
if(length != NULL)
*length = runtime.settings.length;
if(counter != NULL)
*counter = runtime.settings.counter;
if(lower != NULL)
*lower = runtime.settings.lower;
if(upper != NULL)
*upper = runtime.settings.upper;
if(digits != NULL)
*digits = runtime.settings.digits;
if(symbols != NULL)
*symbols = runtime.settings.symbols;
if(exclude != NULL && exclude_size > 0)
copy_text(exclude, (size_t)exclude_size, runtime.settings.exclude);
if(theme_source != NULL)
*theme_source = runtime.settings.theme_source;
if(theme_mode != NULL)
*theme_mode = runtime.settings.theme_mode;
if(theme_id != NULL)
*theme_id = runtime.settings.theme_id;
if(theme_style != NULL)
*theme_style = runtime.settings.theme_style;
return 0;
}
int
pass_save_master(const char *master, int require_biometric)
{
if(master == NULL || master[0] == '\0') {
runtime.secure_action = PASS_SECURE_ACTION_NONE;
copy_text(runtime.status, sizeof(runtime.status), "Enter master password first");
return 1;
}
if(require_biometric && !android_bridge_biometric_available()) {
runtime.secure_action = PASS_SECURE_ACTION_NONE;
copy_text(runtime.status, sizeof(runtime.status),
android_bridge_biometric_setup_required()
? "Set up Android fingerprint first"
: "Fingerprint unlock unavailable");
return 1;
}
runtime.secure_action = PASS_SECURE_ACTION_SAVE;
android_bridge_save_master(master, require_biometric);
copy_text(runtime.status, sizeof(runtime.status), "Saving master");
return 0;
}
int
pass_unlock_master(void)
{
if(!android_bridge_master_saved()) {
runtime.secure_action = PASS_SECURE_ACTION_NONE;
copy_text(runtime.status, sizeof(runtime.status), "No saved master password");
return 1;
}
runtime.secure_action = PASS_SECURE_ACTION_UNLOCK;
android_bridge_unlock_master();
copy_text(runtime.status, sizeof(runtime.status), "Unlock requested");
return 0;
}
int
pass_clear_master(void)
{
android_bridge_clear_master();
memset(runtime.unlocked_master, 0, sizeof(runtime.unlocked_master));
runtime.has_unlocked_master = 0;
runtime.secure_action = PASS_SECURE_ACTION_NONE;
copy_text(runtime.status, sizeof(runtime.status), "Saved master forgotten");
return 0;
}
int
pass_can_unlock_master(void)
{
return android_bridge_master_saved() &&
android_bridge_master_biometric() &&
android_bridge_biometric_available();
}
int
pass_biometric_available(void)
{
return android_bridge_biometric_available();
}
int
pass_master_saved(void)
{
return android_bridge_master_saved();
}
char *
pass_fingerprint_status(void)
{
if(!android_bridge_biometric_available()) {
copy_text(runtime.fingerprint_status, sizeof(runtime.fingerprint_status),
android_bridge_biometric_setup_required()
? "Android fingerprint setup required"
: "Fingerprint unlock is not available");
} else if(android_bridge_master_saved()) {
copy_text(runtime.fingerprint_status, sizeof(runtime.fingerprint_status),
android_bridge_master_biometric()
? "Saved master uses fingerprint unlock"
: "Saved master unlocks without fingerprint");
} else {
copy_text(runtime.fingerprint_status, sizeof(runtime.fingerprint_status),
"No saved master password");
}
return runtime.fingerprint_status;
}
int
pass_take_unlocked_master(char *out)
{
if(out == NULL || !runtime.has_unlocked_master)
return 0;
copy_text(out, 1024, runtime.unlocked_master);
memset(runtime.unlocked_master, 0, sizeof(runtime.unlocked_master));
runtime.has_unlocked_master = 0;
return 1;
}
+64
View File
@@ -0,0 +1,64 @@
#ifndef PASS_RUNTIME_H
#define PASS_RUNTIME_H
#include <stddef.h>
#if defined(__cplusplus)
extern "C" {
#endif
void pass_runtime_init(void);
void pass_runtime_tick(void);
void pass_runtime_shutdown(void);
const int *pass_runtime_master_emoji_codepoints(int *count);
char *pass_master_emoji(const char *master);
int pass_safe_left(void);
int pass_safe_top(void);
int pass_safe_right(void);
int pass_safe_bottom(void);
int pass_generate(const char *site, const char *login, const char *master,
int length, int counter,
int lower, int upper, int digits, int symbols,
const char *exclude);
char *pass_generated(void);
char *pass_status(void);
int pass_copy(void);
int pass_save_profile(const char *name, const char *site, const char *login,
int length, int counter,
int lower, int upper, int digits, int symbols,
const char *exclude);
int pass_profile_count(void);
char *pass_profile_label(int index);
int pass_generate_profile(int index, const char *master);
int pass_delete_profile(int index);
int pass_save_settings(int auto_copy, int clear_seconds, int show_fingerprint,
int length, int counter,
int lower, int upper, int digits, int symbols,
const char *exclude,
int theme_source, int theme_mode,
int theme_id, int theme_style);
int pass_load_settings(int *auto_copy, int *clear_seconds, int *show_fingerprint,
int *length, int *counter,
int *lower, int *upper, int *digits, int *symbols,
char *exclude, int exclude_size,
int *theme_source, int *theme_mode,
int *theme_id, int *theme_style);
int pass_save_master(const char *master, int require_biometric);
int pass_unlock_master(void);
int pass_clear_master(void);
int pass_can_unlock_master(void);
int pass_biometric_available(void);
int pass_master_saved(void);
char *pass_fingerprint_status(void);
int pass_take_unlocked_master(char *out);
#if defined(__cplusplus)
}
#endif
#endif
+5 -5
View File
@@ -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.6" date="2026-08-24"/><release version="0.2.5" date="2026-08-24"/><release version="0.2.4" date="2026-08-22"/><release version="0.2.3" date="2026-08-21"/><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>
+3 -3
View File
@@ -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
-30
View File
@@ -1,30 +0,0 @@
package gopass
import (
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
)
const derivationRounds = 100_000
func deriveKey(password, salt []byte) []byte {
blockInput := make([]byte, len(salt)+4)
copy(blockInput, salt)
binary.BigEndian.PutUint32(blockInput[len(salt):], 1)
mac := hmac.New(sha256.New, password)
_, _ = mac.Write(blockInput)
previous := mac.Sum(nil)
key := append([]byte(nil), previous...)
for round := 1; round < derivationRounds; round++ {
mac.Reset()
_, _ = mac.Write(previous)
previous = mac.Sum(previous[:0])
for i := range key {
key[i] ^= previous[i]
}
}
return key
}
+1 -1
View File
@@ -1,4 +1,4 @@
name "gopass"
name "pass"
generated "build/kryon/generated"
default_target "Run"
-79
View File
@@ -1,79 +0,0 @@
package gopass
import (
"crypto/hmac"
"crypto/sha256"
"math/big"
"strconv"
"strings"
)
// referenceGenerate is intentionally self-contained so the examples exercise
// the public generator against a second implementation of the specification.
func referenceGenerate(site, login, master string, options Options) string {
definitions := []struct {
on bool
set string
}{
{options.Lowercase, "abcdefghijklmnopqrstuvwxyz"},
{options.Uppercase, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{options.Digits, "0123456789"},
{options.Symbols, "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"},
}
classes := make([]string, 0, 4)
pool := ""
for _, definition := range definitions {
if !definition.on {
continue
}
filtered := ""
for _, character := range definition.set {
if !strings.ContainsRune(options.Exclude, character) {
filtered += string(character)
}
}
classes = append(classes, filtered)
pool += filtered
}
salt := []byte(site + login + strconv.FormatUint(options.Counter, 10))
message := append(append([]byte(nil), salt...), 0, 0, 0, 1)
mac := hmac.New(sha256.New, []byte(master))
_, _ = mac.Write(message)
last := mac.Sum(nil)
derived := append([]byte(nil), last...)
for iteration := 2; iteration <= 100_000; iteration++ {
mac.Reset()
_, _ = mac.Write(last)
last = mac.Sum(nil)
for i, value := range last {
derived[i] ^= value
}
}
value := new(big.Int).SetBytes(derived)
draw := func(size int) int {
base := big.NewInt(int64(size))
remainder := new(big.Int)
value.DivMod(value, base, remainder)
return int(remainder.Int64())
}
result := make([]byte, options.Length-len(classes))
for i := range result {
result[i] = pool[draw(len(pool))]
}
required := make([]byte, len(classes))
for i, class := range classes {
required[i] = class[draw(len(class))]
}
for _, character := range required {
at := draw(len(result) + 1)
next := make([]byte, 0, len(result)+1)
next = append(next, result[:at]...)
next = append(next, character)
next = append(next, result[at:]...)
result = next
}
return string(result)
}
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
root_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
apk="$root_dir/build/pass-android-debug.apk"
package_name="${PASS_ANDROID_PACKAGE:-xyz.waozi.pass}"
if [ ! -s "$apk" ]; then
echo "android smoke: missing APK artifact: $apk" >&2
exit 1
fi
if ! command -v adb >/dev/null 2>&1; then
echo "android smoke: skipped, adb is not installed" >&2
exit 0
fi
device="${PASS_ANDROID_DEVICE:-}"
if [ -z "$device" ]; then
device=$(adb devices | awk 'NR > 1 && $2 == "device" { print $1; exit }')
fi
if [ -z "$device" ]; then
echo "android smoke: skipped, no connected adb device" >&2
exit 0
fi
adb -s "$device" install -r "$apk" >/dev/null
adb -s "$device" shell monkey -p "$package_name" 1 >/dev/null
sleep 2
if ! adb -s "$device" shell pidof "$package_name" >/dev/null; then
echo "android smoke: $package_name did not stay running on $device" >&2
exit 1
fi
echo "android smoke: launched $package_name on $device"
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env bash
set -euo pipefail
root="${1:-.}"
cd "$root"
emit_error() {
local file="$1"
local message="$2"
if [ -n "${GITHUB_ACTIONS:-}" ]; then
printf '::error file=%s::%s\n' "$file" "$message" >&2
else
printf '%s: %s\n' "$file" "$message" >&2
fi
}
check_gitmodules_file() {
local file="$1"
local line key url
local status=0
local entries=()
[ -f "$file" ] || return 0
if ! mapfile -t entries < <(git config --file "$file" --get-regexp '^submodule\..*\.url$'); then
emit_error "$file" "has no submodule URL entries"
return 1
fi
for line in "${entries[@]}"; do
key="${line%% *}"
url="${line#* }"
case "$url" in
https://*) ;;
*)
emit_error "$file" "$key uses non-HTTPS submodule URL: $url"
status=1
;;
esac
done
printf 'checked %s\n' "$file"
return "$status"
}
queue=(".")
for ((i = 0; i < ${#queue[@]}; i++)); do
repo="${queue[$i]}"
modules_file="$repo/.gitmodules"
[ -f "$modules_file" ] || continue
check_gitmodules_file "$modules_file"
mapfile -t submodule_paths < <(
git -C "$repo" config --file .gitmodules --get-regexp '^submodule\..*\.path$' \
| sed 's/^[^ ]* //'
)
for path in "${submodule_paths[@]}"; do
if [ ! -d "$repo/$path" ]; then
emit_error "$modules_file" "submodule path is not checked out: $path"
exit 1
fi
queue+=("$repo/$path")
done
done
echo "all discovered submodule URLs use public HTTPS"
+56
View File
@@ -0,0 +1,56 @@
#!/bin/sh
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
kryon_dir=${KRYON_DIR:-"$root/vendor/kryon"}
arch=$(uname -m)
if [ "$arch" = "amd64" ]; then
arch=x86_64
fi
platform=$(uname -s | tr '[:upper:]' '[:lower:]')
build_dir="$kryon_dir/build/$platform-$arch"
k2c="$build_dir/bin/k2c"
work=${TMPDIR:-/tmp}/pass-kry-smoke.$$
kry_files=$(find "$root/app" -type f -name '*.kry' | LC_ALL=C sort)
cleanup()
{
rm -rf "$work"
}
trap cleanup EXIT INT TERM
make -C "$kryon_dir" k2c
mkdir -p "$work/c"
"$k2c" --no-main --root "$root" -o "$work/c" $kry_files
sh "$kryon_dir/tests/check_clean_generated_output.sh" "$work/c"
c_amalgam="$work/pass_kry_generated.c"
pass_c=
for file in $(find "$work/c" -type f -name '*.c' | LC_ALL=C sort); do
case "$file" in
*/app/pass.c)
pass_c=$file
;;
*)
printf '#include "%s"\n' "$file" >> "$c_amalgam"
;;
esac
done
if [ -n "$pass_c" ]; then
printf '#include "%s"\n' "$pass_c" >> "$c_amalgam"
fi
cc -fsyntax-only \
-D_DEFAULT_SOURCE \
-D_GNU_SOURCE \
-D_FILE_OFFSET_BITS=64 \
-I"$kryon_dir/include" \
-I"$kryon_dir/src" \
-I"$work/c" \
-I"$root/native" \
-I"$root/droid/app/src/main/cpp" \
"$c_amalgam"
echo "pass .kry to C smoke ok"
+6 -6
View File
@@ -2,20 +2,20 @@
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
version=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' "$root/version.go")
version=$(sed -n '1p' "$root/VERSION")
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"
+9 -9
View File
@@ -2,25 +2,25 @@
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
version=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' "$root/version.go")
version=$(sed -n '1p' "$root/VERSION")
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"
+84
View File
@@ -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
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env bash
set -euo pipefail
root_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
site_dir="$root_dir/build/site"
port="${PASS_WEB_SMOKE_PORT:-18080}"
url="http://127.0.0.1:$port/app/"
tmp_dir=$(mktemp -d)
server_pid=""
cleanup() {
if [ -n "$server_pid" ] && kill -0 "$server_pid" 2>/dev/null; then
kill "$server_pid" 2>/dev/null || true
wait "$server_pid" 2>/dev/null || true
fi
rm -rf "$tmp_dir"
}
trap cleanup EXIT
for file in "$site_dir/app/index.html" "$site_dir/app/app.js" "$site_dir/app/index.js" "$site_dir/app/index.wasm"; do
if [ ! -s "$file" ]; then
echo "missing web build artifact: $file" >&2
exit 1
fi
done
browser="${PASS_WEB_SMOKE_BROWSER:-}"
if [ -z "$browser" ]; then
for candidate in chromium chromium-browser google-chrome chrome; do
if command -v "$candidate" >/dev/null 2>&1; then
browser="$candidate"
break
fi
done
fi
if [ -z "$browser" ]; then
echo "web smoke: skipped, no Chromium-compatible browser found" >&2
exit 0
fi
(cd "$site_dir" && python3 -m http.server "$port" --bind 127.0.0.1 >"$tmp_dir/server.log" 2>&1) &
server_pid=$!
python3 - "$url" <<'PY'
import sys
import time
import urllib.request
url = sys.argv[1]
deadline = time.time() + 10
last_error = None
while time.time() < deadline:
try:
with urllib.request.urlopen(url, timeout=1) as response:
if response.status == 200:
sys.exit(0)
except Exception as exc:
last_error = exc
time.sleep(0.2)
raise SystemExit(f"web smoke: server did not answer {url}: {last_error}")
PY
screenshot="$tmp_dir/pass-web.png"
dom="$tmp_dir/dom.html"
"$browser" \
--headless=new \
--no-sandbox \
--disable-gpu \
--disable-dev-shm-usage \
--user-data-dir="$tmp_dir/chrome" \
--window-size=720,740 \
--virtual-time-budget=15000 \
--screenshot="$screenshot" \
--dump-dom \
"$url" >"$dom"
if [ ! -s "$screenshot" ]; then
echo "web smoke: browser did not write a screenshot" >&2
exit 1
fi
if ! grep -q '<canvas' "$dom"; then
echo "web smoke: app DOM did not include the canvas" >&2
exit 1
fi
python3 - "$screenshot" <<'PY'
import struct
import sys
import zlib
path = sys.argv[1]
with open(path, "rb") as handle:
data = handle.read()
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
raise SystemExit("web smoke: screenshot is not a PNG")
pos = 8
width = height = bit_depth = color_type = None
compressed = bytearray()
while pos < len(data):
size = struct.unpack(">I", data[pos:pos + 4])[0]
kind = data[pos + 4:pos + 8]
payload = data[pos + 8:pos + 8 + size]
pos += 12 + size
if kind == b"IHDR":
width, height, bit_depth, color_type = struct.unpack(">IIBB", payload[:10])[:4]
elif kind == b"IDAT":
compressed.extend(payload)
elif kind == b"IEND":
break
if width is None or height is None:
raise SystemExit("web smoke: PNG has no IHDR")
if bit_depth != 8 or color_type not in (2, 6):
raise SystemExit(f"web smoke: unsupported PNG format bit_depth={bit_depth} color_type={color_type}")
channels = 4 if color_type == 6 else 3
stride = width * channels
raw = zlib.decompress(compressed)
rows = []
offset = 0
previous = bytearray(stride)
for _ in range(height):
filter_type = raw[offset]
offset += 1
current = bytearray(raw[offset:offset + stride])
offset += stride
for index in range(stride):
left = current[index - channels] if index >= channels else 0
up = previous[index]
upper_left = previous[index - channels] if index >= channels else 0
if filter_type == 1:
current[index] = (current[index] + left) & 0xff
elif filter_type == 2:
current[index] = (current[index] + up) & 0xff
elif filter_type == 3:
current[index] = (current[index] + ((left + up) // 2)) & 0xff
elif filter_type == 4:
predictor = left + up - upper_left
pa = abs(predictor - left)
pb = abs(predictor - up)
pc = abs(predictor - upper_left)
current[index] = (current[index] + (left if pa <= pb and pa <= pc else up if pb <= pc else upper_left)) & 0xff
elif filter_type != 0:
raise SystemExit(f"web smoke: unsupported PNG filter {filter_type}")
rows.append(current)
previous = current
colors = set()
step_y = max(1, height // 80)
step_x = max(1, width // 80)
for y in range(0, height, step_y):
row = rows[y]
for x in range(0, width, step_x):
start = x * channels
colors.add(tuple(row[start:start + channels]))
if len(colors) >= 16:
print(f"web smoke: rendered {width}x{height} canvas screenshot with varied pixels")
raise SystemExit(0)
raise SystemExit(f"web smoke: screenshot looked blank, only {len(colors)} sampled colors")
PY
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

+16
View File
@@ -0,0 +1,16 @@
{
"schemaVersion": 1,
"slug": "pass",
"name": "Pass",
"summary": "Deterministic password generator with CLI, desktop, Android, and browser builds.",
"repository": {
"platform": "github",
"url": "https://github.com/waozixyz/pass",
"owner": "waozixyz",
"name": "pass"
},
"homepage": "https://pass.waozi.xyz",
"banner": "showcase/banner.png",
"tags": ["security", "passwords", "desktop", "mobile", "web"],
"featured": true
}
+57 -4
View File
@@ -12,12 +12,65 @@ if [ -z "$release_date" ]; then
exit 1
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
printf '%s\n' "$release_version" > VERSION
# 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 -Fx "$release_version" VERSION >/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
# Generate the Fastlane changelog for the Android versionCode being built.
# Fastlane file names are versionCode values, not changelog positions, and
# store listings cap changelogs at 500 characters.
changelog_dir=fastlane/metadata/android/en-US/changelogs
mkdir -p "$changelog_dir"
changelog=$(awk -v ver="$release_version" '
BEGIN { in_section = 0; buf = "" }
/^## \[/ {
if (in_section) exit
if (index($0, "[" ver "]") > 0) {
in_section = 1
next
}
}
in_section {
if ($0 == "") next
if (/^- /) {
if (buf != "") print buf
buf = $0
next
}
if (buf != "") {
line = $0
sub(/^[ \t]+/, "", line)
buf = buf " " line
}
}
END { if (buf != "") print buf }
' CHANGELOG.md)
if [ -z "$changelog" ]; then
echo "No changelog bullets found for $release_version in CHANGELOG.md" >&2
exit 1
fi
printf '%s\n' "$changelog" | head -c 500 > "$changelog_dir/$release_code.txt"
+42
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more