33 Commits
Author SHA1 Message Date
waozi b2ddcb69a8 Keep bundle runtime caches matched to their toolchain 2026-10-28 13:15:42 -03:00
waozi a69631e327 Release Werkzeug 0.4.7 with Workbook on every platform 2026-10-28 12:56:43 -03:00
waozi dd550dd58b Verify the shared profile document without confusing favicon requests 2026-10-28 04:19:25 -03:00
waozi 36fd01fe5d Open the shared browser profile after the active tool has saved 2026-10-28 04:07:42 -03:00
waozi 0cb5600c14 Load the shared browser profile from the Ziran host 2026-10-28 03:54:01 -03:00
waozi ead336b215 Format the shared browser profile readiness condition 2026-10-28 03:48:57 -03:00
waozi 6cea9233ef Use the shared Waozi browser profile and Entity manager 2026-10-28 03:48:29 -03:00
waozi fbd7c4038a Select the Add action below the node input in Android tests 2026-10-27 03:52:56 -03:00
waozi 7bfa8fef2b Follow the shared Profile Nodes flow in the Android test 2026-10-27 03:08:45 -03:00
waozi bee76ab379 Read small dark-theme labels in the Android input test 2026-10-27 02:51:21 -03:00
waozi d8284a83e0 Pin the Apps controller built with Kryon 0931212f
Werkzeug 0.4.6 moved Kryon with Entity ca637d0, which changes the shared
Apps controller bundle; this is its digest from the locked build.
2026-10-27 02:19:43 -03:00
waozi f2dad4b37f Release Werkzeug 0.4.6
Entity ca637d0 saves account aliases typed with capitals, an @ or spaces
and says when an alias is taken.
2026-10-27 02:03:08 -03:00
waozi 40f2cdf731 Retry Android SDK downloads across build workflows 2026-10-26 20:06:30 -03:00
waozi b193cbfa9f Fix Android native app startup with private runtime directories 2026-10-26 19:46:29 -03:00
waozi 4e139b3ffb Identify Android controller integrity failures 2026-10-26 19:25:17 -03:00
waozi a5e69bb227 Report Android Apps controller startup failures 2026-10-26 18:04:35 -03:00
waozi b0003dc032 Capture private emulator asset diagnostics on test failure 2026-10-26 17:47:14 -03:00
waozi e26d26f5db Fix workflows for the root web app and retry Android SDK setup 2026-10-26 17:29:40 -03:00
waozi a45fd1d3ed Open the card embed page beside the root app in the browser test 2026-10-26 02:47:32 -03:00
waozi 2e5d765962 Check the site's root app files in the Pages build 2026-10-26 02:38:57 -03:00
waozi 4d499720d8 Make werk.waozi.xyz the web app itself
The site serves Werkzeug at its root instead of a separate landing page;
/app/ forwards there and download links keep their addresses. Browser
storage is per origin, so saved vaults stay.
2026-10-26 02:32:31 -03:00
waozi ae502a322d Build Auth from its package and hash with the crypto package: manifest, lock, Makefile, Pass, the host, tests, Android sources and docs 2026-10-24 23:43:18 -03:00
waozi 1a4e0e0891 Auth comes from its own Ziran package (waozixyz/auth) and SHA-256 and PBKDF2 from the crypto package, replacing apps/auth and shared/; Pass keeps reading at most 508 salt bytes, as existing vault keys need 2026-10-24 23:43:05 -03:00
waozi 3b8c4eaf64 Use Kryon shared app and render stages on Android
Compose Werkzeug frames through the shared Android pipeline and drain it before closing app state. Preserve the native linker callbacks during source generation. Pin the verified Kryon and Ziran revisions and the regenerated Apps controller validated by its native behavior fixture.
2026-10-24 06:40:35 -03:00
waozi 60a68d258a Add the Werkzeug 0.4.4 build to the F-Droid recipe
Matches fdroiddata merge request 53909. New release tags are added by
F-Droid's update checker, which copies this build for each tag.
2026-10-24 02:17:58 -03:00
waozi 0a2ab3bb45 Show only the tools as large tiles in mini mode
The ?mini embed and desktop --mini now open on the tool tiles alone, with no
Profile, search or title bar. Opening a tool keeps its bar with Back, which
returns to the tiles. Mini mode is read with Kryon's shared mini_embed.
2026-10-24 02:04:09 -03:00
waozi b9a6c6d350 Remove the Plan 9 build of the pass command 2026-10-23 22:10:21 -03:00
waozi b53050764b Keep F-Droid dependency handling upstream 2026-10-23 20:54:23 -03:00
waozi b8722b6b28 Restore compatible Werkzeug updates and reproducible builds
Keep the original Android package and signing identity for in-place Pass updates, align the portable bundles and locked toolchain, and make native builds reproducible. Fix staged installation, desktop tool icons and navigation tests.
2026-10-23 19:59:51 -03:00
waozi 26047247f9 Prepare the Werkzeug package migration and correct mobile input navigation 2026-10-23 18:53:22 -03:00
waozi c801c62542 Use xyz.waozi.werk as the Werkzeug Android application ID 2026-10-23 18:26:55 -03:00
waozi 7601d7c58c Keep private launcher displays stable across restarts 2026-10-23 18:22:03 -03:00
waozi 47d77ab0ad Use a compact Apps presentation without package sizes 2026-10-23 18:17:46 -03:00
118 changed files with 2220 additions and 3800 deletions

No files matched your search

