Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7967b90b99 | ||
|
|
d54c5c5b19 | ||
|
|
4ecabd56d2 | ||
|
|
68f9187776 | ||
|
|
6ff30ee6b1 | ||
|
|
7ec153aa5c | ||
|
|
f61c65b440 | ||
|
|
808c692026 | ||
|
|
025c2a5ca8 | ||
|
|
247d7d63ee | ||
|
|
ee6609dad0 | ||
|
|
32f1ad00ba | ||
|
|
3007696783 | ||
|
|
4fcd59890b | ||
|
|
eecbb33f18 | ||
|
|
41587d7f0f | ||
|
|
72fc32b970 | ||
|
|
c6e7977396 | ||
|
|
7a5c147d64 | ||
|
|
eceaa0380b | ||
|
|
9493b9e01d | ||
|
|
74d19b7cf8 | ||
|
|
d092192325 | ||
|
|
b9d1e1bd35 | ||
|
|
1818096275 | ||
|
|
78fe91d184 | ||
|
|
eed4c75706 | ||
|
|
d4c0f367f9 | ||
|
|
fdeea88672 | ||
|
|
cfa0b5c904 | ||
|
|
3e38257654 | ||
|
|
2bcccf0b12 |
No files matched your search
@@ -8,9 +8,3 @@ libfontconfig1-dev
|
||||
libpango1.0-dev
|
||||
xvfb
|
||||
xauth
|
||||
libgtk-3-dev
|
||||
python3-pil
|
||||
tesseract-ocr
|
||||
imagemagick
|
||||
gnumeric
|
||||
zenity
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
- name: Install CLI test dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y openssl xclip xvfb xauth tesseract-ocr imagemagick
|
||||
sudo apt-get install -y openssl xclip xvfb xauth
|
||||
- name: Install Emscripten
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -175,17 +175,6 @@ jobs:
|
||||
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: Install screenshot OCR
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y tesseract-ocr
|
||||
# Without /dev/kvm access the emulator runs unaccelerated and is too
|
||||
# slow to answer input before Android reports it not responding.
|
||||
- name: Enable KVM for the emulator
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger --name-match=kvm
|
||||
- name: Run Android input tests
|
||||
uses: reactivecircus/android-emulator-runner@v2
|
||||
with:
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
name: Google Play testing bundle
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
bundle:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
- name: Install build tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential cmake pkg-config libssl-dev
|
||||
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 preserved release key
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
test -n "$KEYSTORE_BASE64"
|
||||
umask 077
|
||||
mkdir -p "$HOME/.android"
|
||||
printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$HOME/.android/pass-release.keystore"
|
||||
- name: Build signed testing candidate
|
||||
env:
|
||||
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
|
||||
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
|
||||
run: |
|
||||
test -n "$KEYSTORE_PASSWORD"
|
||||
test -n "$KEY_ALIAS"
|
||||
make android-bundle
|
||||
- name: Validate the candidate
|
||||
run: |
|
||||
curl --fail --show-error --location --retry 3 \
|
||||
https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar \
|
||||
--output "$RUNNER_TEMP/bundletool.jar"
|
||||
python3 scripts/android-bundle-check.py "build/werk-$(cat VERSION).aab" \
|
||||
--bundletool "$RUNNER_TEMP/bundletool.jar" --version "$(cat VERSION)"
|
||||
- name: Remove temporary release key
|
||||
if: always()
|
||||
run: rm -f "$HOME/.android/pass-release.keystore"
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: werkzeug-play-testing
|
||||
path: build/*.aab
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -202,11 +202,14 @@ jobs:
|
||||
cd build/site
|
||||
zip -qr ../werk-web.zip .
|
||||
|
||||
# The whole app folder: its page loads content-hashed script and
|
||||
# Wasm names, and the service worker caches the files in assets.json.
|
||||
mkdir -p ../werk-html5
|
||||
cp -R app/. ../werk-html5/
|
||||
cp -R icons/. ../werk-html5/icons/
|
||||
cp app/index.html ../werk-html5/
|
||||
cp app/index.js ../werk-html5/
|
||||
cp app/index.wasm ../werk-html5/
|
||||
cp app/sw.js ../werk-html5/
|
||||
cp app/emoji-OFL.txt ../werk-html5/
|
||||
cp manifest.webmanifest ../werk-html5/
|
||||
cp -R icons ../werk-html5/icons
|
||||
sed -i \
|
||||
-e 's#href="/manifest.webmanifest"#href="manifest.webmanifest"#g' \
|
||||
-e 's#href="/icons/#href="icons/#g' \
|
||||
|
||||
@@ -48,10 +48,6 @@ jobs:
|
||||
test -s build/site/index.html
|
||||
test -s build/site/app/index.html
|
||||
test -s build/site/app/index.wasm
|
||||
- name: Install screenshot OCR
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y tesseract-ocr imagemagick
|
||||
- name: Verify browser input, storage, cache upgrades, and offline launch
|
||||
env:
|
||||
WERK_WEB_BROWSER: google-chrome
|
||||
|
||||
@@ -1,36 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## [0.4.2] - 2026-10-23
|
||||
|
||||
- Linux packages include the libraries needed for sync and importing QR-code pictures.
|
||||
- Packaging a new AppImage preserves previous downloads.
|
||||
|
||||
## [0.4.1] - 2026-10-23
|
||||
|
||||
- Open Pass, Auth, Calculator, Clock and Workbook directly from the Linux application menu, each with its own icon.
|
||||
- Desktop installs add shortcuts for Werkzeug and every tool to your configured desktop folder.
|
||||
- Tool windows show their own names and icons in the desktop switcher.
|
||||
|
||||
## [0.4.0] - 2026-10-19
|
||||
|
||||
- A new purple W logo across the app, Android and the website.
|
||||
- Calculator gets a Scientific mode.
|
||||
- Auth imports Google Authenticator, Aegis and Ente Auth exports, and on the desktop a picture of their QR code.
|
||||
- Rename an Auth account, note the websites it signs in to, or remove it.
|
||||
- Choose your own Daochi node, and pause sync without losing your account.
|
||||
- On the desktop, Profile manages your account: create it, import or back up its key, and link devices by QR code.
|
||||
- Sign in with a Daochi account key you already have, such as Inbe's.
|
||||
- `werk sync` and `werk auth` work without a window on Linux.
|
||||
- Reach every tool from the web app's mini version.
|
||||
- Fix the web version freezing when Clock opens.
|
||||
- Show π, √ and other symbols on phones older than Android 10.
|
||||
- Fix Profile breaking after choosing a file on desktops whose language writes decimals with a comma.
|
||||
- The `pass` command unlocks vaults whose text is wrapped with spaces or tabs on systems with OpenSSL 3.0.
|
||||
|
||||
## [0.3.1] - 2026-10-13
|
||||
|
||||
- Fix the web version on itch.io, which opened to a blank page.
|
||||
|
||||
## [0.3.0] - 2026-10-13
|
||||
|
||||
- Pass is now Werkzeug: a home screen of small private tools, each its own app and all preinstalled.
|
||||
|
||||
@@ -11,29 +11,22 @@ MINGCUTE_DIR = $(shell $(ZIRAN) pkg path mingcute $(LOCK_FLAGS))
|
||||
# BLAKE2b and XChaCha20-Poly1305 from Monocypher.
|
||||
LIBOQS_DIR = $(shell $(ZIRAN) pkg path liboqs $(LOCK_FLAGS))
|
||||
MONOCYPHER_DIR = $(shell $(ZIRAN) pkg path monocypher $(LOCK_FLAGS))
|
||||
QRCODE_DIR = $(shell $(ZIRAN) pkg path qrcode $(LOCK_FLAGS))
|
||||
WORKBOOK_DIR = $(shell $(ZIRAN) pkg path workbook $(LOCK_FLAGS))
|
||||
ENTITY_DIR = $(shell $(ZIRAN) pkg path entity $(LOCK_FLAGS))
|
||||
APPS_DIR = $(shell $(ZIRAN) pkg path apps $(LOCK_FLAGS))
|
||||
LIBOQS_FLAGS := -DCMAKE_BUILD_TYPE=MinSizeRel -DBUILD_SHARED_LIBS=OFF -DOQS_BUILD_ONLY_LIB=ON \
|
||||
-DOQS_USE_OPENSSL=OFF -DOQS_DIST_BUILD=OFF -DOQS_OPT_TARGET=generic -DOQS_MINIMAL_BUILD=SIG_ml_dsa_44
|
||||
MONOCYPHER_SOURCES = $(MONOCYPHER_DIR)/src/monocypher.c $(MONOCYPHER_DIR)/src/optional/monocypher-ed25519.c
|
||||
CC ?= cc
|
||||
BIN_DIR ?= $(HOME)/bin
|
||||
DATA_DIR ?= $(if $(XDG_DATA_HOME),$(XDG_DATA_HOME),$(HOME)/.local/share)
|
||||
DESKTOP_DIR ?= $(shell xdg-user-dir DESKTOP 2>/dev/null)
|
||||
# The tool bundles and Werkzeug's other files.
|
||||
LIB_DIR ?= $(HOME)/.local/lib/werk
|
||||
WEB_CC ?= $(if $(wildcard $(HOME)/emsdk/upstream/emscripten/emcc),$(HOME)/emsdk/upstream/emscripten/emcc,emcc)
|
||||
SOURCES := $(wildcard src/*.zi shared/*.zi apps/*/*.zi)
|
||||
LIBRARY_SOURCES = $(wildcard $(KRYON_DIR)/src/ui/*.zi $(KRYON_DIR)/src/ui/*/module.zi $(KRYON_DIR)/src/kss/*.zi $(KRYON_DIR)/src/backend/*.zi $(KRYON_DIR)/src/backend/*/module.zi $(ZIRAN_ROOT)/std/*.zi)
|
||||
ZIRAN_RUNTIME_SOURCES = $(wildcard $(ZIRAN_ROOT)/cmd/zir/*.[ch] $(ZIRAN_ROOT)/include/*.h)
|
||||
ENTITY_SOURCES = $(wildcard $(ENTITY_DIR)/src/*.zi $(ENTITY_DIR)/assets/entity/*)
|
||||
CFLAGS := -std=c99 -O2 -Wno-unused-variable -I$(ZIRAN_ROOT)/include
|
||||
PROJECT := --project $(LOCK_FLAGS)
|
||||
ANDROID_ABIS ?= armeabi-v7a,arm64-v8a
|
||||
|
||||
.PHONY: all apps portable-apps cli gui native run test source-check core-test ziran-core-test cli-test pass-state-test app-logic-test lesspass-compat-test entity-account-test gui-smoke gui-test web web-canvas site web-smoke android-debug android-emulator android-release android-smoke android-input-test e2e check-package-urls install install-cli install-gui uninstall-cli uninstall-gui package-deb package-appimage plan9-c
|
||||
.PHONY: all apps cli gui native run test source-check core-test ziran-core-test cli-test pass-state-test app-logic-test lesspass-compat-test gui-smoke gui-test web web-canvas site web-smoke android-debug android-emulator android-release android-smoke android-input-test e2e check-package-urls install install-cli install-gui uninstall-cli uninstall-gui package-deb package-appimage plan9-c
|
||||
all: cli gui
|
||||
native: all
|
||||
|
||||
@@ -47,48 +40,26 @@ build/pass: build/generated/cli/.complete
|
||||
cli: build/pass
|
||||
cp build/pass pass
|
||||
|
||||
# Each app is its own bundle; Werkzeug runs them in one window. Workbook runs
|
||||
# only in the Linux desktop app, so the web and Android apps leave it out.
|
||||
# Each app is its own bundle; Werkzeug runs them in one window.
|
||||
APPS := pass auth calculator clock
|
||||
PORTABLE_BUNDLES := $(APPS:%=build/apps/%.zib) build/apps/entity.zib build/apps/apps.zib
|
||||
APP_BUNDLES := $(PORTABLE_BUNDLES) build/apps/workbook.zib
|
||||
APP_BUNDLES := $(APPS:%=build/apps/%.zib)
|
||||
SHARED_SOURCES := $(wildcard shared/*.zi)
|
||||
APPS_UI_SOURCES = $(wildcard $(APPS_DIR)/src/*.zi $(APPS_DIR)/ui/*.zi $(APPS_DIR)/ui/locales/*.json)
|
||||
APP_MODULE_PATHS = --module-path shared --module-path kryon=$(KRYON_DIR)/src/backend --module-path kryon=$(KRYON_DIR)/src/ui --module-path $(KRYON_DIR)/src/ui --module-path $(MINGCUTE_DIR)/src --module-path $(ZIRAN_ROOT)/std
|
||||
APP_MODULE_PATHS = --module-path shared --module-path $(KRYON_DIR)/src/ui --module-path $(MINGCUTE_DIR)/src --module-path $(ZIRAN_ROOT)/std
|
||||
apps: $(APP_BUNDLES)
|
||||
portable-apps: $(PORTABLE_BUNDLES)
|
||||
# Compile the shared screen with the host's compiler and UI library. The
|
||||
# reviewed payload must match both the build pin and the native host pin.
|
||||
build/apps/apps.zib: $(APPS_UI_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock apps-controller.sha256 Makefile scripts/ziran.sh
|
||||
mkdir -p $(@D)
|
||||
python3 '$(APPS_DIR)/scripts/generate-ui-locales.py' --check
|
||||
$(ZIRAN) bundle --root $(APPS_DIR)/ui --module-path $(APPS_DIR)/src $(APP_MODULE_PATHS) \
|
||||
--define KRYON_HOSTED_UI --entry apps:Main -o $@ $(APPS_DIR)/ui/apps.zi
|
||||
sha256sum $@ | cut -d ' ' -f 1 > $(@D)/apps.sha256
|
||||
test "$$(cat $(@D)/apps.sha256)" = "$$(cat apps-controller.sha256)"
|
||||
.SECONDEXPANSION:
|
||||
build/apps/%.zib: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(SHARED_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
|
||||
build/apps/%.zib: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(SHARED_SOURCES) ziran.lock
|
||||
mkdir -p $(@D)
|
||||
$(ZIRAN) bundle --root . --module-path apps/$* $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI --define WERK_APP \
|
||||
$(if $(wildcard apps/$*/assets),--asset-dir assets=apps/$*/assets) --entry $*:Main -o $@ apps/$*/$*.zi
|
||||
|
||||
build/apps/workbook.zib: $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(WORKBOOK_DIR)/Makefile ziran.lock
|
||||
$(MAKE) -C $(WORKBOOK_DIR) ZIRAN=$(ZIRAN_ROOT)/build/bin/ziran bundle
|
||||
install -m 0600 $(WORKBOOK_DIR)/build/workbook.zib $@
|
||||
|
||||
build/apps/entity.zib: $(ENTITY_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
|
||||
mkdir -p $(@D)
|
||||
$(ZIRAN) bundle --root $(ENTITY_DIR) --module-path $(ENTITY_DIR)/src $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI \
|
||||
--module-path qrcode=$(QRCODE_DIR)/src --asset-dir assets=$(ENTITY_DIR)/assets --entry entity:Main -o $@ $(ENTITY_DIR)/src/entity.zi
|
||||
|
||||
# The portable bundle runtime the host links, built from the locked Ziran.
|
||||
build/ziran/libziran.a: ziran.lock $(ZIRAN_RUNTIME_SOURCES)
|
||||
build/ziran/libziran.a: ziran.lock
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY $(MAKE) -C $(ZIRAN_ROOT) BUILD_DIR=$(abspath build/ziran) $(abspath $@)
|
||||
|
||||
build/generated/desktop/.complete: $(wildcard src/*.zi) $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(SHARED_SOURCES) $(LIBRARY_SOURCES) $(ENTITY_SOURCES) ziran.toml ziran.lock
|
||||
build/generated/desktop/.complete: $(wildcard src/*.zi) $(SHARED_SOURCES) $(LIBRARY_SOURCES) ziran.toml ziran.lock
|
||||
rm -rf $(@D)
|
||||
mkdir -p $(@D)
|
||||
$(ZIRAN) build $(PROJECT) --define PLATFORM_DESKTOP --target=c --entry desktop:main -o $(@D) src/desktop.zi
|
||||
$(ZIRAN) build $(PROJECT) --target=c --entry desktop:main -o $(@D) src/desktop.zi
|
||||
touch $@
|
||||
build/liboqs/lib/liboqs.a: ziran.lock
|
||||
cmake -S $(LIBOQS_DIR) -B build/liboqs $(LIBOQS_FLAGS) > /dev/null
|
||||
@@ -96,8 +67,7 @@ build/liboqs/lib/liboqs.a: ziran.lock
|
||||
build/werk: build/generated/desktop/.complete build/ziran/libziran.a build/liboqs/lib/liboqs.a Makefile
|
||||
$(CC) $(CFLAGS) -Ibuild/generated/desktop -I$(MONOCYPHER_DIR)/src -I$(MONOCYPHER_DIR)/src/optional \
|
||||
build/generated/desktop/*.c $(MONOCYPHER_SOURCES) build/ziran/libziran.a build/liboqs/lib/liboqs.a \
|
||||
$(shell pkg-config --libs sdl2 cairo freetype2 fontconfig pangocairo gtk+-3.0) -lX11 -l:libcurl.so.4 -lm -lpthread -o $@.new
|
||||
mv -f $@.new $@
|
||||
$(shell pkg-config --libs sdl2 cairo freetype2 fontconfig pangocairo) -l:libcurl.so.4 -lm -lpthread -o $@
|
||||
build/pfp.png: $(KRYON_DIR)/icons/pfp.png
|
||||
cp $< $@
|
||||
gui: build/werk build/pfp.png apps
|
||||
@@ -117,18 +87,12 @@ cli-test: cli
|
||||
sh scripts/cli_test.sh ./pass
|
||||
lesspass-compat-test: cli
|
||||
python3 scripts/lesspass_compat_test.py --cli ./pass
|
||||
entity-account-test: build/liboqs/lib/liboqs.a
|
||||
ZIRAN_BIN=$(ZIRAN) python3 scripts/entity_account_test.py
|
||||
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test entity-account-test
|
||||
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test
|
||||
gui-smoke: gui
|
||||
sh scripts/gui_smoke.sh
|
||||
gui-test: gui
|
||||
python3 scripts/private-display.py python3 scripts/apps_gui_test.py
|
||||
sh scripts/werk_gui_test.sh
|
||||
python3 scripts/private-display.py python3 scripts/workbook_gui_test.py
|
||||
python3 scripts/private-display.py python3 scripts/launcher_gui_test.py
|
||||
sh scripts/migration_test.sh
|
||||
python3 -I scripts/auth_command_test.py
|
||||
|
||||
# The bundle runtime for the browser, built from the locked Ziran.
|
||||
WEB_AR ?= $(dir $(WEB_CC))emar
|
||||
@@ -140,14 +104,14 @@ build/generated/browser/.complete: $(wildcard src/*.zi) $(SHARED_SOURCES) $(LIBR
|
||||
mkdir -p $(@D)
|
||||
$(ZIRAN) build $(PROJECT) --define PLATFORM_WEB --target=c -o $(@D) src/browser.zi
|
||||
touch $@
|
||||
build/web-app/index.js: build/generated/browser/.complete build/web-runtime/libziran.a $(PORTABLE_BUNDLES) build/pfp.png assets/app/icon.png assets/fonts/NotoSans-Regular.ttf
|
||||
build/web-app/index.js: build/generated/browser/.complete build/web-runtime/libziran.a $(APP_BUNDLES) build/pfp.png assets/app/icon.png assets/fonts/NotoSans-Regular.ttf
|
||||
mkdir -p $(@D)
|
||||
$(WEB_CC) -O2 -Wno-parentheses-equality -I$(ZIRAN_ROOT)/include -iquote build/generated/browser build/generated/browser/*.c \
|
||||
build/web-runtime/libziran.a \
|
||||
--js-library $(ZIRAN_ROOT)/web/ziran_web.js -sEXPORTED_RUNTIME_METHODS=FS,IDBFS -lidbfs.js \
|
||||
-sASYNCIFY -sALLOW_MEMORY_GROWTH=1 -sSTACK_SIZE=16777216 -sASYNCIFY_STACK_SIZE=1048576 -sENVIRONMENT=web \
|
||||
--embed-file assets/fonts/NotoSans-Regular.ttf@/kryon-font.ttf \
|
||||
$(foreach bundle,$(PORTABLE_BUNDLES),--embed-file $(bundle)@/apps/$(notdir $(bundle))) --embed-file build/pfp.png@/pfp.png --embed-file assets/app/icon.png@/icon.png -o $@
|
||||
--embed-file build/apps@/apps --embed-file build/pfp.png@/pfp.png --embed-file assets/app/icon.png@/icon.png -o $@
|
||||
build/web-app/index.html: build/web-app/index.js web/site/app/index.html
|
||||
cp web/site/app/index.html $@
|
||||
build/generated/worker/.complete: src/service_worker.zi ziran.toml ziran.lock
|
||||
@@ -166,31 +130,20 @@ web-smoke: site
|
||||
bash scripts/web_smoke.sh
|
||||
|
||||
# CMake emits JNI and foreign ABI types separately for each Android ABI.
|
||||
android-debug: portable-apps
|
||||
android-debug: apps
|
||||
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
|
||||
mkdir -p build
|
||||
cp droid/app/build/outputs/apk/debug/app-universal-debug.apk build/werk-android-debug.apk
|
||||
python3 scripts/android_apk_check.py build/werk-android-debug.apk
|
||||
cp droid/app/build/outputs/apk/debug/app-arm64-v8a-debug.apk build/werk-android-arm64-v8a-debug.apk
|
||||
cp droid/app/build/outputs/apk/debug/app-armeabi-v7a-debug.apk build/werk-android-armeabi-v7a-debug.apk
|
||||
android-emulator: portable-apps
|
||||
android-emulator: apps
|
||||
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=x86_64 $(GRADLE_ARGS)
|
||||
mkdir -p build
|
||||
cp droid/app/build/outputs/apk/debug/app-debug.apk build/werk-android-emulator.apk
|
||||
python3 scripts/android_apk_check.py build/werk-android-emulator.apk
|
||||
android-release: portable-apps
|
||||
android-release: apps
|
||||
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleRelease -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
|
||||
.PHONY: android-bundle
|
||||
android-bundle: portable-apps
|
||||
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew bundleRelease -Pabi=$(ANDROID_ABIS) $(GRADLE_ARGS)
|
||||
cp droid/app/build/outputs/bundle/release/app-release.aab build/werk-$(shell cat VERSION).aab
|
||||
.PHONY: android-fdroid
|
||||
# F-Droid owns signing and updates. Keep the same package/version as the
|
||||
# reference release; the suffix belongs to the unsigned output filename.
|
||||
android-fdroid:
|
||||
$(MAKE) android-release GRADLE_ARGS="$(GRADLE_ARGS) -PfDroidBuild=true"
|
||||
cp droid/app/build/outputs/apk/release/app-universal-release-unsigned.apk build/werk-$(shell cat VERSION)-fdroid-unsigned.apk
|
||||
python3 scripts/android_apk_check.py build/werk-$(shell cat VERSION)-fdroid-unsigned.apk
|
||||
android-smoke:
|
||||
bash scripts/android_smoke.sh
|
||||
android-input-test:
|
||||
@@ -210,22 +163,16 @@ install-cli: cli
|
||||
mkdir -p $(BIN_DIR)
|
||||
install -m 0755 pass $(BIN_DIR)/pass
|
||||
install-gui: gui
|
||||
mkdir -p "$(BIN_DIR)" "$(DATA_DIR)/applications" "$(DATA_DIR)/icons/hicolor/512x512/apps" "$(DATA_DIR)/mime/packages"
|
||||
install -d -m 0700 "$(LIB_DIR)" "$(LIB_DIR)/apps"
|
||||
install -m 0755 build/werk "$(BIN_DIR)/werk.new"
|
||||
mv -f "$(BIN_DIR)/werk.new" "$(BIN_DIR)/werk"
|
||||
install -m 0600 $(APP_BUNDLES) "$(LIB_DIR)/apps/"
|
||||
install -m 0644 build/pfp.png "$(LIB_DIR)/pfp.png"
|
||||
python3 scripts/install-launchers.py --data-dir "$(DATA_DIR)" --bin-dir "$(BIN_DIR)" $(if $(filter-out $(HOME),$(DESKTOP_DIR)),--desktop-dir "$(DESKTOP_DIR)")
|
||||
install -m 0644 packaging/linux/werk-bundle.xml "$(DATA_DIR)/mime/packages/werk-bundle.xml"
|
||||
@if command -v update-mime-database >/dev/null; then update-mime-database "$(DATA_DIR)/mime"; fi
|
||||
@if command -v update-desktop-database >/dev/null; then update-desktop-database "$(DATA_DIR)/applications"; fi
|
||||
@if command -v gtk-update-icon-cache >/dev/null; then gtk-update-icon-cache -f -t "$(DATA_DIR)/icons/hicolor"; fi
|
||||
mkdir -p $(BIN_DIR) $(LIB_DIR)/apps $(DATA_DIR)/applications $(DATA_DIR)/icons/hicolor/512x512/apps
|
||||
install -m 0755 build/werk $(BIN_DIR)/werk
|
||||
install -m 0644 $(APP_BUNDLES) $(LIB_DIR)/apps/
|
||||
install -m 0644 build/pfp.png $(LIB_DIR)/pfp.png
|
||||
cp packaging/linux/xyz.waozi.werk.desktop $(DATA_DIR)/applications/xyz.waozi.werk.desktop
|
||||
cp assets/app/icon.png $(DATA_DIR)/icons/hicolor/512x512/apps/werk.png
|
||||
uninstall-cli:
|
||||
rm -f $(BIN_DIR)/pass
|
||||
uninstall-gui:
|
||||
python3 scripts/install-launchers.py --data-dir "$(DATA_DIR)" $(if $(filter-out $(HOME),$(DESKTOP_DIR)),--desktop-dir "$(DESKTOP_DIR)") --uninstall
|
||||
rm -f $(BIN_DIR)/werk
|
||||
rm -f $(BIN_DIR)/werk $(DATA_DIR)/applications/xyz.waozi.werk.desktop $(DATA_DIR)/icons/hicolor/512x512/apps/werk.png
|
||||
rm -rf $(LIB_DIR)
|
||||
package-deb: gui
|
||||
./scripts/package-deb.sh
|
||||
|
||||
@@ -15,37 +15,26 @@ Small private tools in one app. The home screen opens each one:
|
||||
affiliation with the LessPass project.
|
||||
- **Auth**: two-factor sign-in codes (TOTP, RFC 6238, with SHA-1, SHA-256 or
|
||||
SHA-512 and 6 to 8 digits). Add accounts by pasting `otpauth://` links, one
|
||||
or many such as Ente Auth's plain-text export, a Google Authenticator
|
||||
export link or an unencrypted Aegis export, or by entering the secret key.
|
||||
On the desktop, Import file reads an export or a picture of its QR code
|
||||
(it uses zenity, and GdkPixbuf and ZBar for pictures).
|
||||
Tap a code to copy it; it is cleared from the clipboard after 30 seconds.
|
||||
Edit renames an account, notes the websites where it signs in, such as
|
||||
`github.com`, or removes it.
|
||||
or many such as an authenticator's plain-text export, or by entering the
|
||||
secret key. Tap a code to copy it; it is cleared from the clipboard after
|
||||
30 seconds.
|
||||
- **Calculator**: arithmetic with brackets, powers and percent, by keypad or
|
||||
keyboard, and a Scientific mode with trigonometry, logarithms, roots and
|
||||
factorials.
|
||||
keyboard.
|
||||
- **Clock**: the local time and date, and a stopwatch that keeps running
|
||||
while the app is closed.
|
||||
|
||||
- **Workbook** (Linux): a spreadsheet editor with bottom sheet tabs and File/Edit menus. Its own `workbook.zib` bundle runs inside Werkzeug. File → Download Workbook.zib saves a copy you can share or open with `werk --bundle FILE.zib`.
|
||||
|
||||
The profile holds your name, a picture and the appearance every tool shares:
|
||||
system, light or dark, an accent color and Material or Classic widgets.
|
||||
|
||||
Werkzeug is a harness for practical tools. Each built-in tool uses the shared
|
||||
Kryon app interface, so another compatible harness can run its bundle too.
|
||||
On the desktop, `werk --bundle /path/to/diary.zib` opens Inner Breeze's Diary
|
||||
through that interface, with its own private documents and optional photo
|
||||
picker. It needs no `inbe.zib`. These local Diary documents do not yet join
|
||||
Werkzeug's account sync. External bundles cannot replace a built-in tool or
|
||||
receive Pass's device secret or Auth's records.
|
||||
Werkzeug was previously Pass. On its first start it moves Pass's saved
|
||||
profiles, settings and theme into the new layout; the Android app keeps
|
||||
Pass's package, so it updates in place and keeps a saved master password.
|
||||
|
||||
## Privacy
|
||||
|
||||
Everything is computed on the device. Werkzeug makes no network requests
|
||||
unless you set up sync or explicitly request an account or device-link action.
|
||||
Each tool keeps its own files, readable only by your user:
|
||||
unless you turn on sync. Each tool keeps its own files, readable only by your
|
||||
user:
|
||||
|
||||
| Platform | Data |
|
||||
|---|---|
|
||||
@@ -59,77 +48,27 @@ Android app sandbox.
|
||||
|
||||
## Sync
|
||||
|
||||
Profile uses the shared Self bundle. Desktop Account management shows the
|
||||
public ID, alias, sync status and queued changes, and provides account creation,
|
||||
key-file import, backups, device linking and logout. Switching accounts asks
|
||||
whether to keep and merge local Auth records or replace them. A private rollback
|
||||
journal preserves the previous key and records if a switch is interrupted.
|
||||
|
||||
The account can use a [Daochi](https://github.com/kryonlabs/daochi) node,
|
||||
`api.waozi.xyz` by default. Tools work locally without an account. Saved nodes
|
||||
and the preferred node live in Profile → Nodes; choosing a node preserves the
|
||||
account and its paused state. The sync switch pauses automatic synchronization
|
||||
and stays paused after restarting. Logout keeps local Auth records.
|
||||
|
||||
Desktop key backups retain Werkzeug's Auth vault key as protected recovery
|
||||
context. Use a passphrase to encrypt the backup. Importing a legacy account key
|
||||
for the already-connected identity preserves its existing vault key. The shared
|
||||
QR workflow also preserves that context and asks both devices to compare digits
|
||||
before connecting. Legacy clients cannot read the extended QR payload when
|
||||
Werkzeug vault context is included.
|
||||
|
||||
Desktop Self and participating native apps share public profile preferences only
|
||||
for the same verified account ID. Account keys and Auth records stay in the
|
||||
host's private store. Android retains its existing native Account screen and
|
||||
legacy device-link flow; browser account sync is unavailable.
|
||||
|
||||
The embedded web app (`/app/?mini`) opens on Home with every tool, and also
|
||||
provides Profile. Use `?mini&app=pass`, `auth`, `calculator` or `clock` to
|
||||
open a particular tool first. Browser sync is currently unavailable.
|
||||
Profile → Sync keeps Auth's accounts on all your devices through a
|
||||
[Daochi](https://github.com/kryonlabs/daochi) account, `api.waozi.xyz` by
|
||||
default. Sync is off until you create or connect an account.
|
||||
|
||||
- Each record is sealed on the device with XChaCha20-Poly1305 under a random
|
||||
vault key that is never sent to the node unencrypted. The seal covers the
|
||||
vault key that never leaves your devices unencrypted. The seal covers the
|
||||
account, the record and the time of the change, so the server can neither
|
||||
read nor alter a record or a removal.
|
||||
- The account key (ML-DSA-44) signs in and signs each sync together with
|
||||
the device's own Ed25519 key.
|
||||
- Desktop device linking uses the shared Self QR/code exchange with X25519
|
||||
and encrypted key transfer. Confirm the matching number on both devices.
|
||||
Android's existing 12-character connection code remains available in its
|
||||
native account screen.
|
||||
- To connect another device, open Profile → Sync → Connect a device and enter
|
||||
the 12-character code on the other device. The devices swap X25519 keys
|
||||
through the server's link mailbox, and the account and vault keys travel
|
||||
sealed with a key derived from that exchange and the code, so the server
|
||||
cannot open or replace them. The code works for 10 minutes.
|
||||
- The server can still withhold changes or serve an older copy to a device
|
||||
that has not seen a newer one. A lost device keeps the keys it had: stop
|
||||
syncing there if you can, and replace two-factor secrets you care about.
|
||||
|
||||
`scripts/sync_e2e_test.sh` runs two devices against a local Daochi node.
|
||||
|
||||
## The `werk sync` and `werk auth` commands
|
||||
|
||||
On Linux, the same data works without a window, for devices without a
|
||||
screen and for scripts:
|
||||
|
||||
```text
|
||||
werk sync status | create | show | join [CODE] | key [FILE] | now
|
||||
werk auth list
|
||||
werk auth code ID
|
||||
werk auth import [FILE]
|
||||
werk auth rename ID SERVICE ACCOUNT
|
||||
werk auth sites ID [WEBSITE ...]
|
||||
werk auth remove ID
|
||||
```
|
||||
|
||||
`werk sync show` prints a code for another device to enter; `werk sync join`
|
||||
reads one from its argument or standard input. `werk sync key` signs in with
|
||||
an account key from FILE or standard input; for a key with a passphrase, give
|
||||
FILE and the passphrase on standard input. `werk auth list` prints the
|
||||
accounts as JSON with their ids and websites, never their secrets.
|
||||
`werk auth code ID` prints the current code and the seconds it stays valid.
|
||||
`werk auth import` reads a file, or standard input: otpauth links, Google
|
||||
Authenticator export links, an unencrypted Aegis export, or a PNG or JPEG of
|
||||
an export's QR code when GdkPixbuf and ZBar (`libzbar0`) are installed.
|
||||
Changes sync right away when the device has an account. `werk --app auth`
|
||||
opens the window on one tool, as Harmony's Auth entry does.
|
||||
|
||||
## Tools are separate apps
|
||||
|
||||
Each tool lives in `apps/<tool>/` and is built into its own portable bundle,
|
||||
@@ -142,44 +81,22 @@ other.
|
||||
## Build and test
|
||||
|
||||
Dependencies and the compiler are pinned in `ziran.lock`. Desktop builds need
|
||||
SDL2, Cairo, FreeType, Fontconfig, Pango, GTK 3 and X11 development packages.
|
||||
Workbook uses the installed Gnumeric library; file choosers need Zenity. Browser
|
||||
SDL2, Cairo, FreeType, Fontconfig and Pango development packages; browser
|
||||
builds need Emscripten; Android builds need JDK 21 and the SDK/NDK versions in
|
||||
`droid/app/build.gradle`. Desktop tests use Xvfb, xdotool, xclip and
|
||||
ImageMagick on private displays.
|
||||
|
||||
```sh
|
||||
make gui # build/werk and the app bundles in build/apps
|
||||
make install-gui # Werkzeug and each tool in the app menu and on the desktop
|
||||
make test # Pass/CLI, Auth, Calculator and private account recovery fixtures
|
||||
make test # Pass core and CLI, Pass state, Auth codes, Calculator
|
||||
make gui-smoke # light and dark home screens on a private Xvfb display
|
||||
make gui-test # every tool, clipboard and profile on a private display,
|
||||
# and werk auth without one
|
||||
make gui-test # every tool, clipboard and profile on a private display
|
||||
make site # build/site: browser app and offline worker
|
||||
make web-smoke # private headless Chromium
|
||||
make android-debug # ARM32, ARM64 and universal APKs
|
||||
make android-fdroid # unsigned F-Droid candidate, same Android ID and version
|
||||
make android-emulator # the x86_64 APK for a private emulator
|
||||
```
|
||||
|
||||
Linux installs include separate Pass, Auth, Calculator, Clock and Workbook
|
||||
launchers, each with its own icon. They open the selected tool directly and
|
||||
share Werkzeug's existing private data. `make install-gui` also adds shortcuts
|
||||
to the desktop folder configured by `xdg-user-dir`; set `DESKTOP_DIR=` to skip
|
||||
those shortcuts. Debian packages include the same application-menu entries.
|
||||
|
||||
F-Droid metadata is maintained in `packaging/fdroid`. The `android-fdroid`
|
||||
target disables developer signing even when a release keystore is configured
|
||||
and writes `build/werk-VERSION-fdroid-unsigned.apk`. It adds no version or
|
||||
package suffix, preserving existing installations and reference-APK checks.
|
||||
The unsigned candidate is for builders, not installation. Werkzeug currently
|
||||
has no built-in updater: F-Droid or your chosen installer handles updates.
|
||||
Android requires the same signing certificate for an in-place update; the
|
||||
F-Droid recipe retains the developer-signature reproducibility requirement.
|
||||
|
||||
The [F-Droid TODO](packaging/fdroid/TODO.md) records completed checks, the
|
||||
remaining submission/reproducibility steps and the prepared merge-request text.
|
||||
|
||||
For development with the real project repositories, create an ignored
|
||||
`ziran.local.toml`:
|
||||
|
||||
@@ -229,7 +146,7 @@ print the generated password instead. Run `pass --help` for all flags.
|
||||
|
||||
```text
|
||||
apps/pass/ Pass: LessPass core, settings and profiles, screens, CLI
|
||||
apps/auth/ Auth: TOTP, otpauth links, exports, accounts and screens
|
||||
apps/auth/ Auth: TOTP, otpauth links, accounts and screens
|
||||
apps/calculator/ Calculator
|
||||
apps/clock/ Clock and stopwatch
|
||||
shared/ the app interface, protocol and SHA-256/PBKDF2
|
||||
@@ -237,7 +154,6 @@ src/werk.zi home screen, profile screen and the bar above a tool
|
||||
src/apps.zi loads, checks and runs the app bundles
|
||||
src/platform.zi files, clock, clipboard and secrets per platform
|
||||
src/desktop.zi, src/android_main.zi, src/browser.zi platform main loops
|
||||
src/command.zi werk sync and werk auth without a window
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
8c5806d7ff5a4fdaf6b98a7668acbf0aad236ece1d5e68ffe1f7b268a1afb077
|
||||
@@ -17,12 +17,12 @@
|
||||
#import "tree"
|
||||
#import "text_buffer"
|
||||
#import "number_text"
|
||||
#import "kryon/app_context"
|
||||
#import "kryon/app_protocol"
|
||||
#import "werk_app"
|
||||
#import "app_protocol"
|
||||
#import "totp"
|
||||
#import "exports"
|
||||
#import "sha256"
|
||||
Icon :: #import "mingcute_regular_shield";
|
||||
Edit :: #import "mingcute_regular_edit_2";
|
||||
Remove :: #import "mingcute_regular_delete_2";
|
||||
|
||||
ACCOUNT_LIMIT :: 128
|
||||
LIST_LIMIT :: 65536
|
||||
@@ -31,13 +31,11 @@ CODE_CLEAR_SECONDS :: 30
|
||||
|
||||
VIEW_LIST :: 0
|
||||
VIEW_ADD :: 1
|
||||
VIEW_EDIT :: 2
|
||||
|
||||
FIELD_LINKS :: 1
|
||||
FIELD_ISSUER :: 2
|
||||
FIELD_NAME :: 3
|
||||
FIELD_SECRET :: 4
|
||||
FIELD_SITES :: 5
|
||||
|
||||
FieldState :: struct {
|
||||
cursor: s32
|
||||
@@ -61,18 +59,14 @@ account_count: s32;
|
||||
loaded: bool;
|
||||
view: s32;
|
||||
focused: s32;
|
||||
fields: [6]FieldState;
|
||||
// A whole export fits: Aegis's JSON is about 250 bytes per account.
|
||||
links: [65536]u8;
|
||||
fields: [5]FieldState;
|
||||
links: [16384]u8;
|
||||
issuer: [64]u8;
|
||||
name: [128]u8;
|
||||
secret: [256]u8;
|
||||
sites: [256]u8;
|
||||
status: [128]u8;
|
||||
// The account being edited, and whether its Remove was tapped once; a
|
||||
// second tap removes it.
|
||||
editing: s32 = -1;
|
||||
remove_pending: bool;
|
||||
// The account whose Remove was tapped once; a second tap removes it.
|
||||
remove_pending: s32 = -1;
|
||||
list_scroll: s32;
|
||||
store: [LIST_LIMIT]u8;
|
||||
session: Session;
|
||||
@@ -89,10 +83,22 @@ Clear :: (bytes: []u8) {
|
||||
}
|
||||
}
|
||||
|
||||
HexDigit :: (value: u8) -> u8 {
|
||||
return ifx value < cast(u8)10 then cast(u8)48 + value else cast(u8)87 + value
|
||||
}
|
||||
|
||||
// An account's record id comes from its link, so the same account added on
|
||||
// two devices is one record. An edited account keeps its id.
|
||||
// two devices is one record.
|
||||
SetRecordId :: (index: s32, link: string) {
|
||||
unused RecordIdFor(link, record_ids[index][:])
|
||||
digest := Sha256(link)
|
||||
for at: 0..15 {
|
||||
record_ids[index][at * 2] = HexDigit(digest[at] >> cast(u8)4)
|
||||
record_ids[index][at * 2 + 1] = HexDigit(digest[at] & cast(u8)15)
|
||||
}
|
||||
record_ids[index][32] = cast(u8)0
|
||||
for at: 0..31 {
|
||||
digest[at] = cast(u8)0
|
||||
}
|
||||
}
|
||||
|
||||
// Writes the records of accounts added since the last save.
|
||||
@@ -105,9 +111,7 @@ SaveAccounts :: () -> bool {
|
||||
{
|
||||
link := LinkText(*accounts[index], line[:])
|
||||
if link != "" {
|
||||
if record_ids[index][0] == cast(u8)0 {
|
||||
SetRecordId(index, link)
|
||||
}
|
||||
SetRecordId(index, link)
|
||||
recorded[index] = RecordWrite(TextUntilNul(record_ids[index][:]), link)
|
||||
}
|
||||
}
|
||||
@@ -125,7 +129,7 @@ LoadAccounts :: () {
|
||||
count := ReadStore("accounts.txt", store[:])
|
||||
if count > 0 {
|
||||
account_count = 0
|
||||
unused AddExport(TextView(store[0:count]), false)
|
||||
unused AddLinks(TextView(store[0:count]), false)
|
||||
if SaveAccounts() {
|
||||
unused WriteStore("accounts.txt", "")
|
||||
}
|
||||
@@ -134,7 +138,6 @@ LoadAccounts :: () {
|
||||
while account_count > 0 {
|
||||
account_count -= 1
|
||||
accounts[account_count] = Account.{}
|
||||
record_ids[account_count][0] = cast(u8)0
|
||||
}
|
||||
listed := RecordList(ids[:])
|
||||
start: s32 = 0
|
||||
@@ -161,42 +164,51 @@ LoadAccounts :: () {
|
||||
}
|
||||
}
|
||||
|
||||
// The same secret gives the same codes, whatever the account is called.
|
||||
SameAccount :: (left: *Account, right: *Account) -> bool {
|
||||
return TextUntilNul(left.secret[:]) == TextUntilNul(right.secret[:])
|
||||
return TextUntilNul(left.issuer[:]) == TextUntilNul(right.issuer[:]) &&
|
||||
TextUntilNul(left.name[:]) == TextUntilNul(right.name[:]) &&
|
||||
TextUntilNul(left.secret[:]) == TextUntilNul(right.secret[:])
|
||||
}
|
||||
|
||||
// Adds the accounts of an export: otpauth links separated by spaces or line
|
||||
// breaks, Google Authenticator's export links or Aegis's JSON. Returns how
|
||||
// many were new.
|
||||
AddExport :: (text: string, report: bool) -> s32 {
|
||||
result := ReadExport(text)
|
||||
// Adds every otpauth link in text, separated by spaces or line breaks.
|
||||
// Returns how many were new.
|
||||
AddLinks :: (text: string, report: bool) -> s32 {
|
||||
added: s32 = 0
|
||||
refused := result.skipped
|
||||
found: s32 = 0
|
||||
while found < result.count {
|
||||
account := *export_accounts[found]
|
||||
known := false
|
||||
index: s32 = 0
|
||||
while index < account_count {
|
||||
if SameAccount(*accounts[index], account) {
|
||||
known = true
|
||||
refused: s32 = 0
|
||||
start: s64 = 0
|
||||
while start < text.count {
|
||||
while start < text.count && text[start] <= cast(u8)32 {
|
||||
start += 1
|
||||
}
|
||||
end := start
|
||||
while end < text.count && text[end] > cast(u8)32 {
|
||||
end += 1
|
||||
}
|
||||
if end > start {
|
||||
account: Account
|
||||
if ParseLink(text[start:end], *account) && account_count < ACCOUNT_LIMIT {
|
||||
known := false
|
||||
index: s32 = 0
|
||||
while index < account_count {
|
||||
if SameAccount(*accounts[index], *account) {
|
||||
known = true
|
||||
}
|
||||
index += 1
|
||||
}
|
||||
if !known {
|
||||
accounts[account_count] = account
|
||||
codes[account_count] = CachedCode.{.step = -1}
|
||||
recorded[account_count] = false
|
||||
account_count += 1
|
||||
added += 1
|
||||
}
|
||||
} else {
|
||||
refused += 1
|
||||
}
|
||||
index += 1
|
||||
account = Account.{}
|
||||
}
|
||||
if !known && account_count >= ACCOUNT_LIMIT {
|
||||
refused += 1
|
||||
} else if !known {
|
||||
accounts[account_count] = account.*
|
||||
codes[account_count] = CachedCode.{.step = -1}
|
||||
record_ids[account_count][0] = cast(u8)0
|
||||
recorded[account_count] = false
|
||||
account_count += 1
|
||||
added += 1
|
||||
}
|
||||
found += 1
|
||||
start = end
|
||||
}
|
||||
ClearExport()
|
||||
if report {
|
||||
number: [24]u8
|
||||
message: [128]u8
|
||||
@@ -207,9 +219,6 @@ AddExport :: (text: string, report: bool) -> s32 {
|
||||
used = AppendText(message[:], used, ", skipped ")
|
||||
used = AppendText(message[:], used, FormatInteger(cast(s64)refused, number[:]))
|
||||
}
|
||||
if result.encrypted {
|
||||
used = AppendText(message[:], 0, "This export is encrypted; export it without a password")
|
||||
}
|
||||
SetStatus(TextView(message[0:used]))
|
||||
}
|
||||
return added
|
||||
@@ -235,37 +244,12 @@ AddManual :: () -> bool {
|
||||
}
|
||||
accounts[account_count] = account
|
||||
codes[account_count] = CachedCode.{.step = -1}
|
||||
record_ids[account_count][0] = cast(u8)0
|
||||
recorded[account_count] = false
|
||||
account_count += 1
|
||||
account = Account.{}
|
||||
return true
|
||||
}
|
||||
|
||||
// Saves the edited name and websites. The account keeps its record id, so
|
||||
// the change replaces it on every device.
|
||||
SaveEdit :: () -> bool {
|
||||
account := *accounts[editing]
|
||||
if name[0] == cast(u8)0 && issuer[0] == cast(u8)0 {
|
||||
SetStatus("Enter a name for the account")
|
||||
return false
|
||||
}
|
||||
websites: [256]u8
|
||||
if !NormalizeSites(TextUntilNul(sites[:]), websites[:]) {
|
||||
SetStatus("Enter websites such as github.com, separated by spaces")
|
||||
return false
|
||||
}
|
||||
account.issuer = issuer
|
||||
account.name = name
|
||||
account.sites = websites
|
||||
recorded[editing] = false
|
||||
if !SaveAccounts() {
|
||||
SetStatus("Could not save the account")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
RemoveAccount :: (index: s32) -> bool {
|
||||
if recorded[index] && !RecordRemove(TextUntilNul(record_ids[index][:])) {
|
||||
return false
|
||||
@@ -281,7 +265,6 @@ RemoveAccount :: (index: s32) -> bool {
|
||||
account_count -= 1
|
||||
accounts[account_count] = Account.{}
|
||||
codes[account_count] = CachedCode.{}
|
||||
record_ids[account_count][0] = cast(u8)0
|
||||
recorded[account_count] = false
|
||||
return true
|
||||
}
|
||||
@@ -389,35 +372,9 @@ Field :: (id: s32, label: string, placeholder: string, buffer: []u8, bounds: Rec
|
||||
ApplyEdit(buffer, edit)
|
||||
}
|
||||
|
||||
// Opens an account's name, websites and Remove.
|
||||
OpenEdit :: (index: s32) {
|
||||
account := *accounts[index]
|
||||
issuer = account.issuer
|
||||
name = account.name
|
||||
sites = account.sites
|
||||
fields[FIELD_ISSUER] = FieldState.{}
|
||||
fields[FIELD_NAME] = FieldState.{}
|
||||
fields[FIELD_SITES] = FieldState.{}
|
||||
editing = index
|
||||
remove_pending = false
|
||||
focused = 0
|
||||
view = VIEW_EDIT
|
||||
SetStatus("")
|
||||
}
|
||||
|
||||
CloseEdit :: () {
|
||||
Clear(issuer[:])
|
||||
Clear(name[:])
|
||||
Clear(sites[:])
|
||||
editing = -1
|
||||
remove_pending = false
|
||||
focused = 0
|
||||
view = VIEW_LIST
|
||||
}
|
||||
|
||||
// One account: its name, current code (tap to copy), the seconds left and
|
||||
// Edit.
|
||||
DrawRow :: (index: s32, x: float32, y: float32, inner: float32, row: float32) {
|
||||
// Remove. True when Remove was confirmed.
|
||||
DrawRow :: (index: s32, x: float32, y: float32, inner: float32, row: float32) -> bool {
|
||||
account := *accounts[index]
|
||||
Box(session, BoxProps.{.key = cast(u64)(1000 + index), .bounds = Rectangle.{x, y, inner, row - 8.0},
|
||||
.radius = 10.0})
|
||||
@@ -440,16 +397,26 @@ DrawRow :: (index: s32, x: float32, y: float32, inner: float32, row: float32) {
|
||||
}
|
||||
remaining := cast(s64)account.period - Unix() % cast(s64)account.period
|
||||
number: [24]u8
|
||||
// The seconds left, centred beside the code.
|
||||
Label(cast(u64)(5000 + index), FormatInteger(remaining, number[:]),
|
||||
Rectangle.{x + inner - 52.0, y + 27.0, 16.0, 18.0}, 12)
|
||||
edit := ButtonProps.{.key = cast(u64)(6000 + index), .id = 6000 + index, .label = "Edit",
|
||||
Rectangle.{x + inner - 52.0, y + 24.0, 16.0, 18.0}, 12)
|
||||
remove := ButtonProps.{.key = cast(u64)(6000 + index), .id = 6000 + index,
|
||||
.label = ifx remove_pending == index then "Tap again to remove" else "Remove",
|
||||
.bounds = Rectangle.{x + inner - 40.0, y + 16.0, 36.0, 36.0},
|
||||
.icon_shape = Edit.Shape, .icon_only = true,
|
||||
.icon_shape = Remove.Shape, .icon_only = true,
|
||||
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
|
||||
if Button(session, edit) != 0 {
|
||||
OpenEdit(index)
|
||||
if remove_pending == index {
|
||||
remove.tone = ButtonTone.ButtonToneDanger
|
||||
remove.emphasis = ButtonEmphasis.ButtonEmphasisFilled
|
||||
}
|
||||
if Button(session, remove) == 0 {
|
||||
return false
|
||||
}
|
||||
if remove_pending == index {
|
||||
return true
|
||||
}
|
||||
remove_pending = index
|
||||
SetStatus("Tap the red button again to remove this account")
|
||||
return false
|
||||
}
|
||||
|
||||
ListView :: (area: Rectangle, left: float32, width: float32) {
|
||||
@@ -474,8 +441,13 @@ ListView :: (area: Rectangle, left: float32, width: float32) {
|
||||
x := scroll.content.x
|
||||
inner := scroll.content.width - 10.0
|
||||
index: s32 = 0
|
||||
while index < account_count && view == VIEW_LIST {
|
||||
DrawRow(index, x, scroll.content.y + cast(float32)index * row, inner, row)
|
||||
while index < account_count {
|
||||
y := scroll.content.y + cast(float32)index * row
|
||||
if DrawRow(index, x, y, inner, row) {
|
||||
remove_pending = -1
|
||||
SetStatus(ifx RemoveAccount(index) then "Account removed" else "Could not remove the account")
|
||||
break
|
||||
}
|
||||
index += 1
|
||||
}
|
||||
End(session)
|
||||
@@ -484,22 +456,18 @@ ListView :: (area: Rectangle, left: float32, width: float32) {
|
||||
|
||||
AddView :: (area: Rectangle, left: float32, width: float32) {
|
||||
y := area.y + 12.0
|
||||
Label(cast(u64)20, "Paste otpauth links or an authenticator export", Rectangle.{left, y, width, 20.0}, 14)
|
||||
Field(FIELD_LINKS, "Links or export", "otpauth://totp/…", links[:], Rectangle.{left, y + 24.0, width, 40.0}, true)
|
||||
Label(cast(u64)20, "Paste otpauth:// links, one or many", Rectangle.{left, y, width, 20.0}, 14)
|
||||
Field(FIELD_LINKS, "Links", "otpauth://totp/…", links[:], Rectangle.{left, y + 24.0, width, 40.0}, true)
|
||||
y += 76.0
|
||||
// The desktop can also read an export file or a picture of its QR code.
|
||||
files := FileImportAvailable()
|
||||
button := ifx files then (width - 8.0) / 2.0 else width
|
||||
if Action(21, "Import", Rectangle.{left, y, button, 40.0}, true) {
|
||||
ImportLinks()
|
||||
}
|
||||
if files && Action(25, "Import file", Rectangle.{left + button + 8.0, y, button, 40.0}, false) {
|
||||
count := FileImport(links[:])
|
||||
if count > 0 {
|
||||
ImportLinks()
|
||||
} else if count < 0 {
|
||||
Clear(links[:])
|
||||
SetStatus("That file is not an authenticator export or its QR code")
|
||||
if Action(21, "Import links", Rectangle.{left, y, width, 40.0}, true) {
|
||||
added := AddLinks(TextUntilNul(links[:]), true)
|
||||
if added > 0 && !SaveAccounts() {
|
||||
SetStatus("Could not save the accounts")
|
||||
}
|
||||
Clear(links[:])
|
||||
fields[FIELD_LINKS] = FieldState.{}
|
||||
if added > 0 {
|
||||
view = VIEW_LIST
|
||||
}
|
||||
}
|
||||
y += 64.0
|
||||
@@ -533,63 +501,6 @@ AddView :: (area: Rectangle, left: float32, width: float32) {
|
||||
}
|
||||
}
|
||||
|
||||
// Adds the accounts in the links field, then forgets the field.
|
||||
ImportLinks :: () {
|
||||
added := AddExport(TextUntilNul(links[:]), true)
|
||||
if added > 0 && !SaveAccounts() {
|
||||
SetStatus("Could not save the accounts")
|
||||
}
|
||||
Clear(links[:])
|
||||
fields[FIELD_LINKS] = FieldState.{}
|
||||
if added > 0 {
|
||||
view = VIEW_LIST
|
||||
}
|
||||
}
|
||||
|
||||
EditView :: (area: Rectangle, left: float32, width: float32) {
|
||||
y := area.y + 12.0
|
||||
Field(FIELD_ISSUER, "Service", "Service, such as GitHub", issuer[:], Rectangle.{left, y, width, 40.0}, false)
|
||||
y += 48.0
|
||||
Field(FIELD_NAME, "Account", "Account name or email", name[:], Rectangle.{left, y, width, 40.0}, false)
|
||||
y += 56.0
|
||||
Label(cast(u64)40, "Websites where it signs in, such as github.com", Rectangle.{left, y, width, 20.0}, 14)
|
||||
y += 24.0
|
||||
Field(FIELD_SITES, "Websites", "github.com", sites[:], Rectangle.{left, y, width, 40.0}, false)
|
||||
y += 56.0
|
||||
half := (width - 8.0) / 2.0
|
||||
if Action(41, "Save", Rectangle.{left, y, half, 40.0}, true) {
|
||||
if SaveEdit() {
|
||||
CloseEdit()
|
||||
SetStatus("Account saved")
|
||||
}
|
||||
return
|
||||
}
|
||||
if Action(42, "Cancel", Rectangle.{left + half + 8.0, y, half, 40.0}, false) {
|
||||
CloseEdit()
|
||||
SetStatus("")
|
||||
return
|
||||
}
|
||||
y += 64.0
|
||||
remove := ButtonProps.{.key = cast(u64)43, .id = 43, .bounds = Rectangle.{left, y, width, 40.0},
|
||||
.label = ifx remove_pending then "Tap again to remove" else "Remove account",
|
||||
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
|
||||
if remove_pending {
|
||||
remove.tone = ButtonTone.ButtonToneDanger
|
||||
remove.emphasis = ButtonEmphasis.ButtonEmphasisFilled
|
||||
}
|
||||
if Button(session, remove) == 0 {
|
||||
return
|
||||
}
|
||||
if !remove_pending {
|
||||
remove_pending = true
|
||||
SetStatus("Tap the red button again to remove this account")
|
||||
return
|
||||
}
|
||||
removed := RemoveAccount(editing)
|
||||
CloseEdit()
|
||||
SetStatus(ifx removed then "Account removed" else "Could not remove the account")
|
||||
}
|
||||
|
||||
Draw :: () {
|
||||
session = AppSession()
|
||||
area := AppBounds()
|
||||
@@ -600,8 +511,6 @@ Draw :: () {
|
||||
left := area.x + (area.width - width) * 0.5
|
||||
if view == VIEW_ADD {
|
||||
AddView(area, left, width)
|
||||
} else if view == VIEW_EDIT && editing >= 0 && editing < account_count {
|
||||
EditView(area, left, width)
|
||||
} else {
|
||||
ListView(area, left, width)
|
||||
}
|
||||
@@ -612,20 +521,13 @@ Draw :: () {
|
||||
#program_export "AuthMain"
|
||||
Main :: () -> s32 {
|
||||
if AppMode() == APP_IDENTIFY {
|
||||
AppIdentity("auth")
|
||||
AppDescribe("Auth", Icon.Shape)
|
||||
return APP_PROTOCOL
|
||||
}
|
||||
if AppMode() != APP_FRAME {
|
||||
return 0
|
||||
}
|
||||
// Records from another device replace the list, and close an edit.
|
||||
// Records from another device replace the list.
|
||||
if !loaded || RecordsVersion() != records_version {
|
||||
LoadAccounts()
|
||||
loaded = true
|
||||
if view == VIEW_EDIT {
|
||||
CloseEdit()
|
||||
}
|
||||
}
|
||||
Draw()
|
||||
return 0
|
||||
|
||||
@@ -1,388 +0,0 @@
|
||||
// Authenticator exports: otpauth links, one or many as Ente Auth and other
|
||||
// apps export them, Google Authenticator's otpauth-migration links and
|
||||
// Aegis's unencrypted JSON. Encrypted exports are recognized and refused.
|
||||
#import "text_buffer"
|
||||
#import "json_scan"
|
||||
#import "totp"
|
||||
|
||||
EXPORT_LIMIT :: 128
|
||||
MIGRATION_LIMIT :: 16384
|
||||
|
||||
ExportResult :: struct {
|
||||
// Accounts read into export_accounts.
|
||||
count: s32
|
||||
// Entries that are not time-based codes or could not be read.
|
||||
skipped: s32
|
||||
// The export is encrypted; only unencrypted exports can be read.
|
||||
encrypted: bool
|
||||
}
|
||||
|
||||
export_accounts: [EXPORT_LIMIT]Account;
|
||||
export_result: ExportResult;
|
||||
migration_text: [MIGRATION_LIMIT]u8;
|
||||
migration_bytes: [MIGRATION_LIMIT]u8;
|
||||
aegis_positions: [EXPORT_LIMIT * 2]s32;
|
||||
|
||||
Wipe :: (bytes: []u8) {
|
||||
index: s64 = 0
|
||||
while index < bytes.count {
|
||||
bytes[index] = cast(u8)0
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
|
||||
Keep :: (account: *Account) {
|
||||
if export_result.count >= EXPORT_LIMIT || (account.issuer[0] == cast(u8)0 && account.name[0] == cast(u8)0) {
|
||||
export_result.skipped += 1
|
||||
return
|
||||
}
|
||||
export_accounts[export_result.count] = account.*
|
||||
export_result.count += 1
|
||||
}
|
||||
|
||||
// Forgets the accounts read, secrets included.
|
||||
ClearExport :: () {
|
||||
index: s32 = 0
|
||||
while index < EXPORT_LIMIT {
|
||||
export_accounts[index] = Account.{}
|
||||
index += 1
|
||||
}
|
||||
export_result = ExportResult.{}
|
||||
}
|
||||
|
||||
// "Issuer:alice" names carry the issuer; the account keeps only "alice".
|
||||
SplitLabel :: (account: *Account) {
|
||||
issuer: [64]u8
|
||||
rest: [128]u8
|
||||
{
|
||||
name := TextUntilNul(account.name[:])
|
||||
colon: s64 = 0
|
||||
while colon < name.count && name[colon] != cast(u8)58 {
|
||||
colon += 1
|
||||
}
|
||||
if colon >= name.count || !CopyLimited(name[0:colon], issuer[:]) {
|
||||
return
|
||||
}
|
||||
start := colon + 1
|
||||
while start < name.count && name[start] == cast(u8)32 {
|
||||
start += 1
|
||||
}
|
||||
unused CopyLimited(name[start:name.count], rest[:])
|
||||
}
|
||||
if account.issuer[0] == cast(u8)0 {
|
||||
account.issuer = issuer
|
||||
} else if TextUntilNul(issuer[:]) != TextUntilNul(account.issuer[:]) {
|
||||
return
|
||||
}
|
||||
account.name = rest
|
||||
}
|
||||
|
||||
Base64Value :: (byte: u8) -> s32 {
|
||||
if byte >= cast(u8)65 && byte <= cast(u8)90 {
|
||||
return cast(s32)(byte - cast(u8)65)
|
||||
}
|
||||
if byte >= cast(u8)97 && byte <= cast(u8)122 {
|
||||
return cast(s32)(byte - cast(u8)97) + 26
|
||||
}
|
||||
if byte >= cast(u8)48 && byte <= cast(u8)57 {
|
||||
return cast(s32)(byte - cast(u8)48) + 52
|
||||
}
|
||||
// A "+" that a link turned into a space, and the URL-safe alphabet.
|
||||
if byte == cast(u8)43 || byte == cast(u8)32 || byte == cast(u8)45 {
|
||||
return 62
|
||||
}
|
||||
if byte == cast(u8)47 || byte == cast(u8)95 {
|
||||
return 63
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Decodes Base64 up to its padding. Returns the byte count, or -1.
|
||||
Base64Decode :: (text: string, output: []u8) -> s32 {
|
||||
buffer: u32 = 0
|
||||
bits: s32 = 0
|
||||
count: s32 = 0
|
||||
index: s64 = 0
|
||||
while index < text.count && text[index] != cast(u8)61 {
|
||||
value := Base64Value(text[index])
|
||||
index += 1
|
||||
if value < 0 {
|
||||
return -1
|
||||
}
|
||||
buffer = (buffer << cast(u32)6) | cast(u32)value
|
||||
bits += 6
|
||||
if bits >= 8 {
|
||||
bits -= 8
|
||||
if count >= cast(s32)output.count {
|
||||
return -1
|
||||
}
|
||||
output[count] = cast(u8)(buffer >> cast(u32)bits)
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// A protocol buffer varint; at becomes -1 when the data ends inside it.
|
||||
Varint :: (data: []u8, end: s32, at: *s32) -> u64 {
|
||||
value: u64 = 0
|
||||
shift: u64 = 0
|
||||
while at.* >= 0 && at.* < end && shift < cast(u64)64 {
|
||||
byte := data[at.*]
|
||||
at.* += 1
|
||||
value = value | (cast(u64)(byte & cast(u8)127) << shift)
|
||||
if byte < cast(u8)128 {
|
||||
return value
|
||||
}
|
||||
shift += cast(u64)7
|
||||
}
|
||||
at.* = -1
|
||||
return 0
|
||||
}
|
||||
|
||||
// Moves past one field's value; false when the data is malformed.
|
||||
SkipField :: (data: []u8, end: s32, at: *s32, wire: u64) -> bool {
|
||||
if wire == cast(u64)0 {
|
||||
unused Varint(data, end, at)
|
||||
} else if wire == cast(u64)1 {
|
||||
at.* += 8
|
||||
} else if wire == cast(u64)5 {
|
||||
at.* += 4
|
||||
} else if wire == cast(u64)2 {
|
||||
length := Varint(data, end, at)
|
||||
if at.* < 0 || length > cast(u64)(end - at.*) {
|
||||
return false
|
||||
}
|
||||
at.* += cast(s32)length
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
return at.* >= 0 && at.* <= end
|
||||
}
|
||||
|
||||
// One account of a migration payload (Google's OtpParameters): the secret's
|
||||
// bytes, name, issuer, algorithm, digits and type.
|
||||
ReadParameters :: (data: []u8, start: s32, end: s32) {
|
||||
account := Account.{.kind = HASH_SHA1, .digits = 6, .period = 30}
|
||||
secret_at: s32 = -1
|
||||
secret_count: s32 = 0
|
||||
readable := true
|
||||
at := start
|
||||
while readable && at < end {
|
||||
key := Varint(data, end, *at)
|
||||
if at < 0 {
|
||||
readable = false
|
||||
break
|
||||
}
|
||||
field := key >> cast(u64)3
|
||||
wire := key & cast(u64)7
|
||||
if wire == cast(u64)2 {
|
||||
length := Varint(data, end, *at)
|
||||
if at < 0 || length > cast(u64)(end - at) {
|
||||
readable = false
|
||||
break
|
||||
}
|
||||
value := TextView(data[at:at + cast(s32)length])
|
||||
if field == cast(u64)1 {
|
||||
secret_at = at
|
||||
secret_count = cast(s32)length
|
||||
} else if field == cast(u64)2 {
|
||||
readable = CopyLimited(value, account.name[:])
|
||||
} else if field == cast(u64)3 {
|
||||
readable = CopyLimited(value, account.issuer[:])
|
||||
}
|
||||
at += cast(s32)length
|
||||
} else if wire == cast(u64)0 {
|
||||
value := Varint(data, end, *at)
|
||||
if at < 0 {
|
||||
readable = false
|
||||
break
|
||||
}
|
||||
if field == cast(u64)4 {
|
||||
// 0 unspecified and 1 SHA-1, 2 SHA-256, 3 SHA-512; 4 is MD5.
|
||||
if value == cast(u64)2 {
|
||||
account.kind = HASH_SHA256
|
||||
} else if value == cast(u64)3 {
|
||||
account.kind = HASH_SHA512
|
||||
} else if value > cast(u64)1 {
|
||||
readable = false
|
||||
}
|
||||
} else if field == cast(u64)5 {
|
||||
// 0 unspecified and 1 six digits, 2 eight.
|
||||
if value == cast(u64)2 {
|
||||
account.digits = 8
|
||||
} else if value > cast(u64)1 {
|
||||
readable = false
|
||||
}
|
||||
} else if field == cast(u64)6 {
|
||||
// 1 is a counter-based (HOTP) account, 2 time-based.
|
||||
readable = value != cast(u64)1
|
||||
}
|
||||
} else {
|
||||
readable = SkipField(data, end, *at, wire)
|
||||
}
|
||||
}
|
||||
secret: [256]u8
|
||||
readable = readable && secret_at >= 0 && secret_count <= KEY_LIMIT &&
|
||||
Base32Encode(data[secret_at:secret_at + secret_count], secret_count, secret[:]) > 0 &&
|
||||
SetSecret(*account, TextUntilNul(secret[:]))
|
||||
if readable {
|
||||
SplitLabel(*account)
|
||||
Keep(*account)
|
||||
} else {
|
||||
export_result.skipped += 1
|
||||
}
|
||||
Wipe(secret[:])
|
||||
account = Account.{}
|
||||
}
|
||||
|
||||
// otpauth-migration://offline?data=…: Base64 of a MigrationPayload whose
|
||||
// first field repeats once per account.
|
||||
ReadMigration :: (link: string) {
|
||||
prefix := "otpauth-migration://offline?"
|
||||
if !StartsWithIgnoringCase(link, prefix) {
|
||||
export_result.skipped += 1
|
||||
return
|
||||
}
|
||||
query := link[prefix.count:link.count]
|
||||
data := ""
|
||||
position: s64 = 0
|
||||
while position < query.count {
|
||||
end := position
|
||||
while end < query.count && query[end] != cast(u8)38 {
|
||||
end += 1
|
||||
}
|
||||
if StartsWithIgnoringCase(query[position:end], "data=") {
|
||||
data = query[position + 5:end]
|
||||
}
|
||||
position = end + 1
|
||||
}
|
||||
count: s32 = -1
|
||||
if data != "" && Unescape(data, migration_text[:]) {
|
||||
count = Base64Decode(TextUntilNul(migration_text[:]), migration_bytes[:])
|
||||
}
|
||||
if count <= 0 {
|
||||
export_result.skipped += 1
|
||||
}
|
||||
at: s32 = 0
|
||||
while count > 0 && at >= 0 && at < count {
|
||||
key := Varint(migration_bytes[:], count, *at)
|
||||
if at < 0 {
|
||||
break
|
||||
}
|
||||
if key == cast(u64)10 {
|
||||
length := Varint(migration_bytes[:], count, *at)
|
||||
if at < 0 || length > cast(u64)(count - at) {
|
||||
export_result.skipped += 1
|
||||
break
|
||||
}
|
||||
ReadParameters(migration_bytes[:], at, at + cast(s32)length)
|
||||
at += cast(s32)length
|
||||
} else if !SkipField(migration_bytes[:], count, *at, key & cast(u64)7) {
|
||||
break
|
||||
}
|
||||
}
|
||||
Wipe(migration_text[:])
|
||||
Wipe(migration_bytes[:])
|
||||
}
|
||||
|
||||
ReadText :: (text: string, at: s32, output: []u8) -> string {
|
||||
if at < 0 || ReadStringText(text, at, output) < 0 {
|
||||
output[0] = cast(u8)0
|
||||
}
|
||||
return TextUntilNul(output)
|
||||
}
|
||||
|
||||
// Aegis's export: {"db":{"entries":[{"type":"totp","name":…,"issuer":…,
|
||||
// "info":{"secret":…,"algo":…,"digits":…,"period":…}}]}}. An encrypted
|
||||
// Aegis export keeps db as a string; Ente Auth's has encryptedData.
|
||||
ReadAegis :: (text: string) {
|
||||
db := FieldAt(text, 0, "db")
|
||||
if (db >= 0 && text[db] == cast(u8)34) || FieldAt(text, 0, "encryptedData") >= 0 {
|
||||
export_result.encrypted = true
|
||||
return
|
||||
}
|
||||
entries := FieldAt(text, db, "entries")
|
||||
total := ArrayPositions(text, entries, aegis_positions[:])
|
||||
if total > EXPORT_LIMIT * 2 {
|
||||
total = EXPORT_LIMIT * 2
|
||||
}
|
||||
index: s32 = 0
|
||||
while index < total {
|
||||
entry := aegis_positions[index]
|
||||
index += 1
|
||||
info := FieldAt(text, entry, "info")
|
||||
kind: [16]u8
|
||||
if ReadText(text, FieldAt(text, entry, "type"), kind[:]) != "totp" || info < 0 {
|
||||
export_result.skipped += 1
|
||||
continue
|
||||
}
|
||||
account := Account.{.kind = HASH_SHA1, .digits = 6, .period = 30}
|
||||
secret: [256]u8
|
||||
readable := SetSecret(*account, ReadText(text, FieldAt(text, info, "secret"), secret[:]))
|
||||
algorithm: [16]u8
|
||||
if ReadText(text, FieldAt(text, info, "algo"), algorithm[:]) != "" {
|
||||
account.kind = ParseAlgorithm(TextUntilNul(algorithm[:]))
|
||||
readable = readable && account.kind != 0
|
||||
}
|
||||
digits := ReadNumber(text, FieldAt(text, info, "digits"))
|
||||
if digits.valid {
|
||||
account.digits = cast(s32)digits.value
|
||||
readable = readable && account.digits >= 6 && account.digits <= 8
|
||||
}
|
||||
period := ReadNumber(text, FieldAt(text, info, "period"))
|
||||
if period.valid {
|
||||
account.period = cast(s32)period.value
|
||||
readable = readable && account.period >= 1 && account.period <= 300
|
||||
}
|
||||
issuer: [64]u8
|
||||
name: [128]u8
|
||||
readable = readable && CopyLimited(ReadText(text, FieldAt(text, entry, "issuer"), issuer[:]), account.issuer[:]) &&
|
||||
CopyLimited(ReadText(text, FieldAt(text, entry, "name"), name[:]), account.name[:])
|
||||
if readable {
|
||||
Keep(*account)
|
||||
} else {
|
||||
export_result.skipped += 1
|
||||
}
|
||||
Wipe(secret[:])
|
||||
account = Account.{}
|
||||
}
|
||||
}
|
||||
|
||||
// Reads every account in an export into export_accounts.
|
||||
ReadExport :: (text: string) -> ExportResult {
|
||||
ClearExport()
|
||||
start: s64 = 0
|
||||
while start < text.count && text[start] <= cast(u8)32 {
|
||||
start += 1
|
||||
}
|
||||
if start < text.count && text[start] == cast(u8)123 {
|
||||
ReadAegis(text[start:text.count])
|
||||
return export_result
|
||||
}
|
||||
while start < text.count {
|
||||
while start < text.count && text[start] <= cast(u8)32 {
|
||||
start += 1
|
||||
}
|
||||
end := start
|
||||
while end < text.count && text[end] > cast(u8)32 {
|
||||
end += 1
|
||||
}
|
||||
if end > start {
|
||||
word := text[start:end]
|
||||
if StartsWithIgnoringCase(word, "otpauth-migration://") {
|
||||
ReadMigration(word)
|
||||
} else {
|
||||
account: Account
|
||||
if ParseLink(word, *account) {
|
||||
Keep(*account)
|
||||
} else {
|
||||
export_result.skipped += 1
|
||||
}
|
||||
account = Account.{}
|
||||
}
|
||||
}
|
||||
start = end
|
||||
}
|
||||
return export_result
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
// Reading authenticator exports, with the RFC 6238 test keys only.
|
||||
#import "text_buffer"
|
||||
#import "totp"
|
||||
#import "exports"
|
||||
|
||||
// Example Co:[email protected] (SHA-1, 6 digits), Second:bob (SHA-256,
|
||||
// 8 digits) and a counter-based account, as Google Authenticator exports them.
|
||||
MIGRATION :: "otpauth-migration://offline?data=CjoKFDEyMzQ1Njc4OTAxMjM0NTY3ODkwEhxFeGFtcGxlIENvOmFsaWNlQGV4YW1wbGUuY29tIAEoATACCjUKIDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyEgNib2IaBlNlY29uZCACKAIwAgorChQxMjM0NTY3ODkwMTIzNDU2Nzg5MBIHY291bnRlchoESG90cCABKAEwARABGAEgACi5YA%3D%3D"
|
||||
|
||||
AEGIS :: #string END
|
||||
{"version":1,"header":{"slots":null,"params":null},"db":{"version":2,"entries":[
|
||||
{"type":"totp","uuid":"1","name":"carol","issuer":"Third","icon":null,
|
||||
"info":{"secret":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ","algo":"SHA512","digits":7,"period":60}},
|
||||
{"type":"hotp","uuid":"2","name":"dave","issuer":"Counter",
|
||||
"info":{"secret":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ","algo":"SHA1","digits":6,"counter":1}}]}}
|
||||
END;
|
||||
|
||||
AEGIS_ENCRYPTED :: "{\"version\":1,\"header\":{\"slots\":[{\"type\":1}],\"params\":{}},\"db\":\"c2VhbGVk\"}"
|
||||
|
||||
// Ente Auth's plain text export: one link per line, with its own fields.
|
||||
ENTE :: #string END
|
||||
otpauth://totp/First:one?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=First&algorithm=sha1&digits=6&period=30&codeDisplay=%7B%22pinned%22%3Afalse%2C%22tags%22%3A%5B%5D%7D
|
||||
otpauth://totp/Second:two?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Second&algorithm=sha1&digits=6&period=30
|
||||
not-a-link
|
||||
END;
|
||||
|
||||
Code :: (index: s32, unix: s64, output: []u8) -> string {
|
||||
account := *export_accounts[index]
|
||||
return CodeNow(account.kind, account.key[:], account.key_count, account.digits, account.period, unix, output)
|
||||
}
|
||||
|
||||
#program_export
|
||||
Run :: () -> s32 {
|
||||
code: [12]u8
|
||||
result := ReadExport(MIGRATION)
|
||||
if result.count != 2 || result.skipped != 1 || result.encrypted {
|
||||
return 10
|
||||
}
|
||||
if TextUntilNul(export_accounts[0].issuer[:]) != "Example Co" ||
|
||||
TextUntilNul(export_accounts[0].name[:]) != "[email protected]" || export_accounts[0].digits != 6 ||
|
||||
Code(0, 59, code[:]) != "287082" {
|
||||
return 11
|
||||
}
|
||||
if TextUntilNul(export_accounts[1].issuer[:]) != "Second" || TextUntilNul(export_accounts[1].name[:]) != "bob" ||
|
||||
export_accounts[1].kind != HASH_SHA256 || Code(1, 59, code[:]) != "46119246" {
|
||||
return 12
|
||||
}
|
||||
result = ReadExport(AEGIS)
|
||||
if result.count != 1 || result.skipped != 1 || TextUntilNul(export_accounts[0].issuer[:]) != "Third" ||
|
||||
export_accounts[0].kind != HASH_SHA512 || export_accounts[0].digits != 7 || export_accounts[0].period != 60 {
|
||||
return 20
|
||||
}
|
||||
result = ReadExport(AEGIS_ENCRYPTED)
|
||||
if result.count != 0 || !result.encrypted {
|
||||
return 21
|
||||
}
|
||||
result = ReadExport(ENTE)
|
||||
if result.count != 2 || result.skipped != 1 || TextUntilNul(export_accounts[1].name[:]) != "two" {
|
||||
return 30
|
||||
}
|
||||
ClearExport()
|
||||
if export_accounts[0].secret[0] != cast(u8)0 || export_accounts[0].key_count != 0 {
|
||||
return 31
|
||||
}
|
||||
// Websites: hosts or addresses, kept in the account's link.
|
||||
sites: [256]u8
|
||||
if !NormalizeSites("https://GitHub.com/login, account.proton.me", sites[:]) ||
|
||||
TextUntilNul(sites[:]) != "github.com account.proton.me" || NormalizeSites("github", sites[:]) ||
|
||||
NormalizeSites("[email protected]", sites[:]) || NormalizeSites("github..com", sites[:]) {
|
||||
return 40
|
||||
}
|
||||
account: Account
|
||||
again: Account
|
||||
saved: [1024]u8
|
||||
if !ParseLink("otpauth://totp/Example:alice?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&sites=example.com%20login.example.org", *account) ||
|
||||
TextUntilNul(account.sites[:]) != "example.com login.example.org" ||
|
||||
!ParseLink(LinkText(*account, saved[:]), *again) || TextUntilNul(again.sites[:]) != "example.com login.example.org" {
|
||||
return 41
|
||||
}
|
||||
encoded: [64]u8
|
||||
key := "12345678901234567890"
|
||||
bytes: [20]u8
|
||||
for index: 0..19 {
|
||||
bytes[index] = key[index]
|
||||
}
|
||||
if Base32Encode(bytes[:], 20, encoded[:]) != 32 || TextUntilNul(encoded[:]) != "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" ||
|
||||
Base32Encode(bytes[:], 1, encoded[:]) != 2 || TextUntilNul(encoded[:]) != "GE" {
|
||||
return 42
|
||||
}
|
||||
id: [33]u8
|
||||
if RecordIdFor(TextView(saved[0:0]), id[:]) != "e3b0c44298fc1c149afbf4c8996fb924" {
|
||||
return 43
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -356,44 +356,9 @@ Base32Decode :: (text: string, output: []u8) -> s32 {
|
||||
return count
|
||||
}
|
||||
|
||||
// Encodes bytes as Base32 without padding. Returns the length, or -1 when
|
||||
// it does not fit in output.
|
||||
Base32Encode :: (bytes: []u8, count: s32, output: []u8) -> s32 {
|
||||
alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
|
||||
buffer: u32 = 0
|
||||
bits: s32 = 0
|
||||
used: s32 = 0
|
||||
index: s32 = 0
|
||||
while index < count {
|
||||
buffer = (buffer << cast(u32)8) | cast(u32)bytes[index]
|
||||
bits += 8
|
||||
index += 1
|
||||
while bits >= 5 {
|
||||
bits -= 5
|
||||
if used >= cast(s32)output.count - 1 {
|
||||
return -1
|
||||
}
|
||||
output[used] = alphabet[cast(s64)((buffer >> cast(u32)bits) & cast(u32)31)]
|
||||
used += 1
|
||||
}
|
||||
}
|
||||
if bits > 0 {
|
||||
if used >= cast(s32)output.count - 1 {
|
||||
return -1
|
||||
}
|
||||
output[used] = alphabet[cast(s64)((buffer << cast(u32)(5 - bits)) & cast(u32)31)]
|
||||
used += 1
|
||||
}
|
||||
output[used] = cast(u8)0
|
||||
return used
|
||||
}
|
||||
|
||||
Account :: struct {
|
||||
issuer: [64]u8
|
||||
name: [128]u8
|
||||
// The websites where this account signs in, such as github.com,
|
||||
// separated by spaces.
|
||||
sites: [256]u8
|
||||
// The secret as Base32, kept to save it again.
|
||||
secret: [256]u8
|
||||
key: [KEY_LIMIT]u8
|
||||
@@ -548,80 +513,6 @@ CopyLimited :: (text: string, output: []u8) -> bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// A host name such as github.com or account.proton.me.
|
||||
ValidHost :: (host: string) -> bool {
|
||||
if host.count < 3 || host.count > 253 || host[0] == cast(u8)46 || host[0] == cast(u8)45 ||
|
||||
host[host.count - 1] == cast(u8)46 {
|
||||
return false
|
||||
}
|
||||
dot := false
|
||||
index: s64 = 0
|
||||
while index < host.count {
|
||||
byte := Lower(host[index])
|
||||
letter := byte >= cast(u8)97 && byte <= cast(u8)122
|
||||
digit := byte >= cast(u8)48 && byte <= cast(u8)57
|
||||
if byte == cast(u8)46 {
|
||||
if host[index - 1] == cast(u8)46 {
|
||||
return false
|
||||
}
|
||||
dot = true
|
||||
} else if !letter && !digit && byte != cast(u8)45 {
|
||||
return false
|
||||
}
|
||||
index += 1
|
||||
}
|
||||
return dot
|
||||
}
|
||||
|
||||
// Reads websites separated by spaces or commas, each a host or an address
|
||||
// such as https://github.com/login, into lowercase hosts separated by
|
||||
// single spaces. False when one is not a website.
|
||||
NormalizeSites :: (text: string, output: []u8) -> bool {
|
||||
used: s64 = 0
|
||||
output[0] = cast(u8)0
|
||||
start: s64 = 0
|
||||
while start < text.count {
|
||||
while start < text.count && (text[start] <= cast(u8)32 || text[start] == cast(u8)44) {
|
||||
start += 1
|
||||
}
|
||||
end := start
|
||||
while end < text.count && text[end] > cast(u8)32 && text[end] != cast(u8)44 {
|
||||
end += 1
|
||||
}
|
||||
if end > start {
|
||||
site := text[start:end]
|
||||
if StartsWithIgnoringCase(site, "https://") {
|
||||
site = site[8:site.count]
|
||||
} else if StartsWithIgnoringCase(site, "http://") {
|
||||
site = site[7:site.count]
|
||||
}
|
||||
host_end: s64 = 0
|
||||
while host_end < site.count && site[host_end] != cast(u8)47 && site[host_end] != cast(u8)63 &&
|
||||
site[host_end] != cast(u8)35 {
|
||||
host_end += 1
|
||||
}
|
||||
host := site[0:host_end]
|
||||
if !ValidHost(host) || used + host.count + 1 >= output.count {
|
||||
output[0] = cast(u8)0
|
||||
return false
|
||||
}
|
||||
if used > 0 {
|
||||
output[used] = cast(u8)32
|
||||
used += 1
|
||||
}
|
||||
index: s64 = 0
|
||||
while index < host.count {
|
||||
output[used] = Lower(host[index])
|
||||
used += 1
|
||||
index += 1
|
||||
}
|
||||
output[used] = cast(u8)0
|
||||
}
|
||||
start = end
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Reads an otpauth://totp/ link. HOTP and other kinds are refused.
|
||||
ParseLink :: (link: string, account: *Account) -> bool {
|
||||
account.* = Account.{.kind = HASH_SHA1, .digits = 6, .period = 30}
|
||||
@@ -667,11 +558,8 @@ ParseLink :: (link: string, account: *Account) -> bool {
|
||||
while equals < pair.count && pair[equals] != cast(u8)61 {
|
||||
equals += 1
|
||||
}
|
||||
key := pair[0:equals]
|
||||
// Other apps add their own fields, such as Ente Auth's codeDisplay.
|
||||
known := key == "secret" || key == "issuer" || key == "algorithm" || key == "digits" ||
|
||||
key == "period" || key == "sites"
|
||||
if equals < pair.count && known {
|
||||
if equals < pair.count {
|
||||
key := pair[0:equals]
|
||||
value: [256]u8
|
||||
if !Unescape(pair[equals + 1:pair.count], value[:]) {
|
||||
return false
|
||||
@@ -701,9 +589,6 @@ ParseLink :: (link: string, account: *Account) -> bool {
|
||||
if account.period < 1 || account.period > 300 {
|
||||
return false
|
||||
}
|
||||
} else if key == "sites" {
|
||||
// An unreadable list only loses the websites, not the account.
|
||||
unused NormalizeSites(text, account.sites[:])
|
||||
}
|
||||
}
|
||||
position = end + 1
|
||||
@@ -784,29 +669,8 @@ LinkText :: (account: *Account, output: []u8) -> string {
|
||||
}
|
||||
used = AppendText(output, used, "&period=")
|
||||
used = AppendText(output, used, TextView(period[8 - length:8]))
|
||||
sites := TextUntilNul(account.sites[:])
|
||||
if sites != "" {
|
||||
used = AppendText(output, used, "&sites=")
|
||||
used = AppendEscaped(output, used, sites)
|
||||
}
|
||||
if used < 0 {
|
||||
return ""
|
||||
}
|
||||
return TextView(output[0:used])
|
||||
}
|
||||
|
||||
// An account's record id: the first 16 bytes of its link's SHA-256 as hex,
|
||||
// so the same account added on two devices is one record.
|
||||
RecordIdFor :: (link: string, output: []u8) -> string {
|
||||
hex := "0123456789abcdef"
|
||||
digest := Sha256(link)
|
||||
for at: 0..15 {
|
||||
output[at * 2] = hex[cast(s64)(digest[at] >> cast(u8)4)]
|
||||
output[at * 2 + 1] = hex[cast(s64)(digest[at] & cast(u8)15)]
|
||||
}
|
||||
output[32] = cast(u8)0
|
||||
for at: 0..31 {
|
||||
digest[at] = cast(u8)0
|
||||
}
|
||||
return TextView(output[0:32])
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
// Evaluates calculator expressions: + − × ÷ (also - * /), ^ for powers,
|
||||
// postfix %, ², ³, ! and ⁻¹, unary signs, brackets, the functions sin cos tan
|
||||
// and their inverses (sin⁻¹ or asin) and hyperbolic forms, ln, log, √, ∛,
|
||||
// abs and exp, the constants π, e and Ans, and E for a power of ten, as in
|
||||
// 6.02E23. A number, constant or function next to another multiplies, so
|
||||
// 2π and 3sin(30) work. Brackets left open at the end are closed there.
|
||||
// a postfix % for percent, unary signs and brackets. Brackets left open at
|
||||
// the end are closed there.
|
||||
#import "text_buffer"
|
||||
#import "number_text"
|
||||
#import "math"
|
||||
|
||||
Answer :: struct {
|
||||
valid: bool
|
||||
@@ -17,13 +13,6 @@ Answer :: struct {
|
||||
source: string;
|
||||
position: s32;
|
||||
failure: string;
|
||||
// Trigonometric angles are degrees when set, otherwise radians.
|
||||
degrees: bool;
|
||||
// The last result, for Ans.
|
||||
last_answer: float64;
|
||||
|
||||
PI_VALUE :: 3.141592653589793
|
||||
E_VALUE :: 2.718281828459045
|
||||
|
||||
EvaluateExpression :: (text: string) -> Answer {
|
||||
source = text
|
||||
@@ -34,18 +23,12 @@ EvaluateExpression :: (text: string) -> Answer {
|
||||
if failure == "" && position < cast(s32)source.count {
|
||||
failure = "Cannot read this expression"
|
||||
}
|
||||
if failure == "" && value != value {
|
||||
failure = "Not a real number"
|
||||
}
|
||||
if failure == "" && !Finite(value) {
|
||||
failure = "Result is too large"
|
||||
}
|
||||
if failure != "" {
|
||||
return Answer.{.error = failure}
|
||||
}
|
||||
if value == 0.0 {
|
||||
value = 0.0
|
||||
}
|
||||
return Answer.{.valid = true, .value = value}
|
||||
}
|
||||
|
||||
@@ -59,7 +42,7 @@ SkipSpaces :: () {
|
||||
}
|
||||
}
|
||||
|
||||
// Whether the next text is the given one, consuming it when it is.
|
||||
// Whether the next character is the given one, consuming it when it is.
|
||||
Take :: (symbol: string) -> bool {
|
||||
SkipSpaces()
|
||||
end := position + cast(s32)symbol.count
|
||||
@@ -70,13 +53,6 @@ Take :: (symbol: string) -> bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Whether the next text is the given one, without consuming it.
|
||||
Peek :: (symbol: string) -> bool {
|
||||
SkipSpaces()
|
||||
end := position + cast(s32)symbol.count
|
||||
return end <= cast(s32)source.count && source[position:end] == symbol
|
||||
}
|
||||
|
||||
ParseSum :: () -> float64 {
|
||||
value := ParseProduct()
|
||||
while failure == "" {
|
||||
@@ -103,8 +79,6 @@ ParseProduct :: () -> float64 {
|
||||
return 0.0
|
||||
}
|
||||
value /= divisor
|
||||
} else if StartsFactor() {
|
||||
value *= ParsePower()
|
||||
} else {
|
||||
return value
|
||||
}
|
||||
@@ -112,23 +86,6 @@ ParseProduct :: () -> float64 {
|
||||
return value
|
||||
}
|
||||
|
||||
// A factor follows without an operator, so the two multiply.
|
||||
StartsFactor :: () -> bool {
|
||||
SkipSpaces()
|
||||
if position >= cast(s32)source.count {
|
||||
return false
|
||||
}
|
||||
byte := source[position]
|
||||
if IsDigit(byte) || byte == cast(u8)46 || byte == cast(u8)40 {
|
||||
return true
|
||||
}
|
||||
// Letters start functions and constants; E alone is a number's exponent.
|
||||
if byte >= cast(u8)97 && byte <= cast(u8)122 || byte == cast(u8)65 {
|
||||
return true
|
||||
}
|
||||
return Peek("π") || Peek("√") || Peek("∛")
|
||||
}
|
||||
|
||||
ParseSigned :: () -> float64 {
|
||||
if Take("-") || Take("−") {
|
||||
return 0.0 - ParseSigned()
|
||||
@@ -140,7 +97,7 @@ ParseSigned :: () -> float64 {
|
||||
}
|
||||
|
||||
ParsePower :: () -> float64 {
|
||||
base := ParsePostfix()
|
||||
base := ParsePercent()
|
||||
if failure == "" && Take("^") {
|
||||
exponent := ParseSigned()
|
||||
return Power(base, exponent)
|
||||
@@ -148,26 +105,10 @@ ParsePower :: () -> float64 {
|
||||
return base
|
||||
}
|
||||
|
||||
ParsePostfix :: () -> float64 {
|
||||
ParsePercent :: () -> float64 {
|
||||
value := ParseAtom()
|
||||
while failure == "" {
|
||||
if Take("%") {
|
||||
value /= 100.0
|
||||
} else if Take("²") {
|
||||
value *= value
|
||||
} else if Take("³") {
|
||||
value = value * value * value
|
||||
} else if Take("⁻¹") {
|
||||
if value == 0.0 {
|
||||
failure = "Cannot divide by zero"
|
||||
return 0.0
|
||||
}
|
||||
value = 1.0 / value
|
||||
} else if Take("!") {
|
||||
value = Factorial(value)
|
||||
} else {
|
||||
return value
|
||||
}
|
||||
while failure == "" && Take("%") {
|
||||
value /= 100.0
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -177,251 +118,17 @@ ParseAtom :: () -> float64 {
|
||||
return 0.0
|
||||
}
|
||||
if Take("(") {
|
||||
return Bracketed()
|
||||
}
|
||||
if Take("π") || Take("pi") {
|
||||
return PI_VALUE
|
||||
}
|
||||
if Take("Ans") {
|
||||
return last_answer
|
||||
}
|
||||
if Take("√") || Take("sqrt") {
|
||||
return Root(Argument(), 2)
|
||||
}
|
||||
if Take("∛") || Take("cbrt") {
|
||||
return Root(Argument(), 3)
|
||||
}
|
||||
// Longer names first: sinh⁻¹ before sinh before sin.
|
||||
names: [21]string = .["sinh⁻¹", "cosh⁻¹", "tanh⁻¹", "asinh", "acosh", "atanh",
|
||||
"sin⁻¹", "cos⁻¹", "tan⁻¹", "asin", "acos", "atan",
|
||||
"sinh", "cosh", "tanh", "sin", "cos", "tan", "ln", "log", "abs"]
|
||||
operations: [21]s32 = .[10, 11, 12, 10, 11, 12, 4, 5, 6, 4, 5, 6, 7, 8, 9, 1, 2, 3, 13, 14, 15]
|
||||
index: s32 = 0
|
||||
while index < 21 {
|
||||
if Take(names[index]) {
|
||||
return Apply(operations[index], Argument())
|
||||
value := ParseSum()
|
||||
// A bracket still open at the end closes there.
|
||||
SkipSpaces()
|
||||
if !Take(")") && position < cast(s32)source.count {
|
||||
failure = "Missing closing bracket"
|
||||
}
|
||||
index += 1
|
||||
}
|
||||
if Take("exp") {
|
||||
return Exponential(Argument())
|
||||
}
|
||||
if Take("e") {
|
||||
return E_VALUE
|
||||
return value
|
||||
}
|
||||
return ParseNumber()
|
||||
}
|
||||
|
||||
Bracketed :: () -> float64 {
|
||||
value := ParseSum()
|
||||
// A bracket still open at the end closes there.
|
||||
SkipSpaces()
|
||||
if !Take(")") && position < cast(s32)source.count && failure == "" {
|
||||
failure = "Missing closing bracket"
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// A function's argument: a bracketed expression, or the signed value that
|
||||
// follows, as in √9 or sin 30.
|
||||
Argument :: () -> float64 {
|
||||
if Take("(") {
|
||||
return Bracketed()
|
||||
}
|
||||
return ParseSigned()
|
||||
}
|
||||
|
||||
Apply :: (operation: s32, value: float64) -> float64 {
|
||||
if failure != "" {
|
||||
return 0.0
|
||||
}
|
||||
if operation == 1 {
|
||||
return Sine(value)
|
||||
}
|
||||
if operation == 2 {
|
||||
return Cosine(value)
|
||||
}
|
||||
if operation == 3 {
|
||||
return Tangent(value)
|
||||
}
|
||||
if operation >= 4 && operation <= 6 {
|
||||
if operation != 6 && (value > 1.0 || value < -1.0) {
|
||||
failure = "Not a real number"
|
||||
return 0.0
|
||||
}
|
||||
angle := ifx operation == 4 then Asin(value) else ifx operation == 5 then Acos(value) else Atan(value)
|
||||
return ifx degrees then angle * 180.0 / PI_VALUE else angle
|
||||
}
|
||||
if operation == 7 {
|
||||
return Sinh(value)
|
||||
}
|
||||
if operation == 8 {
|
||||
return Cosh(value)
|
||||
}
|
||||
if operation == 9 {
|
||||
return Tanh(value)
|
||||
}
|
||||
if operation == 10 {
|
||||
return Asinh(value)
|
||||
}
|
||||
if operation == 11 {
|
||||
return Checked(Acosh(value))
|
||||
}
|
||||
if operation == 12 {
|
||||
if value >= 1.0 || value <= -1.0 {
|
||||
failure = ifx value == 1.0 || value == -1.0 then "Result is too large" else "Not a real number"
|
||||
return 0.0
|
||||
}
|
||||
return Atanh(value)
|
||||
}
|
||||
if operation == 13 || operation == 14 {
|
||||
if value <= 0.0 {
|
||||
failure = ifx value == 0.0 then "Result is too large" else "Not a real number"
|
||||
return 0.0
|
||||
}
|
||||
return ifx operation == 13 then Log(value) else Log10Exact(value)
|
||||
}
|
||||
return ifx value < 0.0 then 0.0 - value else value
|
||||
}
|
||||
|
||||
// A NaN from a function outside its domain is an error, not a value.
|
||||
Checked :: (value: float64) -> float64 {
|
||||
if value != value && failure == "" {
|
||||
failure = "Not a real number"
|
||||
return 0.0
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// log10 exactly for powers of ten, which people expect to be whole.
|
||||
Log10Exact :: (value: float64) -> float64 {
|
||||
result := Log10(value)
|
||||
nearest := cast(float64)RoundToInteger(result)
|
||||
if nearest - result < 1.0e-12 && result - nearest < 1.0e-12 && Power(10.0, nearest) == value {
|
||||
return nearest
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// An angle in degrees, reduced to [0, 360).
|
||||
Degrees360 :: (value: float64) -> float64 {
|
||||
turns := cast(float64)RoundToInteger(value / 360.0)
|
||||
reduced := value - turns * 360.0
|
||||
if reduced < 0.0 {
|
||||
reduced += 360.0
|
||||
}
|
||||
return reduced
|
||||
}
|
||||
|
||||
Radians :: (value: float64) -> float64 {
|
||||
return ifx degrees then value * PI_VALUE / 180.0 else value
|
||||
}
|
||||
|
||||
// In degrees, whole quarter turns give exact results: sin 180° is 0.
|
||||
Sine :: (value: float64) -> float64 {
|
||||
if degrees && value < 1.0e15 && value > -1.0e15 {
|
||||
reduced := Degrees360(value)
|
||||
if reduced == 0.0 || reduced == 180.0 {
|
||||
return 0.0
|
||||
}
|
||||
if reduced == 90.0 {
|
||||
return 1.0
|
||||
}
|
||||
if reduced == 270.0 {
|
||||
return -1.0
|
||||
}
|
||||
if reduced == 30.0 || reduced == 150.0 {
|
||||
return 0.5
|
||||
}
|
||||
if reduced == 210.0 || reduced == 330.0 {
|
||||
return -0.5
|
||||
}
|
||||
}
|
||||
return Sin(Radians(value))
|
||||
}
|
||||
|
||||
Cosine :: (value: float64) -> float64 {
|
||||
if degrees && value < 1.0e15 && value > -1.0e15 {
|
||||
reduced := Degrees360(value)
|
||||
if reduced == 90.0 || reduced == 270.0 {
|
||||
return 0.0
|
||||
}
|
||||
if reduced == 0.0 {
|
||||
return 1.0
|
||||
}
|
||||
if reduced == 180.0 {
|
||||
return -1.0
|
||||
}
|
||||
if reduced == 60.0 || reduced == 300.0 {
|
||||
return 0.5
|
||||
}
|
||||
if reduced == 120.0 || reduced == 240.0 {
|
||||
return -0.5
|
||||
}
|
||||
}
|
||||
return Cos(Radians(value))
|
||||
}
|
||||
|
||||
Tangent :: (value: float64) -> float64 {
|
||||
if degrees && value < 1.0e15 && value > -1.0e15 {
|
||||
reduced := Degrees360(value)
|
||||
if reduced == 90.0 || reduced == 270.0 {
|
||||
failure = "Undefined"
|
||||
return 0.0
|
||||
}
|
||||
if reduced == 0.0 || reduced == 180.0 {
|
||||
return 0.0
|
||||
}
|
||||
if reduced == 45.0 || reduced == 225.0 {
|
||||
return 1.0
|
||||
}
|
||||
if reduced == 135.0 || reduced == 315.0 {
|
||||
return -1.0
|
||||
}
|
||||
}
|
||||
return Tan(Radians(value))
|
||||
}
|
||||
|
||||
Root :: (value: float64, degree: s32) -> float64 {
|
||||
if failure != "" {
|
||||
return 0.0
|
||||
}
|
||||
if degree == 2 {
|
||||
if value < 0.0 {
|
||||
failure = "Not a real number"
|
||||
return 0.0
|
||||
}
|
||||
return Sqrt(value)
|
||||
}
|
||||
return Cbrt(value)
|
||||
}
|
||||
|
||||
Exponential :: (value: float64) -> float64 {
|
||||
if failure != "" {
|
||||
return 0.0
|
||||
}
|
||||
return Exp(value)
|
||||
}
|
||||
|
||||
Factorial :: (value: float64) -> float64 {
|
||||
whole := RoundToInteger(value)
|
||||
if value < 0.0 || cast(float64)whole != value {
|
||||
failure = "Factorial needs a whole number"
|
||||
return 0.0
|
||||
}
|
||||
if whole > 170 {
|
||||
failure = "Result is too large"
|
||||
return 0.0
|
||||
}
|
||||
result: float64 = 1.0
|
||||
factor: s64 = 2
|
||||
while factor <= whole {
|
||||
result *= cast(float64)factor
|
||||
factor += 1
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
ParseNumber :: () -> float64 {
|
||||
SkipSpaces()
|
||||
value: float64 = 0.0
|
||||
@@ -443,29 +150,6 @@ ParseNumber :: () -> float64 {
|
||||
}
|
||||
if digits == 0 {
|
||||
failure = ifx position >= cast(s32)source.count then "Incomplete expression" else "Cannot read this expression"
|
||||
return value
|
||||
}
|
||||
// E and a whole power of ten: 6.02E23, 1E−5.
|
||||
if position < cast(s32)source.count && source[position] == cast(u8)69 {
|
||||
position += 1
|
||||
negative := false
|
||||
if Take("-") || Take("−") {
|
||||
negative = true
|
||||
} else {
|
||||
unused Take("+")
|
||||
}
|
||||
power: s64 = 0
|
||||
power_digits: s32 = 0
|
||||
while position < cast(s32)source.count && IsDigit(source[position]) && power < 100000 {
|
||||
power = power * 10 + cast(s64)(source[position] - cast(u8)48)
|
||||
position += 1
|
||||
power_digits += 1
|
||||
}
|
||||
if power_digits == 0 {
|
||||
failure = ifx position >= cast(s32)source.count then "Incomplete expression" else "Cannot read this expression"
|
||||
return value
|
||||
}
|
||||
value *= Power(10.0, cast(float64)(ifx negative then 0 - power else power))
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -474,22 +158,35 @@ IsDigit :: (byte: u8) -> bool {
|
||||
return byte >= cast(u8)48 && byte <= cast(u8)57
|
||||
}
|
||||
|
||||
// Whole exponents multiply exactly; others use the real power, which a
|
||||
// negative base does not have.
|
||||
// Whole exponents multiply exactly; others are refused rather than
|
||||
// approximated.
|
||||
Power :: (base: float64, exponent: float64) -> float64 {
|
||||
if failure != "" {
|
||||
whole := cast(s64)exponent
|
||||
if cast(float64)whole != exponent || whole > 4096 || whole < -4096 {
|
||||
failure = "Powers must be whole numbers"
|
||||
return 0.0
|
||||
}
|
||||
if base == 0.0 && exponent < 0.0 {
|
||||
failure = "Cannot divide by zero"
|
||||
return 0.0
|
||||
negative := whole < 0
|
||||
if negative {
|
||||
whole = 0 - whole
|
||||
}
|
||||
whole := cast(float64)RoundToInteger(exponent) == exponent && exponent < 1.0e15 && exponent > -1.0e15
|
||||
if base < 0.0 && !whole {
|
||||
failure = "Not a real number"
|
||||
return 0.0
|
||||
result: float64 = 1.0
|
||||
factor := base
|
||||
while whole > 0 {
|
||||
if whole % 2 == 1 {
|
||||
result *= factor
|
||||
}
|
||||
factor *= factor
|
||||
whole /= 2
|
||||
}
|
||||
return Pow(base, exponent)
|
||||
if negative {
|
||||
if result == 0.0 {
|
||||
failure = "Cannot divide by zero"
|
||||
return 0.0
|
||||
}
|
||||
return 1.0 / result
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Up to ten significant digits; very large and very small numbers use an
|
||||
|
||||
@@ -16,7 +16,6 @@ Refuses :: (expression: string) -> bool {
|
||||
|
||||
#program_export
|
||||
Run :: () -> s32 {
|
||||
degrees = false
|
||||
if !Shows("12+30×2", "72") || !Shows("12+30*2", "72") || !Shows("(1+2)×3", "9") {
|
||||
return 1
|
||||
}
|
||||
@@ -29,48 +28,8 @@ Run :: () -> s32 {
|
||||
if !Shows("0.1+0.2", "0.3") || !Shows("10^20", "1e20") || !Shows("2^-2", "0.25") {
|
||||
return 4
|
||||
}
|
||||
if !Refuses("1÷0") || !Refuses("3+") || !Refuses("4)") || !Refuses("(−8)^0.5") {
|
||||
if !Refuses("1÷0") || !Refuses("2^0.5") || !Refuses("3+") || !Refuses("4)") {
|
||||
return 5
|
||||
}
|
||||
// Powers, roots and logarithms.
|
||||
if !Shows("2^0.5", "1.414213562") || !Shows("√144", "12") || !Shows("√(2)", "1.414213562") ||
|
||||
!Shows("∛27", "3") || !Shows("∛(−8)", "-2") || !Shows("3²", "9") || !Shows("2³", "8") {
|
||||
return 6
|
||||
}
|
||||
if !Shows("ln(e)", "1") || !Shows("log(1000)", "3") || !Shows("e^(2)", "7.389056099") ||
|
||||
!Shows("10^(3)", "1000") || !Shows("exp(1)", "2.718281828") || !Refuses("ln(−1)") || !Refuses("√(−4)") {
|
||||
return 7
|
||||
}
|
||||
// Factorials, reciprocals, constants, Ans and E notation.
|
||||
if !Shows("5!", "120") || !Shows("0!", "1") || !Shows("4⁻¹", "0.25") || !Shows("2π", "6.283185307") ||
|
||||
!Shows("π", "3.141592654") || !Refuses("2.5!") || !Refuses("171!") || !Refuses("0⁻¹") {
|
||||
return 8
|
||||
}
|
||||
last_answer = 21.0
|
||||
if !Shows("Ans×2", "42") || !Shows("6.02E23", "6.02e23") || !Shows("1E−3", "0.001") || !Shows("2(3+4)", "14") ||
|
||||
!Shows("abs(−7)", "7") || !Shows("3sqrt(16)", "12") {
|
||||
return 9
|
||||
}
|
||||
// Radians.
|
||||
if !Shows("sin(π÷2)", "1") || !Shows("cos(0)", "1") || !Shows("tan(π÷4)", "1") ||
|
||||
!Shows("sin⁻¹(1)", "1.570796327") || !Shows("atan(1)×4", "3.141592654") {
|
||||
return 10
|
||||
}
|
||||
// Degrees, with exact quarter turns.
|
||||
degrees = true
|
||||
if !Shows("sin(30)", "0.5") || !Shows("sin(180)", "0") || !Shows("cos(90)", "0") || !Shows("cos(−60)", "0.5") ||
|
||||
!Shows("tan(45)", "1") || !Refuses("tan(90)") || !Shows("sin(390)", "0.5") || !Shows("sin 30 + 1", "1.5") {
|
||||
return 11
|
||||
}
|
||||
if !Shows("sin⁻¹(0.5)", "30") || !Shows("cos⁻¹(0)", "90") || !Shows("tan⁻¹(1)", "45") || !Refuses("asin(2)") {
|
||||
return 12
|
||||
}
|
||||
degrees = false
|
||||
// Hyperbolic functions and their inverses.
|
||||
if !Shows("sinh(1)", "1.175201194") || !Shows("cosh(0)", "1") || !Shows("tanh(1)", "0.761594156") ||
|
||||
!Shows("sinh⁻¹(1)", "0.881373587") || !Shows("cosh⁻¹(2)", "1.316957897") ||
|
||||
!Shows("tanh⁻¹(0.5)", "0.549306144") || !Refuses("acosh(0.5)") || !Refuses("atanh(1)") {
|
||||
return 13
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
// Calculator: a keypad and keyboard calculator. Basic covers ordinary
|
||||
// arithmetic with brackets; Scientific adds trigonometry in degrees or
|
||||
// radians, hyperbolic functions, powers, roots, logarithms, factorials and
|
||||
// constants. It keeps the expression in memory; the mode and angle unit are
|
||||
// saved.
|
||||
// Calculator: a keypad and keyboard calculator for ordinary arithmetic with
|
||||
// brackets. It keeps the expression and the last result in memory only.
|
||||
#import "session"
|
||||
#import "geometry"
|
||||
#import "text_props"
|
||||
@@ -15,8 +12,8 @@
|
||||
#import "box_widget"
|
||||
#import "text_buffer"
|
||||
#import "number_text"
|
||||
#import "kryon/app_context"
|
||||
#import "kryon/app_protocol"
|
||||
#import "werk_app"
|
||||
#import "app_protocol"
|
||||
#import "arithmetic"
|
||||
Icon :: #import "mingcute_regular_counter";
|
||||
DeleteBack :: #import "mingcute_regular_delete_back";
|
||||
@@ -29,13 +26,8 @@ EXPRESSION_LIMIT :: 256
|
||||
expression: [EXPRESSION_LIMIT]u8;
|
||||
expression_length: s32;
|
||||
result_text: [64]u8;
|
||||
// The expression shows the last result, which typing a number replaces.
|
||||
// The expression shows the last result, which typing a digit replaces.
|
||||
showing_result: bool;
|
||||
loaded: bool;
|
||||
scientific: bool;
|
||||
// One-shot shifts for the next scientific function key.
|
||||
second: bool;
|
||||
hyperbolic: bool;
|
||||
|
||||
ExpressionText :: () -> string {
|
||||
return TextView(expression[0:expression_length])
|
||||
@@ -47,26 +39,10 @@ Clear :: () {
|
||||
showing_result = false
|
||||
}
|
||||
|
||||
// Whether text begins a new value rather than continuing the last one: a
|
||||
// result is replaced by a number, constant or function, and continued by
|
||||
// an operator.
|
||||
StartsValue :: (text: string) -> bool {
|
||||
first := text[0]
|
||||
if first >= cast(u8)48 && first <= cast(u8)57 || first == cast(u8)46 || first == cast(u8)40 {
|
||||
return true
|
||||
}
|
||||
if first >= cast(u8)97 && first <= cast(u8)122 || first == cast(u8)65 {
|
||||
return true
|
||||
}
|
||||
count := cast(s32)text.count
|
||||
return count >= 2 && text[0:2] == "π" || count >= 3 && (text[0:3] == "√" || text[0:3] == "∛")
|
||||
}
|
||||
|
||||
Append :: (text: string) {
|
||||
if text.count == 0 {
|
||||
return
|
||||
}
|
||||
if showing_result && StartsValue(text) {
|
||||
starts_number := text[0] >= cast(u8)48 && text[0] <= cast(u8)57 || text[0] == cast(u8)46 ||
|
||||
text[0] == cast(u8)40
|
||||
if showing_result && starts_number {
|
||||
expression_length = 0
|
||||
}
|
||||
showing_result = false
|
||||
@@ -104,7 +80,6 @@ Evaluate :: () {
|
||||
CopyResult(answer.error)
|
||||
return
|
||||
}
|
||||
last_answer = answer.value
|
||||
formatted: [64]u8
|
||||
text := FormatNumber(answer.value, formatted[:])
|
||||
expression_length = 0
|
||||
@@ -122,38 +97,25 @@ CopyResult :: (text: string) {
|
||||
result_text[index] = cast(u8)0
|
||||
}
|
||||
|
||||
// calculator.txt holds "scientific degrees" as 0 or 1 each.
|
||||
LoadSettings :: () {
|
||||
buffer: [16]u8
|
||||
count := ReadStore("calculator.txt", buffer[:])
|
||||
if count >= 3 {
|
||||
scientific = buffer[0] == cast(u8)49
|
||||
degrees = buffer[2] == cast(u8)49
|
||||
} else {
|
||||
degrees = true
|
||||
}
|
||||
}
|
||||
|
||||
SaveSettings :: () {
|
||||
buffer: [3]u8
|
||||
buffer[0] = cast(u8)(ifx scientific then 49 else 48)
|
||||
buffer[1] = cast(u8)32
|
||||
buffer[2] = cast(u8)(ifx degrees then 49 else 48)
|
||||
unused WriteStore("calculator.txt", TextView(buffer[0:3]))
|
||||
}
|
||||
|
||||
// Typed characters and keys act like the keypad; letters spell functions
|
||||
// such as sin and sqrt.
|
||||
// Typed characters and keys act like the keypad.
|
||||
Keyboard :: () {
|
||||
key := AppKey()
|
||||
if key == 257 || key == 335 {
|
||||
Evaluate()
|
||||
}
|
||||
if key == 259 {
|
||||
Backspace()
|
||||
}
|
||||
if key == 256 {
|
||||
Clear()
|
||||
}
|
||||
typed := AppFieldInput().text
|
||||
index: s32 = 0
|
||||
while index < cast(s32)typed.count {
|
||||
byte := typed[index]
|
||||
if byte >= cast(u8)48 && byte <= cast(u8)57 || byte == cast(u8)46 || byte == cast(u8)40 ||
|
||||
byte == cast(u8)41 || byte == cast(u8)43 || byte == cast(u8)45 || byte == cast(u8)37 ||
|
||||
byte == cast(u8)94 || byte == cast(u8)33 || byte >= cast(u8)97 && byte <= cast(u8)122 ||
|
||||
byte >= cast(u8)65 && byte <= cast(u8)90 {
|
||||
byte == cast(u8)94 {
|
||||
Append(typed[index:index + 1])
|
||||
}
|
||||
if byte == cast(u8)42 {
|
||||
@@ -170,197 +132,44 @@ Keyboard :: () {
|
||||
}
|
||||
index += 1
|
||||
}
|
||||
// Text queued before a command key belongs to the expression it acts on.
|
||||
if key == 257 || key == 335 {
|
||||
Evaluate()
|
||||
}
|
||||
if key == 259 {
|
||||
Backspace()
|
||||
}
|
||||
if key == 256 {
|
||||
Clear()
|
||||
}
|
||||
}
|
||||
|
||||
ACTION_INSERT :: 0
|
||||
ACTION_CLEAR :: 1
|
||||
ACTION_DELETE :: 2
|
||||
ACTION_EVALUATE :: 3
|
||||
ACTION_SECOND :: 4
|
||||
ACTION_HYPERBOLIC :: 5
|
||||
ACTION_NEGATE :: 6
|
||||
KEYS :: 20
|
||||
|
||||
Key :: struct {
|
||||
label: string
|
||||
input: string
|
||||
action: s32
|
||||
accent: bool
|
||||
// A function key whose 2nd or hyp shift is used up when pressed.
|
||||
shifted: bool
|
||||
}
|
||||
|
||||
BASIC_KEYS :: 20
|
||||
|
||||
BasicKey :: (index: s32) -> Key {
|
||||
labels: [BASIC_KEYS]string = .["C", "(", ")", "÷",
|
||||
KeyAt :: (index: s32) -> Key {
|
||||
labels: [KEYS]string = .["C", "(", ")", "÷",
|
||||
"7", "8", "9", "×",
|
||||
"4", "5", "6", "−",
|
||||
"1", "2", "3", "+",
|
||||
"", "0", ".", "="]
|
||||
inputs: [BASIC_KEYS]string = .["", "(", ")", "÷",
|
||||
"Delete", "0", ".", "="]
|
||||
inputs: [KEYS]string = .["", "(", ")", "÷",
|
||||
"7", "8", "9", "×",
|
||||
"4", "5", "6", "-",
|
||||
"1", "2", "3", "+",
|
||||
"", "0", ".", ""]
|
||||
key := Key.{.label = labels[index], .input = inputs[index]}
|
||||
return Key.{.label = labels[index], .input = inputs[index], .accent = index == 19}
|
||||
}
|
||||
|
||||
Press :: (index: s32) {
|
||||
if index == 0 {
|
||||
key.action = ACTION_CLEAR
|
||||
Clear()
|
||||
return
|
||||
}
|
||||
if index == 16 {
|
||||
key.action = ACTION_DELETE
|
||||
Backspace()
|
||||
return
|
||||
}
|
||||
if index == 19 {
|
||||
key.action = ACTION_EVALUATE
|
||||
key.accent = true
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// Eight rows of five; = spans the last two columns.
|
||||
SCIENTIFIC_KEYS :: 39
|
||||
|
||||
ScientificKey :: (index: s32) -> Key {
|
||||
labels: [SCIENTIFIC_KEYS]string = .["2nd", "hyp", "sin", "cos", "tan",
|
||||
"x²", "xʸ", "√x", "ln", "log",
|
||||
"(", ")", "1/x", "n!", "π",
|
||||
"C", "", "%", "÷", "e",
|
||||
"7", "8", "9", "×", "EE",
|
||||
"4", "5", "6", "−", "Ans",
|
||||
"1", "2", "3", "+", "|x|",
|
||||
"±", "0", ".", "="]
|
||||
inputs: [SCIENTIFIC_KEYS]string = .["", "", "", "", "",
|
||||
"²", "^", "√(", "ln(", "log(",
|
||||
"(", ")", "⁻¹", "!", "π",
|
||||
"", "", "%", "÷", "e",
|
||||
"7", "8", "9", "×", "E",
|
||||
"4", "5", "6", "-", "Ans",
|
||||
"1", "2", "3", "+", "abs(",
|
||||
"", "0", ".", ""]
|
||||
key := Key.{.label = labels[index], .input = inputs[index]}
|
||||
if index == 0 {
|
||||
key.action = ACTION_SECOND
|
||||
key.accent = second
|
||||
}
|
||||
if index == 1 {
|
||||
key.action = ACTION_HYPERBOLIC
|
||||
key.accent = hyperbolic
|
||||
}
|
||||
if index >= 2 && index <= 4 {
|
||||
names: [3]string = .["sin", "cos", "tan"]
|
||||
hyperbolic_names: [3]string = .["sinh", "cosh", "tanh"]
|
||||
inverse_names: [3]string = .["sin⁻¹", "cos⁻¹", "tan⁻¹"]
|
||||
inverse_hyperbolic_names: [3]string = .["sinh⁻¹", "cosh⁻¹", "tanh⁻¹"]
|
||||
name := names[index - 2]
|
||||
if hyperbolic {
|
||||
name = ifx second then inverse_hyperbolic_names[index - 2] else hyperbolic_names[index - 2]
|
||||
} else if second {
|
||||
name = inverse_names[index - 2]
|
||||
}
|
||||
key.label = name
|
||||
key.shifted = true
|
||||
}
|
||||
if second {
|
||||
if index == 5 {
|
||||
key.label = "x³"
|
||||
key.input = "³"
|
||||
}
|
||||
if index == 6 {
|
||||
key.label = "ʸ√x"
|
||||
key.input = "^(1÷"
|
||||
}
|
||||
if index == 7 {
|
||||
key.label = "∛x"
|
||||
key.input = "∛("
|
||||
}
|
||||
if index == 8 {
|
||||
key.label = "eˣ"
|
||||
key.input = "e^("
|
||||
}
|
||||
if index == 9 {
|
||||
key.label = "10ˣ"
|
||||
key.input = "10^("
|
||||
}
|
||||
}
|
||||
if index >= 5 && index <= 9 {
|
||||
key.shifted = true
|
||||
}
|
||||
if index == 15 {
|
||||
key.action = ACTION_CLEAR
|
||||
}
|
||||
if index == 16 {
|
||||
key.action = ACTION_DELETE
|
||||
}
|
||||
if index == 35 {
|
||||
key.action = ACTION_NEGATE
|
||||
}
|
||||
if index == 38 {
|
||||
key.action = ACTION_EVALUATE
|
||||
key.accent = true
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
Press :: (key: Key) {
|
||||
if key.action == ACTION_CLEAR {
|
||||
Clear()
|
||||
} else if key.action == ACTION_DELETE {
|
||||
Backspace()
|
||||
} else if key.action == ACTION_EVALUATE {
|
||||
Evaluate()
|
||||
} else if key.action == ACTION_SECOND {
|
||||
second = !second
|
||||
} else if key.action == ACTION_HYPERBOLIC {
|
||||
hyperbolic = !hyperbolic
|
||||
} else if key.action == ACTION_NEGATE {
|
||||
Append("−")
|
||||
} else if key.input != "" {
|
||||
Append(key.input)
|
||||
} else {
|
||||
// A trigonometric key: its name and an opening bracket.
|
||||
text: [24]u8
|
||||
used: s32 = AppendTo(text[:], 0, key.label)
|
||||
used = AppendTo(text[:], used, "(")
|
||||
Append(TextView(text[0:used]))
|
||||
}
|
||||
if key.shifted {
|
||||
second = false
|
||||
hyperbolic = false
|
||||
}
|
||||
}
|
||||
|
||||
Tab :: (session: Session, id: s32, label: string, bounds: Rectangle, active: bool) -> bool {
|
||||
props := ButtonProps.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
|
||||
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
|
||||
if active {
|
||||
props.tone = ButtonTone.ButtonToneAccent
|
||||
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
|
||||
}
|
||||
return Button(session, props) != 0
|
||||
}
|
||||
|
||||
DrawKey :: (session: Session, index: s32, key: Key, bounds: Rectangle) {
|
||||
props := ButtonProps.{.key = cast(u64)(100 + index), .id = 100 + index, .bounds = bounds,
|
||||
.label = key.label,
|
||||
.tone = cast(ButtonTone)(ifx key.accent then ButtonToneAccent else ButtonToneNeutral),
|
||||
.emphasis = cast(ButtonEmphasis)(ifx key.accent then ButtonEmphasisFilled else ButtonEmphasisSoft)}
|
||||
// Delete is an icon on a key as wide as the others.
|
||||
if key.action == ACTION_DELETE {
|
||||
props.icon_shape = DeleteBack.Shape
|
||||
props.label = ""
|
||||
}
|
||||
if Button(session, props) != 0 {
|
||||
Press(key)
|
||||
return
|
||||
}
|
||||
Append(KeyAt(index).input)
|
||||
}
|
||||
|
||||
Draw :: () {
|
||||
@@ -368,74 +177,52 @@ Draw :: () {
|
||||
area := AppBounds()
|
||||
gap: float32 = 8.0
|
||||
width := area.width - 32.0
|
||||
if width > 460.0 {
|
||||
width = 460.0
|
||||
if width > 420.0 {
|
||||
width = 420.0
|
||||
}
|
||||
left := area.x + (area.width - width) * 0.5
|
||||
top := area.y + 12.0
|
||||
half := (width - gap) / 2.0
|
||||
if Tab(session, 1, "Basic", Rectangle.{left, top, half, 36.0}, !scientific) && scientific {
|
||||
scientific = false
|
||||
SaveSettings()
|
||||
}
|
||||
if Tab(session, 2, "Scientific", Rectangle.{left + half + gap, top, half, 36.0}, scientific) && !scientific {
|
||||
scientific = true
|
||||
SaveSettings()
|
||||
}
|
||||
top += 36.0 + gap
|
||||
display_height: float32 = ifx scientific then 104.0 else 112.0
|
||||
display := Rectangle.{left, top, width, display_height}
|
||||
Box(session, BoxProps.{.key = cast(u64)3, .bounds = display, .radius = 12.0})
|
||||
top := area.y + 16.0
|
||||
display := Rectangle.{left, top, width, 112.0}
|
||||
Box(session, BoxProps.{.key = cast(u64)1, .bounds = display, .radius = 12.0})
|
||||
shown := ExpressionText()
|
||||
if shown == "" {
|
||||
shown = "0"
|
||||
}
|
||||
font: s32 = 32
|
||||
if shown.count > 18 {
|
||||
font = 24
|
||||
}
|
||||
if shown.count > 28 {
|
||||
font = 18
|
||||
}
|
||||
Text(session, TextProps.{.key = cast(u64)4,
|
||||
.bounds = Rectangle.{left + 16.0, top + 14.0, width - 32.0, 48.0},
|
||||
.text = shown, .font = font, .align = TextAlign.TextAlignEnd, .wrap = TextWrap.TextWrapEllipsis})
|
||||
Text(session, TextProps.{.key = cast(u64)5,
|
||||
.bounds = Rectangle.{left + 16.0, top + display_height - 36.0, width - 32.0, 24.0},
|
||||
Text(session, TextProps.{.key = cast(u64)2,
|
||||
.bounds = Rectangle.{left + 16.0, top + 16.0, width - 32.0, 48.0},
|
||||
.text = shown, .font = 32, .align = TextAlign.TextAlignEnd, .wrap = TextWrap.TextWrapEllipsis})
|
||||
Text(session, TextProps.{.key = cast(u64)3,
|
||||
.bounds = Rectangle.{left + 16.0, top + 72.0, width - 32.0, 24.0},
|
||||
.text = TextUntilNul(result_text[:]), .font = 16, .align = TextAlign.TextAlignEnd})
|
||||
if scientific {
|
||||
// The angle unit, switched by tapping it.
|
||||
unit := ButtonProps.{.key = cast(u64)6, .id = 6, .bounds = Rectangle.{left + 10.0, top + display_height - 38.0, 64.0, 28.0},
|
||||
.label = ifx degrees then "DEG" else "RAD", .size = ControlSize.ControlSizeSmall,
|
||||
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
|
||||
if Button(session, unit) != 0 {
|
||||
degrees = !degrees
|
||||
SaveSettings()
|
||||
}
|
||||
}
|
||||
pad_top := top + display_height + gap * 2.0
|
||||
columns: s32 = ifx scientific then 5 else 4
|
||||
rows: s32 = ifx scientific then 8 else 5
|
||||
key_width := (width - gap * cast(float32)(columns - 1)) / cast(float32)columns
|
||||
key_height := (area.y + area.height - 16.0 - pad_top - gap * cast(float32)(rows - 1)) / cast(float32)rows
|
||||
pad_top := top + 112.0 + gap * 2.0
|
||||
rows: float32 = 5.0
|
||||
key_width := (width - gap * 3.0) / 4.0
|
||||
key_height := (area.y + area.height - 16.0 - pad_top - gap * (rows - 1.0)) / rows
|
||||
if key_height > 72.0 {
|
||||
key_height = 72.0
|
||||
}
|
||||
if key_height < 34.0 {
|
||||
key_height = 34.0
|
||||
if key_height < 36.0 {
|
||||
key_height = 36.0
|
||||
}
|
||||
count: s32 = ifx scientific then SCIENTIFIC_KEYS else BASIC_KEYS
|
||||
index: s32 = 0
|
||||
while index < count {
|
||||
key := ifx scientific then ScientificKey(index) else BasicKey(index)
|
||||
column := cast(float32)(index % columns)
|
||||
row := cast(float32)(index / columns)
|
||||
while index < KEYS {
|
||||
key := KeyAt(index)
|
||||
column := cast(float32)(index % 4)
|
||||
row := cast(float32)(index / 4)
|
||||
bounds := Rectangle.{left + column * (key_width + gap), pad_top + row * (key_height + gap),
|
||||
key_width, key_height}
|
||||
if scientific && index == SCIENTIFIC_KEYS - 1 {
|
||||
bounds.width = key_width * 2.0 + gap
|
||||
props := ButtonProps.{.key = cast(u64)(100 + index), .id = 100 + index, .bounds = bounds,
|
||||
.label = key.label,
|
||||
.tone = cast(ButtonTone)(ifx key.accent then ButtonToneAccent else ButtonToneNeutral),
|
||||
.emphasis = cast(ButtonEmphasis)(ifx key.accent then ButtonEmphasisFilled else ButtonEmphasisSoft)}
|
||||
// Delete is an icon on a key as wide as the others.
|
||||
if index == 16 {
|
||||
props.icon_shape = DeleteBack.Shape
|
||||
props.label = ""
|
||||
}
|
||||
if Button(session, props) != 0 {
|
||||
Press(index)
|
||||
}
|
||||
DrawKey(session, index, key, bounds)
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
@@ -443,17 +230,9 @@ Draw :: () {
|
||||
#program_export "CalculatorMain"
|
||||
Main :: () -> s32 {
|
||||
if AppMode() == APP_IDENTIFY {
|
||||
AppIdentity("calculator")
|
||||
AppDescribe("Calculator", Icon.Shape)
|
||||
return APP_PROTOCOL
|
||||
}
|
||||
if AppMode() != APP_FRAME {
|
||||
return 0
|
||||
}
|
||||
if !loaded {
|
||||
LoadSettings()
|
||||
loaded = true
|
||||
}
|
||||
Keyboard()
|
||||
Draw()
|
||||
return 0
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
#import "control_props"
|
||||
#import "text_buffer"
|
||||
#import "number_text"
|
||||
#import "kryon/app_context"
|
||||
#import "kryon/app_protocol"
|
||||
#import "werk_app"
|
||||
#import "app_protocol"
|
||||
Icon :: #import "mingcute_regular_time";
|
||||
|
||||
VIEW_CLOCK :: 0
|
||||
@@ -32,8 +32,6 @@ running: bool;
|
||||
started_at: float64;
|
||||
elapsed: float64;
|
||||
session: Session;
|
||||
local_offset: s32;
|
||||
local_offset_read_at: float64 = -61.0;
|
||||
|
||||
// The civil date of a day count since 1970-01-01 (proleptic Gregorian).
|
||||
CivilFromDays :: (days: s64) -> Civil {
|
||||
@@ -80,15 +78,11 @@ AppendNumber :: (output: []u8, used: s32, value: s64) -> s32 {
|
||||
|
||||
LocalSeconds :: () -> s64 {
|
||||
now := AppNow()
|
||||
if now - local_offset_read_at > 60.0 {
|
||||
local_offset = AppLocalOffset()
|
||||
local_offset_read_at = now
|
||||
}
|
||||
seconds := cast(s64)now
|
||||
if cast(float64)seconds > now {
|
||||
seconds -= 1
|
||||
}
|
||||
return seconds + cast(s64)local_offset
|
||||
return seconds + cast(s64)AppLocalOffset()
|
||||
}
|
||||
|
||||
TimeText :: (output: []u8) -> string {
|
||||
@@ -265,13 +259,9 @@ Draw :: () {
|
||||
#program_export "ClockMain"
|
||||
Main :: () -> s32 {
|
||||
if AppMode() == APP_IDENTIFY {
|
||||
AppIdentity("clock")
|
||||
AppDescribe("Clock", Icon.Shape)
|
||||
return APP_PROTOCOL
|
||||
}
|
||||
if AppMode() != APP_FRAME {
|
||||
return 0
|
||||
}
|
||||
if !loaded {
|
||||
LoadStopwatch()
|
||||
loaded = true
|
||||
|
||||
@@ -19,7 +19,6 @@ NativeSetTerminal :: (fd: s32, action: s32, state: *void) -> s32 #foreign libc "
|
||||
NativeSession :: () -> s32 #foreign libc "setsid";
|
||||
NativeShutdown :: (fd: s32, direction: s32) -> s32 #foreign libc "shutdown";
|
||||
NativePipe :: (fds: *s32) -> s32 #foreign libc "pipe";
|
||||
NativeDescriptorFlags :: (fd: s32, command: s32, value: s32) -> s32 #foreign libc "fcntl";
|
||||
NativeFork :: () -> s32 #foreign libc "fork";
|
||||
NativeDup :: (source: s32, destination: s32) -> s32 #foreign libc "dup2";
|
||||
NativeExit :: (code: s32) -> void #foreign libc "_exit";
|
||||
@@ -129,37 +128,7 @@ DecryptVault :: (vault: string, output: []u8) -> bool {
|
||||
passphrase: [1024]u8
|
||||
defer { ClearBytes(passphrase[:]) }
|
||||
if !ReadSecret(passphrase[:], "Vault passphrase: ") { return false }
|
||||
// Legacy vaults may wrap their base64 with spaces, tabs or CRLF, which
|
||||
// OpenSSL 3.0 rejects. Send it without whitespace through a pipe that
|
||||
// openssl opens as its input; stdin stays the passphrase.
|
||||
encoded: [60000]u8
|
||||
file := NativeOpen(*path[0], 0)
|
||||
if file < 0 { return false }
|
||||
size: s32 = 0
|
||||
while true {
|
||||
byte: u8
|
||||
count := NativeRead(file, *byte, cast(usize)1)
|
||||
if count != cast(isize)1 { break }
|
||||
if byte == cast(u8)32 || (byte >= cast(u8)9 && byte <= cast(u8)13) { continue }
|
||||
if size >= cast(s32)encoded.count - 1 { unused NativeClose(file); return false }
|
||||
encoded[size] = byte; size += 1
|
||||
}
|
||||
unused NativeClose(file)
|
||||
encoded[size] = cast(u8)10
|
||||
pipe: [2]s32
|
||||
if NativePipe(*pipe[0]) != 0 { return false }
|
||||
// Only openssl keeps the reading end; the writer closes before it starts.
|
||||
if NativeDescriptorFlags(pipe[1], 2, 1) != 0 ||
|
||||
NativeWrite(pipe[1], *encoded[0], cast(usize)(size + 1)) != cast(isize)(size + 1) {
|
||||
unused NativeClose(pipe[0]); unused NativeClose(pipe[1]); return false
|
||||
}
|
||||
unused NativeClose(pipe[1])
|
||||
defer { unused NativeClose(pipe[0]) }
|
||||
digits: [12]u8; place: s32 = 11; number := pipe[0]
|
||||
while true { place -= 1; digits[place] = cast(u8)(48 + number % 10); number /= 10; if number == 0 { break } }
|
||||
input: [32]u8
|
||||
if AppendText(input[:], AppendText(input[:], 0, "/dev/fd/"), TextView(digits[place:11])) < 0 { return false }
|
||||
args: [16]string = .["openssl", "enc", "-d", "-aes-256-cbc", "-md", "sha512", "-a", "-A", "-pbkdf2", "-iter", "100000", "-in", TextUntilNul(input[:]), "-pass", "stdin", "-salt"]
|
||||
args: [16]string = .["openssl", "enc", "-d", "-aes-256-cbc", "-md", "sha512", "-a", "-A", "-pbkdf2", "-iter", "100000", "-in", TextUntilNul(path[:]), "-pass", "stdin", "-salt"]
|
||||
child := Channel.StartChannel(args[:], false)
|
||||
if child.error != 0 { return false }
|
||||
defer { unused Channel.CloseChannel(*child, 1000) }
|
||||
|
||||
@@ -22,8 +22,8 @@
|
||||
#import "tree"
|
||||
#import "text_buffer"
|
||||
#import "utf8"
|
||||
#import "kryon/app_context"
|
||||
#import "kryon/app_protocol"
|
||||
#import "werk_app"
|
||||
#import "app_protocol"
|
||||
#import "pass_core"
|
||||
#import "pass_state"
|
||||
#import "pass_text"
|
||||
@@ -474,13 +474,9 @@ Draw :: () {
|
||||
#program_export "PassMain"
|
||||
Main :: () -> s32 {
|
||||
if AppMode() == APP_IDENTIFY {
|
||||
AppIdentity("pass")
|
||||
AppDescribe("Pass", Icon.Shape)
|
||||
return APP_PROTOCOL
|
||||
}
|
||||
if AppMode() != APP_FRAME {
|
||||
return 0
|
||||
}
|
||||
if !initialized {
|
||||
Initialize()
|
||||
initialized = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#import "sha256"
|
||||
#if #defined(WERK_APP) {
|
||||
#import "kryon/app_context"
|
||||
#import "werk_app"
|
||||
}
|
||||
|
||||
PassOptions :: struct {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#import "pass_text"
|
||||
#import "text_buffer"
|
||||
#import "number_text"
|
||||
#import "kryon/app_context"
|
||||
#import "werk_app"
|
||||
|
||||
Profile :: struct {
|
||||
name: [64]u8
|
||||
|
||||
|
Before Width: | Height: | Size: 208 KiB After Width: | Height: | Size: 9.5 KiB |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<title>Werkzeug — a wrench with a keyhole</title>
|
||||
<g fill="#8254ff" fill-rule="evenodd" transform="translate(-10 10)">
|
||||
<path d="M425.9 145.5A118 118 0 1 1 366.5 86.1L288.5 164.1A42 42 0 0 0 347.9 223.5Z"/>
|
||||
<path d="M239.0 202.3L309.7 273.0L181.0 401.7A50 50 0 0 1 110.3 331.0ZM159.8 324.2a21 21 0 0 0 -11.2 38.7l-5.2 23.0h32.8l-5.2 -23.0a21 21 0 0 0 -11.2 -38.7Z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 482 B |
|
Before Width: | Height: | Size: 1.1 MiB |
|
Before Width: | Height: | Size: 84 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 11 KiB |
@@ -14,17 +14,16 @@ android {
|
||||
}
|
||||
|
||||
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'] ?: System.getenv('KEY_ALIAS') ?: "pass-key" }
|
||||
def getKeystoreAlias = { -> project.findProperty('keystore.alias') ?: keystoreProps['keystore.alias'] ?: "pass-key" }
|
||||
|
||||
def releasePassword = project.findProperty('keystore.password') ?: System.getenv('KEYSTORE_PASSWORD') ?: ""
|
||||
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 fdroidBuild = (project.findProperty('fDroidBuild') ?: 'false').toString().toBoolean()
|
||||
def signRelease = !fdroidBuild \
|
||||
def signRelease = !project.hasProperty('fDroidBuild') \
|
||||
&& releaseKeystore != null && releaseKeystore.exists() \
|
||||
&& releasePassword != ""
|
||||
|
||||
@@ -43,8 +42,8 @@ android {
|
||||
applicationId 'xyz.waozi.pass'
|
||||
minSdk 21
|
||||
targetSdk 36
|
||||
versionCode 16
|
||||
versionName "0.4.2"
|
||||
versionCode 12
|
||||
versionName "0.3.0"
|
||||
// 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'
|
||||
@@ -80,7 +79,6 @@ android {
|
||||
|
||||
dependenciesInfo {
|
||||
includeInApk = false
|
||||
includeInBundle = false
|
||||
}
|
||||
|
||||
packaging {
|
||||
@@ -104,14 +102,14 @@ tasks.named('preBuild').configure { dependsOn prepareFonts }
|
||||
// The tool apps are portable bundles, built once for every ABI.
|
||||
def makeApps = tasks.register('makeApps', Exec) {
|
||||
workingDir '../..'
|
||||
commandLine 'make', 'portable-apps'
|
||||
commandLine 'make', 'apps'
|
||||
}
|
||||
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('generated/appAssets'))
|
||||
def prepareImages = tasks.register('prepareImages', Copy) {
|
||||
dependsOn makeApps
|
||||
from('../../assets/app/icon.png')
|
||||
from("${System.getenv('KRYON_DIR')}/icons/pfp.png")
|
||||
from('../../build/apps') { include '*.zib'; exclude 'workbook.zib'; into 'apps' }
|
||||
from('../../build/apps') { include '*.zib'; into 'apps' }
|
||||
into layout.buildDirectory.dir('generated/appAssets')
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn prepareImages }
|
||||
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 842 B |
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 3.1 KiB |
@@ -1 +0,0 @@
|
||||
- Fix the web version on itch.io, which opened to a blank page.
|
||||
@@ -1,6 +0,0 @@
|
||||
- A new purple W logo.
|
||||
- Calculator gets a Scientific mode.
|
||||
- Auth imports Google Authenticator, Aegis and Ente Auth exports.
|
||||
- Rename an Auth account, note its websites, or remove it.
|
||||
- Choose your own Daochi node, and pause sync without losing your account.
|
||||
- Show π, √ and other symbols on phones older than Android 10.
|
||||
@@ -1,3 +0,0 @@
|
||||
- Open Pass, Auth, Calculator, Clock and Workbook directly from the Linux application menu, each with its own icon.
|
||||
- Desktop installs add shortcuts for Werkzeug and every tool to your configured desktop folder.
|
||||
- Tool windows show their own names and icons in the desktop switcher.
|
||||
@@ -1,2 +0,0 @@
|
||||
- Linux packages include the libraries needed for sync and importing QR-code pictures.
|
||||
- Packaging a new AppImage preserves previous downloads.
|
||||
@@ -1,13 +1,11 @@
|
||||
Werkzeug holds small private tools in one app. Everything is computed on your device and nothing is tracked. It makes no network requests unless you turn on sync.
|
||||
|
||||
• Pass derives strong, repeatable passwords. 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. It is LessPass-compatible, with configurable length, counter, character classes and excluded characters, and an optional master password kept behind device authentication.
|
||||
• Auth shows two-factor sign-in codes (TOTP with SHA-1, SHA-256 or SHA-512). Add accounts by secret key or from otpauth links, Google Authenticator export links, unencrypted Aegis exports or Ente Auth's plain-text export. Rename an account or note the websites where it signs in. Copied codes are cleared from the clipboard after 30 seconds. Optional sync keeps them on all your devices, encrypted on the device so the server never sees them.
|
||||
• Calculator handles everyday arithmetic with brackets, powers and percent, and has a Scientific mode with trigonometry, logarithms, roots, factorials, π and e.
|
||||
• Auth shows two-factor sign-in codes (TOTP with SHA-1, SHA-256 or SHA-512). Add accounts from otpauth links, including an authenticator's plain-text export, or by secret key. Copied codes are cleared from the clipboard after 30 seconds. Optional sync keeps them on all your devices, encrypted on the device so the server never sees them.
|
||||
• Calculator handles everyday arithmetic with brackets, powers and percent.
|
||||
• Clock shows the local time and date and has a stopwatch.
|
||||
|
||||
A profile with your name and picture sets the appearance every tool shares.
|
||||
|
||||
Every tool works without a Daochi account. In Profile → Sync you can choose your own node before connecting an account, or pause sync without forgetting your keys and local records. Sync stays off after restarting until you turn it on again.
|
||||
A profile with your name and picture sets the appearance every tool shares. Werkzeug was previously called Pass; updating keeps your profiles, settings and saved master password.
|
||||
|
||||
Pass is an independent implementation of the LessPass algorithm. Compatibility does not imply endorsement by or affiliation with the LessPass project.
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 208 KiB After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
Before Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 86 KiB |
@@ -1,23 +0,0 @@
|
||||
# Draft: xyz.waozi.pass: rename to Werkzeug and update to 0.4.0
|
||||
|
||||
The app on F-Droid is now Werkzeug: Pass, Auth, Calculator and Clock in one
|
||||
app. The current recipe still selects Pass 0.2.9 with its old name, website
|
||||
and APK name. Update the existing package to the public Werkzeug 0.4.0
|
||||
release, its links, description, screenshots and versioned APK name.
|
||||
Preserve `xyz.waozi.pass` and the allowed signing certificate so existing
|
||||
installations update in place.
|
||||
|
||||
The build uses the exact Ziran toolchain and nine dependency revisions from
|
||||
the release lock, fetched as F-Droid source libraries before the build.
|
||||
Package mappings and native/image paths use those managed sources. The old
|
||||
0.2.9 build keeps its original reference APK filename.
|
||||
|
||||
Werkzeug 0.3.0 and 0.3.1 are not offered: their locks pin dependency commits
|
||||
that upstream history no longer contains, so they cannot be rebuilt.
|
||||
|
||||
A full F-Droid source rebuild and reproducibility comparison remain pending.
|
||||
Keep this request in draft until those checks pass.
|
||||
|
||||
- [Original merged submission](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/46404)
|
||||
- [Existing successful reproducible build](https://monitor.f-droid.org/builds/log/xyz.waozi.pass/10)
|
||||
- [Werkzeug 0.4.0 release](https://github.com/waozixyz/werk/releases/tag/v0.4.0)
|
||||
@@ -1,51 +0,0 @@
|
||||
# Werkzeug F-Droid TODO
|
||||
|
||||
Updated 2026-10-19. The recipe now targets the public Werkzeug 0.4.0 release
|
||||
(Android versionCode 14) with new store text and screenshots. GitLab
|
||||
authentication is still blocked and no new merge request has been created.
|
||||
|
||||
## Prepared and verified
|
||||
|
||||
- [x] Confirm the [original Pass submission](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/46404)
|
||||
was merged and its [0.2.9 reproducible build](https://monitor.f-droid.org/builds/log/xyz.waozi.pass/10) succeeded.
|
||||
- [x] Rename the listing to Werkzeug and pin 0.4.0's toolchain and nine
|
||||
source dependencies, including Self and its QR code library.
|
||||
- [x] Drop 0.3.0 and 0.3.1: their locks pin dependency commits that the
|
||||
2026-10-19 history rewrite removed upstream, so they cannot be rebuilt.
|
||||
- [x] Replace the old Pass screenshots with Werkzeug's home screen and tools.
|
||||
- [x] Verify the public 0.4.0 universal APK: package `xyz.waozi.pass`,
|
||||
versionCode 14, label Werkzeug, both ARM ABIs and the allowed signing
|
||||
certificate. The recipe pins its tagged commit. `make android-fdroid`
|
||||
builds the unsigned F-Droid candidate from the same lock.
|
||||
|
||||
## Resume the F-Droid submission
|
||||
|
||||
1. [ ] Restore GitLab sign-in. The existing ThinkPad spare-browser viewer
|
||||
is paused for manual sign-in; resume automation after the owner confirms.
|
||||
2. [ ] Refresh upstream metadata and search open merge requests for an
|
||||
existing Werkzeug update before creating another one.
|
||||
3. [ ] Submit the metadata and source-library definitions as a **draft**
|
||||
using [the prepared merge-request text](MERGE_REQUEST.md). Record its URL here.
|
||||
4. [ ] Run the full F-Droid source build and reproducibility comparison
|
||||
against the signed public 0.4.0 reference APK. Resolve any CI/build differences.
|
||||
5. [ ] Verify update compatibility: preserve `xyz.waozi.pass`, the existing
|
||||
allowed signing certificate, and the release's versionName/versionCode.
|
||||
Keep `-fdroid` in the output filename only.
|
||||
6. [ ] Once reproducibility and CI pass, request maintainer review. Track
|
||||
the merge and verify Werkzeug's actual catalog availability separately.
|
||||
|
||||
Merge request URL: pending submission.
|
||||
|
||||
## Later
|
||||
|
||||
- [ ] Unfinished Clock/alarm work waits in the git stash "clock features
|
||||
WIP 2". It is not part of 0.4.0; preserve it.
|
||||
|
||||
## Handoff files
|
||||
|
||||
- [Build metadata](metadata/xyz.waozi.pass.yml)
|
||||
- [Pinned source-library definitions](srclibs/)
|
||||
- [Draft merge-request text](MERGE_REQUEST.md)
|
||||
- Local unsigned candidate: `make android-fdroid`
|
||||
|
||||
The unsigned candidate is a build artifact, not an installable release.
|
||||
@@ -1,77 +0,0 @@
|
||||
Categories:
|
||||
- Password & 2FA
|
||||
- Security
|
||||
License: BSD-3-Clause
|
||||
AuthorName: Waozi
|
||||
WebSite: https://werk.waozi.xyz
|
||||
SourceCode: https://github.com/waozixyz/werk
|
||||
IssueTracker: https://github.com/waozixyz/werk/issues
|
||||
Changelog: https://github.com/waozixyz/werk/blob/HEAD/CHANGELOG.md
|
||||
|
||||
AutoName: Werkzeug
|
||||
|
||||
RepoType: git
|
||||
Repo: https://github.com/waozixyz/werk.git
|
||||
Binaries: https://github.com/waozixyz/werk/releases/download/v%v/werk-%v.apk
|
||||
|
||||
Builds:
|
||||
- versionName: 0.2.9
|
||||
versionCode: 10
|
||||
commit: f9d721f179e54c924e048d3fd17c5e96de1047ba
|
||||
subdir: droid/app
|
||||
submodules: true
|
||||
sudo:
|
||||
- apt-get update
|
||||
- apt-get install -y gcc libc-dev
|
||||
gradle:
|
||||
- yes
|
||||
binary: https://github.com/waozixyz/werk/releases/download/v%v/pass-%v.apk
|
||||
scandelete:
|
||||
- vendor/kryon/vendor
|
||||
ndk: 28.2.13676358
|
||||
|
||||
- versionName: 0.4.0
|
||||
versionCode: 14
|
||||
commit: 0d2c2b3a88e1080d3249848815b185757a1915c2
|
||||
subdir: droid/app
|
||||
sudo:
|
||||
- apt-get update
|
||||
- apt-get install -y build-essential libssl-dev
|
||||
gradle:
|
||||
- yes
|
||||
output: build/outputs/apk/release/app-universal-release-unsigned.apk
|
||||
srclibs:
|
||||
- Ziran@1ad0264d9f6ce3df29e9071ab16eae0e1e557049
|
||||
- Kryon@a78576db722b25216e0096870d313b7d2ace96b0
|
||||
- Monocypher@d1895c3799005122b2e68f47f442cc5ba709d866
|
||||
- Oqs@22d2ddbdc236796953c905a05a2cebf5ab1b4ff3
|
||||
- Mingcute@9cc6872f75447c3a24c16764f9829d0f58751cb0
|
||||
- raylib@fafa2cea97d0cb379d832086ba45a989fa6f9c8e
|
||||
- DaochiClient@42aa3ee773d8abdc6b3a10fbcb1b73c992f0f564
|
||||
- liboqs@fd44469daeffe6b28f031f54f9bb66cbae69a572
|
||||
- Self@1ce89cff5a807cca817aec5d1347e18d2f229b27
|
||||
- Qrcode@2944b2e668e735438d8ce24e47a39be3f5c36af5
|
||||
prebuild:
|
||||
- printf '[overrides]\nziran = "$$Ziran$$"\nkryon = "$$Kryon$$"\nmingcute =
|
||||
"$$Mingcute$$"\ndaochi_client = "$$DaochiClient$$"\noqs = "$$Oqs$$"\nliboqs
|
||||
= "$$liboqs$$"\nmonocypher = "$$Monocypher$$"\nraylib = "$$raylib$$"\nself
|
||||
= "$$Self$$"\nqrcode = "$$Qrcode$$"\n' > ../../ziran.local.toml
|
||||
- sed -i -e 's|$ENV{KRYON_DIR}|$$Kryon$$|g' -e 's|$ENV{ZIRAN_ROOT}|$$Ziran$$|g'
|
||||
-e 's|$ENV{RAYLIB_DIR}|$$raylib$$/src|g' -e 's|$ENV{LIBOQS_DIR}|$$liboqs$$|g'
|
||||
-e 's|$ENV{MONOCYPHER_DIR}|$$Monocypher$$|g' src/main/cpp/CMakeLists.txt
|
||||
- sed -i 's@from(.*KRYON_DIR.*@from("$$Kryon$$/icons/pfp.png")@' build.gradle
|
||||
build:
|
||||
- make -C $$Ziran$$ all
|
||||
- make -C ../.. apps ZIRAN=$$Ziran$$/build/bin/ziran
|
||||
ndk: 28.2.13676358
|
||||
gradleprops:
|
||||
- fDroidBuild=true
|
||||
- abi=armeabi-v7a,arm64-v8a
|
||||
- splitApks=true
|
||||
|
||||
AllowedAPKSigningKeys: 1ac82db5bc8f742b8161fdd7083cefc16b39524dce7d103a7eb7f1ee19589c2d
|
||||
|
||||
AutoUpdateMode: Version
|
||||
UpdateCheckMode: Tags
|
||||
CurrentVersion: 0.4.0
|
||||
CurrentVersionCode: 14
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/ziranlang/daochi-client.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/kryonlabs/kryon.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/kryonlabs/mingcute.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/LoupVaillant/Monocypher.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/ziranlang/oqs.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/ziranlang/qrcode.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/waozixyz/entity.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/ziranlang/ziran.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/open-quantum-safe/liboqs.git
|
||||
@@ -1,2 +0,0 @@
|
||||
RepoType: git
|
||||
Repo: https://github.com/raysan5/raylib.git
|
||||
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor 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 the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
Before Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 12 KiB |
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
|
||||
<mime-type type="application/x-ziran-bundle">
|
||||
<comment>Ziran application bundle</comment>
|
||||
<glob pattern="*.zib"/>
|
||||
</mime-type>
|
||||
</mime-info>
|
||||
@@ -11,5 +11,5 @@
|
||||
<launchable type="desktop-id">xyz.waozi.werk.desktop</launchable>
|
||||
<url type="homepage">https://github.com/waozixyz/werk</url>
|
||||
<provides><binary>werk</binary></provides>
|
||||
<releases><release version="0.4.2" date="2026-10-23"/><release version="0.4.1" date="2026-10-23"/><release version="0.4.0" date="2026-10-15"/><release version="0.3.1" date="2026-10-13"/><release version="0.3.0" date="2026-10-13"/><release version="0.2.10" date="2026-10-05"/><release version="0.2.9" date="2026-09-05"/><release version="0.2.8" date="2026-08-26"/><release version="0.2.7" date="2026-08-24"/><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>
|
||||
<releases><release version="0.3.0" date="2026-10-13"/><release version="0.2.10" date="2026-10-05"/><release version="0.2.9" date="2026-09-05"/><release version="0.2.8" date="2026-08-26"/><release version="0.2.7" date="2026-08-24"/><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>
|
||||
@@ -1,12 +0,0 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Auth
|
||||
Comment=Two-factor sign-in codes with Werkzeug
|
||||
Exec=werk --app auth
|
||||
TryExec=werk
|
||||
Icon=werk-auth
|
||||
Terminal=false
|
||||
Categories=Utility;Security;
|
||||
Keywords=Werkzeug;TOTP;2FA;Authenticator;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-auth
|
||||
@@ -1,12 +0,0 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Calculator
|
||||
Comment=Everyday and scientific calculations with Werkzeug
|
||||
Exec=werk --app calculator
|
||||
TryExec=werk
|
||||
Icon=werk-calculator
|
||||
Terminal=false
|
||||
Categories=Utility;Calculator;
|
||||
Keywords=Werkzeug;Math;Scientific;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-calculator
|
||||
@@ -1,12 +0,0 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Clock
|
||||
Comment=Local time and stopwatch with Werkzeug
|
||||
Exec=werk --app clock
|
||||
TryExec=werk
|
||||
Icon=werk-clock
|
||||
Terminal=false
|
||||
Categories=Utility;Clock;
|
||||
Keywords=Werkzeug;Time;Stopwatch;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-clock
|
||||
@@ -1,12 +1,9 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Werkzeug
|
||||
Comment=Private everyday tools
|
||||
Exec=werk --bundle %f
|
||||
TryExec=werk
|
||||
Comment=Passwords, two-factor codes, a calculator and a clock
|
||||
Exec=werk
|
||||
Icon=werk
|
||||
Terminal=false
|
||||
Categories=Utility;Security;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk
|
||||
MimeType=application/x-ziran-bundle;
|
||||
@@ -1,12 +0,0 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Pass
|
||||
Comment=Generate repeatable passwords with Werkzeug
|
||||
Exec=werk --app pass
|
||||
TryExec=werk
|
||||
Icon=werk-pass
|
||||
Terminal=false
|
||||
Categories=Utility;Security;
|
||||
Keywords=Werkzeug;Password;LessPass;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-pass
|
||||
@@ -1,12 +0,0 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Workbook
|
||||
Comment=Edit spreadsheets with Werkzeug
|
||||
Exec=werk --app workbook
|
||||
TryExec=werk
|
||||
Icon=werk-workbook
|
||||
Terminal=false
|
||||
Categories=Office;Spreadsheet;
|
||||
Keywords=Werkzeug;Spreadsheet;Formula;
|
||||
StartupNotify=true
|
||||
StartupWMClass=werk-workbook
|
||||
@@ -1,55 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate a Werkzeug Play candidate without uploading it."""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("bundle", type=Path)
|
||||
parser.add_argument("--bundletool", type=Path, required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--unsigned", action="store_true", help="Validate structure only; this candidate cannot be uploaded")
|
||||
args = parser.parse_args()
|
||||
bundle = args.bundle.resolve(strict=True)
|
||||
tool = args.bundletool.resolve(strict=True)
|
||||
subprocess.run(["java", "-jar", str(tool), "validate", "--bundle=" + str(bundle)],
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
xml = subprocess.check_output(["java", "-jar", str(tool), "dump", "manifest", "--bundle=" + str(bundle)], text=True)
|
||||
manifest = ET.fromstring(xml)
|
||||
android = "{http://schemas.android.com/apk/res/android}"
|
||||
assert manifest.get("package") == "xyz.waozi.pass", "Preserve the installed app ID"
|
||||
assert manifest.get(android + "versionName") == args.version
|
||||
assert int(manifest.find("uses-sdk").get(android + "targetSdkVersion")) >= 36
|
||||
assert manifest.find("application").get(android + "debuggable", "false") == "false"
|
||||
if not args.unsigned:
|
||||
signed = subprocess.check_output(["jarsigner", "-verify", str(bundle)], text=True,
|
||||
env=dict(os.environ, LC_ALL="C"))
|
||||
assert "jar verified." in signed, "The Play candidate must be signed"
|
||||
certificates = subprocess.check_output(["keytool", "-printcert", "-jarfile", str(bundle)], text=True,
|
||||
env=dict(os.environ, LC_ALL="C"))
|
||||
fingerprints = re.findall(r"SHA256:\s*([A-Fa-f0-9:]+)", certificates)
|
||||
expected = "1ac82db5bc8f742b8161fdd7083cefc16b39524dce7d103a7eb7f1ee19589c2d"
|
||||
assert fingerprints and {x.replace(":", "").lower() for x in fingerprints} == {expected}, "Bundle signer differs from the existing release key"
|
||||
with zipfile.ZipFile(bundle) as archive:
|
||||
for app in ("pass", "auth", "calculator", "clock", "entity", "apps"):
|
||||
assert f"base/assets/apps/{app}.zib" in archive.namelist(), f"Missing {app}"
|
||||
for font in ("ui.ttf", "emoji.ttf"):
|
||||
assert "base/assets/fonts/" + font in archive.namelist()
|
||||
abis = {x.split("/")[2] for x in archive.namelist() if x.startswith("base/lib/") and x.endswith(".so")}
|
||||
assert abis == {"arm64-v8a", "armeabi-v7a"}
|
||||
root = Path(__file__).resolve().parents[1] / "build/play-verify"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=root) as directory:
|
||||
for name in archive.namelist():
|
||||
if not name.startswith("base/lib/arm64-v8a/") or not name.endswith(".so"): continue
|
||||
library = Path(directory) / Path(name).name
|
||||
library.write_bytes(archive.read(name))
|
||||
headers = subprocess.check_output(["readelf", "-lW", str(library)], text=True)
|
||||
loads = [line.split() for line in headers.splitlines() if line.strip().startswith("LOAD ")]
|
||||
assert loads and all(int(parts[-1], 16) >= 16384 for parts in loads), "Native library needs 16 KB alignment"
|
||||
print("Werkzeug " + args.version + ": " + ("unsigned structure verified; signing pending" if args.unsigned else "signed Play bundle verified"))
|
||||
@@ -1,35 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check real F-Droid/debug artifacts without installing anything."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from zipfile import ZipFile
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
fdroid, debug, emulator = map(Path, sys.argv[1:])
|
||||
identity = None
|
||||
for path, expected_abis in [(fdroid, {"armeabi-v7a", "arm64-v8a"}),
|
||||
(debug, {"armeabi-v7a", "arm64-v8a"}),
|
||||
(emulator, {"x86_64"})]:
|
||||
badging = subprocess.check_output(["aapt", "dump", "badging", str(path)], text=True)
|
||||
package = re.search(r"package: name='([^']+)' versionCode='([^']+)' versionName='([^']+)'", badging)
|
||||
assert package, f"{path}: no package identity"
|
||||
current = package.groups()
|
||||
assert current[0] == "xyz.waozi.pass", "Updating must preserve Pass's Android ID"
|
||||
assert current[2] == (root / "VERSION").read_text().strip(), "Channel added a version suffix"
|
||||
if identity is None:
|
||||
identity = current
|
||||
assert current == identity, "F-Droid and direct builds have different identities"
|
||||
assert "application-label:'Werkzeug'" in badging
|
||||
permissions = subprocess.check_output(["aapt", "dump", "permissions", str(path)], text=True)
|
||||
assert not any(name in permissions for name in
|
||||
["REQUEST_INSTALL_PACKAGES", "INSTALL_PACKAGES", "DELETE_PACKAGES"]), "App can compete with its installer"
|
||||
with ZipFile(path) as archive:
|
||||
abis = {name.split('/')[1] for name in archive.namelist()
|
||||
if name.startswith('lib/') and name.endswith('/libmain.so')}
|
||||
assert abis == expected_abis, f"{path}: wrong ABIs {abis}"
|
||||
assert archive.read("assets/icon.png") == (root / "assets/app/icon.png").read_bytes(), "Stale app logo"
|
||||
signature = subprocess.run(["apksigner", "verify", str(path)], capture_output=True)
|
||||
assert (signature.returncode != 0) == (path == fdroid), "F-Droid must be unsigned; debug must be signed"
|
||||
print("Android distribution: matching package/version, Werkzeug label/logo, correct ABIs, builder signing and no installer permissions")
|
||||
@@ -1,8 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Drive only a private emulator; never choose a connected phone implicitly."""
|
||||
from pathlib import Path
|
||||
import csv
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
@@ -29,39 +27,6 @@ def shell(*arguments, check=True):
|
||||
def shot(name):
|
||||
(output / f"{name}.png").write_bytes(adb("exec-out", "screencap", "-p").stdout)
|
||||
|
||||
def find_label(word):
|
||||
shot("label")
|
||||
data = subprocess.check_output(["tesseract", str(output / "label.png"), "stdout", "--psm", "11", "-c", "tessedit_create_tsv=1"],
|
||||
stderr=subprocess.DEVNULL, text=True)
|
||||
for item in csv.DictReader(io.StringIO(data), delimiter="\t"):
|
||||
if item["text"].strip().lower() == word.lower():
|
||||
return (int(item["left"]) + int(item["width"]) // 2,
|
||||
int(item["top"]) + int(item["height"]) // 2)
|
||||
raise AssertionError(f"Could not find {word!r} in the private emulator")
|
||||
|
||||
def tap_label(word):
|
||||
tap(*find_label(word))
|
||||
|
||||
def dismiss_other_apps_not_responding():
|
||||
"""A slow emulator can show an "isn't responding" dialog for another app,
|
||||
the system or Werkzeug over Werkzeug, as CI's did. Choose Wait, found
|
||||
through the accessibility tree. A real hang does not recover, so the
|
||||
next assertion still fails."""
|
||||
for _ in range(6):
|
||||
dumped = adb("shell", "uiautomator", "dump", "/sdcard/werk-ui.xml", check=False)
|
||||
tree = shell("cat", "/sdcard/werk-ui.xml", check=False) if dumped.returncode == 0 else ""
|
||||
# The tree escapes the apostrophe in "isn't responding".
|
||||
if " responding" not in tree:
|
||||
return
|
||||
if "Werkzeug isn" in tree:
|
||||
print("warning: the emulator reported Werkzeug slow to respond; waiting")
|
||||
wait = re.search(r'text="Wait"[^>]*bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', tree)
|
||||
if wait:
|
||||
left, top_edge, right, bottom_edge = map(int, wait.groups())
|
||||
tap((left + right) // 2, (top_edge + bottom_edge) // 2)
|
||||
time.sleep(3)
|
||||
raise AssertionError("An \"isn't responding\" dialog kept covering Werkzeug")
|
||||
|
||||
def alive():
|
||||
if not shell("pidof", package, check=False).strip():
|
||||
details = adb("logcat", "-d", "-b", "crash").stdout.decode()
|
||||
@@ -72,25 +37,19 @@ def alive():
|
||||
if line.strip().startswith(("mResumedActivity:", "ResumedActivity:"))), "")
|
||||
assert package in resumed, f"Werkzeug activity closed or lost foreground: {resumed}"
|
||||
|
||||
# CI's software-rendered emulator needs longer to apply each step.
|
||||
PAUSE = 1.0 if os.environ.get("CI") else 0.25
|
||||
|
||||
def tap(x, y):
|
||||
shell("input", "tap", str(x), str(y)); time.sleep(PAUSE)
|
||||
shell("input", "tap", str(x), str(y)); time.sleep(0.25)
|
||||
|
||||
def type_text(text):
|
||||
shell("input", "text", text.replace(" ", "%s")); time.sleep(PAUSE + 0.05)
|
||||
shell("input", "text", text.replace(" ", "%s")); time.sleep(0.3)
|
||||
|
||||
def system_bars(height):
|
||||
"""The app's first and last rows in pixels: Werkzeug keeps its content
|
||||
between the status bar and the navigation bar."""
|
||||
dump = shell("dumpsys", "window")
|
||||
# Android 12 and older name inset sources ITYPE_STATUS_BAR and so on.
|
||||
status = re.search(r"type=(?:statusBars|ITYPE_STATUS_BAR) frame=\[0,0\]\[\d+,(\d+)\]", dump)
|
||||
# A display cutout taller than the status bar pushes the app down further.
|
||||
cutout = re.search(r"type=(?:displayCutout|ITYPE_[A-Z_]*CUTOUT[A-Z_]*) frame=\[0,0\]\[\d+,(\d+)\]", dump)
|
||||
navigation = re.search(r"type=(?:navigationBars|ITYPE_NAVIGATION_BAR) frame=\[0,(\d+)\]\[\d+,(\d+)\]", dump)
|
||||
top = max(int(status.group(1)) if status else 0, int(cutout.group(1)) if cutout else 0)
|
||||
status = re.search(r"type=statusBars frame=\[0,0\]\[\d+,(\d+)\]", dump)
|
||||
navigation = re.search(r"type=navigationBars frame=\[0,(\d+)\]\[\d+,(\d+)\]", dump)
|
||||
top = int(status.group(1)) if status else 0
|
||||
bottom = int(navigation.group(1)) if navigation and int(navigation.group(2)) == height else height
|
||||
return top, bottom
|
||||
|
||||
@@ -101,12 +60,10 @@ try:
|
||||
# This is the test emulator and only this package's fixture data is cleared.
|
||||
shell("pm", "clear", package)
|
||||
shell("am", "start", "-n", package + "/android.app.NativeActivity")
|
||||
time.sleep(2); alive(); dismiss_other_apps_not_responding(); shot("launch")
|
||||
time.sleep(2); alive(); shot("launch")
|
||||
size = shell("wm", "size").strip().split()[-1]
|
||||
width, height = map(int, size.split("x"))
|
||||
# Werkzeug scales by the screen density, as Android's dp do.
|
||||
densities = re.findall(r"density: (\d+)", shell("wm", "density"))
|
||||
zoom = int(densities[-1]) / 160
|
||||
zoom = width / 390
|
||||
top, bottom = system_bars(height)
|
||||
# Pass's tile on the home screen, then Pass below Werkzeug's 56-unit bar.
|
||||
tap(int(127 * zoom), top + int(132 * zoom)); time.sleep(0.5); alive(); shot("pass")
|
||||
@@ -127,16 +84,13 @@ try:
|
||||
assert "test master" not in saved
|
||||
# Generate from the saved profile and copy it.
|
||||
tap(int(100 * zoom), top + int((210 + bar) * zoom))
|
||||
# A slow emulator may still be deriving the password.
|
||||
time.sleep(2); dismiss_other_apps_not_responding()
|
||||
time.sleep(0.5)
|
||||
tap(int(100 * zoom), bottom - int(119 * zoom)) # Copy, at the bottom of the scrolled form
|
||||
shot("generated")
|
||||
tap(width // 2, bottom - int(35 * zoom))
|
||||
tap(int(90 * zoom), top + int((55 + bar) * zoom))
|
||||
shell("input", "keyevent", "123") # Move to the end.
|
||||
for _ in "Android test":
|
||||
shell("input", "keyevent", "67"); time.sleep(0.1)
|
||||
dismiss_other_apps_not_responding()
|
||||
shell("input", "keyevent", *("67" for _ in "Android test"))
|
||||
# Type the reference password as the new name. Pasting the copy works
|
||||
# through the keyboard's clipboard suggestion, which Gboard offers only
|
||||
# once per clip, so it is not automated here.
|
||||
@@ -149,7 +103,7 @@ try:
|
||||
assert shell("run-as", package, "cat", "files/apps/pass/profiles.tsv") == expected, "Android second profile mismatch"
|
||||
shell("am", "force-stop", package)
|
||||
shell("am", "start", "-n", package + "/android.app.NativeActivity")
|
||||
time.sleep(1); alive(); dismiss_other_apps_not_responding()
|
||||
time.sleep(1); alive()
|
||||
assert shell("run-as", package, "cat", "files/apps/pass/profiles.tsv") == expected
|
||||
assert shell("run-as", package, "stat", "-c", "%a", "files/apps/pass/profiles.tsv").strip() == "600"
|
||||
shot("persisted")
|
||||
@@ -157,37 +111,14 @@ try:
|
||||
# after the last, at the caret the keyboard reports.
|
||||
tap(int(28 * zoom), top + int(28 * zoom)); time.sleep(0.5)
|
||||
tap(width - int(60 * zoom), top + int(28 * zoom)); time.sleep(0.8); alive()
|
||||
# Entity's profile card: the picture, then Name.
|
||||
tap(width // 2, top + int(357 * zoom)); type_text("Ada Lovelace")
|
||||
tap(width // 2, top + int(232 * zoom)); type_text("Ada Lovelace")
|
||||
shot("profile-name")
|
||||
shell("input", "keyevent", "4"); time.sleep(0.3)
|
||||
# Leaving Profile saves it.
|
||||
tap(int(28 * zoom), top + int(28 * zoom)); time.sleep(0.5); alive()
|
||||
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
|
||||
assert "name=Ada Lovelace\n" in settings, f"Profile name typed out of order: {settings!r}"
|
||||
tap(width - int(60 * zoom), top + int(28 * zoom)); time.sleep(0.8)
|
||||
# Entity's Nodes section: the empty "Node address" field, then Add.
|
||||
tap_label("Node")
|
||||
type_text("https://sync.example.invalid:8443/")
|
||||
shell("input", "keyevent", "4"); time.sleep(1.2)
|
||||
# OCR misses Add's white label on the accent. It ends the row above
|
||||
# Appearance, wherever the keyboard left the page scrolled.
|
||||
_, appearance = find_label("Appearance")
|
||||
tap(width - int(81 * zoom), appearance - int(56 * zoom)); time.sleep(0.8)
|
||||
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
|
||||
assert "node=https://sync.example.invalid:8443\n" in settings, "Custom node was not saved"
|
||||
assert adb("shell", "run-as", package, "test", "-f", "files/account/keys.txt", check=False).returncode != 0
|
||||
shot("custom-node")
|
||||
# Updating this same package preserves both the tool's files and the
|
||||
# profile. No owner phone is selected by this harness.
|
||||
shell("am", "force-stop", package)
|
||||
adb("install", "-r", str(apk))
|
||||
shell("am", "start", "-n", package + "/android.app.NativeActivity")
|
||||
time.sleep(1); alive(); dismiss_other_apps_not_responding()
|
||||
assert shell("run-as", package, "cat", "files/profile/settings.txt") == settings
|
||||
assert shell("run-as", package, "cat", "files/apps/pass/profiles.tsv") == expected
|
||||
shot("updated")
|
||||
print("Werkzeug Android: input, profiles, custom node and in-place package update preserved private data")
|
||||
print("Werkzeug Android: home, Pass keyboard, masked master, profiles, generation, restart and profile name pass")
|
||||
except BaseException:
|
||||
shot("failure")
|
||||
raise
|
||||
@@ -1,37 +1,16 @@
|
||||
#!/bin/sh
|
||||
# Auth's codes (RFC 6238 vectors) and export reading, and the Calculator's
|
||||
# arithmetic, run as portable bundles like the apps themselves.
|
||||
# Auth's codes (RFC 6238 vectors) and the Calculator's arithmetic, run as
|
||||
# portable bundles like the apps themselves.
|
||||
set -eu
|
||||
ziran=${1:?pass the ziran command}
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$root"
|
||||
ziran_root=$("$ziran" pkg path ziran)
|
||||
kryon=$("$ziran" pkg path kryon)
|
||||
mingcute=$("$ziran" pkg path mingcute)
|
||||
mkdir -p build/app-logic-test
|
||||
"$ziran" bundle --root . --module-path apps/auth --module-path shared --module-path "$ziran_root/std" \
|
||||
--entry totp_test:Run -o build/app-logic-test/totp.zib apps/auth/totp_test.zi
|
||||
test "$("$ziran" run build/app-logic-test/totp.zib)" = 0
|
||||
"$ziran" bundle --root . --module-path apps/auth --module-path shared --module-path "$ziran_root/std" \
|
||||
--entry exports_test:Run -o build/app-logic-test/exports.zib apps/auth/exports_test.zi
|
||||
test "$("$ziran" run build/app-logic-test/exports.zib)" = 0
|
||||
"$ziran" bundle --root . --module-path apps/calculator --module-path "$ziran_root/std" \
|
||||
--entry arithmetic_test:Run -o build/app-logic-test/arithmetic.zib apps/calculator/arithmetic_test.zi
|
||||
test "$("$ziran" run build/app-logic-test/arithmetic.zib)" = 0
|
||||
set -- --root tests --module-path apps/calculator \
|
||||
--module-path "kryon=$kryon/src/backend" --module-path "kryon=$kryon/src/ui" \
|
||||
--module-path "$kryon/src/ui" --module-path "$mingcute/src" --module-path "$ziran_root/std" \
|
||||
--entry calculator_input_test:main
|
||||
"$ziran" bundle "$@" --define KRYON_HOSTED_UI \
|
||||
--bind app_context:AppKeyHost=calculator_input_test:AppKeyHost \
|
||||
--bind app_context:AppFieldInputHost=calculator_input_test:AppFieldInputHost \
|
||||
-o build/app-logic-test/input.zib tests/calculator_input_test.zi
|
||||
test "$("$ziran" run build/app-logic-test/input.zib)" = 42
|
||||
"$ziran" build "$@" --target=c -o build/app-logic-test/input-c tests/calculator_input_test.zi
|
||||
${CC:-cc} -std=c99 -O2 -ffunction-sections -fdata-sections -Wl,--gc-sections \
|
||||
-I"$ziran_root/include" -Ibuild/app-logic-test/input-c build/app-logic-test/input-c/*.c -lm \
|
||||
-o build/app-logic-test/input-native
|
||||
status=0
|
||||
build/app-logic-test/input-native || status=$?
|
||||
test "$status" = 42
|
||||
echo 'Auth codes, Calculator arithmetic and batched keyboard commands pass'
|
||||
echo 'Auth codes and Calculator arithmetic tests pass'
|
||||
@@ -1,177 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the shared Apps controller and native tool navigation."""
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
from PIL import Image
|
||||
|
||||
assert os.environ.get("WERK_TEST_PRIVATE_DISPLAY") == "1", "Use private-display.py"
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
work = Path(os.environ.get("WERK_APPS_TEST_OUTPUT", root / "build/apps-gui-test"))
|
||||
binary = Path(os.environ.get("WERK_TEST_BINARY", root / "build/werk"))
|
||||
assets = Path(os.environ.get("WERK_TEST_ASSETS", root / "build"))
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
work.mkdir(parents=True)
|
||||
expected = (root / "apps-controller.sha256").read_text().strip()
|
||||
assert hashlib.sha256((assets / "apps/apps.zib").read_bytes()).hexdigest() == expected
|
||||
environment = dict(os.environ, HOME=str(work / "home"), WERK_DATA=str(work / "data"),
|
||||
WERK_ASSETS=str(assets), ENTITY_DATA=str(work / "entity"),
|
||||
XDG_CONFIG_HOME=str(work / "config"), XDG_DATA_HOME=str(work / "share"),
|
||||
XDG_CACHE_HOME=str(work / "cache"))
|
||||
for name in ("HOME", "WERK_DATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME"):
|
||||
Path(environment[name]).mkdir(parents=True)
|
||||
profile = Path(environment["WERK_DATA"]) / "profile"
|
||||
profile.mkdir()
|
||||
(profile / "settings.txt").write_text("theme_mode=1\n")
|
||||
|
||||
|
||||
def command(*arguments):
|
||||
return subprocess.check_output(arguments, env=environment, text=True, timeout=20)
|
||||
|
||||
|
||||
def capture(name):
|
||||
time.sleep(.3)
|
||||
picture = work / (name + ".png")
|
||||
command("import", "-window", window, str(picture))
|
||||
# Separate dark text from the soft card fills for reliable recognition.
|
||||
with Image.open(picture) as source:
|
||||
labels = source.convert("L").point(lambda value: 0 if value < 140 else 255)
|
||||
labels.resize((source.width * 3, source.height * 3)).save(work / "labels.png")
|
||||
source.resize((source.width * 3, source.height * 3)).save(work / "full-text.png")
|
||||
return command("tesseract", str(work / "labels.png"), "stdout", "--psm", "11")
|
||||
|
||||
|
||||
def click(x, y):
|
||||
command("xdotool", "mousemove", "--window", window, str(x), str(y))
|
||||
command("xdotool", "click", "--window", window, "1")
|
||||
time.sleep(.2)
|
||||
|
||||
|
||||
def word_position(word):
|
||||
capture("control")
|
||||
for target in ("labels.png", "full-text.png"):
|
||||
text = command("tesseract", str(work / target), "stdout", "--psm", "11",
|
||||
"-c", "tessedit_create_tsv=1")
|
||||
for item in csv.DictReader(io.StringIO(text), delimiter="\t"):
|
||||
if item["text"].strip() == word:
|
||||
return ((int(item["left"]) + int(item["width"]) // 2) // 3,
|
||||
(int(item["top"]) + int(item["height"]) // 2) // 3)
|
||||
raise AssertionError("Missing visible app control: " + word)
|
||||
|
||||
|
||||
def click_word(word):
|
||||
click(*word_position(word))
|
||||
|
||||
|
||||
def key(value):
|
||||
command("xdotool", "key", "--window", window, value)
|
||||
time.sleep(.2)
|
||||
|
||||
|
||||
def type_text(value):
|
||||
command("xdotool", "type", "--window", window, "--delay", "30", value)
|
||||
time.sleep(.3)
|
||||
|
||||
|
||||
app = subprocess.Popen([str(binary)], env=environment)
|
||||
try:
|
||||
deadline = time.monotonic() + 30
|
||||
window = None
|
||||
while time.monotonic() < deadline:
|
||||
assert app.poll() is None, "Werkzeug exited during startup"
|
||||
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)],
|
||||
env=environment, capture_output=True, text=True)
|
||||
if found.returncode == 0:
|
||||
window = found.stdout.splitlines()[0]
|
||||
break
|
||||
time.sleep(.1)
|
||||
assert window, "Werkzeug did not show its owned window"
|
||||
command("xdotool", "windowfocus", "--sync", window)
|
||||
# Window creation precedes loading the portable apps and the first frame.
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
home = capture("home")
|
||||
# The native fallback does not display package sizes.
|
||||
if "kB" in home or "MB" in home:
|
||||
break
|
||||
assert app.poll() is None, "Werkzeug exited while loading Apps"
|
||||
assert time.monotonic() < deadline, "Shared Apps controller did not render: " + home
|
||||
for name in ("Auth", "Calculator", "Clock", "Workbook", "Pass"):
|
||||
click_word(name)
|
||||
assert command("xdotool", "getwindowname", window).strip() == name
|
||||
assert "stopped" not in capture(name.lower()).lower(), name + " failed to run"
|
||||
click(28, 28)
|
||||
assert command("xdotool", "getwindowname", window).strip() == "Werkzeug"
|
||||
for width, height in ((360, 640), (720, 520)):
|
||||
command("xdotool", "windowsize", "--sync", window, str(width), str(height))
|
||||
text = capture(f"home-{width}")
|
||||
assert all(name in text for name in ("Pass", "Auth", "Calculator", "Clock", "Workbook")), text
|
||||
command("xdotool", "windowsize", "--sync", window, "420", "760")
|
||||
time.sleep(.3)
|
||||
click(330, 92) # Shared List view control, beside the search field.
|
||||
preferences = Path(environment["WERK_DATA"]) / "profile/apps.json"
|
||||
assert json.loads(preferences.read_text())["list"] is True
|
||||
text = capture("list")
|
||||
assert all(name in text for name in ("Pass", "Auth", "Calculator", "Clock", "Workbook")), text
|
||||
click(100, 92)
|
||||
type_text("clock")
|
||||
text = capture("search")
|
||||
assert "Clock" in text and "Calculator" not in text and "Workbook" not in text, text
|
||||
click(278, 92) # Clear search is part of the shared field.
|
||||
assert "Calculator" in capture("search-cleared")
|
||||
click(382, 372) # Clock's options at the end of its list row.
|
||||
text = capture("options")
|
||||
assert all(label in text for label in ("Open", "Pin", "Properties")), text
|
||||
click_word("Pin")
|
||||
capture("pinned")
|
||||
saved = json.loads(preferences.read_text())
|
||||
assert next(item for item in saved["apps"] if item["id"] == "clock")["favorite"]
|
||||
click(382, 204) # Clock now appears first, in Pinned.
|
||||
assert "Unpin" in capture("pinned-options")
|
||||
click_word("Properties")
|
||||
name = word_position("Name")
|
||||
click(120, name[1] + 34)
|
||||
key("ctrl+a")
|
||||
type_text("Timepiece")
|
||||
# The icon choices are: own icon, then Pass, Auth, Calculator, Clock, Workbook.
|
||||
click(name[0] - 16 + 120, name[1] + 116)
|
||||
# White text on the filled Save button is not reliably recognized by OCR.
|
||||
click(310, name[1] + 182)
|
||||
saved = json.loads(preferences.read_text())
|
||||
clock = next(item for item in saved["apps"] if item["id"] == "clock")
|
||||
assert clock["title"] == "Timepiece" and clock["icon"] == "auth", clock
|
||||
assert "Timepiece" in capture("renamed")
|
||||
assert preferences.stat().st_mode & 0o777 == 0o600
|
||||
app.terminate()
|
||||
app.wait(timeout=10)
|
||||
app = subprocess.Popen([str(binary)], env=environment)
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)],
|
||||
env=environment, capture_output=True, text=True)
|
||||
if found.returncode == 0:
|
||||
window = found.stdout.splitlines()[0]
|
||||
if "Timepiece" in capture("restarted"):
|
||||
break
|
||||
assert time.monotonic() < deadline, "Launcher preferences did not survive restart"
|
||||
time.sleep(.1)
|
||||
click(382, 204)
|
||||
click_word("Open")
|
||||
assert command("xdotool", "getwindowname", window).strip() == "Clock"
|
||||
click(28, 28)
|
||||
click(382, 204)
|
||||
click_word("Unpin")
|
||||
saved = json.loads(preferences.read_text())
|
||||
clock = next(item for item in saved["apps"] if item["id"] == "clock")
|
||||
assert not clock["favorite"] and clock["title"] == "Timepiece" and clock["icon"] == "auth"
|
||||
print("Shared Apps: list/grid, search, menus, pins, name/icon edits, restart persistence, five tools and resized layouts verified locally")
|
||||
finally:
|
||||
if app.poll() is None:
|
||||
app.terminate()
|
||||
app.wait(timeout=10)
|
||||
@@ -1,129 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""`werk auth …` and `werk sync status` without a window, on disposable data.
|
||||
|
||||
Uses fixture keys only (RFC 6238's) and never a display: DISPLAY and the
|
||||
other session variables are removed, so a window could not open.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
werk = root / "build/werk"
|
||||
output = root / "build/auth-command-test"
|
||||
shutil.rmtree(output, ignore_errors=True)
|
||||
data = output / "data"
|
||||
data.mkdir(parents=True)
|
||||
environment = {key: value for key, value in os.environ.items()
|
||||
if key not in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS")}
|
||||
environment["WERK_DATA"] = str(data)
|
||||
# No account exists, so nothing may reach this unreachable node.
|
||||
environment["WERK_SYNC_SERVER"] = "https://sync.example.invalid"
|
||||
|
||||
SECRET = base64.b32encode(b"12345678901234567890").decode()
|
||||
FIXTURE = f"otpauth://totp/Fixture:alice?secret={SECRET}&issuer=Fixture"
|
||||
# Example Co:[email protected] (the same key), Second:bob (SHA-256, 8 digits)
|
||||
# and a counter-based account, as Google Authenticator exports them.
|
||||
MIGRATION = ("otpauth-migration://offline?data=CjoKFDEyMzQ1Njc4OTAxMjM0NTY3ODkwEhxFeGFtcGxlIENvOmFsaWNl"
|
||||
"QGV4YW1wbGUuY29tIAEoATACCjUKIDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyEgNib2IaBlNlY29uZCAC"
|
||||
"KAIwAgorChQxMjM0NTY3ODkwMTIzNDU2Nzg5MBIHY291bnRlchoESG90cCABKAEwARABGAEgACi5YA%3D%3D")
|
||||
AEGIS = json.dumps({"version": 1, "header": {"slots": None, "params": None}, "db": {"version": 2, "entries": [
|
||||
{"type": "totp", "name": "carol", "issuer": "Third",
|
||||
"info": {"secret": SECRET, "algo": "SHA1", "digits": 7, "period": 60}}]}})
|
||||
AEGIS_ENCRYPTED = json.dumps({"version": 1, "header": {"slots": [{"type": 1}], "params": {}}, "db": "c2VhbGVk"})
|
||||
|
||||
|
||||
def run(*args, stdin="", status=0):
|
||||
result = subprocess.run([str(werk), *args], env=environment, input=stdin, capture_output=True,
|
||||
text=True, timeout=30)
|
||||
assert result.returncode == status, (args, result.returncode, result.stdout, result.stderr)
|
||||
assert SECRET not in result.stdout + result.stderr, "a secret reached the output"
|
||||
return result.stdout
|
||||
|
||||
|
||||
def accounts():
|
||||
listed = json.loads(run("auth", "list"))
|
||||
return {entry["issuer"]: entry for entry in listed}
|
||||
|
||||
|
||||
def totp(secret, at, digits=6, period=30, digest=hashlib.sha1):
|
||||
key = base64.b32decode(secret)
|
||||
mac = hmac.new(key, struct.pack(">Q", int(at) // period), digest).digest()
|
||||
offset = mac[-1] & 15
|
||||
value = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7fffffff
|
||||
return f"{value % 10 ** digits:0{digits}d}"
|
||||
|
||||
|
||||
run("auth", status=2)
|
||||
assert run("sync", "status") == "Account: none on this device\nAuth accounts: 0\n"
|
||||
|
||||
# Links and Google's export: the second copy of the key and the counter
|
||||
# account are left out.
|
||||
assert run("auth", "import", stdin=f"{FIXTURE}\n{MIGRATION}\n") == "Added 2 accounts, skipped 1\n"
|
||||
listed = accounts()
|
||||
assert sorted(listed) == ["Fixture", "Second"], listed
|
||||
assert listed["Second"]["digits"] == 8 and listed["Fixture"]["sites"] == []
|
||||
fixture = listed["Fixture"]["id"]
|
||||
records = data / "records/auth.txt"
|
||||
assert records.stat().st_mode & 0o077 == 0 and SECRET in records.read_text()
|
||||
|
||||
# The code, and how long it stays valid.
|
||||
before = time.time()
|
||||
code, seconds = run("auth", "code", fixture).split()
|
||||
after = time.time()
|
||||
assert code in {totp(SECRET, before), totp(SECRET, after)}, code
|
||||
assert 1 <= int(seconds) <= 30
|
||||
second = listed["Second"]["id"]
|
||||
code = run("auth", "code", second).split()[0]
|
||||
key = base64.b32encode(b"12345678901234567890123456789012").decode()
|
||||
assert code in {totp(key, before, 8, digest=hashlib.sha256), totp(key, time.time(), 8, digest=hashlib.sha256)}
|
||||
run("auth", "code", "0" * 32, status=1)
|
||||
run("auth", "code", "../escape", status=1)
|
||||
|
||||
# Renaming and websites keep the account's record.
|
||||
assert run("auth", "rename", fixture, "Fixture", "[email protected]") == "Saved\n"
|
||||
assert run("auth", "sites", fixture, "https://GitHub.com/login", "account.proton.me") == "Saved\n"
|
||||
listed = accounts()
|
||||
assert listed["Fixture"]["id"] == fixture and listed["Fixture"]["account"] == "[email protected]"
|
||||
assert listed["Fixture"]["sites"] == ["github.com", "account.proton.me"], listed["Fixture"]
|
||||
run("auth", "sites", fixture, "github..com", status=1)
|
||||
assert run("auth", "sites", fixture) == "Saved\n" and accounts()["Fixture"]["sites"] == []
|
||||
assert run("auth", "import", stdin=FIXTURE) == "Added 0 accounts\n", "the same key was added twice"
|
||||
|
||||
# Aegis from a file; an encrypted export is refused.
|
||||
export = output / "aegis.json"
|
||||
export.write_text(AEGIS)
|
||||
assert run("auth", "import", str(export)) == "Added 0 accounts\n"
|
||||
assert run("auth", "remove", fixture) == "Removed\n"
|
||||
assert run("auth", "import", str(export)) == "Added 1 account\n"
|
||||
third = accounts()["Third"]
|
||||
assert third["digits"] == 7 and third["period"] == 60
|
||||
export.write_text(AEGIS_ENCRYPTED)
|
||||
run("auth", "import", str(export), status=1)
|
||||
run("auth", "import", str(output / "missing.json"), status=1)
|
||||
|
||||
# A QR image of the export, where the system can read one.
|
||||
try:
|
||||
import qrcode
|
||||
except ImportError:
|
||||
qrcode = None
|
||||
zbar = any(Path(folder, "libzbar.so.0").exists() for folder in ("/usr/lib/x86_64-linux-gnu", "/usr/lib64", "/usr/lib"))
|
||||
if qrcode and zbar:
|
||||
assert run("auth", "remove", second) == "Removed\n"
|
||||
image = output / "export.png"
|
||||
qrcode.make(MIGRATION).save(image)
|
||||
# Example Co has Third's key.
|
||||
assert run("auth", "import", str(image)) == "Added 1 account, skipped 1\n"
|
||||
assert sorted(accounts()) == ["Second", "Third"]
|
||||
qr = "QR image"
|
||||
else:
|
||||
qr = "no QR image (needs python3-qrcode and libzbar0)"
|
||||
assert run("sync", "status").endswith("Auth accounts: 2\n")
|
||||
print(f"Werkzeug auth command: import, list, code, rename, websites, removal and {qr} without a window")
|
||||
@@ -1,11 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resize the owner-selected modular W bitmap for all distribution sizes."""
|
||||
"""Render the Werkzeug mark, a wrench with a keyhole, from the canonical vector for all distribution sizes."""
|
||||
from pathlib import Path
|
||||
import io
|
||||
import cairosvg
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / 'assets/app/logo.png'
|
||||
SVG = ROOT / 'assets/app/icon.svg'
|
||||
def render(size, background=None):
|
||||
image = Image.open(SOURCE).convert('RGBA').resize((size, size), Image.Resampling.LANCZOS)
|
||||
image = Image.open(io.BytesIO(cairosvg.svg2png(url=str(SVG), output_width=size, output_height=size))).convert('RGBA')
|
||||
if background:
|
||||
base = Image.new('RGBA', image.size, background); base.alpha_composite(image); image = base
|
||||
return image
|
||||
@@ -27,7 +29,7 @@ for path, size in [('assets/app/readme-banner.png',(1536,512)), ('assets/app/rea
|
||||
box=d.textbbox((0,0),name,font=font); tw=box[2]; gap=icon_size*.18
|
||||
if icon_size+gap+tw <= w*.86: break
|
||||
icon_size-=2
|
||||
mark=render(icon_size)
|
||||
mark=render(int(icon_size*1.5)); mark=mark.crop(mark.getbbox()) # the mark without the icon's padding
|
||||
left=int((w-mark.width-gap-tw)/2); top=int((h-mark.height)/2)
|
||||
image.paste(mark,(left,top),mark)
|
||||
d.text((left+mark.width+gap, (h-(box[3]-box[1]))/2-box[1]),name,font=font,fill='#291747')
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test native Entity account transitions with private fixture data only."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ZIRAN = os.environ.get('ZIRAN_BIN', str(ROOT / 'scripts/ziran.sh'))
|
||||
ENV = {key: value for key, value in os.environ.items()
|
||||
if key not in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS')}
|
||||
|
||||
def package(name):
|
||||
return Path(subprocess.check_output([ZIRAN, 'pkg', 'path', name], cwd=ROOT, text=True).strip())
|
||||
|
||||
std_root = package('ziran')
|
||||
monocypher = package('monocypher')
|
||||
output = ROOT / 'build/entity-account-test'
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
generated = output / 'generated'
|
||||
shutil.rmtree(generated, ignore_errors=True)
|
||||
subprocess.run([ZIRAN, 'build', '--project', '--root', str(ROOT), '--define', 'PLATFORM_DESKTOP', '--target=c',
|
||||
'--entry', 'entity_account_test:Check', '-o', str(generated),
|
||||
'tests/entity_account_test.zi'], cwd=ROOT, env=ENV, check=True)
|
||||
(generated / 'main.c').write_text('#include "tests/entity_account_test.h"\n#include <stdio.h>\n#include <string.h>\n'
|
||||
'int main(void) { int result = Check(); if (result) fprintf(stderr, "Entity account fixture %d failed\\n", result); return result != 0; }\n')
|
||||
executable = output / 'test'
|
||||
subprocess.run([os.environ.get('CC', 'cc'), '-std=c11', '-O2', '-ffunction-sections', '-fdata-sections',
|
||||
'-Wl,--gc-sections', f'-I{std_root / "include"}', f'-I{generated}', f'-I{monocypher / "src"}',
|
||||
*map(str, generated.rglob('*.c')), str(monocypher / 'src/monocypher.c'),
|
||||
str(monocypher / 'src/optional/monocypher-ed25519.c'),
|
||||
str(ROOT / 'build/liboqs/lib/liboqs.a'), '-l:libcurl.so.4', '-lpthread', '-lm', '-o', str(executable)], check=True, env=ENV)
|
||||
data = output / 'data'
|
||||
shutil.rmtree(data, ignore_errors=True)
|
||||
ENV.update(WERK_DATA=str(data), XDG_CACHE_HOME=str(output / 'cache'))
|
||||
subprocess.run([str(executable)], check=True, env=ENV)
|
||||
# A concurrent CLI reader must wait for an active GUI switch instead of
|
||||
# treating its rollback journal as an interrupted transaction.
|
||||
ready = data / 'account/switch/held'
|
||||
ready.unlink(missing_ok=True)
|
||||
writer = subprocess.Popen([str(executable)], env=dict(ENV, WERK_TEST_JOURNAL_MODE='hold'))
|
||||
reader = None
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
while not ready.exists() and time.monotonic() < deadline:
|
||||
assert writer.poll() is None, 'Journal writer exited before holding the lock'
|
||||
time.sleep(.02)
|
||||
assert ready.exists(), 'Journal lock fixture did not start'
|
||||
reader = subprocess.Popen([str(executable)], env=dict(ENV, WERK_TEST_JOURNAL_MODE='recover'))
|
||||
time.sleep(.2)
|
||||
assert reader.poll() is None and (data / 'account/switch/pending').exists(), 'A concurrent reader recovered an active journal'
|
||||
assert writer.wait(timeout=5) == 0 and reader.wait(timeout=5) == 0
|
||||
finally:
|
||||
for process in (reader, writer):
|
||||
if process and process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=5)
|
||||
ready.unlink(missing_ok=True)
|
||||
for path in data.rglob('*'):
|
||||
assert path.stat().st_mode & 0o077 == 0, f'Non-private fixture path: {path.name}'
|
||||
print('Entity: vault retention, merge/replace, tombstones, pause choice, failed writes, interrupted-switch recovery, concurrent reader locking and logout passed.')
|
||||
@@ -6,10 +6,6 @@ root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$root"
|
||||
work="$root/build/gui-smoke"
|
||||
rm -rf "$work"
|
||||
mkdir -p "$work/home/.local/lib/werk/apps"
|
||||
for app in pass auth calculator clock; do
|
||||
printf 'obsolete bundle\n' > "$work/home/.local/lib/werk/apps/$app.zib"
|
||||
done
|
||||
for mode in light dark; do
|
||||
mkdir -p "$work/$mode/data/profile" "$work/$mode/cache"
|
||||
value=1
|
||||
@@ -17,25 +13,11 @@ for mode in light dark; do
|
||||
value=2
|
||||
fi
|
||||
printf 'theme_mode=%s\n' "$value" > "$work/$mode/data/profile/settings.txt"
|
||||
python3 scripts/private-display.py \
|
||||
env -u WERK_ASSETS HOME="$work/home" WERK_DATA="$work/$mode/data" XDG_CACHE_HOME="$work/$mode/cache" \
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS xvfb-run -a -e /dev/stderr \
|
||||
env WERK_DATA="$work/$mode/data" XDG_CACHE_HOME="$work/$mode/cache" WERK_ASSETS="$root/build" \
|
||||
KRYON_CAPTURE_PATH="$work/werk-$mode.png" "$root/build/werk"
|
||||
test -s "$work/werk-$mode.png"
|
||||
done
|
||||
python3 - "$work" <<'PY'
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
import sys
|
||||
work = Path(sys.argv[1])
|
||||
# Isolate the dark labels from the muted tile fills before text recognition.
|
||||
with Image.open(work / "werk-light.png") as source:
|
||||
labels = source.convert("L").point(lambda value: 0 if value < 130 else 255)
|
||||
labels.resize((source.width * 3, source.height * 3)).save(work / "labels.png")
|
||||
PY
|
||||
rendered=$(tesseract "$work/labels.png" stdout --psm 11 2>/dev/null)
|
||||
for app in Pass Auth Calculator Clock; do
|
||||
printf '%s\n' "$rendered" | grep -q "$app" || { echo "Missing preinstalled app: $app" >&2; exit 1; }
|
||||
done
|
||||
if cmp -s "$work/werk-light.png" "$work/werk-dark.png"; then
|
||||
echo 'Werkzeug light and dark themes rendered the same frame' >&2
|
||||
exit 1
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install the same tool launchers in user installs and Linux packages."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--data-dir", type=Path, required=True)
|
||||
parser.add_argument("--bin-dir", type=Path)
|
||||
parser.add_argument("--desktop-dir", type=Path)
|
||||
parser.add_argument("--uninstall", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
def executable(path):
|
||||
# Desktop Entry Exec quoting has an additional escaping layer.
|
||||
value = str(path).replace("\\", "\\\\\\\\").replace('"', '\\\\"')
|
||||
value = value.replace("`", "\\\\`").replace("$", "\\\\$").replace("%", "%%")
|
||||
return '"' + value + '"'
|
||||
|
||||
|
||||
for source in sorted((root / "packaging/linux").glob("xyz.waozi.werk*.desktop")):
|
||||
destinations = [args.data_dir / "applications" / source.name]
|
||||
if args.desktop_dir:
|
||||
destinations.append(args.desktop_dir / source.name)
|
||||
content = source.read_text()
|
||||
if args.bin_dir:
|
||||
content = content.replace("Exec=werk ", "Exec=" + executable(args.bin_dir / "werk") + " ")
|
||||
content = content.replace("TryExec=werk", "TryExec=" + str(args.bin_dir / "werk"))
|
||||
for target in destinations:
|
||||
if args.uninstall:
|
||||
target.unlink(missing_ok=True)
|
||||
else:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(content)
|
||||
target.chmod(0o755 if target.parent == args.desktop_dir else 0o644)
|
||||
if target.parent == args.desktop_dir and shutil.which("gio"):
|
||||
subprocess.run(["gio", "set", str(target), "metadata::trusted", "true"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
icons = {"werk": root / "assets/app/icon.png"}
|
||||
icons.update({path.stem: path for path in (root / "packaging/linux/icons").glob("*.png")})
|
||||
for name, source in icons.items():
|
||||
target = args.data_dir / "icons/hicolor/512x512/apps" / (name + ".png")
|
||||
if args.uninstall:
|
||||
target.unlink(missing_ok=True)
|
||||
else:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, target)
|
||||
target.chmod(0o644)
|
||||
|
||||
notice = args.data_dir / "doc/werk/MingCute-LICENSE.txt"
|
||||
if args.uninstall:
|
||||
notice.unlink(missing_ok=True)
|
||||
else:
|
||||
notice.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(root / "packaging/linux/icons/LICENSE-MingCute.txt", notice)
|
||||
notice.chmod(0o644)
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Launch the installed desktop entries against disposable private data."""
|
||||
import configparser
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
assert os.environ.get("WERK_TEST_PRIVATE_DISPLAY") == "1", "Use private-display.py"
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
work = root / "build/launcher-gui-test"
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
stage = work / "install with spaces"
|
||||
share = stage / "share"
|
||||
desktop = stage / "Desktop"
|
||||
library = stage / "lib/werk"
|
||||
subprocess.run(["make", "install-gui", f"BIN_DIR={stage / 'bin'}", f"DATA_DIR={share}",
|
||||
f"LIB_DIR={library}", f"DESKTOP_DIR={desktop}"], cwd=root, check=True)
|
||||
environment = dict(os.environ, HOME=str(work / "home"), WERK_DATA=str(work / "data"),
|
||||
WERK_ASSETS=str(library), ENTITY_DATA=str(work / "entity"),
|
||||
XDG_DATA_HOME=str(share), XDG_CONFIG_HOME=str(work / "config"),
|
||||
XDG_CACHE_HOME=str(work / "cache"))
|
||||
for key in ("HOME", "WERK_DATA", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"):
|
||||
Path(environment[key]).mkdir(parents=True, exist_ok=True)
|
||||
profile = work / "data/profile"
|
||||
profile.mkdir(parents=True)
|
||||
(profile / "settings.txt").write_text("theme_mode=1\n")
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, env=environment, text=True, timeout=20)
|
||||
|
||||
|
||||
for tool, name in (("", "Werkzeug"), ("pass", "Pass"), ("auth", "Auth"),
|
||||
("calculator", "Calculator"), ("clock", "Clock"), ("workbook", "Workbook")):
|
||||
identity = "xyz.waozi.werk" + ("." + tool if tool else "")
|
||||
entry = share / "applications" / (identity + ".desktop")
|
||||
assert entry.read_bytes() == (desktop / entry.name).read_bytes()
|
||||
assert (desktop / entry.name).stat().st_mode & 0o100
|
||||
subprocess.run(["desktop-file-validate", str(entry)], check=True)
|
||||
config = configparser.ConfigParser(interpolation=None)
|
||||
config.read(entry)
|
||||
values = config["Desktop Entry"]
|
||||
assert values["Name"] == name
|
||||
assert (share / "icons/hicolor/512x512/apps" / (values["Icon"] + ".png")).is_file()
|
||||
argv = shlex.split(values["Exec"])
|
||||
if not tool:
|
||||
argv = argv[:1]
|
||||
process = subprocess.Popen(argv, env=environment)
|
||||
try:
|
||||
window = None
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, f"{name} exited during startup"
|
||||
result = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(process.pid)],
|
||||
env=environment, text=True, capture_output=True)
|
||||
if result.returncode == 0:
|
||||
window = result.stdout.splitlines()[0]
|
||||
if command("xdotool", "getwindowname", window).strip() == name:
|
||||
break
|
||||
time.sleep(.1)
|
||||
assert window and command("xdotool", "getwindowname", window).strip() == name
|
||||
wm_class = command("xprop", "-id", window, "WM_CLASS")
|
||||
assert values["StartupWMClass"] in wm_class, wm_class
|
||||
picture = work / ((tool or "werkzeug") + ".png")
|
||||
deadline = time.monotonic() + 15
|
||||
text = ""
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, f"{name} exited before rendering"
|
||||
time.sleep(.3)
|
||||
command("import", "-window", window, str(picture))
|
||||
text = command("tesseract", str(picture), "stdout", "--psm", "11")
|
||||
if name in text: break
|
||||
assert name in text, f"{name} did not render its direct tool screen: {text}"
|
||||
assert "unavailable" not in text.lower(), text
|
||||
print(f"Installed {name} entry opened the correct screen and window identity", flush=True)
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
|
||||
subprocess.run(["python3", str(root / "scripts/install-launchers.py"), "--data-dir", str(share),
|
||||
"--desktop-dir", str(desktop), "--uninstall"], check=True)
|
||||
assert not list((share / "applications").glob("xyz.waozi.werk*.desktop"))
|
||||
assert not list(desktop.glob("xyz.waozi.werk*.desktop"))
|
||||
print("All six installed launchers, distinct icons and shortcut removal verified locally")
|
||||
@@ -5,25 +5,24 @@ root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
version=$(sed -n '1p' "$root/VERSION")
|
||||
arch=${APPIMAGE_ARCH:-$(uname -m)}
|
||||
linuxdeploy=${LINUXDEPLOY:-linuxdeploy}
|
||||
artifacts=${WERK_BUILD_DIR:-$root/build}
|
||||
appdir="$root/build/package/appimage/werk.AppDir"
|
||||
out="$root/build/release/werk-${version}-${arch}.AppImage"
|
||||
|
||||
test -n "$version"
|
||||
rm -rf "$appdir"
|
||||
mkdir -p "$appdir/usr/bin" "$appdir/usr/lib/werk/apps" "$appdir/usr/share/applications" \
|
||||
"$appdir/usr/share/mime/packages" "$appdir/usr/share/metainfo" "$appdir/usr/share/icons/hicolor/512x512/apps" "$(dirname "$out")"
|
||||
cp "$artifacts/werk" "$appdir/usr/bin/werk"
|
||||
cp "$artifacts"/apps/*.zib "$appdir/usr/lib/werk/apps/"
|
||||
cp "$artifacts/pfp.png" "$appdir/usr/lib/werk/pfp.png"
|
||||
python3 "$root/scripts/install-launchers.py" --data-dir "$appdir/usr/share"
|
||||
cp "$root/packaging/linux/werk-bundle.xml" "$appdir/usr/share/mime/packages/werk-bundle.xml"
|
||||
"$appdir/usr/share/metainfo" "$appdir/usr/share/icons/hicolor/512x512/apps" "$(dirname "$out")"
|
||||
cp "$root/build/werk" "$appdir/usr/bin/werk"
|
||||
cp "$root"/build/apps/*.zib "$appdir/usr/lib/werk/apps/"
|
||||
cp "$root/build/pfp.png" "$appdir/usr/lib/werk/pfp.png"
|
||||
cp "$root/packaging/linux/xyz.waozi.werk.desktop" "$appdir/usr/share/applications/xyz.waozi.werk.desktop"
|
||||
cp "$root/packaging/linux/xyz.waozi.werk.appdata.xml" "$appdir/usr/share/metainfo/xyz.waozi.werk.appdata.xml"
|
||||
cp "$root/assets/app/icon.png" "$appdir/usr/share/icons/hicolor/512x512/apps/werk.png"
|
||||
cp "$root/assets/app/icon.png" "$root/build/package/appimage/werk.png"
|
||||
run_dir=$(mktemp -d "$root/build/package/appimage/output.XXXXXX")
|
||||
(cd "$run_dir" && ARCH="$arch" "$linuxdeploy" --appdir "$appdir" --desktop-file "$root/packaging/linux/xyz.waozi.werk.desktop" \
|
||||
--icon-file "$root/build/package/appimage/werk.png" --output appimage)
|
||||
image=$(find "$run_dir" -maxdepth 1 -type f -name '*.AppImage' -print | head -n 1)
|
||||
rm -f "$root"/Werkzeug-*.AppImage "$root"/werk-*.AppImage
|
||||
ARCH="$arch" "$linuxdeploy" --appdir "$appdir" --desktop-file "$root/packaging/linux/xyz.waozi.werk.desktop" \
|
||||
--icon-file "$root/build/package/appimage/werk.png" --output appimage
|
||||
image=$(find "$root" -maxdepth 1 -type f -name '*.AppImage' -print | head -n 1)
|
||||
test -n "$image"
|
||||
mv "$image" "$out"
|
||||
chmod 0755 "$out"
|
||||
|
||||
@@ -4,20 +4,19 @@ set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
version=$(sed -n '1p' "$root/VERSION")
|
||||
arch=${DEB_ARCH:-$(dpkg --print-architecture)}
|
||||
artifacts=${WERK_BUILD_DIR:-$root/build}
|
||||
stage="$root/build/package/deb/werk"
|
||||
out="$root/build/release"
|
||||
|
||||
test -n "$version"
|
||||
rm -rf "$stage"
|
||||
mkdir -p "$stage/DEBIAN" "$stage/usr/bin" "$stage/usr/lib/werk/apps" "$stage/usr/share/applications" \
|
||||
"$stage/usr/share/mime/packages" "$stage/usr/share/metainfo" "$stage/usr/share/icons/hicolor/512x512/apps" "$stage/usr/share/doc/werk" "$out"
|
||||
cp "$artifacts/werk" "$stage/usr/bin/werk"
|
||||
cp "$artifacts"/apps/*.zib "$stage/usr/lib/werk/apps/"
|
||||
cp "$artifacts/pfp.png" "$stage/usr/lib/werk/pfp.png"
|
||||
python3 "$root/scripts/install-launchers.py" --data-dir "$stage/usr/share"
|
||||
cp "$root/packaging/linux/werk-bundle.xml" "$stage/usr/share/mime/packages/werk-bundle.xml"
|
||||
"$stage/usr/share/metainfo" "$stage/usr/share/icons/hicolor/512x512/apps" "$stage/usr/share/doc/werk" "$out"
|
||||
cp "$root/build/werk" "$stage/usr/bin/werk"
|
||||
cp "$root"/build/apps/*.zib "$stage/usr/lib/werk/apps/"
|
||||
cp "$root/build/pfp.png" "$stage/usr/lib/werk/pfp.png"
|
||||
cp "$root/packaging/linux/xyz.waozi.werk.desktop" "$stage/usr/share/applications/xyz.waozi.werk.desktop"
|
||||
cp "$root/packaging/linux/xyz.waozi.werk.appdata.xml" "$stage/usr/share/metainfo/xyz.waozi.werk.appdata.xml"
|
||||
cp "$root/assets/app/icon.png" "$stage/usr/share/icons/hicolor/512x512/apps/werk.png"
|
||||
cp "$root/LICENSE" "$root/README.md" "$stage/usr/share/doc/werk/"
|
||||
find "$stage" -type d -exec chmod 0755 {} \;
|
||||
chmod 0755 "$stage/usr/bin/werk"
|
||||
@@ -29,7 +28,7 @@ Version: $version
|
||||
Architecture: $arch
|
||||
Maintainer: Waozi <[email protected]>
|
||||
Installed-Size: $installed
|
||||
Depends: libc6, libsdl2-2.0-0, libcairo2, libfreetype6, libfontconfig1, libpangocairo-1.0-0, libgtk-3-0, libx11-6, libcurl4 | libcurl4t64, libzbar0, gnumeric, zenity
|
||||
Depends: libc6, libsdl2-2.0-0, libcairo2, libfreetype6, libfontconfig1, libpangocairo-1.0-0
|
||||
Section: utils
|
||||
Priority: optional
|
||||
Homepage: https://werk.waozi.xyz/
|
||||
|
||||
@@ -7,15 +7,15 @@ root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$root"
|
||||
ziran_root=$("$ziran" pkg path ziran)
|
||||
kryon=$("$ziran" pkg path kryon)
|
||||
args="--root tests --module-path apps/pass --module-path shared --module-path kryon=$kryon/src/backend --module-path kryon=$kryon/src/ui --module-path $kryon/src/ui --module-path $ziran_root/std"
|
||||
args="--root tests --module-path apps/pass --module-path shared --module-path $kryon/src/ui --module-path $ziran_root/std"
|
||||
mkdir -p build/pass-state-test
|
||||
"$ziran" build $args --target=c -o build/pass-state-test/c tests/pass_state_test.zi
|
||||
${CC:-cc} -std=c99 -O2 -ffunction-sections -fdata-sections -Wl,--gc-sections -I"$ziran_root/include" -Ibuild/pass-state-test/c build/pass-state-test/c/*.c -o build/pass-state-test/native
|
||||
${CC:-cc} -std=c99 -O2 -I"$ziran_root/include" -Ibuild/pass-state-test/c build/pass-state-test/c/*.c -o build/pass-state-test/native
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY build/pass-state-test/native
|
||||
binds=""
|
||||
for name in ReadStoreHost WriteStoreHost ClipboardCopyHost SecureAvailableHost SecureSavedHost \
|
||||
SecureRequestHost SecureForgetHost SecurePollHost; do
|
||||
binds="$binds --bind app_context:$name=pass_state_host:$name"
|
||||
binds="$binds --bind werk_app:$name=pass_state_host:$name"
|
||||
done
|
||||
"$ziran" bundle $args --entry pass_state_test:PassStateAnswer $binds \
|
||||
-o build/pass-state-test/portable.zib tests/pass_state_test.zi tests/pass_state_host.zi
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run a GUI test under a verified, owned Xvfb server."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import select
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
environment = dict(os.environ)
|
||||
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER"):
|
||||
environment.pop(key, None)
|
||||
environment["YUE_DESKTOP_RECOVERY"] = "0"
|
||||
environment["WERK_TEST_PRIVATE_DISPLAY"] = "1"
|
||||
environment["SDL_RENDER_DRIVER"] = "software"
|
||||
read_fd, write_fd = os.pipe()
|
||||
server = subprocess.Popen(["Xvfb", "-displayfd", str(write_fd), "-screen", "0", "1280x1024x24", "-nolisten", "tcp"],
|
||||
pass_fds=(write_fd,), env=environment)
|
||||
os.close(write_fd)
|
||||
try:
|
||||
assert select.select([read_fd], [], [], 20)[0], "Xvfb did not allocate a private display"
|
||||
display = os.read(read_fd, 32).decode().strip()
|
||||
assert display.isdecimal() and server.poll() is None, "Private Xvfb did not start"
|
||||
process = Path(f"/proc/{server.pid}")
|
||||
executable = process.joinpath("exe").resolve()
|
||||
assert executable == Path(shutil.which("Xvfb")).resolve(), "Unexpected X server executable"
|
||||
assert process.stat().st_uid == os.getuid(), "Private server has another owner"
|
||||
command = process.joinpath("cmdline").read_bytes().replace(b"\0", b" ").decode()
|
||||
assert f"-displayfd {write_fd} " in command, "Unexpected display allocation source"
|
||||
evidence = Path(__file__).resolve().parents[1] / "build/desktop-task"
|
||||
evidence.mkdir(parents=True, exist_ok=True)
|
||||
with (evidence / "private-displays.log").open("a") as receipt:
|
||||
receipt.write(f"pid={server.pid} executable={executable} display=:{display} command={command}\n")
|
||||
environment["DISPLAY"] = ":" + display
|
||||
print(f"Verified owned private Xvfb for {sys.argv[1]}", flush=True)
|
||||
result = subprocess.run(sys.argv[1:], env=environment)
|
||||
raise SystemExit(result.returncode)
|
||||
finally:
|
||||
os.close(read_fd)
|
||||
if server.poll() is None:
|
||||
server.terminate()
|
||||
server.wait(timeout=10)
|
||||
@@ -1,28 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render the tools' existing MingCute vector icons as Linux launcher PNGs."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import xml.etree.ElementTree as ET
|
||||
import cairosvg
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
mingcute = Path(subprocess.check_output([str(root / "scripts/ziran.sh"), "pkg", "path", "mingcute"], text=True).strip())
|
||||
output = root / "packaging/linux/icons"
|
||||
output.mkdir(exist_ok=True)
|
||||
icons = {
|
||||
"pass": ("regular/system/keyhole.svg", "#6750A4"),
|
||||
"auth": ("regular/system/shield.svg", "#146B58"),
|
||||
"calculator": ("regular/education/counter.svg", "#245F9B"),
|
||||
"clock": ("regular/system/time.svg", "#9A4F19"),
|
||||
"workbook": ("extra/table_row_add.svg", "#356B30"),
|
||||
}
|
||||
for app, (relative, color) in icons.items():
|
||||
source = ET.parse(mingcute / "svg" / relative).getroot()
|
||||
for node in source.iter():
|
||||
for attribute in ("stroke", "fill"):
|
||||
if node.get(attribute) not in (None, "none"):
|
||||
node.set(attribute, "#FFFFFF")
|
||||
body = "".join(ET.tostring(node, encoding="unicode") for node in source)
|
||||
svg = f'<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><rect x="16" y="16" width="480" height="480" rx="112" fill="{color}"/><g transform="translate(88 88) scale(14)">{body}</g></svg>'
|
||||
cairosvg.svg2png(bytestring=svg.encode(), write_to=str(output / f"werk-{app}.png"))
|
||||
(output / "LICENSE-MingCute.txt").write_bytes((mingcute / "LICENSE").read_bytes())
|
||||
@@ -30,12 +30,6 @@ ${CC:-cc} -std=c99 -O2 -Wno-unused-variable -I"$("$ziran" pkg path ziran)/includ
|
||||
$(pkg-config --libs sdl2 cairo freetype2 fontconfig pangocairo) -l:libcurl.so.4 -lm -lpthread \
|
||||
-o "$work/sync_e2e"
|
||||
|
||||
mkdir -p "$work/preferences"
|
||||
for mode in preferences paused; do
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u WERK_SYNC_SERVER \
|
||||
WERK_DATA="$work/preferences" "$work/sync_e2e" "$mode"
|
||||
done
|
||||
|
||||
port=$((20000 + $$ % 20000))
|
||||
server=http://127.0.0.1:$port
|
||||
secret=$(od -An -tx1 -N32 /dev/urandom | tr -d ' \n')
|
||||
@@ -73,63 +67,9 @@ device b join "$work/code.txt"
|
||||
wait $shower || { cat "$work/show.log"; exit 1; }
|
||||
device a remove
|
||||
device b absent
|
||||
# The same through `werk` without a window: one device creates the account
|
||||
# and imports a link, another connects with the code `werk sync show`
|
||||
# prints, receives the account with its website and removes it again.
|
||||
make build/werk > /dev/null
|
||||
werk() {
|
||||
dir=$1
|
||||
shift
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS WERK_DATA="$work/$dir" \
|
||||
WERK_SYNC_SERVER="$server" "$root/build/werk" "$@"
|
||||
}
|
||||
mkdir -p "$work/werk-a" "$work/werk-b"
|
||||
werk werk-a sync create > /dev/null
|
||||
printf '%s\n' 'otpauth://totp/Test:carol?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Test&sites=example.com' |
|
||||
werk werk-a auth import > /dev/null
|
||||
werk werk-a sync show > "$work/werk-show.log" 2>&1 &
|
||||
shower=$!
|
||||
tries=0
|
||||
until grep -q 'other device: ' "$work/werk-show.log"; do
|
||||
tries=$((tries + 1))
|
||||
if [ $tries -gt 100 ]; then
|
||||
cat "$work/werk-show.log"
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.1
|
||||
done
|
||||
sed -n 's/.*other device: //p' "$work/werk-show.log" | werk werk-b sync join > /dev/null
|
||||
wait $shower || { cat "$work/werk-show.log"; exit 1; }
|
||||
listed=$(werk werk-b auth list)
|
||||
case $listed in
|
||||
*'"issuer":"Test","account":"carol","sites":["example.com"]'*) ;;
|
||||
*) echo "the connected device did not receive the account: $listed"; exit 1 ;;
|
||||
esac
|
||||
id=$(printf '%s' "$listed" | sed -n 's/.*"id":"\([0-9a-f]*\)".*/\1/p')
|
||||
werk werk-b auth remove "$id" > /dev/null
|
||||
test "$(werk werk-a auth list)" = '[]' || { echo 'the removal did not reach the first device'; exit 1; }
|
||||
|
||||
# A Daochi account key, as Inbe exports it, signs devices in to the same
|
||||
# records: one with the plain key, one with the passphrase-protected copy.
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY "$work/sync_e2e" keyfiles "$work/account.key" "$work/account-locked.key" \
|
||||
'fixture passphrase' > /dev/null
|
||||
mkdir -p "$work/werk-c" "$work/werk-d" "$work/werk-e"
|
||||
werk werk-c sync key "$work/account.key" > /dev/null
|
||||
printf '%s\n' 'otpauth://totp/Keyed:dave?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Keyed' |
|
||||
werk werk-c auth import > /dev/null
|
||||
if printf 'wrong\n' | werk werk-e sync key "$work/account-locked.key" > /dev/null 2>&1; then
|
||||
echo 'a wrong passphrase signed in'
|
||||
exit 1
|
||||
fi
|
||||
printf 'fixture passphrase\n' | werk werk-d sync key "$work/account-locked.key" > /dev/null
|
||||
case $(werk werk-d auth list) in
|
||||
*'"issuer":"Keyed","account":"dave"'*) ;;
|
||||
*) echo 'the device signed in with the key did not receive the account'; exit 1 ;;
|
||||
esac
|
||||
|
||||
# The server stored only sealed records: the test secret never reached it.
|
||||
if grep -a -q GEZDGNBVGY3TQOJQ "$work/daochi.db"* 2>/dev/null; then
|
||||
echo "the server stored a secret in plain text"
|
||||
exit 1
|
||||
fi
|
||||
echo 'Werkzeug sync: account, connected device, record and removal through a local Daochi node, also with werk sync, werk auth and an account key'
|
||||
echo 'Werkzeug sync: account, connected device, record and removal through a local Daochi node'
|
||||
@@ -1,7 +1,7 @@
|
||||
// Exercise the built site's Werkzeug app in a private headless browser with a
|
||||
// disposable profile: the home screen, a tool opened by clicking Home and by
|
||||
// ?app=, Calculator typing, Clock, and every tool in embedded mini mode.
|
||||
import {spawn, spawnSync} from 'node:child_process';
|
||||
// disposable profile: the home screen, a tool opened by ?app=, Calculator
|
||||
// typing, and Pass alone by ?mini as embedding pages use it.
|
||||
import {spawn} from 'node:child_process';
|
||||
import {readFile, writeFile, mkdir, mkdtemp} from 'node:fs/promises';
|
||||
import {createServer} from 'node:http';
|
||||
import {resolve, join, extname} from 'node:path';
|
||||
@@ -93,43 +93,6 @@ try {
|
||||
const shot = await command('Page.captureScreenshot', {format: 'png'});
|
||||
await writeFile(join(output, name + '.png'), Buffer.from(shot.data, 'base64'));
|
||||
};
|
||||
const expectText = async (name, expected) => {
|
||||
await screenshot(name);
|
||||
let result = spawnSync('tesseract', [join(output, name + '.png'), 'stdout', '--psm', '11'],
|
||||
{env: environment, encoding: 'utf8', timeout: 20000});
|
||||
if (result.status !== 0) throw Error('Screenshot OCR failed: ' + result.stderr);
|
||||
if (!result.stdout.toLowerCase().includes(expected.toLowerCase())) {
|
||||
const readable = join(output, name + '-labels.png');
|
||||
const prepared = spawnSync('convert', [join(output, name + '.png'), '-colorspace', 'Gray',
|
||||
'-threshold', '55%', '-resize', '300%', readable], {env: environment, encoding: 'utf8'});
|
||||
if (prepared.status !== 0) throw Error('Could not prepare UI text: ' + prepared.stderr);
|
||||
result = spawnSync('tesseract', [readable, 'stdout', '--psm', '11'],
|
||||
{env: environment, encoding: 'utf8', timeout: 20000});
|
||||
if (result.status !== 0) throw Error('Screenshot OCR failed: ' + result.stderr);
|
||||
}
|
||||
if (!result.stdout.toLowerCase().includes(expected.toLowerCase()))
|
||||
throw Error(`${name}: expected ${expected}, saw ${result.stdout}`);
|
||||
};
|
||||
const click = async (x, y) => {
|
||||
await command('Input.dispatchMouseEvent', {type: 'mousePressed', x, y, button: 'left', clickCount: 1});
|
||||
await command('Input.dispatchMouseEvent', {type: 'mouseReleased', x, y, button: 'left', clickCount: 1});
|
||||
await delay(350);
|
||||
};
|
||||
const clickText = async label => {
|
||||
await screenshot('control');
|
||||
const readable = join(output, 'control-labels.png');
|
||||
const prepared = spawnSync('convert', [join(output, 'control.png'), '-colorspace', 'Gray',
|
||||
'-threshold', '55%', '-resize', '300%', readable], {env: environment, encoding: 'utf8'});
|
||||
if (prepared.status !== 0) throw Error('Could not prepare UI text: ' + prepared.stderr);
|
||||
const result = spawnSync('tesseract', [readable, 'stdout', '--psm', '11',
|
||||
'-c', 'tessedit_create_tsv=1'], {env: environment, encoding: 'utf8', timeout: 20000});
|
||||
if (result.status !== 0) throw Error('Screenshot OCR failed: ' + result.stderr);
|
||||
const rows = result.stdout.trim().split('\n').slice(1).map(line => line.split('\t'));
|
||||
const row = rows.find(values => values[11]?.trim() === label);
|
||||
if (!row) throw Error('Missing visible app control: ' + label);
|
||||
await click((Number(row[6]) + Number(row[8]) / 2) / 3,
|
||||
(Number(row[7]) + Number(row[9]) / 2) / 3);
|
||||
};
|
||||
// The canvas has drawn a frame with something besides the background.
|
||||
const painted = `(() => {
|
||||
const canvas = document.querySelector('canvas');
|
||||
@@ -164,55 +127,14 @@ try {
|
||||
};
|
||||
await command('Runtime.enable');
|
||||
await command('Page.enable');
|
||||
await command('Page.addScriptToEvaluateOnNewDocument', {source: `
|
||||
window.__timezoneReads = 0;
|
||||
const getTimezoneOffset = Date.prototype.getTimezoneOffset;
|
||||
Date.prototype.getTimezoneOffset = function() {
|
||||
window.__timezoneReads++;
|
||||
return getTimezoneOffset.call(this);
|
||||
};
|
||||
`});
|
||||
await command('Emulation.setDeviceMetricsOverride', {width: 420, height: 760, deviceScaleFactor: 1, mobile: false});
|
||||
await open('', 'home');
|
||||
const timezoneReadsBefore = await evaluate('window.__timezoneReads');
|
||||
await click(330, 92); // Shared List view.
|
||||
await clickText('Clock');
|
||||
await expectText('home-clock', 'Clock');
|
||||
await delay(1200);
|
||||
const timezoneReads = (await evaluate('window.__timezoneReads')) - timezoneReadsBefore;
|
||||
if (timezoneReads > 6) throw Error(`Clock read the time zone ${timezoneReads} times in 1.2 seconds`);
|
||||
await click(28, 28);
|
||||
await expectText('home-returned', 'Werkzeug');
|
||||
await open('?app=calculator', 'calculator');
|
||||
await type('12+30*2=');
|
||||
await delay(400);
|
||||
await expectText('calculator-typed', '72');
|
||||
// Clock also opens directly, where a broken time binding froze the page.
|
||||
await open('?app=clock', 'clock');
|
||||
// The embedded mini version opens on Home with every tool; a tool
|
||||
// would show its own name as the title.
|
||||
await open('?mini', 'mini-home');
|
||||
await expectText('mini-home', 'Werkzeug');
|
||||
for (const app of ['pass', 'auth', 'calculator', 'clock']) {
|
||||
await open('?mini&app=' + app, app + '-mini-direct');
|
||||
await expectText(app + '-mini-direct', app);
|
||||
await click(28, 28);
|
||||
await expectText(app + '-mini-home', 'Werkzeug');
|
||||
await clickText(app[0].toUpperCase() + app.slice(1));
|
||||
await expectText(app + '-mini-reopened', app);
|
||||
}
|
||||
await command('Emulation.setDeviceMetricsOverride', {width: 280, height: 480, deviceScaleFactor: 1, mobile: false});
|
||||
await open('?mini&app=unknown', 'mini-narrow-home');
|
||||
await expectText('mini-narrow-home', 'Find an app');
|
||||
await click(100, 92);
|
||||
await type('clock');
|
||||
await clickText('Clock');
|
||||
await expectText('mini-narrow-clock', 'Clock');
|
||||
await click(28, 28);
|
||||
await click(250, 28);
|
||||
await expectText('mini-narrow-profile', 'Profile');
|
||||
await screenshot('calculator-typed');
|
||||
await open('?mini', 'pass-mini');
|
||||
if (exceptions.length) throw Error('Page exceptions: ' + exceptions.join(' '));
|
||||
console.log('Werkzeug web: Calculator result, every mini tool, Home, Profile and narrow navigation verified in private Chromium');
|
||||
console.log('Werkzeug web: home, Calculator and Pass in mini mode drew in a private headless browser');
|
||||
} finally {
|
||||
socket?.close();
|
||||
try {
|
||||
|
||||
@@ -5,9 +5,6 @@ Uses disposable data and cache folders and fixture secrets only. Run
|
||||
through scripts/werk_gui_test.sh, which starts the private display.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
@@ -16,7 +13,6 @@ import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
from PIL import Image
|
||||
|
||||
assert os.environ.get("WERK_TEST_PRIVATE_DISPLAY") == "1", "Run scripts/werk_gui_test.sh"
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
@@ -26,34 +22,17 @@ data = output / "data"
|
||||
cache = output / "cache"
|
||||
data.mkdir(parents=True)
|
||||
cache.mkdir(parents=True)
|
||||
(data / "profile").mkdir()
|
||||
(data / "profile/settings.txt").write_text("name=Fixture Person\ntheme_mode=1\n")
|
||||
environment = dict(os.environ)
|
||||
environment.pop("WAYLAND_DISPLAY", None)
|
||||
environment["WERK_DATA"] = str(data)
|
||||
environment["ENTITY_DATA"] = str(output / "shared-entity")
|
||||
environment["XDG_DATA_HOME"] = str(output / "xdg-data")
|
||||
environment["XDG_CONFIG_HOME"] = str(output / "xdg-config")
|
||||
environment["XDG_CACHE_HOME"] = str(cache)
|
||||
environment["WERK_ASSETS"] = str(root / "build")
|
||||
# Import file runs zenity; this stand-in chooses a fixture Aegis export.
|
||||
fake_bin = output / "bin"
|
||||
fake_bin.mkdir()
|
||||
(fake_bin / "zenity").write_text('#!/bin/sh\nprintf "%s\\n" "$WERK_TEST_IMPORT_FILE"\n')
|
||||
(fake_bin / "zenity").chmod(0o755)
|
||||
environment["PATH"] = f"{fake_bin}:{environment['PATH']}"
|
||||
environment["WERK_TEST_IMPORT_FILE"] = str(output / "aegis.json")
|
||||
app = None
|
||||
window = None
|
||||
|
||||
# The RFC 6238 SHA-1 fixture key, never a real account.
|
||||
FIXTURE_SECRET = base64.b32encode(b"12345678901234567890").decode()
|
||||
FIXTURE_LINK = f"otpauth://totp/Fixture:[email protected]?secret={FIXTURE_SECRET}&issuer=Fixture"
|
||||
# A Google Authenticator export of the same key, an RFC 6238 SHA-256 key and
|
||||
# a counter-based account (see apps/auth/exports_test.zi).
|
||||
MIGRATION_LINK = ("otpauth-migration://offline?data=CjoKFDEyMzQ1Njc4OTAxMjM0NTY3ODkwEhxFeGFtcGxlIENvOmFsaWNl"
|
||||
"QGV4YW1wbGUuY29tIAEoATACCjUKIDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyEgNib2IaBlNlY29uZCAC"
|
||||
"KAIwAgorChQxMjM0NTY3ODkwMTIzNDU2Nzg5MBIHY291bnRlchoESG90cCABKAEwARABGAEgACi5YA%3D%3D")
|
||||
|
||||
|
||||
def command(*args):
|
||||
@@ -105,94 +84,14 @@ def capture(name):
|
||||
command("import", "-window", window, str(output / f"{name}.png"))
|
||||
|
||||
|
||||
def click_word(word, toggle=False, last=False, exact_case=False):
|
||||
capture("control")
|
||||
for factor, labels in ((1, False), (3, False), (3, True)):
|
||||
target = output / "control.png"
|
||||
if factor > 1:
|
||||
target = output / "control-enlarged.png"
|
||||
with Image.open(output / "control.png") as source:
|
||||
readable = source.convert("L").point(lambda value: 0 if value < 140 else 255) if labels else source
|
||||
readable.resize((source.width * factor, source.height * factor)).save(target)
|
||||
text = command("tesseract", str(target), "stdout", "--psm", "11",
|
||||
"-c", "tessedit_create_tsv=1")
|
||||
matches = [item for item in csv.DictReader(io.StringIO(text), delimiter="\t") if (item["text"].strip() == word if exact_case else item["text"].strip().lower() == word.lower())]
|
||||
if last: matches.reverse()
|
||||
for item in matches:
|
||||
if item["text"].strip().lower() == word.lower():
|
||||
click(350 if toggle else (int(item["left"]) + int(item["width"]) // 2) // factor,
|
||||
(int(item["top"]) + int(item["height"]) // 2) // factor)
|
||||
return ((int(item["left"]) + int(item["width"]) // 2) // factor,
|
||||
(int(item["top"]) + int(item["height"]) // 2) // factor)
|
||||
raise AssertionError(f"Could not find {word!r} in the private test window")
|
||||
|
||||
|
||||
def click_scrolled(word, **options):
|
||||
for attempt in range(12):
|
||||
try:
|
||||
return click_word(word, **options)
|
||||
except AssertionError:
|
||||
command("xdotool", "mousemove", "--window", window, "200", "650")
|
||||
command("xdotool", "click", "--window", window, "--repeat", "3", "--delay", "50", "5")
|
||||
time.sleep(.2)
|
||||
raise AssertionError("Missing scrollable control: " + word)
|
||||
|
||||
|
||||
def click_filled():
|
||||
capture("filled-control")
|
||||
with Image.open(output / "filled-control.png") as source:
|
||||
pixels = source.convert("RGB")
|
||||
rows = []
|
||||
for y in range(56, pixels.height):
|
||||
span = [x for x in range(pixels.width)
|
||||
if min(pixels.getpixel((x, y))) < 120
|
||||
and max(pixels.getpixel((x, y))) < 220
|
||||
and max(pixels.getpixel((x, y))) - min(pixels.getpixel((x, y))) > 40]
|
||||
if len(span) > 200:
|
||||
rows.append((min(span), y, max(span)))
|
||||
assert rows, "Missing filled account action"
|
||||
click((rows[0][0] + rows[0][2]) // 2, (rows[0][1] + rows[-1][1]) // 2)
|
||||
|
||||
|
||||
def screen_text():
|
||||
capture("control")
|
||||
return command("tesseract", str(output / "control.png"), "stdout", "--psm", "11")
|
||||
|
||||
|
||||
def field_below(word, offset=40):
|
||||
capture("control")
|
||||
text = command("tesseract", str(output / "control.png"), "stdout", "--psm", "11", "-c", "tessedit_create_tsv=1")
|
||||
for item in csv.DictReader(io.StringIO(text), delimiter="\t"):
|
||||
if item["text"].strip() == word:
|
||||
return int(item["left"]) + 80, int(item["top"]) + offset
|
||||
raise AssertionError("Missing field label: " + word)
|
||||
|
||||
|
||||
def scroll_up():
|
||||
command("xdotool", "mousemove", "--window", window, "210", "400")
|
||||
command("xdotool", "click", "--window", window, "--repeat", "18", "--delay", "40", "4")
|
||||
time.sleep(.4)
|
||||
|
||||
|
||||
def add_node(field):
|
||||
# The private fixture window is 420 units wide; the Add button shares
|
||||
# the node field row and remains visible with either appearance/accent.
|
||||
click(344, field[1])
|
||||
|
||||
|
||||
def scroll_down():
|
||||
command("xdotool", "mousemove", "--window", window, "210", "650")
|
||||
command("xdotool", "click", "--window", window, "--repeat", "12", "--delay", "70", "5")
|
||||
time.sleep(0.4)
|
||||
|
||||
|
||||
def clipboard():
|
||||
return command("xclip", "-selection", "clipboard", "-out")
|
||||
|
||||
|
||||
def open_tool(name):
|
||||
click_word(name, exact_case=True)
|
||||
assert command("xdotool", "getwindowname", window).strip() == name
|
||||
def tile(index):
|
||||
"""The centre of a home screen tile; the window is 420 wide."""
|
||||
left = (420 - (2 * 120 + 16)) // 2
|
||||
return left + (index % 2) * 136 + 60, 56 + 16 + (index // 2) * 136 + 60
|
||||
|
||||
|
||||
def home():
|
||||
@@ -207,66 +106,12 @@ def totp(secret, at):
|
||||
return f"{value % 1000000:06d}"
|
||||
|
||||
|
||||
def import_invalid_key():
|
||||
# Select an invalid fixture through the real native key chooser.
|
||||
# Both the dialog and the main window belong to this test process.
|
||||
scroll_up()
|
||||
click_word("Import")
|
||||
click_filled()
|
||||
dialog = None
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
found = command("xdotool", "search", "--onlyvisible", "--pid", str(app.pid)).splitlines()
|
||||
for candidate in found:
|
||||
if candidate != window and command("xdotool", "getwindowname", candidate).strip() == "Import account key":
|
||||
dialog = candidate
|
||||
break
|
||||
if dialog: break
|
||||
time.sleep(.1)
|
||||
assert dialog, "Native account file chooser did not open"
|
||||
invalid_key = output / "invalid-account.key"
|
||||
invalid_key.write_text("fixture: not an account key")
|
||||
command("xdotool", "windowfocus", "--sync", dialog)
|
||||
command("xdotool", "key", "--clearmodifiers", "ctrl+l")
|
||||
time.sleep(.3)
|
||||
command("xdotool", "type", "--clearmodifiers", "--delay", "5", str(invalid_key))
|
||||
command("xdotool", "key", "--clearmodifiers", "Return")
|
||||
time.sleep(1)
|
||||
visible = command("xdotool", "search", "--onlyvisible", "--pid", str(app.pid)).splitlines()
|
||||
if dialog in visible:
|
||||
geometry = dict(item.split("=", 1) for item in command("xdotool", "getwindowgeometry", "--shell", dialog).splitlines())
|
||||
command("xdotool", "mousemove", "--window", dialog, str(int(geometry["WIDTH"]) - 50), str(int(geometry["HEIGHT"]) - 24))
|
||||
command("xdotool", "click", "1")
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline:
|
||||
found = command("xdotool", "search", "--onlyvisible", "--pid", str(app.pid)).splitlines()
|
||||
if dialog not in found: break
|
||||
time.sleep(.2)
|
||||
if dialog in found:
|
||||
command("xdotool", "windowraise", window)
|
||||
command("xdotool", "windowfocus", "--sync", window)
|
||||
time.sleep(1)
|
||||
capture("chooser-main-after-selection")
|
||||
assert dialog not in found, "Native file selection did not finish"
|
||||
command("xdotool", "windowfocus", "--sync", window)
|
||||
time.sleep(1)
|
||||
assert not (data / "account/keys.txt").exists(), "An invalid key created an account"
|
||||
assert "notvalid" in "".join(screen_text().split()), "Invalid key error was not shown"
|
||||
capture("invalid-account-refused")
|
||||
|
||||
|
||||
try:
|
||||
start()
|
||||
if os.environ.get("WERK_GUI_CHOOSER_ONLY") == "1":
|
||||
click(390, 28)
|
||||
click_word("Connect", exact_case=True)
|
||||
import_invalid_key()
|
||||
print("Native key chooser selected the invalid fixture and returned its validation error")
|
||||
raise SystemExit(0)
|
||||
capture("home")
|
||||
|
||||
# Pass: the same inputs give the LessPass reference password.
|
||||
open_tool("Pass")
|
||||
click(*tile(0))
|
||||
capture("pass-open")
|
||||
left = (420 - 384) // 2
|
||||
click(left + 100, 56 + 12 + 24 + 20)
|
||||
@@ -285,34 +130,23 @@ try:
|
||||
home()
|
||||
|
||||
# Calculator: keyboard input.
|
||||
open_tool("Calculator")
|
||||
click(*tile(2))
|
||||
type_text("12+30*2=")
|
||||
capture("calculator")
|
||||
assert "72" in screen_text(), "Calculator did not show the expected result"
|
||||
home()
|
||||
|
||||
# Clock.
|
||||
open_tool("Clock")
|
||||
click(*tile(3))
|
||||
capture("clock")
|
||||
click_word("Stopwatch")
|
||||
click(110, 382)
|
||||
time.sleep(1.2)
|
||||
click(110, 382)
|
||||
stopwatch = next(data.rglob("stopwatch.txt"))
|
||||
state = [int(value) for value in stopwatch.read_text().split()]
|
||||
assert state[0] == 0 and state[2] >= 1000, "Stopwatch did not advance and stop"
|
||||
capture("stopwatch")
|
||||
click(310, 382)
|
||||
assert stopwatch.read_text().split() == ["0", "0", "0"], "Stopwatch did not reset"
|
||||
home()
|
||||
|
||||
# Auth: import a fixture link and copy its code.
|
||||
open_tool("Auth")
|
||||
click(*tile(1))
|
||||
capture("auth-empty")
|
||||
click(210, 56 + 12 + 20)
|
||||
click(210, 56 + 12 + 24 + 20)
|
||||
type_text(FIXTURE_LINK)
|
||||
click(16 + 95, 56 + 12 + 76 + 20)
|
||||
click(210, 56 + 12 + 76 + 20)
|
||||
capture("auth-list")
|
||||
before = time.time()
|
||||
click(420 - 16 - 10 - 196 + 70 + 16, 56 + 64 + 12 + 22)
|
||||
@@ -325,119 +159,18 @@ try:
|
||||
records = data / "records/auth.txt"
|
||||
saved = records.read_text()
|
||||
assert FIXTURE_SECRET in saved and "\tV\t1\t" in saved and records.stat().st_mode & 0o077 == 0
|
||||
# A Google Authenticator export adds its new time-based account; the
|
||||
# fixture key is already here and the counter-based one is skipped.
|
||||
click(210, 56 + 12 + 20)
|
||||
click(210, 56 + 12 + 24 + 20)
|
||||
type_text(MIGRATION_LINK)
|
||||
click(16 + 95, 56 + 12 + 76 + 20)
|
||||
capture("auth-imported")
|
||||
saved = records.read_text()
|
||||
assert saved.count("\tV\t") == 2 and "Second:bob" in saved, saved.count("\tV\t")
|
||||
# Edit renames the account and keeps the websites where it signs in, in
|
||||
# the same record.
|
||||
edit = (420 - 16 - 10 - 40 + 18, 56 + 64 + 16 + 18)
|
||||
click(*edit)
|
||||
capture("auth-edit")
|
||||
click(210, 56 + 12 + 48 + 20)
|
||||
key("ctrl+a")
|
||||
type_text("[email protected]")
|
||||
click(210, 56 + 12 + 48 + 56 + 24 + 20)
|
||||
type_text("https://GitHub.com/login")
|
||||
click(16 + 95, 56 + 12 + 48 + 56 + 24 + 56 + 20)
|
||||
capture("auth-edited")
|
||||
saved = records.read_text()
|
||||
assert saved.count("\tV\t") == 2 and "Fixture:renamed%40example.com" in saved and "&sites=github.com" in saved
|
||||
# Remove, inside Edit, needs a second tap.
|
||||
click(*edit)
|
||||
remove = (210, 56 + 12 + 48 + 56 + 24 + 56 + 64 + 20)
|
||||
click(*remove)
|
||||
assert "\tD\t" not in records.read_text(), "One tap removed an Auth account"
|
||||
click(*remove)
|
||||
capture("auth-removed")
|
||||
saved = records.read_text()
|
||||
assert saved.count("\tV\t") == 1 and saved.count("\tD\t") == 1 and "Second:bob" in saved
|
||||
# Import file reads an export the owner chooses.
|
||||
(output / "aegis.json").write_text(json.dumps({"version": 1, "header": {"slots": None}, "db": {"version": 2, "entries": [
|
||||
{"type": "totp", "name": "carol", "issuer": "Third",
|
||||
"info": {"secret": FIXTURE_SECRET, "algo": "SHA1", "digits": 6, "period": 30}}]}}))
|
||||
click(210, 56 + 12 + 20)
|
||||
click(16 + 190 + 8 + 95, 56 + 12 + 76 + 20)
|
||||
capture("auth-file-imported")
|
||||
saved = records.read_text()
|
||||
assert saved.count("\tV\t") == 2 and "Third:carol" in saved, saved.count("\tV\t")
|
||||
home()
|
||||
|
||||
# Entity retains existing names; its current profile edits appearance.
|
||||
assert "name=Fixture Person\n" in (data / "profile/settings.txt").read_text()
|
||||
click(390, 28)
|
||||
scroll_down()
|
||||
click_word("Dark")
|
||||
# Profile: a name and dark appearance are saved privately.
|
||||
click(420 - 30, 28)
|
||||
click(210, 56 + 16 + 112 + 28 + 20)
|
||||
type_text("Fixture Person")
|
||||
key("Return")
|
||||
click(332, 56 + 16 + 112 + 88 + 32 + 20)
|
||||
capture("profile")
|
||||
settings = (data / "profile/settings.txt").read_text()
|
||||
assert "name=Fixture Person\n" in settings and "theme_mode=2\n" in settings, settings
|
||||
assert (data / "profile/settings.txt").stat().st_mode & 0o077 == 0
|
||||
# Nodes belong to the common Entity bundle; choosing one creates no account.
|
||||
click_word("Light")
|
||||
scroll_up()
|
||||
click_word("Connect", exact_case=True)
|
||||
node_field = field_below("Nodes", 120)
|
||||
click(*node_field)
|
||||
type_text("https://example.invalid/path")
|
||||
add_node(node_field)
|
||||
assert "node=https://api.waozi.xyz\n" in (data / "profile/settings.txt").read_text()
|
||||
capture("node-invalid")
|
||||
click(*node_field)
|
||||
key("ctrl+a")
|
||||
type_text("https://sync.example.invalid:8443/")
|
||||
add_node(node_field)
|
||||
assert "node=https://sync.example.invalid:8443\n" in (data / "profile/settings.txt").read_text()
|
||||
assert not (data / "account/keys.txt").exists(), "Choosing a node created an account"
|
||||
capture("node-saved")
|
||||
stop()
|
||||
start()
|
||||
click(390, 28)
|
||||
click_word("Connect", exact_case=True)
|
||||
capture("node-restarted")
|
||||
assert "node=https://sync.example.invalid:8443\n" in (data / "profile/settings.txt").read_text()
|
||||
assert not (data / "account/keys.txt").exists()
|
||||
scroll_up()
|
||||
# The filled action's painted bounds are stable even when OCR misses
|
||||
# white labels. Creating an account explicitly asks to merge Auth data.
|
||||
click_filled()
|
||||
time.sleep(.8)
|
||||
click_word("merge", last=True)
|
||||
time.sleep(.8)
|
||||
account_file = data / "account/keys.txt"
|
||||
assert account_file.exists() and "paused=0\n" in account_file.read_text()
|
||||
click_scrolled("Sync", toggle=True)
|
||||
assert "paused=1\n" in account_file.read_text(), "Entity's sync switch did not pause"
|
||||
capture("sync-paused")
|
||||
stop()
|
||||
start()
|
||||
assert "paused=1\n" in account_file.read_text()
|
||||
click(390, 28)
|
||||
# The connected account's public-ID button opens management.
|
||||
click(210, 310)
|
||||
capture("sync-paused-restarted")
|
||||
previous_account = account_file.read_text()
|
||||
scroll_down()
|
||||
node_field = click_scrolled("address")
|
||||
type_text("https://second.example.invalid")
|
||||
add_node(node_field)
|
||||
account = account_file.read_text()
|
||||
assert "server=https://second.example.invalid\n" in account, "The account kept its old node"
|
||||
assert "paused=1\n" in account, "Changing node resumed a paused account"
|
||||
assert ([line for line in previous_account.splitlines() if not line.startswith("server=")]
|
||||
== [line for line in account.splitlines() if not line.startswith("server=")]), "Changing node altered account credentials"
|
||||
scroll_up()
|
||||
click_scrolled("out")
|
||||
click_filled()
|
||||
time.sleep(.8)
|
||||
assert not account_file.exists()
|
||||
assert records.read_text() == saved, "Logging out changed local Auth records"
|
||||
capture("account-logged-out")
|
||||
import_invalid_key()
|
||||
stop()
|
||||
print("Werkzeug GUI test: home, Pass, Calculator, Clock, Auth and Profile ran on a private display")
|
||||
finally:
|
||||
|
||||
@@ -4,4 +4,5 @@
|
||||
set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$root"
|
||||
exec python3 scripts/private-display.py python3 scripts/werk_gui_test.py
|
||||
exec env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS xvfb-run -a -e /dev/stderr \
|
||||
env WERK_TEST_PRIVATE_DISPLAY=1 python3 scripts/werk_gui_test.py
|
||||
@@ -1,147 +0,0 @@
|
||||
"""Exercise the Workbook bundle on the caller's private Xvfb display."""
|
||||
from pathlib import Path
|
||||
import csv
|
||||
import gzip
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from PIL import Image
|
||||
|
||||
assert os.environ.get('WERK_TEST_PRIVATE_DISPLAY') == '1', 'Use private Xvfb'
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
work = root / 'build/workbook-gui-test'
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
for directory in ('home', 'data/profile', 'cache', 'bin'):
|
||||
(work / directory).mkdir(parents=True, exist_ok=True)
|
||||
(work / 'data/profile/settings.txt').write_text('theme_mode=1\n')
|
||||
selector = work / 'selection.txt'
|
||||
fake = work / 'bin/zenity'
|
||||
fake.write_text('#!/bin/sh\ncat "$WORKBOOK_TEST_SELECTION"\n')
|
||||
fake.chmod(0o700)
|
||||
fixture = work / 'source.gnumeric'
|
||||
fixture.write_text('''<?xml version="1.0"?><gnm:Workbook xmlns:gnm="http://www.gnumeric.org/v10.dtd"><gnm:SheetNameIndex><gnm:SheetName>Fixture</gnm:SheetName></gnm:SheetNameIndex><gnm:Sheets><gnm:Sheet><gnm:Name>Fixture</gnm:Name><gnm:MaxCol>1</gnm:MaxCol><gnm:MaxRow>0</gnm:MaxRow><gnm:Cells><gnm:Cell Row="0" Col="0" ValueType="40">11</gnm:Cell><gnm:Cell Row="0" Col="1">=A1*3</gnm:Cell></gnm:Cells></gnm:Sheet></gnm:Sheets></gnm:Workbook>''')
|
||||
original = fixture.read_bytes()
|
||||
env = dict(os.environ, HOME=str(work/'home'), WERK_DATA=str(work/'data'),
|
||||
XDG_CACHE_HOME=str(work/'cache'), XDG_CONFIG_HOME=str(work/'home/.config'),
|
||||
XDG_DATA_HOME=str(work/'home/.local/share'), ENTITY_DATA=str(work/'entity'),
|
||||
WERK_ASSETS=str(root/'build'), WORKBOOK_TEST_SELECTION=str(selector),
|
||||
PATH=str(work/'bin')+':'+os.environ['PATH'])
|
||||
app = None
|
||||
window = None
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, env=env, text=True, timeout=20)
|
||||
|
||||
def start():
|
||||
global app, window
|
||||
app = subprocess.Popen([str(root/'build/werk'), '--app', 'workbook'], env=env)
|
||||
for _ in range(100):
|
||||
assert app.poll() is None, 'Werkzeug exited'
|
||||
found = subprocess.run(['xdotool','search','--onlyvisible','--pid',str(app.pid)], env=env, capture_output=True, text=True)
|
||||
if found.returncode == 0:
|
||||
window = found.stdout.splitlines()[0]
|
||||
command('xdotool','windowsize',window,'960','600')
|
||||
command('xdotool','windowfocus','--sync',window)
|
||||
time.sleep(.6)
|
||||
return
|
||||
time.sleep(.1)
|
||||
raise AssertionError('No private Workbook window')
|
||||
|
||||
def stop():
|
||||
if app and app.poll() is None:
|
||||
app.terminate()
|
||||
app.wait(timeout=10)
|
||||
|
||||
def click(x,y):
|
||||
command('xdotool','mousemove','--window',window,str(x),str(y))
|
||||
time.sleep(.1)
|
||||
command('xdotool','click','1')
|
||||
time.sleep(.35)
|
||||
|
||||
def key(value):
|
||||
command('xdotool','key','--clearmodifiers',value)
|
||||
time.sleep(.3)
|
||||
|
||||
def type_text(value):
|
||||
command('xdotool','type','--clearmodifiers','--delay','30',value)
|
||||
time.sleep(.3)
|
||||
|
||||
def cell(path,row=0,col=0):
|
||||
data = path.read_bytes()
|
||||
if data[:2] == b'\x1f\x8b': data = gzip.decompress(data)
|
||||
doc = ET.fromstring(data)
|
||||
for item in doc.iter('{http://www.gnumeric.org/v10.dtd}Cell'):
|
||||
if item.get('Row') == str(row) and item.get('Col') == str(col): return item.text or ''
|
||||
return ''
|
||||
|
||||
saved = work/'data/apps/workbook/documents/workbook.gnumeric'
|
||||
def expect(value,row=0,col=0,path=saved):
|
||||
for _ in range(80):
|
||||
if path.exists() and cell(path,row,col) == value: return
|
||||
time.sleep(.1)
|
||||
raise AssertionError(f'Missing saved fixture value {value!r}')
|
||||
|
||||
def menu(word):
|
||||
click(28,68)
|
||||
picture = work/'menu.png'
|
||||
command('import','-window',window,str(picture))
|
||||
# Isolate the popup so spreadsheet grid lines do not dominate OCR.
|
||||
target = work/'menu-labels.png'
|
||||
factor = 3
|
||||
with Image.open(picture) as image:
|
||||
popup = image.crop((0,82,175,195))
|
||||
popup.resize((popup.width*factor,popup.height*factor)).save(target)
|
||||
text = command('tesseract',str(target),'stdout','--psm','6','-c','tessedit_create_tsv=1')
|
||||
for item in csv.DictReader(io.StringIO(text), delimiter='\t'):
|
||||
if word.lower() in item['text'].lower():
|
||||
click((int(item['left'])+int(item['width'])//2)//factor,
|
||||
82+(int(item['top'])+int(item['height'])//2)//factor)
|
||||
return
|
||||
raise AssertionError('Missing menu command '+word)
|
||||
|
||||
try:
|
||||
start()
|
||||
selection_picture = work/'selection.png'
|
||||
command('import','-window',window,str(selection_picture))
|
||||
with Image.open(selection_picture) as image:
|
||||
pixels = image.convert('RGB')
|
||||
assert pixels.getpixel((88,177)) != pixels.getpixel((184,177)), 'Selected cell needs a visible fill'
|
||||
assert pixels.getpixel((40,177)) != pixels.getpixel((184,177)), 'Selected cell needs a visible outline'
|
||||
assert pixels.getpixel((88,154)) != pixels.getpixel((184,177)), 'Headers need to be distinct from cells'
|
||||
click(88,177)
|
||||
type_text('5'); key('Return'); expect('5')
|
||||
key('ctrl+z'); expect('')
|
||||
key('ctrl+y'); expect('5')
|
||||
bundle = work/'downloaded.zib'
|
||||
selector.write_text(str(bundle)+'\n')
|
||||
menu('Download')
|
||||
for _ in range(50):
|
||||
if bundle.exists(): break
|
||||
time.sleep(.1)
|
||||
assert bundle.read_bytes() == (root/'build/apps/workbook.zib').read_bytes(), 'Downloaded bytes differ'
|
||||
selector.write_text(str(fixture)+'\n')
|
||||
menu('Open')
|
||||
expect('11'); expect('=A1*3',col=1)
|
||||
assert fixture.read_bytes() == original, 'Import changed the chosen source'
|
||||
exported = work/'export.gnumeric'
|
||||
selector.write_text(str(exported)+'\n')
|
||||
menu('As')
|
||||
expect('11',path=exported); expect('=A1*3',col=1,path=exported)
|
||||
invalid = work/'invalid.gnumeric'
|
||||
invalid.write_text('invalid spreadsheet fixture')
|
||||
selector.write_text(str(invalid)+'\n')
|
||||
menu('Open')
|
||||
time.sleep(.5)
|
||||
expect('11'); expect('=A1*3',col=1)
|
||||
click(88,177); type_text('7'); key('Return'); expect('7')
|
||||
command('import','-window',window,str(work/'workbook.png'))
|
||||
stop(); start()
|
||||
click(88,199); type_text('9'); key('Return'); expect('9',row=1)
|
||||
expect('7')
|
||||
assert saved.stat().st_mode & 0o777 == 0o600
|
||||
print('Workbook in Werkzeug: editing, undo/redo, bundle download, document import/export, failed-import preservation and restart passed')
|
||||
finally:
|
||||
stop()
|
||||
@@ -0,0 +1,6 @@
|
||||
// What the host asks of a run of an app's Main, shared by Werkzeug and its
|
||||
// apps.
|
||||
APP_IDENTIFY :: 1
|
||||
APP_FRAME :: 2
|
||||
// Main's answer to APP_IDENTIFY after it called AppDescribe.
|
||||
APP_PROTOCOL :: 0x57524b31
|
||||
@@ -0,0 +1,202 @@
|
||||
// The interface between Werkzeug and its apps. Every app is a separate
|
||||
// bundle; the host answers these calls for the app that is running. Storage,
|
||||
// secure storage and assets are private to that app.
|
||||
#import "session"
|
||||
#import "geometry"
|
||||
#import "text_input_props"
|
||||
#import "app_protocol"
|
||||
|
||||
host_api :: #system_library "host_api";
|
||||
|
||||
AppModeHost :: () -> s32 #foreign host_api;
|
||||
// The app's name and its icon, a vector Shape from an icon package.
|
||||
AppDescribeHost :: (name: string, icon_shape: string) #foreign host_api;
|
||||
|
||||
// The session and the area the app draws into this frame.
|
||||
AppSessionHost :: () -> Session #foreign host_api;
|
||||
AppBoundsHost :: () -> Rectangle #foreign host_api;
|
||||
AppDarkHost :: () -> bool #foreign host_api;
|
||||
// The key pressed this frame and the held modifiers (1 shift, 2 control).
|
||||
AppKeyHost :: () -> s32 #foreign host_api;
|
||||
AppModifiersHost :: () -> s32 #foreign host_api;
|
||||
// Typing for the text field that has focus.
|
||||
AppFieldInputHost :: () -> TextFieldInput #foreign host_api;
|
||||
// Shows the touch keyboard while a field has focus.
|
||||
AppKeyboardHost :: (visible: bool) #foreign host_api;
|
||||
|
||||
// Seconds since the Unix epoch, and the local offset from UTC in seconds.
|
||||
AppNowHost :: () -> float64 #foreign host_api;
|
||||
AppLocalOffsetHost :: () -> s32 #foreign host_api;
|
||||
|
||||
// The file path of an asset packed in the app's bundle, for Image.
|
||||
AppAssetPathHost :: (name: string) -> string #foreign host_api;
|
||||
|
||||
// PBKDF2 with HMAC-SHA-256 into 32 bytes, computed natively by the host.
|
||||
AppPbkdf2Sha256Host :: (password: string, salt: string, iterations: s32) -> string #foreign host_api;
|
||||
|
||||
// The app's private files. ReadStore returns the byte count, or -1.
|
||||
ReadStoreHost :: (name: string, output: []u8) -> s32 #foreign host_api;
|
||||
WriteStoreHost :: (name: string, value: string) -> bool #foreign host_api;
|
||||
|
||||
// Synced records: small values that follow the owner's account to their
|
||||
// other devices. An id holds letters, digits, '-', '.' and '_'; a value is
|
||||
// one line of at most 1024 bytes. RecordList writes the ids, one per line;
|
||||
// RecordList and RecordRead return the byte count, or -1.
|
||||
RecordListHost :: (output: []u8) -> s32 #foreign host_api;
|
||||
RecordReadHost :: (id: string, output: []u8) -> s32 #foreign host_api;
|
||||
RecordWriteHost :: (id: string, value: string) -> bool #foreign host_api;
|
||||
RecordRemoveHost :: (id: string) -> bool #foreign host_api;
|
||||
// Changes whenever records arrived from another device.
|
||||
RecordsVersionHost :: () -> s32 #foreign host_api;
|
||||
|
||||
// Copies text. After clear_seconds the host clears it again, unless
|
||||
// another application replaced it.
|
||||
ClipboardCopyHost :: (value: string, clear_seconds: s32) -> bool #foreign host_api;
|
||||
|
||||
// One secret kept behind device authentication, where the device has it.
|
||||
// SecurePoll returns 2 with the result, 3 on failure and 0 otherwise.
|
||||
SecureAvailableHost :: () -> bool #foreign host_api;
|
||||
SecureSavedHost :: () -> bool #foreign host_api;
|
||||
SecureRequestHost :: (secret: string, save: bool) -> bool #foreign host_api;
|
||||
SecureForgetHost :: () -> bool #foreign host_api;
|
||||
SecurePollHost :: (output: []u8) -> s32 #foreign host_api;
|
||||
|
||||
// Each call is exported from this module so every app reaches the host
|
||||
// through the same capability names.
|
||||
#program_export
|
||||
AppMode :: () -> s32 {
|
||||
return AppModeHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppDescribe :: (name: string, icon_shape: string) {
|
||||
AppDescribeHost(name, icon_shape)
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppSession :: () -> Session {
|
||||
return AppSessionHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppBounds :: () -> Rectangle {
|
||||
return AppBoundsHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppDark :: () -> bool {
|
||||
return AppDarkHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppKey :: () -> s32 {
|
||||
return AppKeyHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppModifiers :: () -> s32 {
|
||||
return AppModifiersHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppFieldInput :: () -> TextFieldInput {
|
||||
return AppFieldInputHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppKeyboard :: (visible: bool) {
|
||||
AppKeyboardHost(visible)
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppNow :: () -> float64 {
|
||||
return AppNowHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppLocalOffset :: () -> s32 {
|
||||
return AppLocalOffsetHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
AppAssetPath :: (name: string) -> string {
|
||||
return AppAssetPathHost(name)
|
||||
}
|
||||
|
||||
// Writes the 32-byte key into output; false when the host refused.
|
||||
#program_export
|
||||
AppPbkdf2Sha256 :: (password: string, salt: string, iterations: s32, output: []u8) -> bool {
|
||||
derived := AppPbkdf2Sha256Host(password, salt, iterations)
|
||||
if derived.count != 32 || output.count < 32 {
|
||||
return false
|
||||
}
|
||||
for index: 0..31 {
|
||||
output[index] = derived[index]
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
#program_export
|
||||
ReadStore :: (name: string, output: []u8) -> s32 {
|
||||
return ReadStoreHost(name, output)
|
||||
}
|
||||
|
||||
#program_export
|
||||
WriteStore :: (name: string, value: string) -> bool {
|
||||
return WriteStoreHost(name, value)
|
||||
}
|
||||
|
||||
#program_export
|
||||
RecordList :: (output: []u8) -> s32 {
|
||||
return RecordListHost(output)
|
||||
}
|
||||
|
||||
#program_export
|
||||
RecordRead :: (id: string, output: []u8) -> s32 {
|
||||
return RecordReadHost(id, output)
|
||||
}
|
||||
|
||||
#program_export
|
||||
RecordWrite :: (id: string, value: string) -> bool {
|
||||
return RecordWriteHost(id, value)
|
||||
}
|
||||
|
||||
#program_export
|
||||
RecordRemove :: (id: string) -> bool {
|
||||
return RecordRemoveHost(id)
|
||||
}
|
||||
|
||||
#program_export
|
||||
RecordsVersion :: () -> s32 {
|
||||
return RecordsVersionHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
ClipboardCopy :: (value: string, clear_seconds: s32) -> bool {
|
||||
return ClipboardCopyHost(value, clear_seconds)
|
||||
}
|
||||
|
||||
#program_export
|
||||
SecureAvailable :: () -> bool {
|
||||
return SecureAvailableHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
SecureSaved :: () -> bool {
|
||||
return SecureSavedHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
SecureRequest :: (secret: string, save: bool) -> bool {
|
||||
return SecureRequestHost(secret, save)
|
||||
}
|
||||
|
||||
#program_export
|
||||
SecureForget :: () -> bool {
|
||||
return SecureForgetHost()
|
||||
}
|
||||
|
||||
#program_export
|
||||
SecurePoll :: (output: []u8) -> s32 {
|
||||
return SecurePollHost(output)
|
||||
}
|
||||