+10 -14
View File
@@ -55,8 +55,9 @@ jobs:
- name: Verify generated site
run: |
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/index.wasm
test -s build/site/index.wasm
test -s build/site/sw.js
test -s build/site/assets.json
- name: Check fastlane metadata
run: |
set -eu
@@ -142,15 +143,12 @@ jobs:
path: |
droid/app/.cxx
droid/app/build/intermediates/cxx
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('src/*.zi', 'shared/*.zi', 'apps/*/*.zi', 'droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'ziran.lock') }}
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('src/*.zi', 'apps/*/*.zi', 'droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'ziran.lock') }}
restore-keys: |
android-native-${{ runner.os }}-${{ runner.arch }}-
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh
- name: Build debug APK
run: |
set -euo pipefail
@@ -170,15 +168,12 @@ jobs:
java-version: '21'
- uses: gradle/actions/setup-gradle@v3
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh 'platforms;android-30'
- name: Install screenshot OCR
run: |
sudo apt-get update
sudo apt-get install -y tesseract-ocr
sudo apt-get install -y tesseract-ocr python3-pil
# 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
@@ -201,4 +196,5 @@ jobs:
name: android-input-test-reports
path: |
build/android-input/
build/workbook-android-test/
if-no-files-found: ignore
+1 -3
View File
@@ -21,9 +21,7 @@ jobs:
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'
bash scripts/install_android_sdk.sh
- name: Prepare preserved release key
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
+5 -9
View File
@@ -124,15 +124,12 @@ jobs:
path: |
droid/app/.cxx
droid/app/build/intermediates/cxx
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'src/*.zi', 'shared/*.zi', 'apps/*/*.zi', 'ziran.lock') }}
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'src/*.zi', 'apps/*/*.zi', 'ziran.lock') }}
restore-keys: |
android-native-${{ runner.os }}-${{ runner.arch }}-
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
timeout-minutes: 15
run: bash scripts/install_android_sdk.sh
- name: Prepare Android signing key
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
@@ -202,11 +199,10 @@ jobs:
cd build/site
zip -qr ../werk-web.zip .
# The whole app folder: its page loads content-hashed script and
# The site root is the app: 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 -R . ../werk-html5/
sed -i \
-e 's#href="/manifest.webmanifest"#href="manifest.webmanifest"#g' \
-e 's#href="/icons/#href="icons/#g' \
+2 -2
View File
@@ -46,8 +46,8 @@ jobs:
set -euo pipefail
make site
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/index.wasm
test -s build/site/index.wasm
test -s build/site/sw.js
- name: Install screenshot OCR
run: |
sudo apt-get update
+2
View File
@@ -5,3 +5,5 @@
__pycache__/
*.pyc
.wrangler/
/backup/
/work/
+11 -9
View File
@@ -5,12 +5,13 @@ first.
## Tools are separate apps
- Each tool lives in `apps/<tool>/` and builds into its own bundle,
`build/apps/<tool>.zib`. A tool reaches the host only through
`shared/werk_app.zi`; the host (`src/apps.zi`) checks every call a
bundle asks for and keeps each tool's files, assets and secret separate.
- Tools never import another tool's modules. Code two tools need goes in
`shared/`, as SHA-256 and PBKDF2 do.
- Each tool builds into its own bundle, `build/apps/<tool>.zx`: Pass,
Calculator and Clock from `apps/<tool>/`, Auth and Workbook from their own
Ziran packages. The host (`src/apps.zi`) checks every call a bundle asks
for and keeps each tool's files, assets and secret separate.
- Tools never import another tool's modules. Code two tools need comes from
a Ziran package, as SHA-256 and PBKDF2 come from `crypto`; no git
submodules.
- Keep the host interface small and generic (files, clock, clipboard,
key derivation, device secret, input). A new host call needs a new host
build before any bundle can use it.
@@ -23,9 +24,10 @@ first.
- Never commit, print or log a real master password, Auth secret, otpauth
link, export file or current code. Tests use fixture values only, such as
the RFC 6238 keys.
- Keep Pass's on-disk formats and the Android package `xyz.waozi.pass`:
existing installations update in place and keep their saved master
password. `src/migrate.zi` moves Pass's old files once; keep it.
- Keep Pass's on-disk formats and `src/migrate.zi`. The owner's latest choice
on 2026-10-23 is an update of the existing Android/F-Droid app: keep
`xyz.waozi.pass` and its signing certificate, with the display name Werkzeug.
Preserve existing Pass data and any separate `xyz.waozi.werk` installation.
- Every file Werkzeug writes is private (0600 in 0700 folders).
## Platforms and tests
+23
View File
@@ -1,5 +1,28 @@
# Changelog
## [0.4.7] - 2026-10-28
- Use Workbook on Android and the web as well as Linux, with formulas, sheet tabs, automatic saving and document import/export.
- Navigate Workbook cells with touch controls, and keep Android's keyboard focused while editing a cell.
## [0.4.6] - 2026-10-27
- Set an account alias with capitals, an @ or spaces; a taken alias now says so.
## [0.4.5] - 2026-10-26
- Fix Android opening to “Apps are unavailable”; Pass, Auth, Calculator and Clock load normally.
## [0.4.4] - 2026-10-23
- Werkzeug updates the existing Pass Android app using its original application ID and signing certificate, keeping its saved data.
- The app continues to appear as Werkzeug, with Pass, Auth, Calculator and Clock together.
## [0.4.3] - 2026-10-23
- Werkzeug uses its own Android application ID, `xyz.waozi.werk`.
- Werkzeug installs alongside legacy Pass, preserving the older app and its data.
## [0.4.2] - 2026-10-23
- Linux packages include the libraries needed for sync and importing QR-code pictures.
+52 -34
View File
@@ -1,5 +1,8 @@
.DEFAULT_GOAL := all
ZIRAN ?= ./scripts/ziran.sh
# Gradle invokes make again for portable bundles. Inherited environment
# variables otherwise export these shell-derived paths while resolving them.
unexport ZIRAN_ROOT KRYON_DIR RAYLIB_DIR MINGCUTE_DIR LIBOQS_DIR MONOCYPHER_DIR QRCODE_DIR WORKBOOK_DIR ENTITY_DIR APPS_DIR AUTH_DIR CRYPTO_DIR
# Local overrides refer to the real root repositories. Published builds
# require the exact versions recorded in the committed lock.
LOCK_FLAGS := $(if $(wildcard ziran.local.toml),,--locked)
@@ -15,6 +18,9 @@ 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))
# Auth is its own package; SHA-256 and PBKDF2 come from the crypto package.
AUTH_DIR = $(shell $(ZIRAN) pkg path auth $(LOCK_FLAGS))
CRYPTO_DIR = $(shell $(ZIRAN) pkg path crypto $(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
@@ -25,7 +31,7 @@ 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)
SOURCES := $(wildcard src/*.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/*)
@@ -33,7 +39,7 @@ 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 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
all: cli gui
native: all
@@ -47,19 +53,18 @@ 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.
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
SHARED_SOURCES := $(wildcard shared/*.zi)
# Each app is its own bundle, shared by the desktop, web and Android hosts.
APPS := pass calculator clock
PORTABLE_BUNDLES := $(APPS:%=build/apps/%.zx) build/apps/auth.zx build/apps/entity.zx build/apps/apps.zx build/apps/workbook.zx
APP_BUNDLES := $(PORTABLE_BUNDLES)
CRYPTO_SOURCES = $(wildcard $(CRYPTO_DIR)/src/*.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 crypto=$(CRYPTO_DIR)/src --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
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
build/apps/apps.zx: $(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) \
@@ -67,25 +72,35 @@ build/apps/apps.zib: $(APPS_UI_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURC
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/%.zx: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
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/auth.zx: $(wildcard $(AUTH_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile scripts/ziran.sh
mkdir -p $(@D)
$(ZIRAN) bundle --root $(AUTH_DIR) --module-path $(AUTH_DIR)/src $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI --define WERK_APP \
--entry auth:Main -o $@ $(AUTH_DIR)/src/auth.zi
build/apps/entity.zib: $(ENTITY_SOURCES) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
build/apps/workbook.zx: $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(LIBRARY_SOURCES) $(ZIRAN_RUNTIME_SOURCES) ziran.lock Makefile
mkdir -p $(@D)
$(ZIRAN) bundle --root $(WORKBOOK_DIR) --module-path $(WORKBOOK_DIR)/src $(APP_MODULE_PATHS) \
--module-path kryon=$(KRYON_DIR)/src/backend --define KRYON_HOSTED_UI --entry app:Main -o $@ $(WORKBOOK_DIR)/src/app.zi
build/apps/entity.zx: $(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)
env -u DISPLAY -u WAYLAND_DISPLAY $(MAKE) -C $(ZIRAN_ROOT) BUILD_DIR=$(abspath build/ziran) $(abspath $@)
.PHONY: runtime-cache-force
runtime-cache-force:
build/ziran/.toolchain: runtime-cache-force scripts/runtime_cache.py
python3 scripts/runtime_cache.py "$(ZIRAN_ROOT)" "$(abspath build/ziran)"
build/ziran/libziran.a: ziran.lock $(ZIRAN_RUNTIME_SOURCES) build/ziran/.toolchain
env -u DISPLAY -u WAYLAND_DISPLAY -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(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) $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) $(ENTITY_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
@@ -119,7 +134,13 @@ 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
.PHONY: android-sdk-install-test
android-sdk-install-test:
python3 scripts/install_android_sdk_test.py
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test entity-account-test android-sdk-install-test runtime-cache-test
.PHONY: runtime-cache-test
runtime-cache-test:
python3 scripts/runtime_cache_test.py
gui-smoke: gui
sh scripts/gui_smoke.sh
gui-test: gui
@@ -132,10 +153,12 @@ gui-test: gui
# The bundle runtime for the browser, built from the locked Ziran.
WEB_AR ?= $(dir $(WEB_CC))emar
build/web-runtime/libziran.a: ziran.lock
env -u DISPLAY -u WAYLAND_DISPLAY $(MAKE) -C $(ZIRAN_ROOT) BOOTSTRAP=1 BUILD_DIR=$(abspath build/web-runtime) \
build/web-runtime/.toolchain: runtime-cache-force scripts/runtime_cache.py
python3 scripts/runtime_cache.py "$(ZIRAN_ROOT)" "$(abspath build/web-runtime)"
build/web-runtime/libziran.a: ziran.lock build/web-runtime/.toolchain
env -u DISPLAY -u WAYLAND_DISPLAY -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(MAKE) -C $(ZIRAN_ROOT) BOOTSTRAP=1 BUILD_DIR=$(abspath build/web-runtime) \
CC=$(WEB_CC) AR=$(WEB_AR) OBJCOPY=true CFLAGS=-O2 $(abspath $@)
build/generated/browser/.complete: $(wildcard src/*.zi) $(SHARED_SOURCES) $(LIBRARY_SOURCES) ziran.toml ziran.lock
build/generated/browser/.complete: $(wildcard src/*.zi) $(wildcard $(WORKBOOK_DIR)/src/*.zi) $(CRYPTO_SOURCES) $(LIBRARY_SOURCES) ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --define PLATFORM_WEB --target=c -o $(@D) src/browser.zi
@@ -148,8 +171,8 @@ build/web-app/index.js: build/generated/browser/.complete build/web-runtime/libz
-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 $@
build/web-app/index.html: build/web-app/index.js web/site/app/index.html
cp web/site/app/index.html $@
build/web-app/index.html: build/web-app/index.js web/site/index.html
cp web/site/index.html $@
build/generated/worker/.complete: src/service_worker.zi ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
@@ -185,21 +208,17 @@ 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.
# F-Droid compares this source build with the signed upstream release.
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
mkdir -p build/fdroid
cp droid/app/build/outputs/apk/release/app-universal-release-unsigned.apk build/fdroid/werk.apk
python3 scripts/android_apk_check.py build/fdroid/werk.apk
android-smoke:
bash scripts/android_smoke.sh
android-input-test:
python3 scripts/android_input_test.py
# The pass command for Plan 9; transfer the checkout with build/plan9 and run mk.
plan9-c:
mkdir -p build/plan9
$(ZIRAN) build $(PROJECT) --define PLAN9_BUILD --target=plan9-c --entry cli:main -o build/plan9/cli apps/pass/cli.zi
python3 scripts/workbook_android_test.py
check-package-urls:
bash scripts/check_package_urls.sh
@@ -220,7 +239,6 @@ install-gui: gui
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
uninstall-cli:
rm -f $(BIN_DIR)/pass
uninstall-gui:
+31 -230
View File
@@ -1,246 +1,47 @@
<p align="center">
<a href="https://f-droid.org/packages/xyz.waozi.pass/">
<img src="assets/app/badge-f-droid.png" alt="Get it on F-Droid" height="56">
</a>
<img src="fastlane/metadata/android/en-US/images/featureGraphic.png" alt="Werkzeug" width="100%">
</p>
# Werkzeug
Small private tools in one app. The home screen opens each one:
Small, private tools for everyday life. Generate passwords, manage sign-in
codes, calculate and keep time in one free, open-source app.
- **Pass**: a stateless password generator. The same site, login, master
password and settings always give the same password, so there is no
password database to keep. It is an independent implementation of the
LessPass algorithm; compatibility does not imply endorsement by or
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.
- **Calculator**: arithmetic with brackets, powers and percent, by keypad or
keyboard, and a Scientific mode with trigonometry, logarithms, roots and
factorials.
- **Clock**: the local time and date, and a stopwatch that keeps running
while the app is closed.
[Try it online](https://werk.waozi.xyz/)
· [Download the latest release](https://github.com/waozixyz/werk/releases/latest)
· [What's new](CHANGELOG.md)
- **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`.
## Your everyday tools
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.
- **Pass:** generate the same password from your site, login, master password and settings. Save profiles without keeping a password database.
- **Auth:** keep two-factor sign-in codes together. Import existing accounts, rename them and copy a code when you need it.
- **Calculator:** everyday arithmetic and scientific functions, with a keypad or keyboard.
- **Clock:** see the local time and use a stopwatch that keeps running while the app is closed.
- **Workbook:** edit spreadsheets on Linux, Android and the web, with formulas, sheet tabs and portable workbook files.
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.
<p align="center">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/02-pass.png" alt="Pass password generation" width="30%">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/03-auth.png" alt="Auth sign-in codes" width="30%">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/04-calculator.png" alt="Scientific calculator" width="30%">
</p>
## Privacy
## Make it yours
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:
Choose light or dark appearance, an accent color and your profile picture.
On Linux, open each tool directly from its own application-menu or Desktop
shortcut, with its own icon.
| Platform | Data |
|---|---|
| Linux | `$XDG_DATA_HOME/werk` (or `~/.local/share/werk`) |
| Android | the app's private storage |
| Browser | IndexedDB on this site |
## Your data and choices
Auth's accounts are synced records: `otpauth` links in the private
`records/auth.txt`, protected by the file permissions of your account or the
Android app sandbox.
Password generation and local tools work on your device. Account sync and
node connections are optional. Each tool keeps its own private files.
## Sync
Werkzeug was formerly Pass. Android keeps the original `xyz.waozi.pass`
package and signing certificate so existing Pass installations can update
to Werkzeug while keeping their saved data.
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.
[F-Droid update submission (draft)](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/53909)
· [Report a problem](https://github.com/waozixyz/werk/issues)
· [Build, command-line tools and data details](docs/development.md)
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.
- 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
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.
- 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,
`build/apps/<tool>.zib`. All four are preinstalled. A tool reaches the host
only through the calls in `shared/werk_app.zi` (its private files,
clipboard, clock, key derivation and device-protected secret), and the host
checks every call a bundle asks for before it runs. Tools never import each
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
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 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 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`:
```toml
[overrides]
kryon = "../../kryonlabs/kryon"
ziran = "../../ziranlang/ziran"
```
## The `pass` command
```text
pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
pass [OPTIONS] PROFILE SITE
```
`make cli` builds it and `make install-cli` installs it. The default password
has 16 characters and includes lowercase letters, uppercase letters, digits
and symbols. Length must be between 5 and 35, matching LessPass clients. The
default counter is 1.
Passing a master password as an argument can expose it to process inspection
and shell history. Omitting it is safer: `pass` first checks
`LESSPASS_MASTER_PASSWORD`, then reads one line from standard input. Use
`--prompt` to bypass the environment and read from standard input:
```sh
pass --prompt example.com alice
pass --length 24 --counter 2 example.com alice
pass --no-symbols --exclude '0O1Il' example.com alice
```
The Linux CLI also reads saved identities from
`$XDG_CONFIG_HOME/pass/profiles.json` (or `~/.config/pass/profiles.json`).
`pass w example.com` and `pass --profile w example.com` use the saved login
and generation options. Existing OpenSSL-encrypted vaults are unlocked with
a hidden `Vault passphrase:` prompt. A configured vault takes precedence over
`LESSPASS_MASTER_PASSWORD`; `--prompt` bypasses it. Explicit flags override
profile defaults. Profiles and vaults are read without changing them.
`--copy` or a profile's `copy` setting copies through `xclip` on X11;
`--clear-after 90s` releases that clipboard selection after the given time
without erasing a later copy from another application. Use `--no-copy` to
print the generated password instead. Run `pass --help` for all flags.
## Source layout
```text
apps/pass/ Pass: LessPass core, settings and profiles, screens, CLI
apps/auth/ Auth: TOTP, otpauth links, exports, accounts and screens
apps/calculator/ Calculator
apps/clock/ Clock and stopwatch
shared/ the app interface, protocol and SHA-256/PBKDF2
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
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
[`LICENSE`](LICENSE).
BSD 3-Clause. See [LICENSE](LICENSE).
+1 -1
View File
@@ -1 +1 @@
0.4.2
0.4.7
+1 -1
View File
@@ -1 +1 @@
8c5806d7ff5a4fdaf6b98a7668acbf0aad236ece1d5e68ffe1f7b268a1afb077
f6f4eed8f5234c35a7ab2ca0b316c4bbdedf620ecfc22f157b8838c4258934f0
-632
View File
@@ -1,632 +0,0 @@
// Auth: two-factor sign-in codes. Each account is a synced record holding
// its otpauth link, so it follows the owner's Werkzeug account to their
// other devices; secrets are never shown again after adding.
#import "session"
#import "geometry"
#import "text_props"
#import "text_widget"
#import "text_input_props"
#import "text_field_widget"
#import "button_props"
#import "button_widget"
#import "control_props"
#import "box_props"
#import "box_widget"
#import "scroll_props"
#import "scroll_widget"
#import "tree"
#import "text_buffer"
#import "number_text"
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "totp"
#import "exports"
Icon :: #import "mingcute_regular_shield";
Edit :: #import "mingcute_regular_edit_2";
ACCOUNT_LIMIT :: 128
LIST_LIMIT :: 65536
// Copied codes clear from the clipboard after this many seconds.
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
anchor: s32
scroll_x: s32
}
CachedCode :: struct {
step: s64
code: [12]u8
}
accounts: [ACCOUNT_LIMIT]Account;
codes: [ACCOUNT_LIMIT]CachedCode;
// Each account's record id, and whether its record is written.
record_ids: [ACCOUNT_LIMIT][33]u8;
recorded: [ACCOUNT_LIMIT]bool;
records_version: s32 = -1;
ids: [8192]u8;
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;
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;
list_scroll: s32;
store: [LIST_LIMIT]u8;
session: Session;
SetStatus :: (text: string) {
unused CopyLimited(text, status[:])
}
Clear :: (bytes: []u8) {
index: s64 = 0
while index < bytes.count {
bytes[index] = cast(u8)0
index += 1
}
}
// 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.
SetRecordId :: (index: s32, link: string) {
unused RecordIdFor(link, record_ids[index][:])
}
// Writes the records of accounts added since the last save.
SaveAccounts :: () -> bool {
saved := true
index: s32 = 0
while index < account_count {
if !recorded[index] {
line: [1024]u8
{
link := LinkText(*accounts[index], line[:])
if link != "" {
if record_ids[index][0] == cast(u8)0 {
SetRecordId(index, link)
}
recorded[index] = RecordWrite(TextUntilNul(record_ids[index][:]), link)
}
}
Clear(line[:])
saved = saved && recorded[index]
}
index += 1
}
return saved
}
LoadAccounts :: () {
records_version = RecordsVersion()
// Accounts saved before records existed move into records once.
count := ReadStore("accounts.txt", store[:])
if count > 0 {
account_count = 0
unused AddExport(TextView(store[0:count]), false)
if SaveAccounts() {
unused WriteStore("accounts.txt", "")
}
}
Clear(store[:])
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
at: s32 = 0
while listed > 0 && at <= listed && account_count < ACCOUNT_LIMIT {
if at == listed || ids[at] == cast(u8)10 {
if at > start {
id := TextView(ids[start:at])
length := RecordRead(id, store[:])
account: Account
if length > 0 && ParseLink(TextView(store[0:length]), *account) {
accounts[account_count] = account
codes[account_count] = CachedCode.{.step = -1}
unused CopyLimited(id, record_ids[account_count][:])
recorded[account_count] = true
account_count += 1
}
account = Account.{}
Clear(store[0:ifx length > 0 then length else 0])
}
start = at + 1
}
at += 1
}
}
// 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[:])
}
// 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)
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
}
index += 1
}
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
}
ClearExport()
if report {
number: [24]u8
message: [128]u8
used := AppendText(message[:], 0, "Added ")
used = AppendText(message[:], used, FormatInteger(cast(s64)added, number[:]))
used = AppendText(message[:], used, ifx added == 1 then " account" else " accounts")
if refused > 0 {
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
}
AddManual :: () -> bool {
account := Account.{.kind = HASH_SHA1, .digits = 6, .period = 30}
if name[0] == cast(u8)0 && issuer[0] == cast(u8)0 {
SetStatus("Enter a name for the account")
return false
}
if !SetSecret(*account, TextUntilNul(secret[:])) {
SetStatus("The secret key is not valid Base32")
account = Account.{}
return false
}
account.issuer = issuer
account.name = name
if account_count >= ACCOUNT_LIMIT {
SetStatus("Auth holds at most 128 accounts")
account = Account.{}
return false
}
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
}
position := index
while position + 1 < account_count {
accounts[position] = accounts[position + 1]
codes[position] = codes[position + 1]
record_ids[position] = record_ids[position + 1]
recorded[position] = recorded[position + 1]
position += 1
}
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
}
Unix :: () -> s64 {
return cast(s64)AppNow()
}
// The current code, computed once per time step.
Code :: (index: s32) -> string {
account := *accounts[index]
step := Unix() / cast(s64)account.period
if codes[index].step != step {
codes[index].step = step
unused CodeNow(account.kind, account.key[:], account.key_count, account.digits, account.period,
Unix(), codes[index].code[:])
}
return TextUntilNul(codes[index].code[:])
}
Label :: (key: u64, text: string, bounds: Rectangle, font: s32) {
Text(session, TextProps.{.key = key, .bounds = bounds, .text = text, .font = font,
.wrap = TextWrap.TextWrapEllipsis})
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool) -> bool {
props := ButtonProps.{.key = cast(u64)id, .id = id, .bounds = bounds, .label = label,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if accent {
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button(session, props) != 0
}
ApplyEdit :: (buffer: []u8, edit: TextFieldEdit) {
if !edit.changed {
return
}
length: s64 = 0
while length < buffer.count && buffer[length] != cast(u8)0 {
length += 1
}
if edit.start < 0 || edit.end < edit.start || cast(s64)edit.end > length {
return
}
used := length - cast(s64)(edit.end - edit.start) + edit.replacement.count
if used >= buffer.count {
return
}
tail := length - cast(s64)edit.end
if edit.replacement.count > cast(s64)(edit.end - edit.start) {
// Move the tail right, from its end.
index := tail - 1
while index >= 0 {
buffer[cast(s64)edit.start + edit.replacement.count + index] = buffer[cast(s64)edit.end + index]
index -= 1
}
} else {
index: s64 = 0
while index < tail {
buffer[cast(s64)edit.start + edit.replacement.count + index] = buffer[cast(s64)edit.end + index]
index += 1
}
}
index: s64 = 0
while index < edit.replacement.count {
buffer[cast(s64)edit.start + index] = edit.replacement[index]
index += 1
}
index = used
while index < buffer.count {
buffer[index] = cast(u8)0
index += 1
}
}
Field :: (id: s32, label: string, placeholder: string, buffer: []u8, bounds: Rectangle, secure: bool) {
state := *fields[id]
edit: TextFieldEdit
{
props := TextFieldProps.{.key = cast(u64)(500 + id), .focus_id = 500 + id, .bounds = bounds,
.label = label, .placeholder = placeholder, .value = TextUntilNul(buffer),
.cursor = state.cursor, .anchor = state.anchor, .scroll_x = state.scroll_x,
.focused = focused == id, .max_bytes = cast(s32)buffer.count - 1,
.max_codepoints = cast(s32)buffer.count - 1, .secure = secure}
// A secret shows as dots once typed; an empty field shows its hint.
if secure && buffer[0] != cast(u8)0 {
props.display_value = "••••••••"
}
if focused == id {
props.input = AppFieldInput()
}
result := TextField(session, props)
state.cursor = result.cursor
state.anchor = result.anchor
state.scroll_x = result.scroll_x
if result.focused {
focused = id
} else if focused == id {
focused = 0
}
edit = result.edit
}
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) {
account := *accounts[index]
Box(session, BoxProps.{.key = cast(u64)(1000 + index), .bounds = Rectangle.{x, y, inner, row - 8.0},
.radius = 10.0})
title := TextUntilNul(account.issuer[:])
subtitle := TextUntilNul(account.name[:])
if title == "" {
title = subtitle
subtitle = ""
}
text_width := inner - 210.0
Label(cast(u64)(2000 + index), title, Rectangle.{x + 12.0, y + 12.0, text_width, 22.0}, 16)
Label(cast(u64)(3000 + index), subtitle, Rectangle.{x + 12.0, y + 38.0, text_width, 18.0}, 12)
code := Code(index)
if Action(4000 + index, code, Rectangle.{x + inner - 196.0, y + 12.0, 140.0, 44.0}, false) {
if ClipboardCopy(code, CODE_CLEAR_SECONDS) {
SetStatus("Code copied; it clears in 30 seconds")
} else {
SetStatus("The clipboard is unavailable")
}
}
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",
.bounds = Rectangle.{x + inner - 40.0, y + 16.0, 36.0, 36.0},
.icon_shape = Edit.Shape, .icon_only = true,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if Button(session, edit) != 0 {
OpenEdit(index)
}
}
ListView :: (area: Rectangle, left: float32, width: float32) {
if Action(10, "Add account", Rectangle.{left, area.y + 12.0, width, 40.0}, true) {
view = VIEW_ADD
focused = 0
SetStatus("")
return
}
top := area.y + 64.0
height := area.height - 100.0
if account_count == 0 {
Label(cast(u64)11, "No accounts yet. Add one with its otpauth link or secret key.",
Rectangle.{left, top, width, 24.0}, 14)
}
row: float32 = 76.0
scroll := Scroll(session, ScrollProps.{.key = cast(u64)12, .bounds = Rectangle.{left, top, width, height},
.content_height = cast(s32)(cast(float32)account_count * row), .scroll_offset = list_scroll,
.scale = 1.0})
list_scroll = scroll.scroll_offset
if scroll.opened {
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)
index += 1
}
End(session)
}
}
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)
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")
}
}
y += 64.0
Label(cast(u64)22, "Or enter the secret key", Rectangle.{left, y, width, 20.0}, 14)
y += 24.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 += 48.0
Field(FIELD_SECRET, "Secret key", "Secret key", secret[:], Rectangle.{left, y, width, 40.0}, true)
y += 56.0
half := (width - 8.0) / 2.0
if Action(23, "Add", Rectangle.{left, y, half, 40.0}, true) {
if AddManual() {
if SaveAccounts() {
SetStatus("Account added")
} else {
SetStatus("Could not save the accounts")
}
Clear(issuer[:])
Clear(name[:])
Clear(secret[:])
view = VIEW_LIST
}
}
if Action(24, "Cancel", Rectangle.{left + half + 8.0, y, half, 40.0}, false) {
Clear(links[:])
Clear(secret[:])
view = VIEW_LIST
SetStatus("")
}
}
// 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()
width := area.width - 32.0
if width > 520.0 {
width = 520.0
}
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)
}
Label(cast(u64)30, TextUntilNul(status[:]), Rectangle.{left, area.y + area.height - 28.0, width, 20.0}, 12)
AppKeyboard(focused != 0)
}
#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.
if !loaded || RecordsVersion() != records_version {
LoadAccounts()
loaded = true
if view == VIEW_EDIT {
CloseEdit()
}
}
Draw()
return 0
}
-388
View File
@@ -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
}
-95
View File
@@ -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
}
-812
View File
@@ -1,812 +0,0 @@
// Time-based one-time passwords (RFC 6238) with HMAC-SHA-1, SHA-256 or
// SHA-512, and the otpauth:// links authenticator apps export.
#import "text_buffer"
#import "sha256"
HASH_SHA1 :: 1
HASH_SHA256 :: 2
HASH_SHA512 :: 3
// Longest key, message and decoded secret this module handles.
KEY_LIMIT :: 128
HASH_INPUT_LIMIT :: 256
Digest :: struct {
bytes: [64]u8
count: s32
}
// The 80 SHA-512 round constants, each as its high and low 32 bits.
sha512_round_halves: [160]u32 = .[
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f,
0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242,
0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235,
0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275,
0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f,
0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc,
0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6,
0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218,
0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99,
0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc,
0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915,
0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba,
0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc,
0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];
RotateLeft32 :: (value: u32, amount: u32) -> u32 {
return (value << amount) | (value >> (cast(u32)32 - amount))
}
RotateRight64 :: (value: u64, amount: u64) -> u64 {
return (value >> amount) | (value << (cast(u64)64 - amount))
}
// Pads a message the SHA way into blocks: 0x80, zeros, then the bit length
// in the last eight bytes. Returns the padded length.
Pad :: (input: []u8, count: s32, block: s32, output: []u8) -> s32 {
index: s32 = 0
while index < count {
output[index] = input[index]
index += 1
}
output[count] = cast(u8)0x80
length_bytes: s32 = ifx block == 128 then 16 else 8
total := ((count + 1 + length_bytes + block - 1) / block) * block
index = count + 1
while index < total {
output[index] = cast(u8)0
index += 1
}
bits := cast(u64)count * cast(u64)8
for shift: 0..7 {
output[total - 1 - cast(s32)shift] = cast(u8)(bits >> (cast(u64)shift * cast(u64)8))
}
return total
}
Sha1 :: (input: []u8, count: s32) -> Digest {
padded: [HASH_INPUT_LIMIT + 128]u8
total := Pad(input, count, 64, padded[:])
state: [5]u32 = .[0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]
offset: s32 = 0
while offset < total {
words: [80]u32
for index: 0..15 {
at := offset + cast(s32)index * 4
words[index] = (cast(u32)padded[at] << cast(u32)24) | (cast(u32)padded[at + 1] << cast(u32)16) |
(cast(u32)padded[at + 2] << cast(u32)8) | cast(u32)padded[at + 3]
}
for index: 16..79 {
mixed: u32 = words[index - 3] ^ words[index - 8]
mixed = mixed ^ words[index - 14]
mixed = mixed ^ words[index - 16]
words[index] = RotateLeft32(mixed, cast(u32)1)
}
a := state[0]
b := state[1]
c := state[2]
d := state[3]
e := state[4]
for index: 0..79 {
mix: u32
constant: u32
if index < 20 {
mix = (b & c) | (~b & d)
constant = 0x5a827999
} else if index < 40 {
mix = b ^ c ^ d
constant = 0x6ed9eba1
} else if index < 60 {
mix = (b & c) | (b & d) | (c & d)
constant = 0x8f1bbcdc
} else {
mix = b ^ c ^ d
constant = 0xca62c1d6
}
next := RotateLeft32(a, cast(u32)5) + mix + e + constant + words[index]
e = d
d = c
c = RotateLeft32(b, cast(u32)30)
b = a
a = next
}
state[0] += a
state[1] += b
state[2] += c
state[3] += d
state[4] += e
offset += 64
}
digest: Digest
digest.count = 20
for index: 0..4 {
for part: 0..3 {
digest.bytes[index * 4 + part] = cast(u8)(state[index] >> (cast(u32)(3 - part) * cast(u32)8))
}
}
return digest
}
Sha512 :: (input: []u8, count: s32) -> Digest {
padded: [HASH_INPUT_LIMIT + 256]u8
total := Pad(input, count, 128, padded[:])
initial: [16]u32 = .[0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b,
0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b,
0x5be0cd19, 0x137e2179]
state: [8]u64
for index: 0..7 {
state[index] = (cast(u64)initial[index * 2] << cast(u64)32) | cast(u64)initial[index * 2 + 1]
}
offset: s32 = 0
while offset < total {
words: [80]u64
for index: 0..15 {
value: u64 = 0
for part: 0..7 {
value = (value << cast(u64)8) | cast(u64)padded[offset + cast(s32)index * 8 + cast(s32)part]
}
words[index] = value
}
for index: 16..79 {
low: u64 = RotateRight64(words[index - 15], cast(u64)1)
low = low ^ RotateRight64(words[index - 15], cast(u64)8)
low = low ^ (words[index - 15] >> cast(u64)7)
high: u64 = RotateRight64(words[index - 2], cast(u64)19)
high = high ^ RotateRight64(words[index - 2], cast(u64)61)
high = high ^ (words[index - 2] >> cast(u64)6)
words[index] = words[index - 16] + low + words[index - 7] + high
}
a := state[0]
b := state[1]
c := state[2]
d := state[3]
e := state[4]
f := state[5]
g := state[6]
h := state[7]
for index: 0..79 {
major: u64 = RotateRight64(e, cast(u64)14)
major = major ^ RotateRight64(e, cast(u64)18)
major = major ^ RotateRight64(e, cast(u64)41)
choose := (e & f) ^ (~e & g)
constant := (cast(u64)sha512_round_halves[index * 2] << cast(u64)32) | cast(u64)sha512_round_halves[index * 2 + 1]
first := h + major + choose + constant + words[index]
minor: u64 = RotateRight64(a, cast(u64)28)
minor = minor ^ RotateRight64(a, cast(u64)34)
minor = minor ^ RotateRight64(a, cast(u64)39)
mixture := (a & b) ^ (a & c) ^ (b & c)
h = g
g = f
f = e
e = d + first
d = c
c = b
b = a
a = first + minor + mixture
}
state[0] += a
state[1] += b
state[2] += c
state[3] += d
state[4] += e
state[5] += f
state[6] += g
state[7] += h
offset += 128
}
digest: Digest
digest.count = 64
for index: 0..7 {
for part: 0..7 {
digest.bytes[index * 8 + part] = cast(u8)(state[index] >> (cast(u64)(7 - part) * cast(u64)8))
}
}
return digest
}
Hash :: (kind: s32, input: []u8, count: s32) -> Digest {
if kind == HASH_SHA256 {
hashed := Sha256(TextView(input[0:count]))
digest: Digest
digest.count = 32
for index: 0..31 {
digest.bytes[index] = hashed[index]
}
return digest
}
if kind == HASH_SHA512 {
return Sha512(input, count)
}
return Sha1(input, count)
}
// HMAC (RFC 2104). Keys up to KEY_LIMIT bytes and messages up to 64 bytes.
Hmac :: (kind: s32, key: []u8, key_count: s32, message: []u8, message_count: s32) -> Digest {
block: s32 = ifx kind == HASH_SHA512 then 128 else 64
block_key: [128]u8
if key_count > block {
hashed := Hash(kind, key, key_count)
for index: 0..63 {
block_key[index] = hashed.bytes[index]
}
} else {
index: s32 = 0
while index < key_count {
block_key[index] = key[index]
index += 1
}
}
inner_input: [HASH_INPUT_LIMIT]u8
index: s32 = 0
while index < block {
inner_input[index] = block_key[index] ^ cast(u8)0x36
index += 1
}
index = 0
while index < message_count {
inner_input[block + index] = message[index]
index += 1
}
inner := Hash(kind, inner_input[:], block + message_count)
outer_input: [HASH_INPUT_LIMIT]u8
index = 0
while index < block {
outer_input[index] = block_key[index] ^ cast(u8)0x5c
index += 1
}
index = 0
while index < inner.count {
outer_input[block + index] = inner.bytes[index]
index += 1
}
result := Hash(kind, outer_input[:], block + inner.count)
for wipe: 0..127 {
block_key[wipe] = cast(u8)0
}
for wipe: 0..HASH_INPUT_LIMIT - 1 {
inner_input[wipe] = cast(u8)0
outer_input[wipe] = cast(u8)0
}
return result
}
// The code for a counter (HOTP, RFC 4226), zero-padded to digits.
CodeAt :: (kind: s32, key: []u8, key_count: s32, digits: s32, counter: u64, output: []u8) -> string {
message: [8]u8
for index: 0..7 {
message[index] = cast(u8)(counter >> (cast(u64)(7 - index) * cast(u64)8))
}
mac := Hmac(kind, key, key_count, message[:], 8)
offset := cast(s32)(mac.bytes[mac.count - 1] & cast(u8)0x0f)
binary := ((cast(u32)mac.bytes[offset] & cast(u32)0x7f) << cast(u32)24) |
(cast(u32)mac.bytes[offset + 1] << cast(u32)16) |
(cast(u32)mac.bytes[offset + 2] << cast(u32)8) | cast(u32)mac.bytes[offset + 3]
modulus: u32 = 1
for step: 1..digits {
modulus *= cast(u32)10
}
value := binary % modulus
position := digits - 1
while position >= 0 {
output[position] = cast(u8)(48 + cast(s32)(value % cast(u32)10))
value /= cast(u32)10
position -= 1
}
output[digits] = cast(u8)0
return TextView(output[0:digits])
}
// The code for a Unix time (TOTP, RFC 6238).
CodeNow :: (kind: s32, key: []u8, key_count: s32, digits: s32, period: s32, unix: s64, output: []u8) -> string {
step := unix / cast(s64)period
if step < 0 {
step = 0
}
return CodeAt(kind, key, key_count, digits, cast(u64)step, output)
}
// Decodes Base32 (RFC 4648) ignoring case, spaces, hyphens and padding.
// Returns the byte count, or -1 for any other character or a key too long.
Base32Decode :: (text: string, output: []u8) -> s32 {
buffer: u32 = 0
bits: s32 = 0
count: s32 = 0
index: s64 = 0
while index < text.count {
byte := text[index]
index += 1
if byte == cast(u8)32 || byte == cast(u8)45 || byte == cast(u8)61 {
continue
}
value: s32 = -1
if byte >= cast(u8)65 && byte <= cast(u8)90 {
value = cast(s32)(byte - cast(u8)65)
} else if byte >= cast(u8)97 && byte <= cast(u8)122 {
value = cast(s32)(byte - cast(u8)97)
} else if byte >= cast(u8)50 && byte <= cast(u8)55 {
value = cast(s32)(byte - cast(u8)50) + 26
}
if value < 0 {
return -1
}
buffer = (buffer << cast(u32)5) | cast(u32)value
bits += 5
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
}
// 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
key_count: s32
kind: s32
digits: s32
period: s32
}
Lower :: (byte: u8) -> u8 {
if byte >= cast(u8)65 && byte <= cast(u8)90 {
return byte + cast(u8)32
}
return byte
}
StartsWithIgnoringCase :: (text: string, prefix: string) -> bool {
if text.count < prefix.count {
return false
}
index: s64 = 0
while index < prefix.count {
if Lower(text[index]) != Lower(prefix[index]) {
return false
}
index += 1
}
return true
}
HexValue :: (byte: u8) -> s32 {
if byte >= cast(u8)48 && byte <= cast(u8)57 {
return cast(s32)(byte - cast(u8)48)
}
lower := Lower(byte)
if lower >= cast(u8)97 && lower <= cast(u8)102 {
return cast(s32)(lower - cast(u8)97) + 10
}
return -1
}
// Percent-decodes into output ("+" is a space in a query). False when it
// does not fit.
Unescape :: (text: string, output: []u8) -> bool {
used: s64 = 0
index: s64 = 0
while index < text.count {
byte := text[index]
if byte == cast(u8)37 && index + 2 < text.count && HexValue(text[index + 1]) >= 0 && HexValue(text[index + 2]) >= 0 {
byte = cast(u8)(HexValue(text[index + 1]) * 16 + HexValue(text[index + 2]))
index += 2
} else if byte == cast(u8)43 {
byte = cast(u8)32
}
if used >= output.count - 1 || byte < cast(u8)32 {
return false
}
output[used] = byte
used += 1
index += 1
}
output[used] = cast(u8)0
return true
}
ParseNumber :: (text: string) -> s32 {
if text.count == 0 || text.count > 6 {
return -1
}
value: s32 = 0
index: s64 = 0
while index < text.count {
if text[index] < cast(u8)48 || text[index] > cast(u8)57 {
return -1
}
value = value * 10 + cast(s32)(text[index] - cast(u8)48)
index += 1
}
return value
}
ParseAlgorithm :: (text: string) -> s32 {
upper: [8]u8
if text.count > 7 {
return 0
}
index: s64 = 0
while index < text.count {
byte := text[index]
upper[index] = ifx byte >= cast(u8)97 && byte <= cast(u8)122 then byte - cast(u8)32 else byte
index += 1
}
name := TextView(upper[0:text.count])
if name == "SHA1" {
return HASH_SHA1
}
if name == "SHA256" {
return HASH_SHA256
}
if name == "SHA512" {
return HASH_SHA512
}
return 0
}
// Checks a Base32 secret and fills the account's key from it.
SetSecret :: (account: *Account, secret: string) -> bool {
clean: [256]u8
used: s64 = 0
index: s64 = 0
while index < secret.count {
byte := secret[index]
index += 1
if byte == cast(u8)32 || byte == cast(u8)45 || byte == cast(u8)61 {
continue
}
if used >= 255 {
return false
}
clean[used] = ifx byte >= cast(u8)97 && byte <= cast(u8)122 then byte - cast(u8)32 else byte
used += 1
}
count := Base32Decode(TextView(clean[0:used]), account.key[:])
// Shorter keys than 80 bits are refused as RFC 4226 asks; most services
// use 160.
if count < 10 {
return false
}
account.key_count = count
index = 0
while index < used {
account.secret[index] = clean[index]
index += 1
}
account.secret[used] = cast(u8)0
return true
}
CopyLimited :: (text: string, output: []u8) -> bool {
if text.count >= output.count {
return false
}
index: s64 = 0
while index < text.count {
if text[index] < cast(u8)32 {
return false
}
output[index] = text[index]
index += 1
}
output[text.count] = cast(u8)0
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}
prefix := "otpauth://totp/"
if !StartsWithIgnoringCase(link, prefix) {
return false
}
rest := link[prefix.count:link.count]
query_at: s64 = 0
while query_at < rest.count && rest[query_at] != cast(u8)63 {
query_at += 1
}
label: [256]u8
if !Unescape(rest[0:query_at], label[:]) {
return false
}
label_text := TextUntilNul(label[:])
colon: s64 = 0
while colon < label_text.count && label_text[colon] != cast(u8)58 {
colon += 1
}
if colon < label_text.count {
start := colon + 1
while start < label_text.count && label_text[start] == cast(u8)32 {
start += 1
}
if !CopyLimited(label_text[0:colon], account.issuer[:]) ||
!CopyLimited(label_text[start:label_text.count], account.name[:]) {
return false
}
} else if !CopyLimited(label_text, account.name[:]) {
return false
}
has_secret := false
position := query_at + 1
while position < rest.count {
end := position
while end < rest.count && rest[end] != cast(u8)38 {
end += 1
}
pair := rest[position:end]
equals: s64 = 0
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 {
value: [256]u8
if !Unescape(pair[equals + 1:pair.count], value[:]) {
return false
}
text := TextUntilNul(value[:])
if key == "secret" {
if !SetSecret(account, text) {
return false
}
has_secret = true
} else if key == "issuer" {
if !CopyLimited(text, account.issuer[:]) {
return false
}
} else if key == "algorithm" {
account.kind = ParseAlgorithm(text)
if account.kind == 0 {
return false
}
} else if key == "digits" {
account.digits = ParseNumber(text)
if account.digits < 6 || account.digits > 8 {
return false
}
} else if key == "period" {
account.period = ParseNumber(text)
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
}
return has_secret && (account.issuer[0] != cast(u8)0 || account.name[0] != cast(u8)0)
}
Unreserved :: (byte: u8) -> bool {
return byte >= cast(u8)65 && byte <= cast(u8)90 || byte >= cast(u8)97 && byte <= cast(u8)122 ||
byte >= cast(u8)48 && byte <= cast(u8)57 || byte == cast(u8)45 || byte == cast(u8)46 ||
byte == cast(u8)95 || byte == cast(u8)126
}
AppendText :: (output: []u8, used: s64, text: string) -> s64 {
index: s64 = 0
while index < text.count {
if used < 0 || used >= output.count - 1 {
return -1
}
output[used] = text[index]
used += 1
index += 1
}
output[used] = cast(u8)0
return used
}
AppendEscaped :: (output: []u8, used: s64, text: string) -> s64 {
hex := "0123456789ABCDEF"
index: s64 = 0
while index < text.count && used >= 0 {
byte := text[index]
if Unreserved(byte) {
used = AppendText(output, used, text[index:index + 1])
} else if used + 3 < output.count {
output[used] = cast(u8)37
output[used + 1] = hex[cast(s64)(byte >> cast(u8)4)]
output[used + 2] = hex[cast(s64)(byte & cast(u8)15)]
used += 3
output[used] = cast(u8)0
} else {
return -1
}
index += 1
}
return used
}
// The account as an otpauth link, the format Auth saves and imports.
LinkText :: (account: *Account, output: []u8) -> string {
used := AppendText(output, 0, "otpauth://totp/")
issuer := TextUntilNul(account.issuer[:])
if issuer != "" {
used = AppendEscaped(output, used, issuer)
used = AppendText(output, used, ":")
}
used = AppendEscaped(output, used, TextUntilNul(account.name[:]))
used = AppendText(output, used, "?secret=")
used = AppendText(output, used, TextUntilNul(account.secret[:]))
if issuer != "" {
used = AppendText(output, used, "&issuer=")
used = AppendEscaped(output, used, issuer)
}
algorithms: [4]string = .["", "SHA1", "SHA256", "SHA512"]
used = AppendText(output, used, "&algorithm=")
used = AppendText(output, used, algorithms[account.kind])
digits: [2]u8
digits[0] = cast(u8)(48 + account.digits)
used = AppendText(output, used, "&digits=")
used = AppendText(output, used, TextView(digits[0:1]))
period: [8]u8
value := account.period
length: s32 = 0
while value > 0 || length == 0 {
period[7 - length] = cast(u8)(48 + value % 10)
value /= 10
length += 1
}
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])
}
-64
View File
@@ -1,64 +0,0 @@
// RFC 6238 and RFC 4648 test vectors, with the RFCs' public fixture keys.
#import "text_buffer"
#import "totp"
KeyFrom :: (text: string, output: []u8) -> s32 {
index: s64 = 0
while index < text.count {
output[index] = text[index]
index += 1
}
return cast(s32)text.count
}
Expect :: (kind: s32, key: string, unix: s64, expected: string) -> bool {
bytes: [KEY_LIMIT]u8
count := KeyFrom(key, bytes[:])
code: [12]u8
return CodeNow(kind, bytes[:], count, 8, 30, unix, code[:]) == expected
}
#program_export
Run :: () -> s32 {
sha1 := "12345678901234567890"
sha256 := "12345678901234567890123456789012"
sha512 := "1234567890123456789012345678901234567890123456789012345678901234"
times: [6]s64 = .[59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000]
sha1_codes: [6]string = .["94287082", "07081804", "14050471", "89005924", "69279037", "65353130"]
sha256_codes: [6]string = .["46119246", "68084774", "67062674", "91819424", "90698825", "77737706"]
sha512_codes: [6]string = .["90693936", "25091201", "99943326", "93441116", "38618901", "47863826"]
for index: 0..5 {
if !Expect(HASH_SHA1, sha1, times[index], sha1_codes[index]) {
return 10 + cast(s32)index
}
if !Expect(HASH_SHA256, sha256, times[index], sha256_codes[index]) {
return 20 + cast(s32)index
}
if !Expect(HASH_SHA512, sha512, times[index], sha512_codes[index]) {
return 30 + cast(s32)index
}
}
decoded: [KEY_LIMIT]u8
count := Base32Decode("gezd gnbv-gy3t qojq GEZDGNBVGY3TQOJQ====", decoded[:])
if count != 20 || TextView(decoded[0:20]) != sha1 || Base32Decode("GEZ1", decoded[:]) != -1 {
return 40
}
account: Account
link := "otpauth://totp/Example%20Co:alice%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Example%20Co&algorithm=SHA256&digits=8&period=60"
if !ParseLink(link, *account) || TextUntilNul(account.issuer[:]) != "Example Co" ||
TextUntilNul(account.name[:]) != "[email protected]" || account.kind != HASH_SHA256 ||
account.digits != 8 || account.period != 60 || account.key_count != 20 {
return 41
}
saved: [1024]u8
again: Account
if !ParseLink(LinkText(*account, saved[:]), *again) || TextUntilNul(again.secret[:]) != TextUntilNul(account.secret[:]) ||
TextUntilNul(again.issuer[:]) != "Example Co" || again.digits != 8 || again.period != 60 {
return 42
}
if ParseLink("otpauth://hotp/Example:alice?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&counter=1", *again) ||
ParseLink("otpauth://totp/Example:alice?secret=SHORT", *again) {
return 43
}
return 0
}
+28 -69
View File
@@ -4,20 +4,12 @@
#import "version"
#import "c_string"
#import "text_buffer"
#if !#defined(PLAN9_BUILD) {
#import "cli_profiles"
#import "cli_native"
}
#import "cli_profiles"
#import "cli_native"
libc :: #system_library "libc";
Write :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "write";
Read :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "read";
#if #defined(PLAN9_BUILD) {
GetEnvRaw :: (name: *s8) -> *s8 #foreign libc "getenv";
GetEnv :: (name: *u8) -> *u8 { return cast(*u8)GetEnvRaw(cast(*s8)name) }
} else {
GetEnv :: (name: *u8) -> *u8 #foreign libc "getenv";
}
GetEnv :: (name: *u8) -> *u8 #foreign libc "getenv";
Usage :: #string END
Usage: pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
@@ -70,23 +62,6 @@ Error :: (message: string) -> s32 {
return 2
}
ReadMaster :: (buffer: []u8) -> bool {
used: s32 = 0
while used < cast(s32)buffer.count - 1 {
byte: u8
if Read(0, *byte, cast(usize)1) != cast(isize)1 { return used > 0 }
if byte == cast(u8)10 {
if used > 0 && buffer[used - 1] == cast(u8)13 { used -= 1 }
buffer[used] = cast(u8)0
return true
}
if byte == cast(u8)0 { return false }
buffer[used] = byte
used += 1
}
return false
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
options: PassOptions
@@ -153,35 +128,27 @@ main :: (argc: s32, argv: **u8) -> s32 {
}
if version { Print(1, "pass "); Print(1, Version); Print(1, "\n"); return 0 }
site: string; login: string; clear_ms: s64
#if !#defined(PLAN9_BUILD) {
// Keep the decoded profile alive until generation has finished.
profile: LegacyProfile
}
// Keep the decoded profile alive until generation has finished.
profile: LegacyProfile
if profile_name != "" {
if count != 1 { return Error("expected SITE with --profile") }
} else if count < 2 { Print(2, Usage); return 2 }
#if !#defined(PLAN9_BUILD) {
candidate := profile_name
if candidate == "" && count == 2 { candidate = positional[0] }
profile = LoadLegacyProfile(candidate, profile_name != "", *options, explicit)
if !profile.valid { return Error("invalid CLI profiles configuration or unknown profile") }
if profile.found {
site = ifx profile_name != "" then positional[0] else positional[1]
login = TextUntilNul(profile.login[:])
if (explicit & cast(u32)64) == cast(u32)0 { options.exclude = TextUntilNul(profile.exclude[:]) }
} else { site = positional[0]; login = positional[1] }
if !copy { copy = profile.copy }
clear_ms = profile.clear_ms
if clear_after != "" {
clear_ms = DurationMilliseconds(clear_after)
if clear_ms < 0 { return Error("invalid --clear-after duration") }
}
if vault_path == "" && !prompt && count != 3 { vault_path = TextUntilNul(profile.vault[:]) }
} else {
if profile_name != "" || vault_path != "" || clear_after != "" { return Error("profiles and vaults require the Linux CLI") }
if copy && !no_copy { return Error("--copy is not available on Plan 9") }
site = positional[0]; login = positional[1]
candidate := profile_name
if candidate == "" && count == 2 { candidate = positional[0] }
profile = LoadLegacyProfile(candidate, profile_name != "", *options, explicit)
if !profile.valid { return Error("invalid CLI profiles configuration or unknown profile") }
if profile.found {
site = ifx profile_name != "" then positional[0] else positional[1]
login = TextUntilNul(profile.login[:])
if (explicit & cast(u32)64) == cast(u32)0 { options.exclude = TextUntilNul(profile.exclude[:]) }
} else { site = positional[0]; login = positional[1] }
if !copy { copy = profile.copy }
clear_ms = profile.clear_ms
if clear_after != "" {
clear_ms = DurationMilliseconds(clear_after)
if clear_ms < 0 { return Error("invalid --clear-after duration") }
}
if vault_path == "" && !prompt && count != 3 { vault_path = TextUntilNul(profile.vault[:]) }
if vault_path != "" && (prompt || count == 3) { return Error("--vault cannot be combined with --prompt or MASTER_PASSWORD") }
if prompt && count == 3 { return Error("MASTER_PASSWORD cannot be supplied together with --prompt") }
master: [1024]u8
@@ -190,11 +157,9 @@ main :: (argc: s32, argv: **u8) -> s32 {
if !CopyText(positional[2], master[:]) { return Error("master password is too long") }
} else {
unlocked: bool
#if !#defined(PLAN9_BUILD) {
if vault_path != "" {
if !DecryptVault(vault_path, master[:]) { return Error("cannot unlock vault: wrong passphrase, unreadable or corrupted vault") }
unlocked = true
}
if vault_path != "" {
if !DecryptVault(vault_path, master[:]) { return Error("cannot unlock vault: wrong passphrase, unreadable or corrupted vault") }
unlocked = true
}
if !unlocked {
name: [32]u8
@@ -203,11 +168,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
if !prompt && environment != null {
if !CopyText(TextFromCString(environment), master[:]) { return Error("master password is too long") }
} else {
#if !#defined(PLAN9_BUILD) {
if !ReadSecret(master[:], "Master password: ") { return Error("missing master password") }
} else {
if !ReadMaster(master[:]) { return Error("missing master password") }
}
if !ReadSecret(master[:], "Master password: ") { return Error("missing master password") }
}
}
}
@@ -217,13 +178,11 @@ main :: (argc: s32, argv: **u8) -> s32 {
if !generated.valid {
Print(2, "pass: "); Print(2, generated.error); Print(2, "\n"); return 1
}
#if !#defined(PLAN9_BUILD) {
if copy && !no_copy {
if !CopyPassword(TextView(generated.password[0:generated.length]), clear_ms) {
return Error("clipboard unavailable; install xclip or use --no-copy")
}
Print(2, "Password copied to the clipboard.\n"); return 0
if copy && !no_copy {
if !CopyPassword(TextView(generated.password[0:generated.length]), clear_ms) {
return Error("clipboard unavailable; install xclip or use --no-copy")
}
Print(2, "Password copied to the clipboard.\n"); return 0
}
Print(1, TextView(generated.password[0:generated.length])); Print(1, "\n")
return 0
+7 -3
View File
@@ -1,4 +1,4 @@
#import "sha256"
#import "crypto/sha256"
#if #defined(WERK_APP) {
#import "kryon/app_context"
}
@@ -57,10 +57,14 @@ DeriveKey :: (password: string, salt: string) -> [32]u8 {
derive_failed = !AppPbkdf2Sha256(password, salt, 100000, output[:])
return output
} else {
return Pbkdf2Sha256(password, salt, 100000)
return Pbkdf2Sha256(password, ifx salt.count > PASS_SALT_LIMIT then salt[0:PASS_SALT_LIMIT] else salt, 100000)
}
}
// Werkzeug's key derivation has always read at most this many salt bytes,
// and existing vault keys depend on it; the host derives the same way.
PASS_SALT_LIMIT :: 508
PassClassEmptyError :: (class_index: s32) -> string {
if class_index == 0 {
@@ -319,7 +323,7 @@ MasterEmoji :: (master: string, output: []u8) -> s32 {
if output.count <= 0 { return 0 }
output[0] = cast(u8)0
digest := Sha256(master)
digest := Sha256Of(master)
used: s32 = 0
for index: 0..3 {
codepoint: u32 = cast(u32)master_emoji_codepoints[
+4 -4
View File
@@ -1,5 +1,5 @@
#import "pass_core"
#import "sha256"
#import "crypto/sha256"
#program_export
DigestMatches :: (left: [32]u8, right: [32]u8) -> bool {
@@ -11,8 +11,8 @@ DigestMatches :: (left: [32]u8, right: [32]u8) -> bool {
#program_export
Answer :: () -> s32 {
empty := Sha256("")
abc := Sha256("abc")
empty := Sha256Of("")
abc := Sha256Of("abc")
derived := DeriveKey("password", "salt")
if empty[0] != cast(u8)0xe3 || empty[31] != cast(u8)0x55 { return 1 }
if abc[0] != cast(u8)0xba || abc[31] != cast(u8)0xad { return 2 }
@@ -117,7 +117,7 @@ Answer :: () -> s32 {
#program_export
PortableAnswer :: () -> s32 {
digest := HmacSha256("password", "salt")
digest := HmacSha256Of("password", "salt")
if digest[0] != cast(u8)0xfc || digest[31] != cast(u8)0xd0 {
return 1
}
+214
View File
@@ -0,0 +1,214 @@
# Werkzeug development and data
[Back to Werkzeug](../README.md).
## 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:
| Platform | Data |
|---|---|
| Linux | `$XDG_DATA_HOME/werk` (or `~/.local/share/werk`) |
| Android | the app's private storage |
| Browser | IndexedDB on this site |
Auth's accounts are synced records: `otpauth` links in the private
`records/auth.txt`, protected by the file permissions of your account or the
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. In the browser, Profile opens the shared manager at
https://entity.waozi.xyz. Public name, picture and appearance follow the active
waozi.xyz profile. Werkzeug's browser tool data stays local; account sync for
those tool records is unavailable.
The embedded web app (`/app/?mini`) shows only the tools, as large tiles,
with no Profile; `werk --mini` does the same on the desktop. Use
`?mini&app=pass`, `auth`, `calculator` or `clock` to open a particular tool
first; Back returns to the tiles. Browser sync is currently unavailable.
- 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
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.
- 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 is built into its own portable bundle, `build/apps/<tool>.zx`:
Pass, Calculator and Clock from `apps/<tool>/`, Auth from its own Ziran
package ([waozixyz/auth](https://github.com/waozixyz/auth)), and Workbook from
[waozixyz/workbook](https://github.com/waozixyz/workbook). All five are
preinstalled. A tool reaches the host only through Kryon's app context (its
private files, clipboard, clock, key derivation and device-protected
secret), and the host checks every call a bundle asks for before it runs.
Tools never import each other; what two need, such as SHA-256 and PBKDF2,
comes from a Ziran package (`crypto`).
## 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 its built-in spreadsheet engine on Android and the web; Linux
also uses the installed Gnumeric library for imported documents. Linux file choosers need Zenity. 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 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 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/fdroid/werk.apk` for comparison with the signed release. 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`:
```toml
[overrides]
kryon = "../../kryonlabs/kryon"
ziran = "../../ziranlang/ziran"
```
## The `pass` command
```text
pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
pass [OPTIONS] PROFILE SITE
```
`make cli` builds it and `make install-cli` installs it. The default password
has 16 characters and includes lowercase letters, uppercase letters, digits
and symbols. Length must be between 5 and 35, matching LessPass clients. The
default counter is 1.
Passing a master password as an argument can expose it to process inspection
and shell history. Omitting it is safer: `pass` first checks
`LESSPASS_MASTER_PASSWORD`, then reads one line from standard input. Use
`--prompt` to bypass the environment and read from standard input:
```sh
pass --prompt example.com alice
pass --length 24 --counter 2 example.com alice
pass --no-symbols --exclude '0O1Il' example.com alice
```
The Linux CLI also reads saved identities from
`$XDG_CONFIG_HOME/pass/profiles.json` (or `~/.config/pass/profiles.json`).
`pass w example.com` and `pass --profile w example.com` use the saved login
and generation options. Existing OpenSSL-encrypted vaults are unlocked with
a hidden `Vault passphrase:` prompt. A configured vault takes precedence over
`LESSPASS_MASTER_PASSWORD`; `--prompt` bypasses it. Explicit flags override
profile defaults. Profiles and vaults are read without changing them.
`--copy` or a profile's `copy` setting copies through `xclip` on X11;
`--clear-after 90s` releases that clipboard selection after the given time
without erasing a later copy from another application. Use `--no-copy` to
print the generated password instead. Run `pass --help` for all flags.
## Source layout
```text
apps/pass/ Pass: LessPass core, settings and profiles, screens, CLI
auth (package) Auth: TOTP, otpauth links, exports, accounts and screens (waozixyz/auth)
apps/calculator/ Calculator
apps/clock/ Clock and stopwatch
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
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
[`LICENSE`](../LICENSE).
+9 -5
View File
@@ -43,8 +43,8 @@ android {
applicationId 'xyz.waozi.pass'
minSdk 21
targetSdk 36
versionCode 16
versionName "0.4.2"
versionCode 21
versionName "0.4.7"
// 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'
@@ -106,12 +106,16 @@ def makeApps = tasks.register('makeApps', Exec) {
workingDir '../..'
commandLine 'make', 'portable-apps'
}
def kryonSource = providers.exec {
workingDir '../..'
commandLine rootProject.file('../scripts/ziran.sh').absolutePath, 'pkg', 'path', 'kryon'
}.standardOutput.asText.map { it.trim() }
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('generated/appAssets'))
def prepareImages = tasks.register('prepareImages', Copy) {
def prepareImages = tasks.register('prepareImages', Sync) {
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(kryonSource.map { "${it}/icons/pfp.png" })
from('../../build/apps') { include '*.zx'; into 'apps' }
into layout.buildDirectory.dir('generated/appAssets')
}
tasks.named('preBuild').configure { dependsOn prepareImages }
+30 -13
View File
@@ -1,16 +1,6 @@
cmake_minimum_required(VERSION 3.22)
project(Werkzeug C)
get_filename_component(REPO_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../.." ABSOLUTE)
set(KRYON_DIR "$ENV{KRYON_DIR}" CACHE PATH "Locked Kryon source" FORCE)
set(ZIRAN_ROOT "$ENV{ZIRAN_ROOT}" CACHE PATH "Locked Ziran toolchain" FORCE)
set(RAYLIB_DIR "$ENV{RAYLIB_DIR}" CACHE PATH "Locked raylib source" FORCE)
set(LIBOQS_DIR "$ENV{LIBOQS_DIR}" CACHE PATH "Locked liboqs source" FORCE)
set(MONOCYPHER_DIR "$ENV{MONOCYPHER_DIR}" CACHE PATH "Locked Monocypher source" FORCE)
foreach(root KRYON_DIR ZIRAN_ROOT RAYLIB_DIR LIBOQS_DIR MONOCYPHER_DIR)
if(NOT ${root})
message(FATAL_ERROR "Set ${root}; use make android-debug or make android-release")
endif()
endforeach()
set(ZIRAN "${REPO_ROOT}/scripts/ziran.sh")
if(DEFINED ENV{WERK_ZIRAN_COMMAND} AND NOT "$ENV{WERK_ZIRAN_COMMAND}" STREQUAL "")
get_filename_component(ZIRAN "$ENV{WERK_ZIRAN_COMMAND}" ABSOLUTE BASE_DIR "${REPO_ROOT}")
@@ -32,12 +22,33 @@ set(LOCK_FLAGS --locked)
if(EXISTS "${REPO_ROOT}/ziran.local.toml")
set(LOCK_FLAGS)
endif()
# Plain Gradle builds resolve the same packages as Make. F-Droid needs no
# source patches or machine-specific environment variables in its recipe.
function(werk_package variable package suffix)
if(NOT "$ENV{${variable}}" STREQUAL "")
set(path "$ENV{${variable}}")
else()
execute_process(COMMAND "${ZIRAN}" pkg path "${package}" ${LOCK_FLAGS}
WORKING_DIRECTORY "${REPO_ROOT}" OUTPUT_VARIABLE path
OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
string(APPEND path "${suffix}")
endif()
set(${variable} "${path}" CACHE PATH "Locked ${package} source" FORCE)
endfunction()
werk_package(KRYON_DIR kryon "")
werk_package(ZIRAN_ROOT ziran "")
werk_package(RAYLIB_DIR raylib "/src")
werk_package(LIBOQS_DIR liboqs "")
werk_package(MONOCYPHER_DIR monocypher "")
werk_package(WORKBOOK_DIR workbook "")
file(GLOB_RECURSE SOURCE_INPUTS CONFIGURE_DEPENDS
"${REPO_ROOT}/src/*.zi" "${REPO_ROOT}/shared/*.zi" "${KRYON_DIR}/src/*.zi" "${ZIRAN_ROOT}/std/*.zi")
list(APPEND SOURCE_INPUTS "${REPO_ROOT}/ziran.toml" "${REPO_ROOT}/ziran.lock")
"${REPO_ROOT}/src/*.zi" "${WORKBOOK_DIR}/src/*.zi" "${KRYON_DIR}/src/*.zi" "${ZIRAN_ROOT}/std/*.zi")
list(APPEND SOURCE_INPUTS "${REPO_ROOT}/ziran.toml" "${REPO_ROOT}/ziran.lock" "${REPO_ROOT}/scripts/runtime_cache.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${SOURCE_INPUTS})
execute_process(COMMAND "${ZIRAN}" build --project ${LOCK_FLAGS} ${DEFINES}
--target=c --entry android_main:main -o "${GENERATED}" src/android_main.zi
# Native linker callbacks are reached through raylib, outside Zi's entry
# graph. Keep them as the shared Android source generator does.
--target=c --no-main -o "${GENERATED}" src/android_main.zi
WORKING_DIRECTORY "${REPO_ROOT}" COMMAND_ERROR_IS_FATAL ANY)
file(GLOB GENERATED_SOURCES CONFIGURE_DEPENDS "${GENERATED}/*.c")
# Kryon's Android glue compiles its thread configurator with the same zi2c.
@@ -51,6 +62,8 @@ kryon_android_raylib("${RAYLIB_DIR}")
# The portable runtime that runs the app bundles, built from the locked Ziran
# for this ABI.
set(BUNDLE_RUNTIME_DIR "${CMAKE_BINARY_DIR}/bundle-runtime")
execute_process(COMMAND python3 "${REPO_ROOT}/scripts/runtime_cache.py" "${ZIRAN_ROOT}" "${BUNDLE_RUNTIME_DIR}"
COMMAND_ERROR_IS_FATAL ANY)
execute_process(COMMAND make -C "${ZIRAN_ROOT}" BOOTSTRAP=1 "BUILD_DIR=${BUNDLE_RUNTIME_DIR}"
"CC=${CMAKE_C_COMPILER} --target=${CMAKE_C_COMPILER_TARGET} --sysroot=${CMAKE_SYSROOT}"
"AR=${CMAKE_AR}" "OBJCOPY=${CMAKE_OBJCOPY}" "CFLAGS=-O2 -fPIC"
@@ -76,5 +89,9 @@ target_link_libraries(main oqs)
kryon_android_app(main)
target_link_libraries(main "${BUNDLE_RUNTIME_DIR}/libziran.a")
target_link_options(main PRIVATE -Wl,--wrap=pthread_attr_init)
# Linker build IDs include debug-path differences even after stripping. The
# installed code is identical; omit this note for reproducible signed APKs.
# https://f-droid.org/docs/Reproducible_Builds/#ndk-build-id
target_link_options(main PRIVATE -Wl,--build-id=none)
# Werkzeug has no handwritten native sources; every app translation unit above is
# generated from .zi for this ABI. raylib and the NDK own native_app_glue.
@@ -0,0 +1,2 @@
- Werkzeug uses its own Android application ID, `xyz.waozi.werk`.
- Werkzeug installs alongside legacy Pass, preserving the older app and its data.
@@ -0,0 +1,2 @@
- Werkzeug updates the existing Pass Android app using its original application ID and signing certificate, keeping its saved data.
- The app continues to appear as Werkzeug, with Pass, Auth, Calculator and Clock together.
@@ -0,0 +1 @@
- Fix Android opening to “Apps are unavailable”; Pass, Auth, Calculator and Clock load normally.
@@ -0,0 +1 @@
- Set an account alias with capitals, an @ or spaces; a taken alias now says so.
@@ -0,0 +1,2 @@
- Use Workbook on Android and the web as well as Linux, with formulas, sheet tabs, automatic saving and document import/export.
- Navigate Workbook cells with touch controls, and keep Android's keyboard focused while editing a cell.
@@ -4,6 +4,7 @@ Werkzeug holds small private tools in one app. Everything is computed on your de
• 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.
• Clock shows the local time and date and has a stopwatch.
• Workbook edits spreadsheets with formulas, multiple sheets and automatic saving. Import or export a Gnumeric workbook through Android's file chooser, and use the same document on the desktop or web.
A profile with your name and picture sets the appearance every tool shares.
Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

-20
View File
@@ -1,20 +0,0 @@
</$objtype/mkfile
# Generate with `make plan9-c` on the host, then build natively with `mk`.
CLI_FILES=`{ls build/plan9/cli/*.c}
CLI_HEADERS=`{ls build/plan9/cli/*.h}
CLI_OBJECTS=${CLI_FILES:%.c=%.$O}
CFLAGS=-FTVw
all:V: pass
pass: $CLI_OBJECTS
$LD -o $target $prereq
$CLI_OBJECTS: $CLI_HEADERS
%.$O: %.c
$CC $CFLAGS -o $target $stem.c
install:V: pass
cp pass /$objtype/bin/pass
+4
View File
@@ -0,0 +1,4 @@
/config/
/repo/
/tmp/
/logs/
+3 -21
View File
@@ -1,23 +1,5 @@
# Draft: xyz.waozi.pass: rename to Werkzeug and update to 0.4.0
# Update Pass to Werkzeug
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.
Update the existing `xyz.waozi.pass` app to Werkzeug. The package ID and signing certificate are preserved for in-place updates.
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)
Listing text and screenshots are maintained upstream in Fastlane.
+13 -47
View File
@@ -1,51 +1,17 @@
# Werkzeug F-Droid TODO
# Werkzeug F-Droid update status
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.
The owner's latest request is an update of the existing Pass app. Keep `xyz.waozi.pass`, the existing author signing certificate and private app data. The visible name remains Werkzeug. Preserve any separate `xyz.waozi.werk` installation as well.
## Prepared and verified
- [x] Prepare the original Android application ID and matching artifact verifiers.
- [x] Prepare 0.4.4 with version code 18 through `update_version.sh`.
- [x] Build the compatible ARM and private-emulator candidates with matching ZX dependencies and current app bundles.
- [x] Verify both ARM native libraries match byte for byte after independent builds in different directories.
- [ ] Publish the compatible candidate through the normal release workflow and pin its exact source revision in the recipe.
- [ ] Complete source-build and reproducibility verification against its reference APK.
- [ ] Resolve missing explicit dependency licenses and remaining GitLab pipeline results.
- [ ] Obtain owner approval before marking the update ready for review.
- [ ] Verify catalog publication after maintainers merge and F-Droid publishes it.
- [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.
[Update draft](https://gitlab.com/fdroid/fdroiddata/-/merge_requests/53909) · [Recipe](metadata/xyz.waozi.pass.yml) · [Merge-request text](MERGE_REQUEST.md)
## 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.
The local recipe is being prepared; its source pin still needs the verified compatible candidate. A Draft or a successful source build does not imply F-Droid catalog publication.
+8 -34
View File
@@ -12,7 +12,7 @@ AutoName: Werkzeug
RepoType: git
Repo: https://github.com/waozixyz/werk.git
Binaries: https://github.com/waozixyz/werk/releases/download/v%v/werk-%v.apk
Binaries: https://github.com/waozixyz/pass/releases/download/v%v/pass-%v.apk
Builds:
- versionName: 0.2.9
@@ -25,53 +25,27 @@ Builds:
- 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
- versionName: 0.4.4
versionCode: 18
commit: b53050764b8402a96e2e6b9b8c90d6567a3bea77
subdir: droid/app
sudo:
- apt-get update
- apt-get install -y build-essential libssl-dev
- apt-get install -y build-essential cmake 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
binary: https://github.com/waozixyz/werk/releases/download/v%v/werk-%v.apk
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
CurrentVersion: 0.4.4
CurrentVersionCode: 18
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/daochi-client.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/kryonlabs/kryon.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/kryonlabs/mingcute.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/LoupVaillant/Monocypher.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/oqs.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/qrcode.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/waozixyz/entity.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/ziranlang/ziran.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/open-quantum-safe/liboqs.git
-2
View File
@@ -1,2 +0,0 @@
RepoType: git
Repo: https://github.com/raysan5/raylib.git
+1 -1
View File
@@ -2,6 +2,6 @@
<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"/>
<glob pattern="*.zx"/>
</mime-type>
</mime-info>
+1 -1
View File
@@ -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.4.7" date="2026-10-28"/><release version="0.4.6" date="2026-10-27"/><release version="0.4.5" date="2026-10-26"/><release version="0.4.4" date="2026-10-23"/><release version="0.4.3" date="2026-10-23"/><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>
</component>
+35
View File
@@ -0,0 +1,35 @@
# Google Play testing
The public app is **Werkzeug**, package `xyz.waozi.pass`. Preserve the existing
release certificate. This package updates the existing Pass app
(`xyz.waozi.pass`) in place and keeps its private data. A separate
`xyz.waozi.werk` installation remains separate and untouched.
`make android-bundle` builds a release AAB for both ARM architectures, targeting
Android 16/API 36. Supply the existing `keystore.*` Gradle properties to sign it;
without them it is an unsigned build artifact. Never upload an unsigned bundle.
The manual Play bundle workflow signs with the repository's existing Android
release secrets and retains the candidate as an Actions artifact.
Use `listing.json` and the upstream Fastlane listing to create the app in Play
Console. Start with **Internal testing**, which supports up to 100 testers. The
owner must choose the tester email list or Google Group. Record the actual app
and opt-in URLs after creation. No public production rollout is configured.
Review the exact bundle and testing release before making it available to
testers. Internal testing can begin before the full production listing is
complete, and internal-only releases are exempt from the Data safety section.
Before closed/open testing or production, complete the store text, images,
privacy policy, account-deletion requirements, target audience, ads declaration,
content rating and Data safety answers. Accept Play terms only with owner
authorization. Tools work locally without an account; optional account/sync
connects to the chosen Daochi node. Do not declare that the app never connects
or that the node receives no identifiers. Biometric unlock stays on the device.
If Play App Signing is enabled, preserve the existing signing identity for
cross-store compatibility rather than silently generating a different app key.
An upload key and an app-signing key have different roles.
References: [create an app](https://support.google.com/googleplay/android-developer/answer/9859152),
[testing tracks](https://support.google.com/googleplay/android-developer/answer/9845334),
[target API](https://support.google.com/googleplay/android-developer/answer/11926878).
+14
View File
@@ -0,0 +1,14 @@
{
"packageName": "xyz.waozi.pass",
"title": "Werkzeug",
"defaultLanguage": "en-US",
"applicationType": "app",
"category": "TOOLS",
"price": "free",
"contactEmail": "[email protected]",
"website": "https://werk.waozi.xyz",
"privacyPolicy": "https://werk.waozi.xyz/privacy.html",
"initialTrack": "internal",
"storeMetadata": "fastlane/metadata/android",
"status": "prepared; Play Console creation, declarations and upload pending"
}
+8 -3
View File
@@ -8,6 +8,7 @@ import subprocess
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from android_apk_check import elf_section_names
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("bundle", type=Path)
@@ -22,7 +23,7 @@ subprocess.run(["java", "-jar", str(tool), "validate", "--bundle=" + str(bundle)
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("package") == "xyz.waozi.pass", "Werkzeug updates the existing Pass package"
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"
@@ -36,8 +37,11 @@ if not args.unsigned:
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}"
expected_bundles = {f"base/assets/apps/{app}.zx" for app in ("pass", "auth", "calculator", "clock", "workbook", "entity", "apps")}
actual_bundles = {name for name in archive.namelist() if name.startswith("base/assets/apps/") and not name.endswith("/")}
assert actual_bundles == expected_bundles, f"Stale or missing app bundles: {actual_bundles ^ expected_bundles}"
for name in expected_bundles:
assert archive.read(name)[:4] == b"ZX\0\0", f"Obsolete bundle format: {name}"
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")}
@@ -49,6 +53,7 @@ with zipfile.ZipFile(bundle) as archive:
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))
assert ".note.gnu.build-id" not in set(elf_section_names(library.read_bytes())), "Native library contains a build-path-dependent build ID"
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"
+24 -3
View File
@@ -21,6 +21,20 @@ def dex_classes(data):
yield data[offset:data.index(0, offset)].decode("ascii")
def elf_section_names(data):
assert data[:4] == b"\x7fELF" and data[5] == 1, "Expected a little-endian ELF library"
wide = data[4] == 2
assert data[4] in (1, 2), "Unsupported ELF class"
table = struct.unpack_from("<Q" if wide else "<I", data, 40 if wide else 32)[0]
size, count, strings_index = struct.unpack_from("<HHH", data, 58 if wide else 46)
strings_entry = table + strings_index * size
offset, length = struct.unpack_from("<QQ" if wide else "<II", data, strings_entry + (24 if wide else 16))
strings = data[offset:offset + length]
for index in range(count):
name = struct.unpack_from("<I", data, table + index * size)[0]
yield strings[name:strings.index(0, name)].decode("ascii")
def check_apk(path):
with ZipFile(path) as archive:
names = archive.namelist()
@@ -30,10 +44,17 @@ def check_apk(path):
assert all(re.fullmatch(r"Lxyz/waozi/pass/R(?:\$[^;]+)?;", item) for item in classes), f"{path}: packaged application bytecode: {classes}"
for font in ["ui.ttf", "emoji.ttf"]:
assert "assets/fonts/" + font in names, f"{path}: missing {font}"
for app in ["pass", "auth", "calculator", "clock"]:
assert f"assets/apps/{app}.zib" in names, f"{path}: missing the {app} app"
bundles = {f"assets/apps/{app}.zx" for app in ["apps", "entity", "pass", "auth", "calculator", "clock", "workbook"]}
packaged = {name for name in names if name.startswith("assets/apps/") and not name.endswith("/")}
assert packaged == bundles, f"{path}: stale or missing app bundles: {packaged ^ bundles}"
for name in bundles:
assert archive.read(name)[:4] == b"ZX\0\0", f"{path}: {name} has an obsolete bundle format"
assert "assets/pfp.png" in names, f"{path}: missing profile pictures"
assert any(name.endswith("/libmain.so") for name in names), f"{path}: no NativeActivity payload"
native = [name for name in names if name.endswith("/libmain.so")]
assert native, f"{path}: no NativeActivity payload"
for name in native:
assert ".note.gnu.build-id" not in set(elf_section_names(archive.read(name))), \
f"{path}: {name} contains a build-path-dependent build ID"
print(f"{path}: native Ziran app; only generated resource classes")
+2 -2
View File
@@ -16,7 +16,7 @@ for path, expected_abis in [(fdroid, {"armeabi-v7a", "arm64-v8a"}),
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[0] == "xyz.waozi.pass", "Werkzeug updates the existing Pass package"
assert current[2] == (root / "VERSION").read_text().strip(), "Channel added a version suffix"
if identity is None:
identity = current
@@ -31,5 +31,5 @@ for path, expected_abis in [(fdroid, {"armeabi-v7a", "arm64-v8a"}),
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"
assert (signature.returncode != 0) == (path == fdroid), "The source-comparison APK omits signing; debug APKs must be signed"
print("Android distribution: matching package/version, Werkzeug label/logo, correct ABIs, builder signing and no installer permissions")
+100 -47
View File
@@ -1,18 +1,19 @@
#!/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
import time
from android_apk_check import check_apk
from android_labels import label_position
root = Path(__file__).resolve().parents[1]
output = root / "build/android-input"
output.mkdir(parents=True, exist_ok=True)
serial = os.environ.get("WERK_ANDROID_EMULATOR")
if not serial and not os.environ.get("CI"):
raise SystemExit("Set WERK_ANDROID_EMULATOR to your own private test emulator")
if not serial:
devices = subprocess.check_output(["adb", "devices"], text=True).splitlines()
serial = next((line.split()[0] for line in devices if line.startswith("emulator-") and line.split()[-1] == "device"), None)
@@ -20,8 +21,8 @@ if not serial or not serial.startswith("emulator-"):
raise SystemExit("Android input tests require a private emulator")
package = "xyz.waozi.pass"
def adb(*arguments, check=True):
return subprocess.run(["adb", "-s", serial, *arguments], check=check, capture_output=True)
def adb(*arguments, check=True, input=None):
return subprocess.run(["adb", "-s", serial, *arguments], check=check, capture_output=True, input=input, timeout=90)
def shell(*arguments, check=True):
return adb("shell", *arguments, check=check).stdout.decode()
@@ -29,19 +30,34 @@ 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 find_label(word, timeout=15):
deadline = time.monotonic() + timeout
while True:
shot("label")
position = label_position(output / "label.png", word)
if position is not None:
return position
if time.monotonic() >= deadline:
raise AssertionError(f"Could not find {word!r} in the private emulator")
time.sleep(0.3)
def tap_label(word):
tap(*find_label(word))
def scroll_to_label(word, direction="down"):
hide_keyboard()
for attempt in range(7):
try:
return find_label(word, timeout=2)
except AssertionError:
if attempt == 6:
raise
upper = top + int(150 * zoom)
lower = bottom - int(80 * zoom)
start, end = (lower, upper) if direction == "down" else (upper, lower)
shell("input", "swipe", str(width // 2), str(start), str(width // 2), str(end), "450")
time.sleep(PAUSE)
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
@@ -81,25 +97,45 @@ def tap(x, y):
def type_text(text):
shell("input", "text", text.replace(" ", "%s")); time.sleep(PAUSE + 0.05)
def hide_keyboard():
if "mInputShown=true" in shell("dumpsys", "input_method"):
shell("input", "keyevent", "4")
for _ in range(20):
time.sleep(0.15)
if "mInputShown=true" not in shell("dumpsys", "input_method"):
return
raise AssertionError("Soft keyboard did not close")
def fill_field(label, text):
hide_keyboard()
_, y = find_label(label)
tap(int(90 * zoom), y + int(40 * zoom))
type_text(text)
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)
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)
bottom = int(navigation.group(1)) if navigation and int(navigation.group(2)) == height else height
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 round(24 * zoom), int(cutout.group(1)) if cutout else 0)
bottom = int(navigation.group(1)) if navigation and int(navigation.group(2)) == height else height - round(24 * zoom)
return top, bottom
apk = root / "build/werk-android-emulator.apk"
apk = Path(os.environ.get("WERK_ANDROID_APK", root / "build/werk-android-emulator.apk"))
check_apk(apk)
try:
adb("install", "-r", str(apk))
# This is the test emulator and only this package's fixture data is cleared.
shell("pm", "clear", package)
shell("run-as", package, "mkdir", "-p", "files/profile")
adb("shell", f"run-as {package} sh -c 'umask 077; cat > files/profile/settings.txt'",
input=b"name=Fixture Person\ntheme_mode=1\n")
shell("am", "start", "-n", package + "/android.app.NativeActivity")
time.sleep(2); alive(); dismiss_other_apps_not_responding(); shot("launch")
size = shell("wm", "size").strip().split()[-1]
@@ -108,23 +144,27 @@ try:
densities = re.findall(r"density: (\d+)", shell("wm", "density"))
zoom = int(densities[-1]) / 160
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")
# The shared Apps screen can change layout; select the visible tool.
tap_label("Pass"); time.sleep(0.5); alive(); shot("pass")
runtime_modes = shell("run-as", package, "stat", "-c", "%a", "files/cache", "files/cache/ziran-native").split()
assert runtime_modes == ["700", "700"], f"Native runtime cache is not private: {runtime_modes}"
find_label("Site")
bar = 56
tap(int(90 * zoom), top + int((55 + bar) * zoom)); type_text("example.com")
fill_field("Site", "example.com")
assert "mInputShown=true" in shell("dumpsys", "input_method"), "Soft keyboard did not open"
tap(int(90 * zoom), top + int((130 + bar) * zoom)); type_text("alice")
tap(int(90 * zoom), top + int((205 + bar) * zoom)); type_text("test master")
fill_field("Login", "alice")
fill_field("Master", "test master")
shot("keyboard")
shell("input", "keyevent", "4"); time.sleep(0.4); alive()
hide_keyboard(); alive()
tap(width // 2, bottom - int(35 * zoom))
tap(int(90 * zoom), top + int((55 + bar) * zoom)); type_text("Android test")
fill_field("Profile", "Android test")
shell("input", "keyevent", "4"); time.sleep(0.3)
tap(int(100 * zoom), top + int((105 + bar) * zoom))
expected = "Android test\texample.com\talice\t16\t1\t1\t1\t1\t1\t\n"
saved = shell("run-as", package, "cat", "files/apps/pass/profiles.tsv")
assert saved == expected, f"Profile input/persistence mismatch: {saved!r}"
assert "test master" not in saved
print("Android: keyboard input and first saved profile verified", flush=True)
# 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.
@@ -134,8 +174,8 @@ try:
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)
shell("input", "keyevent", *["67" for _ in "Android test"])
time.sleep(0.5)
dismiss_other_apps_not_responding()
# Type the reference password as the new name. Pasting the copy works
# through the keyboard's clipboard suggestion, which Gboard offers only
@@ -153,27 +193,36 @@ try:
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")
# Profile's name is one of Werkzeug's own fields. Each letter must land
# 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")
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()
print("Android: second profile, restart and private permissions verified", flush=True)
# The shared Profile retains existing names and edits appearance.
tap_label("Fixture"); time.sleep(0.8); 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")
assert "name=Fixture Person\n" in settings, "Profile lost the retained name"
tap(*scroll_to_label("Dark")); time.sleep(0.5)
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
assert "theme_mode=2\n" in settings and "name=Fixture Person\n" in settings
shot("profile-appearance")
print("Android: retained profile name and appearance verified", flush=True)
tap(*scroll_to_label("Light"))
# The shared Profile manages nodes on its own page.
hide_keyboard()
tap(*scroll_to_label("Nodes", direction="up"))
tap_label("Add")
node_input = find_label("address")
tap(*node_input)
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)
hide_keyboard()
# The Add action sits below the visible address field. Its white text
# and the page heading are unreliable OCR targets on small displays.
tap(width // 2, node_input[1] + int(64 * zoom))
settings = shell("run-as", package, "cat", "files/profile/settings.txt")
assert "https://sync.example.invalid:8443" in settings, "Custom node was not added"
# The new node is the last row above Add node; its detail page puts
# Make default below the connection status. Check the saved result.
_, add_node_y = scroll_to_label("Add")
tap(width // 2, add_node_y - int(64 * zoom))
_, status_y = find_label("connected")
tap(width // 2, status_y + int(64 * zoom))
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
@@ -190,4 +239,8 @@ try:
print("Werkzeug Android: input, profiles, custom node and in-place package update preserved private data")
except BaseException:
shot("failure")
# These tags report asset loading and native startup without recording the
# test's typed credentials. The emulator and its profile are disposable.
logs = adb("logcat", "-d", "-s", "raylib:I", "Werkzeug:I", check=False)
(output / "startup-logcat.txt").write_bytes(logs.stdout)
raise
+31
View File
@@ -0,0 +1,31 @@
"""Locate visible labels in screenshots from the private Android emulator."""
import csv
import io
import subprocess
from PIL import Image
def label_position(path, word):
def normalized(value):
return "".join(character for character in value.casefold() if character.isalnum())
for scale in (1, 3):
screenshot = path
if scale == 3:
# Tesseract misses white labels on small, dark theme buttons.
# Separate those glyphs from the background before enlarging.
with Image.open(path) as source:
contrast = source.convert("L").point(lambda value: 0 if value > 160 else 255)
contrast = contrast.resize((source.width * scale, source.height * scale),
Image.Resampling.BICUBIC)
screenshot = path.with_name(path.stem + "-contrast.png")
contrast.save(screenshot)
data = subprocess.check_output(
["tesseract", str(screenshot), "stdout", "--psm", "11", "-c", "tessedit_create_tsv=1"],
stderr=subprocess.DEVNULL, text=True)
for item in csv.DictReader(io.StringIO(data), delimiter="\t"):
if normalized(item["text"]) == normalized(word):
return ((int(item["left"]) + int(item["width"]) // 2) // scale,
(int(item["top"]) + int(item["height"]) // 2) // scale)
return None
+13 -10
View File
@@ -8,16 +8,19 @@ cd "$root"
ziran_root=$("$ziran" pkg path ziran)
kryon=$("$ziran" pkg path kryon)
mingcute=$("$ziran" pkg path mingcute)
# Auth runs its own tests from its package, with the hashes from crypto.
auth=$("$ziran" pkg path auth)
crypto=$("$ziran" pkg path crypto)
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 "$auth" --module-path "$auth/src" --module-path "crypto=$crypto/src" --module-path "$ziran_root/std" \
--entry totp_test:Run -o build/app-logic-test/totp.zx "$auth/tests/totp_test.zi"
test "$("$ziran" run build/app-logic-test/totp.zx)" = 0
"$ziran" bundle --root "$auth" --module-path "$auth/src" --module-path "crypto=$crypto/src" --module-path "$ziran_root/std" \
--entry exports_test:Run -o build/app-logic-test/exports.zx "$auth/tests/exports_test.zi"
test "$("$ziran" run build/app-logic-test/exports.zx)" = 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
--entry arithmetic_test:Run -o build/app-logic-test/arithmetic.zx apps/calculator/arithmetic_test.zi
test "$("$ziran" run build/app-logic-test/arithmetic.zx)" = 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" \
@@ -25,8 +28,8 @@ set -- --root tests --module-path apps/calculator \
"$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
-o build/app-logic-test/input.zx tests/calculator_input_test.zi
test "$("$ziran" run build/app-logic-test/input.zx)" = 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 \
+21 -7
View File
@@ -5,6 +5,7 @@ import hashlib
import io
import json
import os
import re
from pathlib import Path
import shutil
import subprocess
@@ -19,7 +20,7 @@ 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
assert hashlib.sha256((assets / "apps/apps.zx").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"),
@@ -79,6 +80,18 @@ def type_text(value):
time.sleep(.3)
def expect_title(expected):
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
assert app.poll() is None, "Werkzeug exited during navigation"
title = command("xdotool", "getwindowname", window).strip()
if title == expected:
return
time.sleep(.1)
capture("navigation-failure")
raise AssertionError(f"Expected window title {expected!r}, got {title!r}")
app = subprocess.Popen([str(binary)], env=environment)
try:
deadline = time.monotonic() + 30
@@ -86,7 +99,7 @@ try:
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)
env=environment, capture_output=True, text=True, timeout=5)
if found.returncode == 0:
window = found.stdout.splitlines()[0]
break
@@ -97,17 +110,17 @@ try:
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:
if all(name in home for name in ("Pass", "Auth", "Calculator", "Clock", "Workbook")):
break
assert app.poll() is None, "Werkzeug exited while loading Apps"
assert time.monotonic() < deadline, "Shared Apps controller did not render: " + home
assert not re.search(r"\d[\d.]*\s*(?:kB|MB)\b", home, re.I), home
for name in ("Auth", "Calculator", "Clock", "Workbook", "Pass"):
click_word(name)
assert command("xdotool", "getwindowname", window).strip() == name
expect_title(name)
assert "stopped" not in capture(name.lower()).lower(), name + " failed to run"
click(28, 28)
assert command("xdotool", "getwindowname", window).strip() == "Werkzeug"
expect_title("Werkzeug")
for width, height in ((360, 640), (720, 520)):
command("xdotool", "windowsize", "--sync", window, str(width), str(height))
text = capture(f"home-{width}")
@@ -119,6 +132,7 @@ try:
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
assert not re.search(r"\d[\d.]*\s*(?:kB|MB)\b", text, re.I), text
click(100, 92)
type_text("clock")
text = capture("search")
@@ -154,7 +168,7 @@ try:
deadline = time.monotonic() + 30
while True:
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)],
env=environment, capture_output=True, text=True)
env=environment, capture_output=True, text=True, timeout=5)
if found.returncode == 0:
window = found.stdout.splitlines()[0]
if "Timepiece" in capture("restarted"):
+2 -3
View File
@@ -11,15 +11,14 @@ def render(size, background=None):
return image
outputs = {'assets/app/icon.png':512, 'fastlane/metadata/android/en-US/images/icon.png':512,
'web/site/icons/favicon-32.png':32, 'web/site/icons/apple-touch-icon.png':180,
'web/site/icons/icon-192.png':192, 'web/site/icons/icon-512.png':512,
'web/site/app/icons/icon-192.png':192, 'web/site/app/icons/icon-512.png':512}
'web/site/icons/icon-192.png':192, 'web/site/icons/icon-512.png':512}
for density, size in [('mdpi',48),('hdpi',72),('xhdpi',96),('xxhdpi',144),('xxxhdpi',192)]:
outputs[f'droid/app/src/main/res/mipmap-{density}/ic_launcher.png'] = size
for path, size in outputs.items():
render(size, '#ffffff' if 'launcher' in path or '/icons/' in path else None).save(ROOT / path)
font_path = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'
name = 'Werkzeug'
for path, size in [('assets/app/readme-banner.png',(1536,512)), ('assets/app/readme-square-630x500.png',(630,500)), ('showcase/banner.png',(1536,1024)), ('web/site/images/social.png',(1536,1024))]:
for path, size in [('assets/app/readme-banner.png',(1536,512)), ('assets/app/readme-square-630x500.png',(630,500)), ('showcase/banner.png',(1536,1024))]:
w,h=size; image=Image.new('RGB',size,'#f7f3ff'); d=ImageDraw.Draw(image)
icon_size=int(min(w*.24,h*.55))
while True: # shrink the mark until the name fits with a margin
+25 -8
View File
@@ -1,6 +1,7 @@
#!/bin/sh
# Renders Werkzeug's home screen in light and dark on private Xvfb displays,
# with disposable profiles, never the user's saved data.
# Renders Werkzeug's home screen in light and dark, and its --mini tool tiles,
# on private Xvfb displays with disposable profiles, never the user's saved
# data.
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
@@ -8,7 +9,7 @@ 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"
printf 'obsolete bundle\n' > "$work/home/.local/lib/werk/apps/$app.zx"
done
for mode in light dark; do
mkdir -p "$work/$mode/data/profile" "$work/$mode/cache"
@@ -22,22 +23,38 @@ for mode in light dark; do
KRYON_CAPTURE_PATH="$work/werk-$mode.png" "$root/build/werk"
test -s "$work/werk-$mode.png"
done
python3 scripts/private-display.py \
env -u WERK_ASSETS HOME="$work/home" WERK_DATA="$work/light/data" XDG_CACHE_HOME="$work/light/cache" \
KRYON_CAPTURE_PATH="$work/werk-mini.png" "$root/build/werk" --mini
test -s "$work/werk-mini.png"
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")
for name in ("light", "mini"):
with Image.open(work / f"werk-{name}.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 / f"labels-{name}.png")
PY
rendered=$(tesseract "$work/labels.png" stdout --psm 11 2>/dev/null)
rendered=$(tesseract "$work/labels-light.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
# Mini mode is the tool tiles alone, without Profile, search or title.
rendered=$(tesseract "$work/labels-mini.png" stdout --psm 11 2>/dev/null)
for app in Pass Auth Calculator Clock; do
printf '%s\n' "$rendered" | grep -q "$app" || { echo "Missing mini tile: $app" >&2; exit 1; }
done
for hidden in Profile Find Werkzeug; do
if printf '%s\n' "$rendered" | grep -qi "$hidden"; then
echo "Werkzeug --mini shows $hidden" >&2
exit 1
fi
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
fi
echo 'Werkzeug desktop: light and dark home screens rendered on private Xvfb displays'
echo 'Werkzeug desktop: light and dark home screens and --mini tool tiles rendered on private Xvfb displays'
+7
View File
@@ -29,6 +29,13 @@ for source in sorted((root / "packaging/linux").glob("xyz.waozi.werk*.desktop"))
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"))
# Local launchers resolve their installed icon directly, including
# custom data directories and paths containing spaces.
for line in content.splitlines():
if line.startswith("Icon="):
name = line.removeprefix("Icon=")
icon = args.data_dir / "icons/hicolor/512x512/apps" / (name + ".png")
content = content.replace(line, "Icon=" + str(icon.resolve()))
for target in destinations:
if args.uninstall:
target.unlink(missing_ok=True)
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
manager=${ANDROID_SDK_MANAGER:-"${ANDROID_HOME:?ANDROID_HOME is required}/cmdline-tools/latest/bin/sdkmanager"}
delay=${ANDROID_SDK_RETRY_DELAY:-10}
accept_licenses() {
# yes can receive SIGPIPE after sdkmanager exits successfully.
yes | "$manager" --licenses >/dev/null || test "${PIPESTATUS[1]}" -eq 0
}
retry() {
local attempt
for attempt in 1 2 3; do
if "$@"; then
return 0
fi
if [ "$attempt" -lt 3 ]; then
echo "Android SDK installer failed; retrying ($attempt/3)" >&2
sleep "$delay"
fi
done
echo "::error::Android SDK installation failed after three attempts" >&2
return 1
}
retry accept_licenses
retry "$manager" 'platforms;android-36' 'build-tools;34.0.0' \
'ndk;28.2.13676358' 'cmake;3.22.1' "$@"
+62
View File
@@ -0,0 +1,62 @@
"""Exercise installer retry and failure propagation without network or an SDK."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class AndroidSdkInstallerTest(unittest.TestCase):
def install(self, failures):
temporary = tempfile.TemporaryDirectory(prefix="werk-sdk-installer-")
self.addCleanup(temporary.cleanup)
directory = Path(temporary.name)
manager = directory / "sdkmanager"
manager.write_text("""#!/usr/bin/env python3
import json, os, sys
from pathlib import Path
root = Path(__file__).parent
if sys.argv[1:] == ['--licenses']:
raise SystemExit(0)
log = root / 'calls.json'
calls = json.loads(log.read_text()) if log.exists() else []
calls.append(sys.argv[1:])
log.write_text(json.dumps(calls))
raise SystemExit(1 if len(calls) <= int(os.environ['SDK_TEST_FAILURES']) else 0)
""")
manager.chmod(0o700)
environment = os.environ | {"ANDROID_SDK_MANAGER": str(manager),
"ANDROID_SDK_RETRY_DELAY": "0",
"SDK_TEST_FAILURES": str(failures)}
result = subprocess.run(["bash", str(ROOT / "scripts/install_android_sdk.sh"),
"platforms;android-30"], env=environment,
capture_output=True, text=True, timeout=10)
calls = json.loads((directory / "calls.json").read_text())
return result, calls
def test_success_does_not_repeat_installation(self):
result, calls = self.install(0)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0], ["platforms;android-36", "build-tools;34.0.0",
"ndk;28.2.13676358", "cmake;3.22.1", "platforms;android-30"])
def test_transient_download_failure_recovers(self):
result, calls = self.install(2)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(len(calls), 3)
self.assertEqual(calls[0], calls[1])
self.assertEqual(calls[1], calls[2])
def test_permanent_failure_stops_the_job(self):
result, calls = self.install(3)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(len(calls), 3)
self.assertIn("failed after three attempts", result.stderr)
if __name__ == "__main__":
unittest.main()
+4 -1
View File
@@ -44,7 +44,10 @@ for tool, name in (("", "Werkzeug"), ("pass", "Pass"), ("auth", "Auth"),
config.read(entry)
values = config["Desktop Entry"]
assert values["Name"] == name
assert (share / "icons/hicolor/512x512/apps" / (values["Icon"] + ".png")).is_file()
icon = Path(values["Icon"])
if not icon.is_absolute():
icon = share / "icons/hicolor/512x512/apps" / (values["Icon"] + ".png")
assert icon.is_file()
argv = shlex.split(values["Exec"])
if not tool:
argv = argv[:1]
+1 -1
View File
@@ -14,7 +14,7 @@ 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"/apps/*.zx "$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"
+1 -1
View File
@@ -13,7 +13,7 @@ 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"/apps/*.zx "$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"
+4 -3
View File
@@ -7,7 +7,8 @@ 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"
crypto=$("$ziran" pkg path crypto)
args="--root tests --module-path apps/pass --module-path crypto=$crypto/src --module-path kryon=$kryon/src/backend --module-path kryon=$kryon/src/ui --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
@@ -18,6 +19,6 @@ for name in ReadStoreHost WriteStoreHost ClipboardCopyHost SecureAvailableHost S
binds="$binds --bind app_context:$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
test "$("$ziran" run build/pass-state-test/portable.zib)" = 42
-o build/pass-state-test/portable.zx tests/pass_state_test.zi tests/pass_state_host.zi
test "$("$ziran" run build/pass-state-test/portable.zx)" = 42
echo 'Pass state: native and portable tests pass'
+1 -1
View File
@@ -14,7 +14,7 @@ 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"],
server = subprocess.Popen(["Xvfb", "-noreset", "-displayfd", str(write_fd), "-screen", "0", "1280x1024x24", "-nolisten", "tcp"],
pass_fds=(write_fd,), env=environment)
os.close(write_fd)
try:
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Keep generated runtime objects tied to one toolchain checkout."""
from pathlib import Path
import shutil
import subprocess
import sys
def prepare(source, output):
root = Path(__file__).resolve().parents[1]
source = Path(source).resolve()
output = Path(output).resolve()
if (not output.is_relative_to(root) or output.name not in {"ziran", "web-runtime", "bundle-runtime"}
or not any(output.is_relative_to(root / parent) for parent in ("build", "droid/app/.cxx", "droid/app/build"))):
raise ValueError("Runtime cache must be an owned build intermediate")
revision = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip()
identity = str(source) + "\n" + revision + "\n"
marker = output / ".toolchain"
if marker.is_file() and marker.read_text() == identity:
return
if output.exists():
shutil.rmtree(output)
output.mkdir(parents=True)
marker.write_text(identity)
if __name__ == "__main__":
prepare(*sys.argv[1:])
+33
View File
@@ -0,0 +1,33 @@
"""A changed compiler checkout must never reuse the old parser's objects."""
from pathlib import Path
import shutil
from runtime_cache import prepare
root = Path(__file__).resolve().parents[1]
fixture = root / "build/runtime-cache-test"
shutil.rmtree(fixture, ignore_errors=True)
fixture.mkdir(parents=True)
outside = fixture / "keep-output"
outside.write_text("owner output")
cache = fixture / "ziran"
try:
prepare(root, cache)
marker = cache / ".toolchain"
original_time = marker.stat().st_mtime_ns
object_file = cache / "parser.o"
object_file.write_text("compiled parser")
prepare(root, cache)
assert object_file.exists() and marker.stat().st_mtime_ns == original_time
marker.write_text("another toolchain checkout\n")
prepare(root, cache)
assert not object_file.exists(), "An incompatible parser object survived"
assert outside.read_text() == "owner output"
try:
prepare(root, root / "build")
except ValueError:
pass
else:
raise AssertionError("The whole build directory must never be cleared")
print("Runtime cache: reuse, toolchain invalidation and output preservation passed")
finally:
shutil.rmtree(fixture)
+1 -1
View File
@@ -12,7 +12,7 @@ for name in tracked:
path = Path(name)
if path.suffix in {".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".kry", ".java", ".kt", ".go", ".rs", ".swift", ".m", ".mm", ".zig"}:
bad.append(name)
if name.startswith("web/site/app/") and path.suffix == ".js":
if name.startswith("web/site/") and path.suffix == ".js":
bad.append(name)
if bad:
raise SystemExit("Non-Ziran app implementation:\n" + "\n".join(bad))
+146 -30
View File
@@ -1,20 +1,29 @@
// 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.
// ?app=, Calculator typing, Clock, and every tool in embedded mini mode, also
// inside an iframe the size of the waozi.xyz app card.
import {spawn, spawnSync} 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';
import {setTimeout as delay} from 'node:timers/promises';
const root = resolve('build/site');
const root = resolve(process.env.WERK_WEB_SITE || 'build/site');
const output = resolve('build/web-test');
await mkdir(output, {recursive: true});
const profile = await mkdtemp(join(output, 'profile-'));
const types = {'.js': 'application/javascript', '.wasm': 'application/wasm', '.html': 'text/html',
'.webmanifest': 'application/manifest+json', '.json': 'application/json', '.png': 'image/png'};
// The waozi.xyz app card embeds the mini app in a 480 px high frame.
const embed = `<!doctype html><meta charset="utf-8"><style>body{margin:0}iframe{display:block;margin:16px;border:0}</style>
<iframe id="mini" src="/?mini&theme=waozi" width="388" height="480"></iframe>`;
const server = createServer(async (request, response) => {
const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
if (pathname === '/embed.html') {
response.setHeader('Content-Type', 'text/html');
response.end(embed);
return;
}
const file = join(root, pathname.endsWith('/') ? pathname + 'index.html' : pathname);
if (!file.startsWith(root + '/')) {
response.writeHead(403).end();
@@ -29,9 +38,10 @@ const server = createServer(async (request, response) => {
}
});
await new Promise(done => server.listen(0, '127.0.0.1', done));
const base = `http://127.0.0.1:${server.address().port}/app/`;
const base = `http://127.0.0.1:${server.address().port}/`;
const environment = {...process.env};
for (const key of ['DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS']) delete environment[key];
environment.YUE_DESKTOP_RECOVERY = '0';
const browser = spawn(process.env.WERK_WEB_BROWSER || 'chromium', ['--headless=new', '--no-sandbox',
'--disable-gpu', '--disable-dev-shm-usage', '--no-first-run', '--remote-debugging-port=0',
'--user-data-dir=' + profile, '--window-size=420,760', 'about:blank'],
@@ -67,8 +77,18 @@ try {
let sequence = 0;
const pending = new Map();
const exceptions = [];
let sharedProfileUrl = '';
let fileChooserNode = 0;
socket.addEventListener('message', event => {
const message = JSON.parse(event.data);
if (message.method === 'Page.fileChooserOpened') fileChooserNode = message.params.backendNodeId;
if (message.method === 'Fetch.requestPaused') {
if (message.params.resourceType === 'Document') sharedProfileUrl = message.params.request.url;
command('Fetch.fulfillRequest', {requestId: message.params.requestId, responseCode: 200,
responseHeaders: [{name:'Content-Type',value:'text/html'}],
body: Buffer.from('<!doctype html><title>Shared profile fixture</title>').toString('base64')}).catch(() => {});
return;
}
if (message.method === 'Runtime.exceptionThrown') exceptions.push(JSON.stringify(message.params.exceptionDetails));
if (message.method === 'Runtime.consoleAPICalled') diagnostics += JSON.stringify(message.params.args);
if (pending.has(message.id)) {
@@ -93,25 +113,40 @@ 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) => {
// The screenshot's text, read as captured and again with its labels
// enlarged in black and white.
const screenText = async name => {
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}`);
let text = result.stdout;
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);
return (text + '\n' + result.stdout).toLowerCase();
};
const expectText = async (name, expected) => {
const text = await screenText(name);
if (!text.includes(expected.toLowerCase())) throw Error(`${name}: expected ${expected}, saw ${text}`);
};
// Mini Home shows the tool tiles: no Profile, search or title bar.
const expectMiniHome = async name => {
const text = await screenText(name);
for (const tool of ['Pass', 'Auth', 'Calculator', 'Clock', 'Workbook'])
if (!text.includes(tool.toLowerCase())) throw Error(`${name}: missing the ${tool} tile, saw ${text}`);
for (const hidden of ['Profile', 'Find an app', 'Werkzeug'])
if (text.includes(hidden.toLowerCase())) throw Error(`${name}: mini Home shows ${hidden}: ${text}`);
};
const click = async (x, y) => {
await command('Input.dispatchMouseEvent', {type: 'mouseMoved', x, y});
await command('Input.dispatchMouseEvent', {type: 'mousePressed', x, y, button: 'left', clickCount: 1});
// Let the canvas observe the press before releasing, as a real click does.
await delay(80);
await command('Input.dispatchMouseEvent', {type: 'mouseReleased', x, y, button: 'left', clickCount: 1});
await delay(350);
};
@@ -125,7 +160,8 @@ try {
'-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);
const word = value => value.replace(/[^\p{L}\p{N}]/gu, '').toLowerCase();
const row = rows.find(values => word(values[11] || '') === word(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);
@@ -139,12 +175,12 @@ try {
if (pixels[i] !== pixels[0] || pixels[i + 1] !== pixels[1] || pixels[i + 2] !== pixels[2]) return true;
return false;
})()`;
const open = async (query, name) => {
await command('Page.navigate', {url: base + query});
const open = async (query, name, page = base + query, frame = 'document') => {
await command('Page.navigate', {url: page});
const until = Date.now() + 40000;
while (Date.now() < until) {
try {
if (await evaluate(painted)) {
if (await evaluate(`(document => ${painted})(${frame})`)) {
await delay(500);
await screenshot(name);
return;
@@ -183,36 +219,116 @@ try {
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');
// The full app keeps its Profile button.
await expectText('home-returned', 'Profile');
await command('Fetch.enable', {patterns:[{urlPattern:'https://entity.waozi.xyz/*'}]});
await clickText('Profile');
for (let end=Date.now()+10000; !sharedProfileUrl && Date.now()<end;) await delay(100);
if (sharedProfileUrl !== 'https://entity.waozi.xyz/' ||
await evaluate('location.href') !== 'https://entity.waozi.xyz/') {
await screenshot('shared-profile-failure');
throw Error('Profile did not open the shared profile manager: ' + JSON.stringify({
requested: sharedProfileUrl, url: await evaluate('location.href'), exceptions, diagnostics: diagnostics.slice(-1000)
}));
}
await command('Fetch.disable');
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.
// Workbook calculates in the browser and commits its private document to
// IndexedDB. Reloading must retain both the cells and their formulas.
await open('?app=workbook', 'workbook');
await expectText('workbook-open', 'Workbook');
const enter = async () => {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Enter', code:'Enter', windowsVirtualKeyCode:13});
await command('Input.dispatchKeyEvent', {type:'keyUp', key:'Enter', code:'Enter', windowsVirtualKeyCode:13});
await delay(350);
};
await click(88,177); await type('12'); await enter();
await click(184,177); await type('=A1*2'); await enter();
const workbookDocument = () => evaluate(`Module.FS.readFile('/pass-data/apps/workbook/documents/workbook.gnumeric', {encoding:'utf8'})`);
const expectWorkbookCell = async (name, expected) => {
await screenshot(name);
const cell = join(output, name + '-cell.png');
const crop = spawnSync('convert', [join(output, name + '.png'), '-crop', '92x18+138+168',
'+repage', '-resize', '600%', '-bordercolor', 'white', '-border', '24', cell],
{env:environment, encoding:'utf8'});
if (crop.status !== 0) throw Error('Could not crop the Workbook result cell: ' + crop.stderr);
const text = spawnSync('tesseract', [cell, 'stdout', '--psm', '7', '-c', 'tessedit_char_whitelist=0123456789'], {env:environment, encoding:'utf8'});
if (text.status !== 0 || !text.stdout.includes(expected))
throw Error(`${name}: expected cell B1 to display ${expected}, saw ${text.stdout}`);
};
let workbook = await workbookDocument();
if (!workbook.includes('>12</gnm:Cell>') || !workbook.includes('>=A1*2</gnm:Cell>'))
throw Error('Workbook did not save the entered cells: ' + workbook);
await expectWorkbookCell('workbook-calculated', '24');
await open('?app=workbook', 'workbook-reopened');
workbook = await workbookDocument();
if (!workbook.includes('>=A1*2</gnm:Cell>')) throw Error('Workbook was not persisted across reload');
await expectWorkbookCell('workbook-reopened-value', '24');
const downloads = join(output, 'downloads');
await mkdir(downloads, {recursive:true});
await command('Browser.setDownloadBehavior', {behavior:'allow', downloadPath:downloads});
await click(28,68); await clickText('As');
let exported = '';
for (let end=Date.now()+15000; Date.now()<end;) {
try { exported = await readFile(join(downloads, 'workbook.gnumeric'), 'utf8'); break; } catch {}
await delay(100);
}
if (exported !== workbook) {
await screenshot('workbook-export-failure');
throw Error('Workbook download differs from the saved document: downloaded ' + exported.length + ' bytes, expected ' + workbook.length);
}
const fixture = join(output, 'incoming.gnumeric');
await writeFile(fixture, '<?xml version="1.0"?><gnm:Workbook xmlns:gnm="http://www.gnumeric.org/v10.dtd"><gnm:Sheets><gnm:Sheet><gnm:Name>Imported</gnm:Name><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>');
await command('Page.setInterceptFileChooserDialog', {enabled:true});
await click(28,68); await clickText('Open');
for (let end=Date.now()+10000; !fileChooserNode;) {
if (Date.now()>end) {
await screenshot('workbook-import-failure');
throw Error('Workbook did not open the browser file chooser');
}
await delay(100);
}
await command('DOM.setFileInputFiles', {backendNodeId:fileChooserNode, files:[fixture]});
await command('Page.setInterceptFileChooserDialog', {enabled:false});
for (let end=Date.now()+15000; !(await workbookDocument()).includes('>=A1*3</gnm:Cell>');) {
if (Date.now()>end) throw Error('Workbook did not import and save the selected document');
await delay(100);
}
await expectWorkbookCell('workbook-imported', '33');
// The embedded mini version opens on the tool tiles; a tool shows its own
// name as the title, and Back returns to the tiles.
await open('?mini', 'mini-home');
await expectText('mini-home', 'Werkzeug');
for (const app of ['pass', 'auth', 'calculator', 'clock']) {
await expectMiniHome('mini-home');
for (const app of ['pass', 'auth', 'calculator', 'clock', 'workbook']) {
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 expectMiniHome(app + '-mini-home');
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 expectMiniHome('mini-narrow-home');
await clickText('Clock');
await expectText('mini-narrow-clock', 'Clock');
await click(28, 28);
await click(250, 28);
await expectText('mini-narrow-profile', 'Profile');
await expectMiniHome('mini-narrow-returned');
// Inside the card's iframe, a tile opens its tool and Back returns.
await command('Emulation.setDeviceMetricsOverride', {width: 420, height: 520, deviceScaleFactor: 1, mobile: false});
await open('', 'card-home', base + 'embed.html', "document.getElementById('mini').contentDocument");
await expectMiniHome('card-home');
await clickText('Calculator');
await expectText('card-calculator', 'Calculator');
await click(16 + 28, 16 + 28);
await expectMiniHome('card-returned');
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: Workbook editing, calculation, import/export and persistence; Calculator, Home, shared Entity profile and five-tool mini mode verified in private Chromium');
} finally {
socket?.close();
try {
+14 -5
View File
@@ -50,7 +50,7 @@ window = None
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).
# a counter-based account (see tests/exports_test.zi in the auth package).
MIGRATION_LINK = ("otpauth-migration://offline?data=CjoKFDEyMzQ1Njc4OTAxMjM0NTY3ODkwEhxFeGFtcGxlIENvOmFsaWNl"
"QGV4YW1wbGUuY29tIAEoATACCjUKIDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyEgNib2IaBlNlY29uZCAC"
"KAIwAgorChQxMjM0NTY3ODkwMTIzNDU2Nzg5MBIHY291bnRlchoESG90cCABKAEwARABGAEgACi5YA%3D%3D")
@@ -71,8 +71,17 @@ def start():
if found.returncode == 0:
window = found.stdout.splitlines()[0]
command("xdotool", "windowfocus", "--sync", window)
time.sleep(0.5)
return
ready = time.monotonic() + 20
while time.monotonic() < ready:
assert app.poll() is None, "Werkzeug exited while loading its tools"
capture("startup")
with Image.open(output / "startup.png") as source:
labels = source.convert("L").point(lambda value: 0 if value < 140 else 255)
labels.resize((source.width * 3, source.height * 3)).save(output / "startup-labels.png")
text = command("tesseract", str(output / "startup-labels.png"), "stdout", "--psm", "11")
if all(name in text for name in ("Pass", "Auth", "Calculator", "Clock")):
return
raise AssertionError("Werkzeug did not finish drawing its home screen")
time.sleep(0.1)
raise AssertionError("Werkzeug did not show its window")
@@ -417,8 +426,8 @@ try:
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)
# Use the visible account-management action after a restart.
click_scrolled("Manage", exact_case=True)
capture("sync-paused-restarted")
previous_account = account_file.read_text()
scroll_down()
+183
View File
@@ -0,0 +1,183 @@
"""Workbook editing and document transfers on an explicitly owned emulator."""
from pathlib import Path
import os
import re
import shlex
import subprocess
import time
import xml.etree.ElementTree as ET
from android_labels import label_position
from android_apk_check import check_apk
root = Path(__file__).resolve().parents[1]
output = root / "build/workbook-android-test"
output.mkdir(parents=True, exist_ok=True)
serial = os.environ.get("WERK_ANDROID_EMULATOR", "")
if not serial and os.environ.get("CI"):
devices = subprocess.check_output(["adb", "devices"], text=True).splitlines()
serial = next((line.split()[0] for line in devices if line.startswith("emulator-") and line.split()[-1] == "device"), "")
assert serial.startswith("emulator-"), "Set WERK_ANDROID_EMULATOR to the private test emulator"
package = "xyz.waozi.pass"
apk = Path(os.environ.get("WERK_ANDROID_APK", root / "build/werk-android-emulator.apk"))
check_apk(apk)
def adb(*args, check=True):
return subprocess.run(["adb", "-s", serial, *map(str, args)], check=check, capture_output=True, timeout=90)
def shell(*args, check=True):
return adb("shell", *args, check=check).stdout.decode()
def shot(name):
path = output / (name + ".png")
path.write_bytes(adb("exec-out", "screencap", "-p").stdout)
return path
def tap(x, y):
shell("input", "tap", round(x), round(y))
time.sleep(.25)
def label(word):
until = time.monotonic() + 20
while time.monotonic() < until:
point = label_position(shot("label"), word)
if point:
tap(*point)
return
time.sleep(.2)
raise AssertionError("Missing Workbook control: " + word)
def native_label(word):
until = time.monotonic() + 20
while time.monotonic() < until:
path = "/data/local/tmp/werk-window.xml"
shell("rm", "-f", path, check=False)
shell("uiautomator", "dump", "--compressed", path, check=False)
data = shell("cat", path, check=False)
try:
nodes = ET.fromstring(data).iter("node")
except ET.ParseError:
nodes = []
for node in nodes:
if node.get("text", "").casefold() == word.casefold():
bounds = list(map(int, re.findall(r"\d+", node.get("bounds", ""))))
if len(bounds) == 4:
tap((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2)
return
point = label_position(shot("system-control"), word)
if point:
tap(*point)
return
time.sleep(.2)
raise AssertionError("Missing system document control: " + word)
def document():
return shell("run-as", package, "cat", "files/apps/workbook/documents/workbook.gnumeric", check=False)
def expect(value, col=0):
until = time.monotonic() + 20
while time.monotonic() < until:
try:
doc = ET.fromstring(document())
cells = doc.iter("{http://www.gnumeric.org/v10.dtd}Cell")
if any(c.get("Row") == "0" and c.get("Col") == str(col) and (c.text or "") == value for c in cells):
return
except ET.ParseError:
pass
time.sleep(.2)
raise AssertionError("Workbook did not save fixture " + repr(value))
def hide_keyboard():
if "mInputShown=true" in shell("dumpsys", "input_method"):
shell("input", "keyevent", "4")
time.sleep(.4)
def edit(col, value):
hide_keyboard()
x, y = (88 + col * 96) * zoom, top + 177 * zoom
tap(x, y)
tap(180 * zoom, top + 127 * zoom)
until = time.monotonic() + 10
while "mInputShown=true" not in shell("dumpsys", "input_method"):
if time.monotonic() > until:
raise AssertionError("Workbook did not focus Android's keyboard")
time.sleep(.2)
shell("input", "keycombination", "113", "29")
shell("input", "text", shlex.quote(value))
time.sleep(.5)
hide_keyboard()
tap(18 * zoom, top + 98 * zoom)
expect(value, col)
def file_menu():
hide_keyboard()
tap(28 * zoom, top + 68 * zoom)
adb("install", "-r", apk)
shell("am", "force-stop", package)
shell("run-as", package, "rm", "-rf", "files/apps/workbook", check=False)
shell("rm", "-f", "/sdcard/Download/workbook.gnumeric", check=False)
shell("am", "start", "-n", package + "/android.app.NativeActivity")
time.sleep(1)
width, height = map(int, shell("wm", "size").strip().split()[-1].split("x"))
zoom = max(1, width / 390)
windows = shell("dumpsys", "window")
(output / "window-dump.txt").write_text(windows)
status = re.search(r"type=(?:statusBars|ITYPE_STATUS_BAR).*?frame=\[0,0\]\[\d+,(\d+)\]", windows)
top = int(status.group(1)) if status else round(24 * zoom)
try:
label("Workbook")
edit(0, "12")
edit(1, "=A1*2")
shot("calculated")
assert shell("run-as", package, "stat", "-c", "%a", "files/apps/workbook/documents/workbook.gnumeric").strip() == "600"
shell("am", "force-stop", package)
shell("am", "start", "-n", package + "/android.app.NativeActivity")
time.sleep(1)
label("Workbook")
expect("12"); expect("=A1*2", 1)
original = document()
file_menu(); label("As")
native_label("Save")
until = time.monotonic() + 30
exported = ""
while time.monotonic() < until:
exported = shell("cat", "/sdcard/Download/workbook.gnumeric", check=False)
if exported == original:
break
time.sleep(.3)
assert exported == original, "Android export changed document bytes"
edit(0, "7")
file_menu(); label("Open")
native_label("workbook.gnumeric")
expect("12"); expect("=A1*2", 1)
assert shell("cat", "/sdcard/Download/workbook.gnumeric") == exported, "Import modified the selected source"
file_menu(); label("Open")
time.sleep(.5)
shell("input", "keyevent", "4")
time.sleep(.5)
expect("12")
edit(0, "9")
shot("transferred")
print("Workbook Android: IME editing, formulas, private save/restart, system document export/import and cancellation passed")
except BaseException:
shot("failure")
(output / "crash-log.txt").write_bytes(adb("logcat", "-d", "-b", "crash", check=False).stdout)
(output / "startup-log.txt").write_bytes(adb("logcat", "-d", "-s", "Werkzeug:I", "art:E", "AndroidRuntime:E", check=False).stdout)
pid = shell("pidof", package, check=False).strip()
if pid:
(output / "application-log.txt").write_bytes(adb("logcat", "-d", "--pid=" + pid, check=False).stdout)
(output / "ui-task.dex").write_bytes(adb("exec-out", "run-as", package, "cat", "files/ui-task.dex", check=False).stdout)
(output / "runtime-trace.txt").write_bytes(adb("exec-out", "run-as", package, "cat", "files/runtime-trace.txt", check=False).stdout)
raise
+5 -5
View File
@@ -27,7 +27,7 @@ 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),
WERK_ASSETS=os.environ.get('WERK_TEST_ASSETS', str(root/'build')), WORKBOOK_TEST_SELECTION=str(selector),
PATH=str(work/'bin')+':'+os.environ['PATH'])
app = None
window = None
@@ -37,9 +37,9 @@ def command(*args):
def start():
global app, window
app = subprocess.Popen([str(root/'build/werk'), '--app', 'workbook'], env=env)
app = subprocess.Popen([os.environ.get('WERK_TEST_APP', str(root/'build/werk')), '--app', 'workbook'], env=env)
for _ in range(100):
assert app.poll() is None, 'Werkzeug exited'
assert app.poll() is None, f'Werkzeug exited with status {app.returncode}'
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]
@@ -115,13 +115,13 @@ try:
type_text('5'); key('Return'); expect('5')
key('ctrl+z'); expect('')
key('ctrl+y'); expect('5')
bundle = work/'downloaded.zib'
bundle = work/'downloaded.zx'
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'
assert bundle.read_bytes() == (root/'build/apps/workbook.zx').read_bytes(), 'Downloaded bytes differ'
selector.write_text(str(fixture)+'\n')
menu('Open')
expect('11'); expect('=A1*3',col=1)
+5 -1
View File
@@ -2,6 +2,10 @@
# Run the Ziran toolchain commit pinned by ziran.lock. Package commands fetch
# their own locked sources into the user's Ziran cache.
set -eu
# An application's installation paths are not compiler build options. In
# particular a staged BIN_DIR containing spaces must not become Ziran's
# binary directory through GNU Make's recursive command-line environment.
unset MAKEFLAGS MFLAGS MAKEOVERRIDES
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
@@ -40,7 +44,7 @@ if [ "$current" != "$tool_commit" ]; then
fi
if [ ! -x "$ziran" ]; then
env -u DISPLAY -u WAYLAND_DISPLAY make -C "$bootstrap" -s all >&2
env -u DISPLAY -u WAYLAND_DISPLAY make -j1 -C "$bootstrap" -s all >&2
fi
exec "$ziran" "$@"
+5 -5
View File
@@ -4,15 +4,15 @@ ziran=${1:?pass the ziran command}
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$repo"
ziran_root=$("$ziran" pkg path ziran)
paths="--module-path apps/pass --module-path shared"
paths="--module-path apps/pass --module-path crypto=$("$ziran" pkg path crypto)/src"
mkdir -p build/core-test
"$ziran" check --root tests $paths tests/core_main.zi
"$ziran" build --target=c --root tests $paths -o build/core-test/c tests/core_main.zi
${CC:-cc} -std=c99 -O2 -I"$ziran_root/include" -Ibuild/core-test/c build/core-test/c/*.c -o build/core-test/native
build/core-test/native
"$ziran" bundle $paths --root . --entry pass_core_test:PortableAnswer -o build/core-test/core.zib apps/pass/pass_core_test.zi
test "$("$ziran" run build/core-test/core.zib)" = 42
"$ziran" bundle $paths --root . --entry pass_core_test:PortableAnswer -o build/core-test/core.zx apps/pass/pass_core_test.zi
test "$("$ziran" run build/core-test/core.zx)" = 42
"$ziran" ir --root apps/pass $paths -o build/core-test/ir apps/pass/pass_core_test.zi
"$ziran" bundle --root build/core-test/ir --entry pass_core_test:PortableAnswer -o build/core-test/saved.zib build/core-test/ir/pass_core_test.zir
test "$("$ziran" run build/core-test/saved.zib)" = 42
"$ziran" bundle --root build/core-test/ir --entry pass_core_test:PortableAnswer -o build/core-test/saved.zx build/core-test/ir/pass_core_test.zir
test "$("$ziran" run build/core-test/saved.zx)" = 42
echo 'Pass core: native, source bundle, and saved IR tests pass'
-232
View File
@@ -1,232 +0,0 @@
// SHA-256, HMAC-SHA-256 and PBKDF2, shared by Werkzeug and its apps.
Sha256State :: struct {
state: [8]u32
bit_length: u64
buffer: [64]u8
buffer_length: s32
}
sha256_round_constants: [64]u32 = .[
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
Sha256RotateRight :: (value: u32, amount: u32) -> u32 {
if amount == cast(u32)0 { return value }
return (value >> amount) |
(value << (cast(u32)32 - amount))
}
Sha256Initialize :: () -> Sha256State {
state: Sha256State
state.state[0] = 0x6a09e667
state.state[1] = 0xbb67ae85
state.state[2] = 0x3c6ef372
state.state[3] = 0xa54ff53a
state.state[4] = 0x510e527f
state.state[5] = 0x9b05688c
state.state[6] = 0x1f83d9ab
state.state[7] = 0x5be0cd19
return state
}
Sha256Compress :: (context: Sha256State, block: [64]u8) -> Sha256State {
words: [64]u32
for index: 0..15 {
words[index] = (cast(u32)block[index * 4] << cast(u32)24) |
(cast(u32)block[index * 4 + 1] << cast(u32)16) |
(cast(u32)block[index * 4 + 2] << cast(u32)8) |
cast(u32)block[index * 4 + 3]
}
for index: 16..63 {
low_left: u32 = Sha256RotateRight(words[index - 15], cast(u32)7)
low_first: u32
low_first = low_left ^ Sha256RotateRight(words[index - 15], cast(u32)18)
low: u32 = low_first ^ (words[index - 15] >> cast(u32)3)
high_left: u32 = Sha256RotateRight(words[index - 2], cast(u32)17)
high_first: u32
high_first = high_left ^ Sha256RotateRight(words[index - 2], cast(u32)19)
high: u32 = high_first ^ (words[index - 2] >> cast(u32)10)
words[index] = words[index - 16] + low + words[index - 7] + high
}
a: u32 = context.state[0]
b: u32 = context.state[1]
c: u32 = context.state[2]
d: u32 = context.state[3]
e: u32 = context.state[4]
f: u32 = context.state[5]
g: u32 = context.state[6]
h: u32 = context.state[7]
for index: 0..63 {
major_left: u32 = Sha256RotateRight(e, cast(u32)6)
major_first: u32
major_first = major_left ^ Sha256RotateRight(e, cast(u32)11)
major: u32 = major_first ^ Sha256RotateRight(e, cast(u32)25)
choose: u32 = (e & f) ^ (~e & g)
first: u32 = h + major + choose +
sha256_round_constants[index] + words[index]
minor_left: u32 = Sha256RotateRight(a, cast(u32)2)
minor_first: u32
minor_first = minor_left ^ Sha256RotateRight(a, cast(u32)13)
minor: u32 = minor_first ^ Sha256RotateRight(a, cast(u32)22)
mixture: u32 = (a & b) ^ (a & c) ^ (b & c)
second: u32 = minor + mixture
h = g
g = f
f = e
e = d + first
d = c
c = b
b = a
a = first + second
}
context.state[0] += a
context.state[1] += b
context.state[2] += c
context.state[3] += d
context.state[4] += e
context.state[5] += f
context.state[6] += g
context.state[7] += h
return context
}
Sha256Update :: (context: Sha256State, data: string) -> Sha256State {
context.bit_length += cast(u64)data.count * cast(u64)8
offset: s32 = 0
length: s32 = cast(s32)data.count
while offset < length {
take: s32 = 64 - context.buffer_length
remaining: s32 = length - offset
if take > remaining { take = remaining }
position: s32 = 0
while position < take {
context.buffer[context.buffer_length + position] =
data[offset + position]
position += 1
}
context.buffer_length += take
offset += take
if context.buffer_length == 64 {
context = Sha256Compress(context, context.buffer)
context.buffer_length = 0
}
}
return context
}
Sha256Final :: (context: Sha256State) -> [32]u8 {
bit_length: u64 = context.bit_length
context.buffer[context.buffer_length] = cast(u8)0x80
context.buffer_length += 1
if context.buffer_length > 56 {
while context.buffer_length < 64 {
context.buffer[context.buffer_length] = cast(u8)0
context.buffer_length += 1
}
context = Sha256Compress(context, context.buffer)
context.buffer_length = 0
}
while context.buffer_length < 56 {
context.buffer[context.buffer_length] = cast(u8)0
context.buffer_length += 1
}
for index: 0..7 {
shift: u64 = cast(u64)(7 - index) * cast(u64)8
context.buffer[context.buffer_length] =
cast(u8)(bit_length >> shift)
context.buffer_length += 1
}
context = Sha256Compress(context, context.buffer)
digest: [32]u8
for index: 0..7 {
digest[index * 4] = cast(u8)(context.state[index] >> cast(u32)24)
digest[index * 4 + 1] =
cast(u8)(context.state[index] >> cast(u32)16)
digest[index * 4 + 2] = cast(u8)(context.state[index] >> cast(u32)8)
digest[index * 4 + 3] = cast(u8)context.state[index]
}
return digest
}
Sha256 :: (data: string) -> [32]u8 {
context := Sha256Initialize()
context = Sha256Update(context, data)
return Sha256Final(context)
}
HmacSha256 :: (key: string, message: string) -> [32]u8 {
block_key: [64]u8
if key.count > 64 {
hashed_key := Sha256(key)
for index: 0..31 { block_key[index] = hashed_key[index] }
} else {
key_length: s32 = cast(s32)key.count
if key_length > 0 {
index: s32 = 0
while index < key_length {
block_key[index] = key[index]
index += 1
}
}
}
pad: [64]u8
for index: 0..63 { pad[index] = block_key[index] ^ cast(u8)0x36 }
context := Sha256Initialize()
context = Sha256Update(context, TextView(pad[0:64]))
context = Sha256Update(context, message)
inner := Sha256Final(context)
for index: 0..63 { pad[index] = block_key[index] ^ cast(u8)0x5c }
context = Sha256Initialize()
context = Sha256Update(context, TextView(pad[0:64]))
context = Sha256Update(context, TextView(inner[0:32]))
return Sha256Final(context)
}
// PBKDF2 with HMAC-SHA-256 and one 32-byte block. Salts longer than 508
// bytes are cut there.
Pbkdf2Sha256 :: (password: string, salt: string, iterations: s32) -> [32]u8 {
block_input: [512]u8
salt_length: s32 = cast(s32)salt.count
if salt_length > 508 { salt_length = 508 }
if salt_length > 0 {
index: s32 = 0
while index < salt_length {
block_input[index] = salt[index]
index += 1
}
}
block_input[salt_length] = cast(u8)0
block_input[salt_length + 1] = cast(u8)0
block_input[salt_length + 2] = cast(u8)0
block_input[salt_length + 3] = cast(u8)1
input_length: s32 = salt_length + 4
output := HmacSha256(password, TextView(block_input[0:input_length]))
previous: [32]u8 = output
round: s32 = 1
while round < iterations {
round += 1
previous = HmacSha256(password, TextView(previous[0:32]))
for index: 0..31 { output[index] ^= previous[index] }
}
return output
}
+26 -1
View File
@@ -11,6 +11,7 @@
libc :: #system_library "libc";
ChangeDirectory :: (path: *u8) -> s32 #foreign libc "chdir";
SetAndroidEnvironment :: (name: *u8, value: *u8, overwrite: s32) -> s32 #foreign libc "setenv";
android :: #system_library "android";
ShowKeyboard :: (activity: *NativeActivity, flags: u32) #foreign android "ANativeActivity_showSoftInput";
HideKeyboard :: (activity: *NativeActivity, flags: u32) #foreign android "ANativeActivity_hideSoftInput";
@@ -38,7 +39,31 @@ secure_master: [1024]u8;
AndroidInitialize :: () -> bool {
path := ActivityInternalDataPath()
return path != null && ChangeDirectory(path) == 0
if path == null || ChangeDirectory(path) != 0 {
return false
}
// The native bundle runtime needs writable build and object-cache folders.
// NativeActivity has no /tmp or inherited desktop cache environment.
temporary: [PATH_LIMIT]u8
cache: [PATH_LIMIT]u8
folder := PathJoin(temporary[:], TextFromCString(path), "cache")
if !EnsureDirectory(folder) {
return false
}
objects := PathJoin(cache[:], folder, "ziran-native")
if !EnsureDirectory(objects) {
return false
}
names: [3]string = .["TMPDIR", "ZIRAN_NATIVE_DIR", "ZIRAN_NATIVE_CACHE"]
values: [3]*u8 = .[*temporary[0], *temporary[0], *cache[0]]
for index: 0..2 {
name: [32]u8
if !CopyCString(names[index], name[:]) ||
SetAndroidEnvironment(*name[0], values[index], 1) != 0 {
return false
}
}
return true
}
AndroidKeyboard :: (visible: bool) {
+57 -27
View File
@@ -6,6 +6,7 @@
#import "c_string"
#import "byte_text_linux"
#import "text_buffer"
#import "files"
UiCallback :: #type (*JniEnv, *void) -> void #c_call;
NativeMethod :: struct { name: *u8; signature: *u8; callback: UiCallback }
@@ -14,9 +15,13 @@ MutexLock :: (mutex: *void) -> s32 #foreign libc "pthread_mutex_lock";
MutexUnlock :: (mutex: *void) -> s32 #foreign libc "pthread_mutex_unlock";
DexOpen :: (path: *u8, mode: *u8) -> *void #foreign libc "fopen";
DexWrite :: (bytes: *u8, size: usize, count: usize, file: *void) -> usize #foreign libc "fwrite";
DexRead :: (bytes: *u8, size: usize, count: usize, file: *void) -> usize #foreign libc "fread";
DexClose :: (file: *void) -> s32 #foreign libc "fclose";
DexDescriptor :: (file: *void) -> s32 #foreign libc "fileno";
DexPrivate :: (fd: s32, mode: s32) -> s32 #foreign libc "fchmod";
DexSync :: (fd: s32) -> s32 #foreign libc "fsync";
DexRename :: (from: *u8, to: *u8) -> s32 #foreign libc "rename";
DexRemove :: (path: *u8) -> s32 #foreign libc "unlink";
ui_mutex: [8]u64;
ui_pending: bool;
@@ -89,6 +94,11 @@ DexRunnable :: (env: *JniEnv, bytes: []u8) -> s32 {
DexMap(bytes, 10, cast(u32)0x1000, cast(u32)1, cast(u32)map, map)
length := map + 136
DexWord(bytes, 32, cast(u32)length); DexWord(bytes, 104, cast(u32)(length - 220))
return DexSeal(env, bytes, length)
}
// A generated JNI bridge contains only a constructor and native callbacks.
DexSeal :: (env: *JniEnv, bytes: []u8, length: s32) -> s32 {
args: [1]JniValue
args[0] = ArgumentObject(TextObject(env, "SHA-1"))
digest := StaticCall(env, "java/security/MessageDigest", "getInstance", "(Ljava/lang/String;)Ljava/security/MessageDigest;", args[:])
@@ -104,6 +114,52 @@ DexRunnable :: (env: *JniEnv, bytes: []u8) -> s32 {
DexWord(bytes, 8, (second << cast(u32)16) | first)
return length
}
// Load a generated bridge from the activity's private, read-only code cache.
DexClass :: (env: *JniEnv, bytes: []u8, length: s32, filename: string, name: string) -> *void {
if length <= 0 || length > bytes.count || length > 4096 || !SafeName(filename) { return null }
path: [1024]u8
base := TextFromCString(ActivityInternalDataPath())
if PathJoin(path[:], base, filename) == "" { return null }
mode: [3]u8
unused CopyCString("rb", mode[:])
file := DexOpen(*path[0], *mode[0])
valid := false
if file != null {
previous: [4096]u8
extra: u8
valid = DexRead(*previous[0], cast(usize)1, cast(usize)length, file) == cast(usize)length &&
DexRead(*extra, cast(usize)1, cast(usize)1, file) == cast(usize)0
for index: 0..length - 1 { if previous[index] != bytes[index] { valid = false } }
if DexClose(file) != 0 { valid = false }
}
if !valid {
temporary: [1280]u8
unused CopyCString(TextUntilNul(path[:]), temporary[:])
used := TextUntilNul(temporary[:]).count
suffix := ".new"
for index: 0..3 { temporary[used + index] = suffix[index] }
temporary[used + 4] = 0
unused DexRemove(*temporary[0])
unused CopyCString("wb", mode[:]); file = DexOpen(*temporary[0], *mode[0])
if file == null { return null }
ok := DexPrivate(DexDescriptor(file), 256) == 0
ok = DexWrite(*bytes[0], cast(usize)1, cast(usize)length, file) == cast(usize)length && ok
ok = DexSync(DexDescriptor(file)) == 0 && ok
ok = DexClose(file) == 0 && ok
if ok { ok = DexRename(*temporary[0], *path[0]) == 0 }
if !ok { unused DexRemove(*temporary[0]) }
if !ok { return null }
}
empty := NoArguments()
parent := ObjectCall(env, NativeApp().activity.activity, "getClassLoader", "()Ljava/lang/ClassLoader;", empty[:])
args: [4]JniValue
args[0] = ArgumentObject(TextObject(env, TextUntilNul(path[:])))
args[1] = ArgumentObject(TextObject(env, base)); args[2] = ArgumentObject(null); args[3] = ArgumentObject(parent)
loader := NewObject(env, "dalvik/system/DexClassLoader", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V", args[:])
args[0] = ArgumentObject(TextObject(env, name))
return ObjectCall(env, loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", args[:])
}
UiRun :: (env: *JniEnv, task: *void) {
UiLock()
if ui_pending { ui_callback(env, task); ui_pending = false }
@@ -116,34 +172,8 @@ UiInitialize :: () -> bool {
env := session.env
bytes: [512]u8
length := DexRunnable(env, bytes[:])
path: [1024]u8
base := TextFromCString(ActivityInternalDataPath())
index: s32 = 0
while index < cast(s32)base.count && index < 900 { path[index] = base[index]; index += 1 }
suffix := "/ui-task.dex"
for position: 0..11 { path[index + cast(s32)position] = suffix[position] }
mode: [3]u8
CopyCString("rb", mode[:])
file := DexOpen(*path[0], *mode[0])
if file != null { DexClose(file) }
else {
CopyCString("wb", mode[:]); file = DexOpen(*path[0], *mode[0])
if file == null || length == 0 { activity_jni_detach(*session); return false }
// Android 14 requires dynamically loaded code to be read-only.
// The already-open descriptor remains writable after chmod.
ok := DexPrivate(DexDescriptor(file), 256) == 0
ok = DexWrite(*bytes[0], cast(usize)1, cast(usize)length, file) == cast(usize)length && ok
ok = DexClose(file) == 0 && ok
if !ok { activity_jni_detach(*session); return false }
}
klass := DexClass(env, bytes[:], length, "ui-task.dex", "xyz.waozi.pass.UiTask")
empty := NoArguments()
parent := ObjectCall(env, session.activity, "getClassLoader", "()Ljava/lang/ClassLoader;", empty[:])
args: [4]JniValue
args[0] = ArgumentObject(TextObject(env, TextUntilNul(path[:])))
args[1] = ArgumentObject(TextObject(env, base)); args[2] = ArgumentObject(null); args[3] = ArgumentObject(parent)
loader := NewObject(env, "dalvik/system/DexClassLoader", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V", args[:])
args[0] = ArgumentObject(TextObject(env, "xyz.waozi.pass.UiTask"))
klass := ObjectCall(env, loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", args[:])
label: [4]u8; descriptor: [4]u8
CopyCString("run", label[:]); CopyCString("()V", descriptor[:])
methods: [1]NativeMethod
+79
View File
@@ -0,0 +1,79 @@
// A framework Fragment routes Android's granted document result into Ziran.
// Like UiTask, its only bytecode is a constructor; all behavior is native.
// Identifier tables and map entries follow Android's DEX 035 format.
#import "android"
#import "android_jni"
Dex :: #import "android_dispatch";
Uleb :: (bytes: []u8, at: *s32, value: u32) {
rest := value
while rest >= cast(u32)128 {
bytes[at.*] = cast(u8)((rest & cast(u32)127) | cast(u32)128)
at.* += 1
rest >>= cast(u32)7
}
bytes[at.*] = cast(u8)rest
at.* += 1
}
DocumentPickerDex :: (env: *JniEnv, bytes: []u8) -> s32 {
magic := "dex\n035"
for index: 0..6 { bytes[index] = magic[index] }
Dex.DexWord(bytes, 36, cast(u32)112)
Dex.DexWord(bytes, 40, cast(u32)0x12345678)
Dex.DexWord(bytes, 56, cast(u32)8); Dex.DexWord(bytes, 60, cast(u32)112)
Dex.DexWord(bytes, 64, cast(u32)5); Dex.DexWord(bytes, 68, cast(u32)144)
Dex.DexWord(bytes, 72, cast(u32)2); Dex.DexWord(bytes, 76, cast(u32)164)
Dex.DexWord(bytes, 88, cast(u32)3); Dex.DexWord(bytes, 92, cast(u32)188)
Dex.DexWord(bytes, 96, cast(u32)1); Dex.DexWord(bytes, 100, cast(u32)212)
Dex.DexWord(bytes, 108, cast(u32)244)
for index: 0..4 { Dex.DexWord(bytes, 144 + cast(s32)index * 4, cast(u32)(index + 1)) }
Dex.DexWord(bytes, 164, cast(u32)5); Dex.DexWord(bytes, 168, cast(u32)4)
Dex.DexWord(bytes, 176, cast(u32)6); Dex.DexWord(bytes, 180, cast(u32)4)
Dex.DexWord(bytes, 184, cast(u32)244)
Dex.DexHalf(bytes, 188, cast(u32)1)
Dex.DexHalf(bytes, 196, cast(u32)3)
Dex.DexHalf(bytes, 204, cast(u32)3); Dex.DexHalf(bytes, 206, cast(u32)1)
Dex.DexWord(bytes, 208, cast(u32)7)
Dex.DexWord(bytes, 212, cast(u32)3); Dex.DexWord(bytes, 216, cast(u32)1)
Dex.DexWord(bytes, 220, cast(u32)1); Dex.DexWord(bytes, 228, cast(u32)0xffffffff)
Dex.DexWord(bytes, 244, cast(u32)3)
Dex.DexHalf(bytes, 252, cast(u32)2)
strings: [8]string = .["<init>", "I", "Landroid/app/Fragment;", "Landroid/content/Intent;",
"Lxyz/waozi/pass/DocumentPicker;", "V", "VIIL", "onActivityResult"]
at: s32 = 256
for index: 0..7 {
Dex.DexWord(bytes, 112 + cast(s32)index * 4, cast(u32)at)
Uleb(bytes, *at, cast(u32)strings[index].count)
for position: 0..strings[index].count - 1 { bytes[at] = strings[index][position]; at += 1 }
at += 1
}
code := (at + 3) & -4
Dex.DexHalf(bytes, code, cast(u32)1); Dex.DexHalf(bytes, code + 2, cast(u32)1)
Dex.DexHalf(bytes, code + 4, cast(u32)1); Dex.DexWord(bytes, code + 12, cast(u32)4)
Dex.DexHalf(bytes, code + 16, cast(u32)0x1070)
Dex.DexHalf(bytes, code + 22, cast(u32)0x000e)
data := code + 24
Dex.DexWord(bytes, 236, cast(u32)data)
at = data
Uleb(bytes, *at, cast(u32)0); Uleb(bytes, *at, cast(u32)0)
Uleb(bytes, *at, cast(u32)1); Uleb(bytes, *at, cast(u32)1)
Uleb(bytes, *at, cast(u32)1); Uleb(bytes, *at, cast(u32)0x10001); Uleb(bytes, *at, cast(u32)code)
Uleb(bytes, *at, cast(u32)2); Uleb(bytes, *at, cast(u32)0x101); Uleb(bytes, *at, cast(u32)0)
map := (at + 3) & -4
Dex.DexWord(bytes, 52, cast(u32)map); Dex.DexWord(bytes, map, cast(u32)11)
Dex.DexMap(bytes, 0, cast(u32)0, cast(u32)1, cast(u32)0, map)
Dex.DexMap(bytes, 1, cast(u32)1, cast(u32)8, cast(u32)112, map)
Dex.DexMap(bytes, 2, cast(u32)2, cast(u32)5, cast(u32)144, map)
Dex.DexMap(bytes, 3, cast(u32)3, cast(u32)2, cast(u32)164, map)
Dex.DexMap(bytes, 4, cast(u32)5, cast(u32)3, cast(u32)188, map)
Dex.DexMap(bytes, 5, cast(u32)6, cast(u32)1, cast(u32)212, map)
Dex.DexMap(bytes, 6, cast(u32)0x1001, cast(u32)1, cast(u32)244, map)
Dex.DexMap(bytes, 7, cast(u32)0x2002, cast(u32)8, cast(u32)256, map)
Dex.DexMap(bytes, 8, cast(u32)0x2001, cast(u32)1, cast(u32)code, map)
Dex.DexMap(bytes, 9, cast(u32)0x2000, cast(u32)1, cast(u32)data, map)
Dex.DexMap(bytes, 10, cast(u32)0x1000, cast(u32)1, cast(u32)map, map)
length := map + 136
Dex.DexWord(bytes, 32, cast(u32)length); Dex.DexWord(bytes, 104, cast(u32)(length - 244))
return Dex.DexSeal(env, bytes, length)
}
+180
View File
@@ -0,0 +1,180 @@
// Android document transfers are asynchronous and use the system chooser.
// The chooser grants one URI; bundles see only their private document name.
#import "android"
#import "android_jni"
#import "android_dispatch"
#import "android_document_dex"
#import "files"
#import "std/c_string"
#import "std/byte_text_linux"
#import "std/text_buffer"
#import "std/vec"
#import "kryon/app_files"
DocumentCallback :: #type (*JniEnv, *void, s32, s32, *void) -> void #c_call;
DocumentNative :: struct { name: *u8; signature: *u8; callback: DocumentCallback }
DOCUMENT_REQUEST :: 6501
// 0 idle, 1 queued, 2 awaiting Android, 3 selected, 4 cancelled, 5 failed.
document_state: s32;
document_files: *AppFiles;
document_name: [256]u8;
document_save: bool;
document_intent: *void;
DocumentSelected :: (env: *JniEnv, fragment: *void, request: s32, result: s32, intent: *void) {
if request != DOCUMENT_REQUEST { return }
UiLock()
if document_state == 2 {
if result == -1 && intent != null {
document_intent = env.functions.NewGlobalRef(env, intent)
document_state = ifx document_intent != null then 3 else 5
} else { document_state = 4 }
}
UiUnlock()
// This bridge is transient: don't leave it in the activity's saved state.
empty := NoArguments()
manager := ObjectCall(env, fragment, "getFragmentManager", "()Landroid/app/FragmentManager;", empty[:])
transaction := ObjectCall(env, manager, "beginTransaction", "()Landroid/app/FragmentTransaction;", empty[:])
args: [1]JniValue = .[ArgumentObject(fragment)]
unused ObjectCall(env, transaction, "remove", "(Landroid/app/Fragment;)Landroid/app/FragmentTransaction;", args[:])
method := Method(env, transaction, "commitAllowingStateLoss", "()I", false)
if method != null { unused env.functions.CallIntMethodA(env, transaction, method, *empty[0]) }
unused JniOk(env)
}
DocumentFragment :: (env: *JniEnv) -> *void {
bytes: [1024]u8
length := DocumentPickerDex(env, bytes[:])
if length == 0 { return null }
klass := DexClass(env, bytes[:], length, "document-picker-v1.dex", "xyz.waozi.pass.DocumentPicker")
empty := NoArguments()
if klass == null { return null }
label: [32]u8; signature: [64]u8
unused CopyCString("onActivityResult", label[:]); unused CopyCString("(IILandroid/content/Intent;)V", signature[:])
methods: [1]DocumentNative = .[DocumentNative.{*label[0], *signature[0], DocumentSelected}]
if env.functions.RegisterNatives(env, klass, cast(*void)*methods[0], 1) != 0 || !JniOk(env) { return null }
unused CopyCString("<init>", label[:]); unused CopyCString("()V", signature[:])
constructor := env.functions.GetMethodID(env, klass, *label[0], *signature[0])
if constructor == null { unused JniOk(env); return null }
return env.functions.NewObjectA(env, klass, constructor, *empty[0])
}
// UiRun holds the dispatcher mutex while this callback executes.
DocumentOpenUi :: (env: *JniEnv, task: *void) {
unused task
fragment := DocumentFragment(env)
if fragment == null { document_state = 5; unused JniOk(env); return }
empty := NoArguments()
activity := NativeApp().activity.activity
manager := ObjectCall(env, activity, "getFragmentManager", "()Landroid/app/FragmentManager;", empty[:])
transaction := ObjectCall(env, manager, "beginTransaction", "()Landroid/app/FragmentTransaction;", empty[:])
args: [2]JniValue
args[0] = ArgumentObject(fragment); args[1] = ArgumentObject(TextObject(env, "werk-document-picker"))
unused ObjectCall(env, transaction, "add", "(Landroid/app/Fragment;Ljava/lang/String;)Landroid/app/FragmentTransaction;", args[:])
commit := Method(env, transaction, "commitAllowingStateLoss", "()I", false)
if commit == null { document_state = 5; return }
unused env.functions.CallIntMethodA(env, transaction, commit, *empty[0])
if !BoolCall(env, manager, "executePendingTransactions", "()Z", empty[:]) { document_state = 5; return }
args[0] = ArgumentObject(TextObject(env, ifx document_save then "android.intent.action.CREATE_DOCUMENT" else "android.intent.action.OPEN_DOCUMENT"))
intent := NewObject(env, "android/content/Intent", "(Ljava/lang/String;)V", args[:])
args[0] = ArgumentObject(TextObject(env, "android.intent.category.OPENABLE"))
unused ObjectCall(env, intent, "addCategory", "(Ljava/lang/String;)Landroid/content/Intent;", args[:])
args[0] = ArgumentObject(TextObject(env, "application/x-gnumeric"))
unused ObjectCall(env, intent, "setType", "(Ljava/lang/String;)Landroid/content/Intent;", args[:])
if document_save {
args[0] = ArgumentObject(TextObject(env, "android.intent.extra.TITLE"))
args[1] = ArgumentObject(TextObject(env, "workbook.gnumeric"))
unused ObjectCall(env, intent, "putExtra", "(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;", args[:])
}
args[0] = ArgumentObject(intent); args[1] = ArgumentInteger(DOCUMENT_REQUEST)
if !VoidCall(env, fragment, "startActivityForResult", "(Landroid/content/Intent;I)V", args[:]) { document_state = 5 }
}
DocumentCopy :: (files: *AppFiles, name: string, save: bool, intent: *void) -> bool {
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return false }
defer { activity_jni_detach(*session) }
env := session.env
defer { env.functions.DeleteGlobalRef(env, intent) }
empty := NoArguments()
uri := ObjectCall(env, intent, "getData", "()Landroid/net/Uri;", empty[:])
resolver := ObjectCall(env, session.activity, "getContentResolver", "()Landroid/content/ContentResolver;", empty[:])
if uri == null || resolver == null { return false }
args: [3]JniValue
args[0] = ArgumentObject(uri)
stream: *void
if save {
args[1] = ArgumentObject(TextObject(env, "wt"))
stream = ObjectCall(env, resolver, "openOutputStream", "(Landroid/net/Uri;Ljava/lang/String;)Ljava/io/OutputStream;", args[:])
} else { stream = ObjectCall(env, resolver, "openInputStream", "(Landroid/net/Uri;)Ljava/io/InputStream;", args[:]) }
if stream == null { return false }
closed := false
defer { if !closed { unused VoidCall(env, stream, "close", "()V", empty[:]) } }
buffer := env.functions.NewByteArray(env, 4096)
if buffer == null || !JniOk(env) { return false }
args[0] = ArgumentObject(buffer)
if save {
value := AppFileRead(files, name)
defer { AppFileFree(value) }
if files.status != 1 { return false }
write := Method(env, stream, "write", "([BII)V", false)
if write == null { return false }
descriptor := cast(*TextDescriptor)(*value)
at: s64 = 0
while at < value.count {
count := cast(s32)(ifx value.count - at > 4096 then 4096 else value.count - at)
env.functions.SetByteArrayRegion(env, buffer, 0, count, *descriptor.data[at])
args[1] = ArgumentInteger(0); args[2] = ArgumentInteger(count)
env.functions.CallVoidMethodA(env, stream, write, *args[0])
if !JniOk(env) { return false }
at += count
}
if !VoidCall(env, stream, "flush", "()V", empty[:]) { return false }
ok := VoidCall(env, stream, "close", "()V", empty[:])
closed = true
return ok
}
read := Method(env, stream, "read", "([B)I", false)
if read == null { return false }
bytes: Vec(u8)
chunk: [4096]u8
while true {
count := env.functions.CallIntMethodA(env, stream, read, *args[0])
if !JniOk(env) { VecFree(bytes); return false }
if count < 0 { break }
if count == 0 || count > 4096 || bytes.count + count > APP_DOCUMENT_LIMIT { VecFree(bytes); return false }
env.functions.GetByteArrayRegion(env, buffer, 0, count, *chunk[0])
if !JniOk(env) { VecFree(bytes); return false }
for index: 0..count - 1 { if !VecPush(bytes, chunk[index]) { VecFree(bytes); return false } }
}
value := BuilderFinish(bytes)
defer { AppFileFree(value) }
closed = true
return VoidCall(env, stream, "close", "()V", empty[:]) && value.count > 0 && AppFileWrite(files, name, value)
}
AndroidDocumentTransfer :: (files: *AppFiles, operation: string, name: string) -> string {
UiLock()
if operation != "poll" {
if document_state != 0 || (operation != "import" && operation != "export") || !AppFileNameValid(name) ||
!CopyCString(name, document_name[:]) { UiUnlock(); return "error" }
document_save = operation == "export"
document_files = files
document_state = 1
} else if document_files != files { UiUnlock(); return "error" }
state := document_state
if state == 1 { document_state = 2 }
intent := document_intent
save := document_save
UiUnlock()
if state == 1 {
if !UiSchedule(DocumentOpenUi) { UiLock(); document_state = 1; UiUnlock() }
return "pending"
}
if state == 2 { return "pending" }
ok := state == 3 && intent != null && DocumentCopy(files, TextUntilNul(document_name[:]), save, intent)
UiLock()
document_state = 0; document_files = null; document_intent = null; document_name[0] = 0
UiUnlock()
return ifx state == 4 then "cancelled" else ifx ok then "ready" else "error"
}
+8
View File
@@ -78,7 +78,15 @@ AndroidWidgetCall :: (context: *void, module: *u8, function: *u8,
}
}
// The editor delivers the typing; the field only draws and selects.
focus := props.input.focus
blur := props.input.blur
commit := props.input.commit
escape := props.input.escape
props.input = TextFieldInput.{}
props.input.focus = focus
props.input.blur = blur
props.input.commit = commit
props.input.escape = escape
synced: [2]HostValue = .[arguments[0], WidgetEncodeTextFieldProps(props, *synced_codec)]
if WidgetHostCall(context, module, function, *synced[0], 2, result) == 0 {
return 0
+65 -53
View File
@@ -42,6 +42,68 @@ NativeThreadAttributes :: (attributes: *void) -> s32 {
return SetThreadStack(attributes, cast(usize)16777216)
}
WerkAndroidFrame :: struct { session: Session; ok: bool }
ComposeAndroidFrame :: (argument: *void) {
frame := cast(*WerkAndroidFrame)argument
session := frame.session
ok := true
width: s32
height: s32
SyncAndroidSurfaceSize(*width, *height)
// Keeps the app clear of the navigation bar and the keyboard.
PollAndroidWindowInsets()
zoom := cast(float32)width / 390.0
if zoom < 1.0 {
zoom = 1.0
}
Render.RaylibSetZoom(zoom)
viewport: AndroidViewport
ResolveAndroidViewport(width, height, AndroidViewportPolicyResizeForIme(), *viewport)
bounds := Rectangle.{cast(float32)viewport.x / zoom, cast(float32)viewport.y / zoom,
cast(float32)viewport.width / zoom, cast(float32)viewport.height / zoom}
KeyboardModifiersSend(session, Render.RaylibModifiers())
key := Render.RaylibPressedKey()
if key != 0 {
KeyboardSend(session, key)
}
codepoint := Render.RaylibTypedCodepoint()
while codepoint != 0 {
TypedCodepointSend(session, codepoint)
codepoint = Render.RaylibTypedCodepoint()
}
Render.BeginRaylibFrame()
ClearAndroidFrame(viewport, ThemePalette().background, zoom)
pointer := Render.PollPointer()
TreePointerUpdate(session, pointer)
TreeSecondaryPointerUpdate(session, Render.PollSecondaryPointer())
PointerWheelSend(session, pointer.x, pointer.y, Render.RaylibWheelMove())
AndroidFieldsBegin()
ok = BeginFrame(session, cast(u64)1, bounds) == FrameStatus.FrameOk
if !ok {
Report("Could not begin frame")
}
if ok {
ok = WerkFrame(session, bounds) == 0
if !ok {
Report("Could not compose frame")
}
}
if ok {
ok = EndFrame(session) == FrameStatus.FrameOk
if !ok {
Report("Could not commit frame")
}
}
AndroidFieldsEnd()
ShowKeyboard(WerkKeyboard())
ok = Render.EndRaylibFrame() && ok
if !ok {
Report("Could not present frame")
}
frame.ok = ok
}
#program_export
main :: () -> s32 {
thread_adapter: AttributeInit = NativeThreadAttributes
@@ -73,60 +135,10 @@ main :: () -> s32 {
WerkStart()
ok: bool = true
while ok && Render.PollRaylib() {
width: s32
height: s32
SyncAndroidSurfaceSize(*width, *height)
// Keeps the app clear of the navigation bar and the keyboard.
PollAndroidWindowInsets()
zoom := cast(float32)width / 390.0
if zoom < 1.0 {
zoom = 1.0
}
Render.RaylibSetZoom(zoom)
viewport: AndroidViewport
ResolveAndroidViewport(width, height, AndroidViewportPolicyResizeForIme(), *viewport)
bounds := Rectangle.{cast(float32)viewport.x / zoom, cast(float32)viewport.y / zoom,
cast(float32)viewport.width / zoom, cast(float32)viewport.height / zoom}
KeyboardModifiersSend(session, Render.RaylibModifiers())
key := Render.RaylibPressedKey()
if key != 0 {
KeyboardSend(session, key)
}
codepoint := Render.RaylibTypedCodepoint()
while codepoint != 0 {
TypedCodepointSend(session, codepoint)
codepoint = Render.RaylibTypedCodepoint()
}
Render.BeginRaylibFrame()
ClearAndroidFrame(viewport, ThemePalette().background, zoom)
pointer := Render.PollPointer()
TreePointerUpdate(session, pointer)
TreeSecondaryPointerUpdate(session, Render.PollSecondaryPointer())
PointerWheelSend(session, pointer.x, pointer.y, Render.RaylibWheelMove())
AndroidFieldsBegin()
ok = BeginFrame(session, cast(u64)1, bounds) == FrameStatus.FrameOk
if !ok {
Report("Could not begin frame")
}
if ok {
ok = WerkFrame(session, bounds) == 0
if !ok {
Report("Could not compose frame")
}
}
if ok {
ok = EndFrame(session) == FrameStatus.FrameOk
if !ok {
Report("Could not commit frame")
}
}
AndroidFieldsEnd()
ShowKeyboard(WerkKeyboard())
ok = Render.EndRaylibFrame() && ok
if !ok {
Report("Could not present frame")
}
frame := WerkAndroidFrame.{.session = session}
ok = Render.RunRaylibAppFrame(ComposeAndroidFrame, cast(*void)*frame) && frame.ok
}
Render.CloseRaylibAppFrames()
ok = SaveApps() && ok
ShowKeyboard(false)
CloseSession(session)
+114 -85
View File
@@ -20,7 +20,7 @@ using UI :: #import "kryon/Widgets";
#import "kryon/key_input"
#import "platform"
#import "files"
#import "sha256"
#import "crypto/sha256"
#import "records"
#import "entity_host"
#import "entity_management"
@@ -32,20 +32,24 @@ using UI :: #import "kryon/Widgets";
}
#if #defined(ANDROID_BUILD) {
#import "android_fields"
#import "android_documents"
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
Spreadsheet :: #import "workbook/service";
Font :: #import "kryon/font_metrics";
Spreadsheet :: #import "workbook/service";
Font :: #import "kryon/font_metrics";
Json :: #import "std/json_scan";
#if #defined(PLATFORM_WEB) {
#import "browser_storage"
}
#if !#defined(ANDROID_BUILD) {
Picker :: #import "kryon/file_picker";
Json :: #import "std/json_scan";
}
using HostValueKind;
APP_LIMIT :: 8
APP_STORE_LIMIT :: 262144
// The preinstalled apps, in their home screen order.
BUNDLED_APPS :: 4
BUNDLED_APPS :: 5
App :: struct {
id: [128]u8
@@ -59,9 +63,7 @@ App :: struct {
document_root: [PATH_LIMIT]u8
bundled: bool
started: bool
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
spreadsheet: Spreadsheet.Context
}
spreadsheet: Spreadsheet.Context
}
// What the running app sees this frame.
@@ -105,9 +107,10 @@ AppCount :: () -> s32 {
AppServiceAllowed :: (context: *void, name: string) -> bool {
app := cast(*App)context
id := TextUntilNul(app.id[:])
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
if name == "spreadsheet.v1" { return app.bundled && id == "workbook" }
if name == "input.v1" || name == "document.pick.v1" || name == "app.bundle.export.v1" { return true }
if name == "spreadsheet.v1" { return app.bundled && id == "workbook" }
if name == "input.v1" || name == "document.pick.v1" { return true }
#if !#defined(ANDROID_BUILD) {
if name == "app.bundle.export.v1" { return true }
}
if name == "entity.assets" || name == "entity.management" { return id == "entity" }
if name == "media.asset" || name == "media.query" || name == "media.pick" {
@@ -350,19 +353,26 @@ AppCall :: (context: *void, module: *u8, function: *u8,
return 0
}
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
if name == "AppServiceHost" && count == 2 {
service := ArgumentText(arguments[0])
request := ArgumentText(arguments[1])
if service == "spreadsheet.v1" {
text := Spreadsheet.Call(*app.spreadsheet, *app.local.files, request)
result.* = HostValue.{.kind = cast(s32)HostString, .type_name = HostTextData("string"), .data = HostTextData(text), .length = cast(usize)text.count}
return 1
if name == "AppServiceHost" && count == 2 {
service := ArgumentText(arguments[0])
request := ArgumentText(arguments[1])
if service == "spreadsheet.v1" {
text := Spreadsheet.Call(*app.spreadsheet, *app.local.files, request)
#if #defined(PLATFORM_WEB) {
operation: [32]u8
if ServiceText(request, "op", operation[:]) == "save" &&
Json.FieldAt(text, 0, "ok") >= 0 && text[Json.FieldAt(text, 0, "ok")] == cast(u8)116 {
if !BrowserStorageSave() { text = "{\"ok\":false}" }
}
}
if service == "app.bundle.export.v1" { ReturnText(result, ExportBundle(app)); return 1 }
if service == "input.v1" { InputCall(app, request, result); return 1 }
if service == "document.pick.v1" { ReturnText(result, DocumentPick(app, request)); return 1 }
result.* = HostValue.{.kind = cast(s32)HostString, .type_name = HostTextData("string"), .data = HostTextData(text), .length = cast(usize)text.count}
return 1
}
#if !#defined(ANDROID_BUILD) {
if service == "app.bundle.export.v1" { ReturnText(result, ExportBundle(app)); return 1 }
}
if service == "input.v1" { InputCall(app, request, result); return 1 }
if service == "document.pick.v1" { ReturnText(result, DocumentPick(app, request)); return 1 }
}
return AppLocalCall(cast(*void)(*app.local), module, function, arguments, count, result)
}
@@ -384,7 +394,11 @@ AppCall :: (context: *void, module: *u8, function: *u8,
ReturnText(result, "")
return 1
}
derived := Pbkdf2Sha256(ArgumentText(arguments[0]), ArgumentText(arguments[1]), cast(s32)iterations)
// Key derivation has always read at most 508 salt bytes; existing
// vault keys depend on it.
salt := ArgumentText(arguments[1])
if salt.count > 508 { salt = salt[0:508] }
derived := Pbkdf2Sha256(ArgumentText(arguments[0]), salt, cast(s32)iterations)
ReturnBytes(result, derived[:])
for index: 0..31 {
derived[index] = cast(u8)0
@@ -565,7 +579,7 @@ LoadApp :: (id: string, path: string) -> bool {
}
LoadApps :: () {
ids: [BUNDLED_APPS]string = .["pass", "auth", "calculator", "clock"]
ids: [BUNDLED_APPS]string = .["pass", "auth", "calculator", "clock", "workbook"]
root := BundledAppsRoot()
if root == "" {
return
@@ -574,7 +588,7 @@ LoadApps :: () {
file: [64]u8
CopyField(file[:], ids[index])
used := ids[index].count
suffix := ".zib"
suffix := ".zx"
position: s64 = 0
while position < suffix.count {
file[used + position] = suffix[position]
@@ -584,13 +598,9 @@ LoadApps :: () {
path: [PATH_LIMIT]u8
unused LoadApp(ids[index], PathJoin(path[:], root, TextUntilNul(file[:])))
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
workbook_path: [PATH_LIMIT]u8
unused LoadApp("workbook", PathJoin(workbook_path[:], root, "workbook.zib"))
}
entity_path: [PATH_LIMIT]u8
entity_index = app_count
if !LoadApp("entity", PathJoin(entity_path[:], root, "entity.zib")) { entity_index = -1 }
if !LoadApp("entity", PathJoin(entity_path[:], root, "entity.zx")) { entity_index = -1 }
}
EntityAppIndex :: () -> s32 { return entity_index }
@@ -689,42 +699,42 @@ AppWidgetCall :: (context: *void, module: *u8, function: *u8,
}
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
input_text: [8192]u8;
InputCall :: (app: *App, request: string, result: *HostValue) {
if request == "clipboard-has-text" { ReturnText(result, ifx SystemClipboardHasText() then "true" else "false"); return }
if request == "clipboard" {
text := SystemClipboardText(input_text[:])
result.* = HostValue.{.kind = cast(s32)HostString, .type_name = HostTextData("string"), .data = HostTextData(text), .length = cast(usize)text.count}
return
}
if request.count > 0 && request[0] == cast(u8)123 {
operation: [32]u8
used := Json.ReadStringText(request, Json.FieldAt(request, 0, "op"), operation[:])
if used == 7 && TextUntilNul(operation[:]) == "measure" {
content: [8192]u8
length := Json.ReadStringText(request, Json.FieldAt(request, 0, "text"), content[:])
if length >= 0 {
digits: [24]u8
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"width\":%}", Font.GlyphWidth(TextView(content[:length]), 14, ""))
value := BuilderFinish(bytes)
ReturnText(result, value); AppFileFree(value); return
}
input_text: [8192]u8;
InputCall :: (app: *App, request: string, result: *HostValue) {
if request == "clipboard-has-text" { ReturnText(result, ifx ClipboardText(input_text[:]) != "" then "true" else "false"); return }
if request == "clipboard" {
text := ClipboardText(input_text[:])
result.* = HostValue.{.kind = cast(s32)HostString, .type_name = HostTextData("string"), .data = HostTextData(text), .length = cast(usize)text.count}
return
}
if request.count > 0 && request[0] == cast(u8)123 {
operation: [32]u8
used := Json.ReadStringText(request, Json.FieldAt(request, 0, "op"), operation[:])
if used == 7 && TextUntilNul(operation[:]) == "measure" {
content: [8192]u8
length := Json.ReadStringText(request, Json.FieldAt(request, 0, "text"), content[:])
if length >= 0 {
digits: [24]u8
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"width\":%}", Font.GlyphWidth(TextView(content[:length]), 14, ""))
value := BuilderFinish(bytes)
ReturnText(result, value); AppFileFree(value); return
}
}
if request != "frame" { ReturnText(result, "{}"); return }
session := app.portable.session
p := PointerSample(session); q := SecondaryPointerSample(session)
wheel := PointerWheelTake(session, app.portable.bounds)
text: Vec(u8)
BuilderPrint(*text, "{\"x\":%,\"y\":%,\"down\":%,\"pressed\":%,\"released\":%,\"secondary_down\":%,\"secondary_pressed\":%,\"secondary_released\":%,\"wheel\":%}",
cast(s32)p.x, cast(s32)p.y, ifx p.down then 1 else 0, ifx p.pressed then 1 else 0, ifx p.released then 1 else 0,
ifx q.down then 1 else 0, ifx q.pressed then 1 else 0, ifx q.released then 1 else 0, cast(s32)wheel)
value := BuilderFinish(text)
ReturnText(result, value)
AppFileFree(value)
}
if request != "frame" { ReturnText(result, "{}"); return }
session := app.portable.session
p := PointerSample(session); q := SecondaryPointerSample(session)
wheel := PointerWheelTake(session, app.portable.bounds)
text: Vec(u8)
BuilderPrint(*text, "{\"x\":%,\"y\":%,\"down\":%,\"pressed\":%,\"released\":%,\"secondary_down\":%,\"secondary_pressed\":%,\"secondary_released\":%,\"wheel\":%}",
cast(s32)p.x, cast(s32)p.y, ifx p.down then 1 else 0, ifx p.pressed then 1 else 0, ifx p.released then 1 else 0,
ifx q.down then 1 else 0, ifx q.pressed then 1 else 0, ifx q.released then 1 else 0, cast(s32)wheel)
value := BuilderFinish(text)
ReturnText(result, value)
AppFileFree(value)
}
#if !#defined(ANDROID_BUILD) {
// A picker grants just the selected transfer. Bundles never receive an
// arbitrary filesystem path; their editable copy remains in their folder.
DocumentPick :: (app: *App, request: string) -> string {
@@ -741,6 +751,13 @@ AppWidgetCall :: (context: *void, module: *u8, function: *u8,
props.filter = ServiceText(request, "filter", filter_bytes[:])
props.suggested_name = ServiceText(request, "suggested_name", suggestion_bytes[:])
props.save = operation == "export"
#if #defined(PLATFORM_WEB) {
if operation == "export" {
value := AppFileRead(*app.local.files, name)
defer { AppFileFree(value) }
return ifx app.local.files.status == 1 && BrowserDownload(props.suggested_name, value) then "ready" else "error"
}
}
path: [4096]u8
selected := Picker.PickFile(props, path[:])
if selected == 0 { return "cancelled" }
@@ -754,7 +771,10 @@ AppWidgetCall :: (context: *void, module: *u8, function: *u8,
if !file.valid { return "error" }
defer { unused CloseFile(file) }
count := FileSize(file)
if count < 1 || count > 67108864 { return "error" }
#if #defined(PLATFORM_WEB) {
defer { unused RemoveFile(TextUntilNul(path[:])) }
}
if count < 1 || count > APP_DOCUMENT_LIMIT { return "error" }
bytes: Vec(u8)
chunk: [4096]u8
offset: s64 = 0
@@ -763,34 +783,43 @@ AppWidgetCall :: (context: *void, module: *u8, function: *u8,
if used <= 0 { return "error" }
for index: 0..used - 1 { if !VecPush(bytes, chunk[index]) { return "error" } }
offset += used
if offset > 67108864 { return "error" }
if offset > APP_DOCUMENT_LIMIT { return "error" }
}
value := BuilderFinish(bytes)
defer { AppFileFree(value) }
return ifx AppFileWrite(*app.local.files, name, value) then "ready" else "error"
}
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
ExportBundle :: (app: *App) -> string {
} else {
DocumentPick :: (app: *App, request: string) -> string {
if request.count > 4096 { return "error" }
operation: [32]u8
name: [256]u8
CopyField(name[:], TextUntilNul(app.id[:]))
used := TextUntilNul(name[:]).count
suffix := ".zib"
for index: 0..3 { name[used + index] = suffix[index] }
name[used + 4] = 0
path: [4096]u8
props := Picker.FilePickerProps.{.title = "Download app bundle", .filter = "App bundle | *.zib", .save = true, .suggested_name = TextUntilNul(name[:])}
selected := Picker.PickFile(props, path[:])
if selected == 0 { return "cancelled" }
if selected != 1 { return "error" }
return ifx WritePrivate(TextUntilNul(path[:]), app.bytes) then "ready" else "error"
return AndroidDocumentTransfer(*app.local.files, ServiceText(request, "op", operation[:]), ServiceText(request, "name", name[:]))
}
}
#if #defined(PLATFORM_DESKTOP) && !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
ServiceText :: (request: string, field: string, out: []u8) -> string {
count := Json.ReadStringText(request, Json.FieldAt(request, 0, field), out)
return ifx count >= 0 && count < out.count then TextView(out[:count]) else ""
#if !#defined(ANDROID_BUILD) {
ExportBundle :: (app: *App) -> string {
#if #defined(PLATFORM_WEB) {
return ifx BrowserDownload("workbook.zx", app.bytes) then "ready" else "error"
} else {
name: [256]u8
CopyField(name[:], TextUntilNul(app.id[:]))
used := TextUntilNul(name[:]).count
suffix := ".zx"
for index: 0..suffix.count - 1 { name[used + index] = suffix[index] }
name[used + suffix.count] = 0
path: [4096]u8
props := Picker.FilePickerProps.{.title = "Download app bundle", .filter = "App bundle | *.zx", .save = true, .suggested_name = TextUntilNul(name[:])}
selected := Picker.PickFile(props, path[:])
if selected == 0 { return "cancelled" }
if selected != 1 { return "error" }
return ifx WritePrivate(TextUntilNul(path[:]), app.bytes) then "ready" else "error"
}
}
}
ServiceText :: (request: string, field: string, out: []u8) -> string {
count := Json.ReadStringText(request, Json.FieldAt(request, 0, field), out)
return ifx count >= 0 && count < out.count then TextView(out[:count]) else ""
}
+8 -3
View File
@@ -1,5 +1,5 @@
// The browser host. ?app=ID opens a tool at start. Embedded ?mini opens
// the home screen with every tool unless ?app selects one.
// The browser host. ?app=ID opens a tool at start. Embedded ?mini shows
// only the tools, opening on their tiles unless ?app selects one.
#import "werk"
#import "apps"
#import "browser_storage"
@@ -7,6 +7,7 @@
Browser :: #import "kryon/Canvas";
using UI :: #import "kryon/Widgets";
#import "kryon/Frame"
#import "kryon/mini_embed"
// The value of name=VALUE in a query such as "?app=pass&x=1".
QueryValue :: (query: string, name: string) -> string {
@@ -33,6 +34,7 @@ QueryValue :: (query: string, name: string) -> string {
#program_export
main :: () -> s32 {
BrowserShareOpen()
if !BrowserStorageOpen() || !Browser.OpenCanvas() {
return 1
}
@@ -43,9 +45,12 @@ main :: () -> s32 {
}
WerkStart()
query := BrowserQuery()
if MiniModeQuery(query) {
WerkMini()
}
selected := QueryValue(query, "app")
if selected != "" {
unused WerkOpen(selected, QueryValue(query, "mini") != "")
unused WerkOpen(selected)
}
ok: bool = true
while ok && Browser.PollCanvas() {
+88
View File
@@ -3,12 +3,51 @@
// profiles and settings carry over. Without storage (private windows,
// embedded previews) the tools still work; nothing is kept.
#import "web"
#import "std/byte_text_linux"
BROWSER_DATA :: "/pass-data"
sync_done: bool;
sync_failed: bool;
browser_persistent: bool;
shared_waiting: bool;
shared_done: bool;
SharedProfileAttached :: (context: s32, value: s32, second: s32, third: s32) {
if shared_waiting { shared_done = true }
}
SharedProfileLoaded :: (context: s32, event: s32, second: s32, third: s32) {
if !shared_waiting { return }
scope := WebScope()
shared := WebGetObject(WebGlobal, WebName("WaoziAccount"))
promise := WebAsObject(WebCall2(shared, WebName("attach"), WebObject(WebModule), WebNumber(5000.0)))
callback := WebFunction(SharedProfileAttached, 0)
unused WebCall2(promise, WebName("then"), WebObject(callback), WebObject(callback))
WebEnd(scope)
}
// Load the common browser identity before local display preferences. The
// tools remain usable from their offline cache when the hub is unavailable.
BrowserShareOpen :: () {
scope := WebScope()
document := WebGetObject(WebGlobal, WebName("document"))
script := WebAsObject(WebCall1(document, WebName("createElement"), WebText("script")))
loaded := WebFunction(SharedProfileLoaded, 0)
failed := WebFunction(SharedProfileAttached, 0)
shared_waiting = true
shared_done = false
WebSet(script, WebName("src"), WebText("https://account.waozi.xyz/share.js"))
WebSet(script, WebName("onload"), WebObject(loaded))
WebSet(script, WebName("onerror"), WebObject(failed))
unused WebCall1(WebGetObject(document, WebName("head")), WebName("appendChild"), WebObject(script))
// Performance.now is available before the canvas opens.
performance := WebGetObject(WebGlobal, WebName("performance"))
started := WebAsNumber(WebCall0(performance, WebName("now")))
while !shared_done && WebAsNumber(WebCall0(performance, WebName("now"))) - started < 8000.0 { WebSleep(10) }
shared_waiting = false
WebEnd(scope)
}
StorageSynced :: (context: s32, error: s32, second: s32, third: s32) {
sync_failed = !WebIsUndefined(WebValueOf(error))
@@ -55,6 +94,9 @@ BrowserStorageOpen :: () -> bool {
}
WebEnd(scope)
browser_persistent = mounted && BrowserSync(true)
scope = WebScope()
WebSet(WebModule, WebName("sharedAccountMounted"), WebBool(browser_persistent))
WebEnd(scope)
return true
}
@@ -63,6 +105,27 @@ BrowserStorageSave :: () -> bool {
return browser_persistent && BrowserSync(false)
}
// Download only bytes the host has already read from the app's own folder.
BrowserDownload :: (name: string, bytes: string) -> bool {
scope := WebScope()
defer WebEnd(scope)
descriptor := cast(*TextDescriptor)(*bytes)
data := WebBytes(WebBytesUint8, cast(*void)descriptor.data, cast(s32)bytes.count)
parts := WebNewArray()
unused WebCall1(parts, WebName("push"), WebObject(data))
blob := WebNew1(WebGetObject(WebGlobal, WebName("Blob")), WebObject(parts))
urls := WebGetObject(WebGlobal, WebName("URL"))
url := WebCall1(urls, WebName("createObjectURL"), WebObject(blob))
document := WebGetObject(WebGlobal, WebName("document"))
anchor := WebAsObject(WebCall1(document, WebName("createElement"), WebText("a")))
WebSet(anchor, WebName("href"), url)
WebSet(anchor, WebName("download"), WebText(name))
unused WebCall0(anchor, WebName("click"))
ok := !WebFailed()
unused WebCall1(urls, WebName("revokeObjectURL"), url)
return ok
}
BrowserDark :: () -> bool {
scope := WebScope()
media := WebAsObject(WebCall1(WebGlobal, WebName("matchMedia"), WebText("(prefers-color-scheme: dark)")))
@@ -91,3 +154,28 @@ BrowserQuery :: () -> string {
}
return TextView(page_text[0:index])
}
BrowserSharedProfile :: (output: []u8) -> string {
scope := WebScope()
defer WebEnd(scope)
value := WebGet(WebModule, WebName("sharedProfileDocument"))
if value.tag != WebStringTag { return "" }
length := WebCopyString(WebAsObject(value), output)
if length <= 0 || length >= cast(s32)output.count { return "" }
return TextView(output[:length])
}
BrowserSharedReady :: () -> bool {
scope := WebScope()
defer WebEnd(scope)
return WebAsBool(WebGet(WebModule, WebName("sharedAccountReady"))) &&
WebAsBool(WebGet(WebModule, WebName("sharedAccountInitialized")))
}
BrowserOpenProfile :: () {
unused BrowserStorageSave()
scope := WebScope()
location := WebGetObject(WebGlobal, WebName("location"))
unused WebCall1(location, WebName("assign"), WebText("https://entity.waozi.xyz/"))
WebEnd(scope)
}
+2 -2
View File
@@ -8,8 +8,8 @@
#import "std/text_buffer"
#import "std/number_text"
#import "std/timer_linux"
#import "totp"
#import "exports"
#import "auth/totp"
#import "auth/exports"
Platform :: #import "platform";
Accounts :: #import "account";
Records :: #import "records";
+13 -2
View File
@@ -6,6 +6,7 @@ Command :: #import "command";
Desktop :: #import "kryon/Desktop";
using UI :: #import "kryon/Widgets";
#import "kryon/Frame"
#import "kryon/mini_embed"
sdl :: #system_library "SDL2";
SetEnvironment :: (name: *u8, value: *u8, overwrite: s32) -> s32 #foreign sdl "SDL_setenv";
@@ -89,9 +90,19 @@ main :: (argc: s32, argv: **u8) -> s32 {
return 1
}
WerkStart()
// `werk --mini` shows only the tools, as a page's ?mini embed does.
arguments: [16]string
count: s64 = 0
while count < cast(s64)argc && count < arguments.count {
arguments[count] = TextFromCString(argv[count])
count += 1
}
if MiniModeArgument(arguments[0:count]) {
WerkMini()
}
// `werk --app auth` opens one tool first, as Harmony's Auth entry does.
if argc >= 3 && TextFromCString(argv[1]) == "--app" {
if !WerkOpen(TextFromCString(argv[2]), false) {
if !WerkOpen(TextFromCString(argv[2])) {
Report("Werkzeug: app is unavailable\n")
SessionClose(session)
Desktop.CloseDesktop()
@@ -100,7 +111,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
}
if argc >= 3 && TextFromCString(argv[1]) == "--bundle" {
index := LoadExternalApp(TextFromCString(argv[2]))
if index < 0 || !WerkOpen(AppId(index), false) {
if index < 0 || !WerkOpen(AppId(index)) {
Report("Werkzeug: incompatible app bundle\n")
SessionClose(session)
Desktop.CloseDesktop()
+21
View File
@@ -14,6 +14,27 @@ Entity :: #import "entity/model";
entity_document: string;
#if #defined(PLATFORM_WEB) {
#import "browser_storage"
shared_browser_profile: [65536]u8;
WerkSharedBrowserProfile :: () {
text := BrowserSharedProfile(shared_browser_profile[:])
state: Entity.EntityState
if text == "" {
if !BrowserSharedReady() { return }
state = Entity.EntityDefault()
} else if !Entity.EntityDecode(text, *state) || state.owner_id[0] == cast(u8)0 { return }
profile.name = state.name
profile.picture = state.picture
profile.theme_mode = state.theme
profile.accent = state.accent
profile.material = state.material
profile.nodes = state.nodes
profile.node_count = state.node_count
profile.node = state.nodes[state.preferred]
}
}
WerkEntityRead :: () -> string {
Entity.EntityFree(entity_document)
state := Entity.EntityDefault()
+80 -4
View File
@@ -15,7 +15,19 @@ Launcher :: #import "apps/launcher";
Controller :: #import "apps/controller";
Rules :: #import "apps/protocol";
AppsControllerSha256 :: "8c5806d7ff5a4fdaf6b98a7668acbf0aad236ece1d5e68ffe1f7b268a1afb077";
#if #defined(ANDROID_BUILD) {
home_log :: #system_library "log";
HomeAndroidLog :: (priority: s32, tag: *u8, message: *u8) -> s32 #foreign home_log "__android_log_write";
HomeReport :: (message: string) {
tag: [16]u8
text: [128]u8
if CopyCString("Werkzeug", tag[:]) && CopyCString(message, text[:]) {
unused HomeAndroidLog(6, *tag[0], *text[0])
}
}
}
AppsControllerSha256 :: "f6f4eed8f5234c35a7ab2ca0b316c4bbdedf620ecfc22f157b8838c4258934f0";
HomePreference :: struct {
title: [256]u8
@@ -42,6 +54,7 @@ HomeState :: struct {
has_pending: bool
loaded: bool
unavailable: bool
frame_failure_reported: bool
}
home: HomeState;
@@ -209,7 +222,7 @@ HomeAssetAllowed :: (path: string) -> bool { return path == "" }
HomeCards :: (context: *void, indices: []s32, bounds: Rectangle,
input: TextFieldInput, section_break: s32, columns: s32) -> bool {
bytes: Vec(u8)
BuilderPrint(*bytes, "\"title\":\"Werkzeug\",\"locale\":\"en\",\"presentation\":{\"mode\":\"%\",\"columns\":%",
BuilderPrint(*bytes, "\"title\":\"Werkzeug\",\"locale\":\"en\",\"presentation\":{\"mode\":\"%\",\"hide_sizes\":true,\"columns\":%",
ifx home.view.grid then "icon" else "list", columns)
if section_break >= 0 { BuilderPrint(*bytes, ",\"section_break\":%", section_break) }
BuilderPrint(*bytes, "},\"children\":[")
@@ -258,11 +271,20 @@ SharedHome :: (session: Session, bounds: Rectangle, dark: bool, selected: s32,
if home.unavailable { return false }
if !home.controller.ready {
path: [PATH_LIMIT]u8
bytes, found := ReadBundle(PathJoin(path[:], BundledAppsRoot(), "apps.zib"))
if !found { home.unavailable = true; return false }
bytes, found := ReadBundle(PathJoin(path[:], BundledAppsRoot(), "apps.zx"))
if !found {
#if #defined(ANDROID_BUILD) {
HomeReport("Apps controller asset could not be read")
}
home.unavailable = true
return false
}
home.bytes = bytes
if !Controller.AppControllerOpen(*home.controller, home.bytes, AppsControllerSha256,
Controller.AppControllerPlatform.{.service = HomeService, .widgets = HomeWidgets}) {
#if #defined(ANDROID_BUILD) {
HomeReport("Apps controller could not be opened")
}
home.unavailable = true
return false
}
@@ -294,8 +316,62 @@ SharedHome :: (session: Session, bounds: Rectangle, dark: bool, selected: s32,
HomeDrain()
AppFileFree(home.response)
home.response = ""
if !result.ran && !home.frame_failure_reported {
#if #defined(ANDROID_BUILD) {
HomeReport("Apps controller could not render its frame")
}
home.frame_failure_reported = true
}
return result.ran
}
SharedHomeOpened :: () -> s32 { return home.opened }
SharedHomeKeyboard :: () -> bool { return home.view.focused || home.controller.app.keyboard }
// Mini mode's Home: only the tools, as large tiles laid out in the columns
// that keep them closest to square. Returns the tool tapped, or -1.
MiniHome :: (session: Session, bounds: Rectangle) -> s32 {
if !home.loaded { HomeLoad() }
count: s32
tools: [APP_LIMIT]s32
for index: cast(s32)0..AppCount() - 1 {
if AppId(index) == "entity" { continue }
tools[count] = index
count += 1
}
if count == 0 { return -1 }
gap: float32 = 12.0
area := Rectangle.{bounds.x + 16.0, bounds.y + 16.0, bounds.width - 32.0, bounds.height - 32.0}
columns: s32 = 1
best: float32 = 0.0
for choice: cast(s32)1..count {
rows := (count + choice - 1) / choice
width := (area.width - gap * cast(float32)(choice - 1)) / cast(float32)choice
height := (area.height - gap * cast(float32)(rows - 1)) / cast(float32)rows
shape := ifx width < height then width / height else height / width
if shape > best {
best = shape
columns = choice
}
}
rows := (count + columns - 1) / columns
width := (area.width - gap * cast(float32)(columns - 1)) / cast(float32)columns
height := (area.height - gap * cast(float32)(rows - 1)) / cast(float32)rows
// A large window keeps tiles a comfortable size, centred.
if width > 240.0 { width = 240.0 }
if height > 240.0 { height = 240.0 }
left := area.x + (area.width - width * cast(float32)columns - gap * cast(float32)(columns - 1)) * 0.5
top := area.y + (area.height - height * cast(float32)rows - gap * cast(float32)(rows - 1)) * 0.5
opened: s32 = -1
for at: cast(s32)0..count - 1 {
index := tools[at]
tile := ButtonProps.{.key = cast(u64)(31000 + at), .id = 31000 + at, .label = HomeTitle(index),
.icon_shape = HomeIcon(index), .icon_placement = IconPlacement.IconPlacementAbove,
.size = ControlSize.ControlSizeLarge, .fit_content = true,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft,
.bounds = Rectangle.{left + cast(float32)(at % columns) * (width + gap),
top + cast(float32)(at / columns) * (height + gap), width, height}}
if Button(session, tile) != 0 { opened = index }
}
return opened
}
+11 -1
View File
@@ -27,6 +27,10 @@ using UI :: #import "kryon/Widgets";
libc :: #system_library "libc";
Environment :: (name: *u8) -> *u8 #foreign libc "getenv";
ExecutableLink :: (path: *u8, output: *u8, limit: usize) -> isize #foreign libc "readlink";
#if #defined(ANDROID_BUILD) {
CanonicalDirectory :: (path: *u8, output: *u8) -> *u8 #foreign libc "realpath";
FreeDirectory :: (path: *void) #foreign libc "free";
}
data_root: [PATH_LIMIT]u8;
cache_root: [PATH_LIMIT]u8;
@@ -68,7 +72,13 @@ DataRoot :: () -> string {
#if #defined(ANDROID_BUILD) {
internal := ActivityInternalDataPath()
if internal != null {
unused CopyCString(TextFromCString(internal), data_root[:])
// Android aliases /data/user/0 and /data/data. Resolve the
// trusted activity root before enforcing private file paths.
canonical := CanonicalDirectory(internal, null)
if canonical != null {
unused CopyCString(TextFromCString(canonical), data_root[:])
FreeDirectory(cast(*void)canonical)
}
}
} else #if #defined(PLATFORM_WEB) {
unused CopyCString(BROWSER_DATA, data_root[:])
+1 -1
View File
@@ -1 +1 @@
Version :: "0.4.2";
Version :: "0.4.7";
+47 -12
View File
@@ -14,6 +14,10 @@ using UI :: #import "kryon/Widgets";
#import "platform"
#import "migrate"
#import "node_url"
#if #defined(PLATFORM_WEB) {
#import "browser_storage"
#import "entity_host"
}
#if #defined(ANDROID_BUILD) {
#import "android_fields"
}
@@ -40,7 +44,8 @@ screen: s32;
entity_account: bool;
entity_reload: bool;
open_app: s32 = -1;
// Started in a page embedding the toolkit, with navigation still available.
// Mini mode, from a page's ?mini or the desktop's --mini, keeps only the
// tools: Home is their tiles alone, and nothing leads to Profile.
mini: bool;
name_field: FieldState;
code_field: FieldState;
@@ -60,6 +65,7 @@ secret_snapshot: [17664]u8;
forget_pending: bool;
choosing_picture: bool;
profile_scroll: s32;
profile_content_height: s32 = 760;
// Where Profile's focused field was drawn, so Profile can scroll it into
// view when it gains focus or the keyboard changes the visible height.
focused_top: float32;
@@ -71,6 +77,9 @@ keyboard_wanted: bool;
WerkStart :: () {
MigratePassData()
LoadProfile()
#if #defined(PLATFORM_WEB) {
WerkSharedBrowserProfile()
}
unused CopyCString(ProfileNode(), node_text[:])
LoadApps()
#if !#defined(PLATFORM_WEB) {
@@ -78,9 +87,13 @@ WerkStart :: () {
}
}
// Opens an app by id at start, such as from the page address. In mini mode
// the host keeps navigation so every tool remains available.
WerkOpen :: (id: string, alone: bool) -> bool {
WerkMini :: () {
mini = true
}
// Opens an app by id at start, such as from the page address. Back still
// leads Home, so every tool remains available.
WerkOpen :: (id: string) -> bool {
index: s32 = 0
while index < AppCount() {
if AppId(index) == id {
@@ -89,7 +102,6 @@ WerkOpen :: (id: string, alone: bool) -> bool {
}
open_app = index
screen = SCREEN_APP
mini = alone
return true
}
index += 1
@@ -179,6 +191,12 @@ TopBar :: (session: Session, viewport: Rectangle) {
.image = PictureImage(profile.picture, Rectangle.{}),
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if Button(session, avatar) != 0 {
#if #defined(PLATFORM_WEB) {
// Home already saved the tool that was closed. The shared
// library controller has no tool records to save here.
BrowserOpenProfile()
return
}
screen = SCREEN_PROFILE
entity_account = false
entity_reload = true
@@ -187,6 +205,14 @@ TopBar :: (session: Session, viewport: Rectangle) {
}
Home :: (session: Session, area: Rectangle, input: TextFieldInput, key: s32, modifiers: s32) {
if mini {
opened := MiniHome(session, area)
if opened >= 0 {
open_app = opened
screen = SCREEN_APP
}
return
}
if SharedHome(session, area, ProfileDark(), open_app, input, key, modifiers) {
opened := SharedHomeOpened()
if opened >= 0 {
@@ -332,10 +358,13 @@ ProfileScreen :: (session: Session, area: Rectangle, input: TextFieldInput, key:
width := area.width - 32.0
scroll := Scroll(session, ScrollProps.{.key = cast(u64)40,
.bounds = Rectangle.{area.x + 16.0, area.y, width, area.height},
.content_height = 760, .scroll_offset = profile_scroll})
.content_height = profile_content_height, .scroll_offset = profile_scroll})
profile_scroll = scroll.scroll_offset
if scroll.opened {
SyncSection(session, scroll.content.x, scroll.content.y + 16.0, scroll.content.width - 12.0, input)
bottom := SyncSection(session, scroll.content.x, scroll.content.y + 16.0, scroll.content.width - 12.0, input)
height := cast(s32)(bottom - scroll.content.y + 16.0)
if height < 0 { height = 0 }
profile_content_height = height
unused End(session)
}
keyboard_wanted = code_field.focused || account_key_field.focused || passphrase_field.focused
@@ -357,6 +386,7 @@ ProfileScreen :: (session: Session, area: Rectangle, input: TextFieldInput, key:
unused CopyCString(ProfileNode(), node_text[:])
entity_account = true
profile_scroll = 0
profile_content_height = 760
}
}
@@ -531,11 +561,12 @@ SaveNode :: () -> bool {
// The account that syncs Auth: create one, connect to one, or connect
// another device to it.
SyncSection :: (session: Session, x: float32, y: float32, width: float32, input: TextFieldInput) {
SyncSection :: (session: Session, x: float32, y: float32, width: float32, input: TextFieldInput) -> float32 {
Heading(session, cast(u64)46, "Account", x, y, width)
y += 32.0
#if #defined(PLATFORM_WEB) {
Note(session, cast(u64)47, "Sync Auth between your devices in the desktop and Android apps.", x, y, width)
return y + 48.0
} else {
half := (width - 8.0) / 2.0
phase := LinkPhaseNow()
@@ -549,7 +580,7 @@ SyncSection :: (session: Session, x: float32, y: float32, width: float32, input:
if Action(session, 72, "Cancel", Rectangle.{x, y + 28.0, width, 40.0}, false) {
LinkCancel()
}
return
return y + 76.0
}
if Action(session, 70, "Create account", Rectangle.{x, y, width, 40.0}, false) {
if !SaveNode() || !CreateAccount() {
@@ -603,7 +634,7 @@ SyncSection :: (session: Session, x: float32, y: float32, width: float32, input:
Label(session, cast(u64)86, TextUntilNul(account_key_status[:]), Rectangle.{x, y, width, 20.0}, 14)
}
}
return
return y + 48.0
}
Label(session, cast(u64)80, AccountServer(), Rectangle.{x, y, width, 24.0}, 14)
y += 32.0
@@ -666,6 +697,7 @@ SyncSection :: (session: Session, x: float32, y: float32, width: float32, input:
forget_pending = true
}
}
return y + 48.0
}
}
@@ -708,8 +740,11 @@ WerkFrame :: (session: Session, viewport: Rectangle) -> s32 {
Box(session, background)
keyboard_wanted = false
content := viewport
TopBar(session, viewport)
content = Rectangle.{viewport.x, viewport.y + BAR_HEIGHT, viewport.width, viewport.height - BAR_HEIGHT}
// Mini Home is the tool tiles alone, without the bar.
if !mini || screen != SCREEN_HOME {
TopBar(session, viewport)
content = Rectangle.{viewport.x, viewport.y + BAR_HEIGHT, viewport.width, viewport.height - BAR_HEIGHT}
}
if screen == SCREEN_HOME {
Home(session, content, input, key, modifiers)
} else if screen == SCREEN_PROFILE {
+20 -41
View File
@@ -4,62 +4,41 @@ set -eu
root_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
out_dir="$root_dir/build/site"
# werk.waozi.xyz is the web app itself. Downloads keep their addresses
# through _redirects, and the app's earlier /app/ address forwards here.
rm -rf "$out_dir"
mkdir -p "$out_dir/app"
# Versioned asset names (AppImage, .deb) are templated into index.html from
# VERSION so the site always links the current release.
version=$(sed -n '1p' "$root_dir/VERSION")
if [ -z "$version" ]; then
echo "Could not read the version from VERSION" >&2
exit 1
fi
sed "s/\${version}/$version/g" "$root_dir/web/site/index.html" > "$out_dir/index.html"
cp "$root_dir/web/site/styles.css" "$out_dir/styles.css"
cp -R "$root_dir/web/site/assets" "$out_dir/assets"
cp -R "$root_dir/web/site/images" "$out_dir/images"
cp "$root_dir/web/site/app/index.html" "$out_dir/app/index.html"
cp "$root_dir/web/site/CNAME" "$out_dir/CNAME"
cp "$root_dir/web/site/robots.txt" "$out_dir/robots.txt"
cp "$root_dir/web/site/sitemap.xml" "$out_dir/sitemap.xml"
cp "$root_dir/web/site/_redirects" "$out_dir/_redirects"
cp "$root_dir/web/site/_headers" "$out_dir/_headers"
cp "$root_dir/web/site/manifest.webmanifest" "$out_dir/manifest.webmanifest"
mkdir -p "$out_dir"
for name in CNAME robots.txt sitemap.xml _redirects _headers manifest.webmanifest; do
cp "$root_dir/web/site/$name" "$out_dir/$name"
done
cp -R "$root_dir/web/site/icons" "$out_dir/icons"
cp -R "$root_dir/web/site/app/icons" "$out_dir/app/icons"
"${MAKE:-make}" -C "$root_dir" web-canvas
cp "$root_dir/build/web-app/index.html" "$out_dir/app/index.html"
cp "$root_dir/build/web-app/sw.js" "$out_dir/app/sw.js"
cp "$root_dir/build/web-app/index.js" "$out_dir/app/index.js"
cp "$root_dir/build/web-app/index.wasm" "$out_dir/app/index.wasm"
cp "$root_dir/assets/fonts/emoji-OFL.txt" "$out_dir/app/emoji-OFL.txt"
for name in index.html sw.js index.js index.wasm; do
cp "$root_dir/build/web-app/$name" "$out_dir/$name"
done
cp "$root_dir/assets/fonts/emoji-OFL.txt" "$out_dir/emoji-OFL.txt"
test -s "$out_dir/app/index.wasm"
test -s "$out_dir/index.wasm"
printf 'built site at %s\n' "$out_dir"
python3 - "$out_dir" <<'META'
import hashlib, json, sys
from pathlib import Path
root = Path(sys.argv[1])
manifest = json.loads((root / "manifest.webmanifest").read_text())
manifest.update(start_url=".", scope=".")
for icon in manifest.get("icons", []):
icon["src"] = icon["src"].lstrip("/")
(root / "app/manifest.webmanifest").write_text(json.dumps(manifest, indent=2) + "\n")
app = root / "app"
wasm = (app / "index.wasm").read_bytes()
wasm = (root / "index.wasm").read_bytes()
wasm_name = "index-" + hashlib.sha256(wasm).hexdigest()[:16] + ".wasm"
(app / wasm_name).write_bytes(wasm)
loader = (app / "index.js").read_text()
(root / wasm_name).write_bytes(wasm)
loader = (root / "index.js").read_text()
assert loader.count('"index.wasm"') == 1, "Expected one Wasm URL in the generated loader"
loader = loader.replace('"index.wasm"', json.dumps(wasm_name))
js_name = "index-" + hashlib.sha256(loader.encode()).hexdigest()[:16] + ".js"
(app / js_name).write_text(loader)
(app / "index.js").write_text(loader)
html = (app / "index.html").read_text()
(root / js_name).write_text(loader)
(root / "index.js").write_text(loader)
html = (root / "index.html").read_text()
assert html.count('src="index.js"') == 1
(app / "index.html").write_text(html.replace('src="index.js"', 'src="' + js_name + '"'))
(root / "index.html").write_text(html.replace('src="index.js"', 'src="' + js_name + '"'))
assets = ["./", js_name, wasm_name, "sw.js", "icons/icon-192.png", "icons/icon-512.png", "manifest.webmanifest", "assets.json"]
(app / "assets.json").write_text(json.dumps(assets) + "\n")
(root / "assets.json").write_text(json.dumps(assets) + "\n")
with (root / "_headers").open("a") as headers:
for name in [js_name, wasm_name]:
headers.write("\n/app/" + name + "\n Cache-Control: public, max-age=31536000, immutable\n")
headers.write("\n/" + name + "\n Cache-Control: public, max-age=31536000, immutable\n")
META
+6 -6
View File
@@ -1,12 +1,12 @@
/app/
/
Cache-Control: no-cache
/app/index.html
/index.html
Cache-Control: no-cache
/app/index.js
/index.js
Cache-Control: no-cache
/app/index.wasm
/index.wasm
Cache-Control: no-cache
/app/sw.js
/sw.js
Cache-Control: no-cache
/app/assets.json
/assets.json
Cache-Control: no-cache
+4
View File
@@ -6,3 +6,7 @@
/downloads/pass-gui-linux-arm64.tar.gz https://github.com/waozixyz/werk/releases/latest/download/werk-linux-arm64.tar.gz 302
/downloads/werk-android.apk https://github.com/waozixyz/werk/releases/latest/download/werk-android.apk 302
/downloads/pass-android.apk https://github.com/waozixyz/werk/releases/latest/download/werk-android.apk 302
# The web app moved from /app/ to the site itself.
/app / 301
/app/* / 301
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 208 KiB

-62
View File
@@ -1,62 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Werkzeug</title>
<meta name="theme-color" content="#f7ede2">
<link rel="manifest" href="manifest.webmanifest">
<link rel="icon" type="image/png" sizes="32x32" href="/icons/favicon-32.png">
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">
<script>
const previewQuery = new URLSearchParams(location.search);
if (previewQuery.has('mini') && previewQuery.get('theme') === 'waozi') {
document.documentElement.dataset.embedTheme = 'waozi';
document.querySelector('meta[name="theme-color"]').content = '#f7f3eb';
}
</script>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #f7ede2;
color: #4a4038;
font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
}
.canvas-stage, .canvas-frame {
position: fixed;
inset: 0;
width: 100vw;
height: 100vh;
height: 100dvh;
overflow: hidden;
background: #f7ede2;
}
canvas.emscripten {
position: absolute;
inset: 0;
width: 100% !important;
height: 100% !important;
border: 0;
outline: 0;
background: #f7ede2;
}
:root[data-embed-theme="waozi"],
:root[data-embed-theme="waozi"] body,
:root[data-embed-theme="waozi"] .canvas-stage,
:root[data-embed-theme="waozi"] .canvas-frame,
:root[data-embed-theme="waozi"] canvas { background: #f7f3eb; color: #202c29; }
</style>
</head>
<body>
<div class="canvas-stage">
<div class="canvas-frame" id="canvas-frame">
<canvas class="emscripten" id="canvas" width="720" height="740" tabindex="-1"></canvas>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
@@ -1,93 +0,0 @@
Copyright 2018 The Manrope Project Authors (https://github.com/googlefonts/manrope)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -1,93 +0,0 @@
Copyright 2020 The Newsreader Project Authors (http://github.com/productiontype/Newsreader)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
-12
View File
@@ -1,12 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 70" width="1200" height="700">
<g fill="none" stroke="#315e48" stroke-width="2.4" stroke-linecap="round">
<path d="M60 62 C60 40 60 28 60 14"/>
<path d="M60 30 C48 28 40 20 38 8 C50 10 58 18 60 30"/>
<path d="M60 30 C72 28 80 20 82 8 C70 10 62 18 60 30"/>
<path d="M60 44 C44 42 34 34 30 20 C44 22 56 32 60 44"/>
<path d="M60 44 C76 42 86 34 90 20 C76 22 64 32 60 44"/>
<path d="M60 56 C40 54 26 44 20 26 C38 30 54 42 60 56"/>
<path d="M60 56 C80 54 94 44 100 26 C82 30 66 42 60 56"/>
<path d="M28 62 C40 60 80 60 92 62"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 628 B

Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more