117 Commits
Author SHA1 Message Date
waoziandClaude Opus 5.5 7967b90b99 Fix the Android release build, browser smoke test and IR core test in CI
The release passes the liboqs and Monocypher sources to Gradle as make does,
the browser test reads the browser CI names and waits for Chromium's first
tab, and the saved-IR test roots its module where every toolchain writes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 15:35:27 -03:00
waoziandClaude Opus 5.5 d54c5c5b19 Keep the Werkzeug name, add its wrench logo and move to werk.waozi.xyz
Werkzeug stays the app's name; werk is its short form for the repository,
files, packages and the werk.waozi.xyz website. A new logo, a wrench with
a keyhole, replaces Pass's asterisk on every icon and image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 15:17:37 -03:00
waoziandClaude Opus 5.5 4ecabd56d2 Rename Werkzeug to Werk
The app, its window and launcher, packages, release files, website,
store listing, wordmarks and source now say Werk; the GitHub repository
is waozixyz/werk and the itch.io page waozi.itch.io/werk. Daochi keeps the
registered app id and record domains under the former name, and Android
keeps the package xyz.waozi.pass, so devices stay linked and installs
update in place.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 15:07:10 -03:00
waoziandClaude Opus 5.5 68f9187776 Call the website and web app Werkzeug instead of Pass
The landing page, link previews, web app title and install manifest name
Werkzeug and its tools. The Android note says the Internet is used only
for optional Auth sync, and the wordmark images read Werkzeug.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 14:57:30 -03:00
waoziandClaude Opus 5.5 6ff30ee6b1 Keep Profile's code field above the keyboard on Android 10 and older
Kryon 159563f4 measures the keyboard from the window's visible frame where
older Android reports it only there. Checked on a Moto e6 play (Android 9):
the sync code field stays above the keyboard, and the phone rejoined an
account with a typed code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 10:50:54 -03:00
waoziandClaude Opus 5.5 7ec153aa5c Keep Profile's focused field above the keyboard
The sync code field sits low in Profile, and the keyboard covered it while
you typed a code: the visible area shrank but the scroll stayed put.
Profile now scrolls the focused field just into view when it gains focus
and whenever the visible height changes, as when the keyboard opens, and
leaves scrolling by hand alone. Checked on an Android 15 emulator: the
field and Connect stay above the keyboard while typing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 10:43:24 -03:00
waoziandClaude Opus 5.5 f61c65b440 Type in order in Profile's fields on Android, and sync over Kryon's HTTP
Profile's name and sync code fields drew with the caret from before the
keyboard's last letter and sent that caret back to the editor, so every
letter landed at the start: a typed code arrived reversed and the phone
waited forever on a connection nobody answered. The fields now read the
editor's text and caret before they draw (AndroidFieldRead) and send their
own afterwards (AndroidFieldSubmit), like the tools' fields already did.

Kryon e52a91c1 lets an app without Java make HTTP requests, so sync now
works on Android. Tested against api.waozi.xyz: an Android 15 emulator
created an account and connected a desktop; a Moto e6 play (Android 9,
32-bit) joined with a typed code; Auth records and removals arrived in
every direction.

The Android input test reads the status and navigation bar insets instead
of assuming the app fills the screen, accepts Android 13's activity dump,
and types a profile name, which fails without this fix. The sync test tool
gains add and present for checks against a phone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 10:39:34 -03:00
waoziandClaude Opus 5.5 808c692026 Sync Auth between the owner's devices through Daochi
Profile → Sync creates a Daochi account, or connects to the account of
another device with a 12-character code, and then keeps Auth's accounts
on every device.

- Tools keep small synced records through new host calls (RecordList,
  RecordRead, RecordWrite, RecordRemove, RecordsVersion). Auth stores
  each account as one, moving its old accounts.txt over once.
- The host seals each record with XChaCha20-Poly1305 under a random
  vault key. The sealed text holds the change time and whether the
  record was removed, and the seal covers the account, collection,
  record and key, so the server can neither read, forge nor reorder a
  change. The newest change wins.
- The ML-DSA-44 account key (liboqs) signs in and, with each device's
  own Ed25519 key, signs every sync (daochi-client, protocol 6, paged
  encrypted records).
- Connecting a device swaps X25519 keys through Daochi's link mailbox;
  the account and vault keys travel sealed with a key derived from the
  exchange and the code, so the node cannot open or replace them.
- The werkzeug app is registered on api.waozi.xyz with a signed
  manifest (scripts/register_daochi_app.py).
- scripts/sync_e2e_test.sh runs two devices against a local node:
  account, connected device, record and removal; the node never stores
  the test secret in plain text.

The Android build gains INTERNET for sync, liboqs and Monocypher. The
web build leaves sync out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 02:46:48 -03:00
waoziandClaude Opus 5.5 025c2a5ca8 Keep Werkzeug clear of Android's navigation bar, with Inbe's font
Tested on a Moto e6 play (Android 9, 32-bit, 3-button navigation):

- The app read no window insets, so the bottom of every screen sat under
  the navigation bar. It now reads them each frame through Kryon's
  PollAndroidWindowInsets and paints the bar strips, as Inbe does.
- Android 9 cannot name a system font and the APK's font did not load, so
  text used raylib's pixel font. The APK and the browser now carry Noto
  Sans, Inbe's font, cut from Kryon's copy to the characters Werkzeug
  draws (Latin, the secret mask, × ÷ −).
- Auth showed the code for 1970 on 32-bit phones; the locked Ziran reads
  the wall clock correctly there. Empty secret fields show their hint
  instead of dots.
- Calculator's delete key is an icon, since the font has no ⌫.
- The profile button shows the name, or Profile, beside the picture.

Locks Kryon f850a301 and Ziran 201be10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 02:22:45 -03:00
waoziandClaude Opus 5.5 247d7d63ee Run Werkzeug on Android and in the browser, and release it as 0.3.0
The Android app keeps its package, so it updates Pass in place: Pass's
saved profiles, settings, theme and master password carry over, every
tool types through the Android keyboard, and the interface uses the
system font. The browser app opens Werkzeug, a single tool with ?app=,
and Pass alone with ?mini for pages that embed it. Desktop installs keep
the tool bundles in lib/werkzeug, and the packages, store listing and
release files are named Werkzeug. The Plan 9 port keeps the pass
command.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 01:02:49 -03:00
waoziandClaude Opus 5.5 ee6609dad0 Turn Pass into Werkzeug: a home screen running separate tool apps
Werkzeug opens Pass, Auth, Calculator and Clock from a home screen.
Each tool is its own bundle in apps/, preinstalled with Werkzeug, and
keeps its files, assets and secret to itself. Pass keeps its LessPass
passwords, profiles and settings; the host derives its keys natively.
Auth shows two-factor codes from otpauth links or secret keys and
copies them for 30 seconds. The profile holds a name, a picture and the
appearance every tool shares. This commit brings the desktop app; the
Android and browser hosts follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 00:22:41 -03:00
waozi 32f1ad00ba Keep Pass compact and center bounded forms when resizing 2026-10-11 12:19:49 -03:00
waozi 3007696783 Use vanilla Kryon styling and hover cursors 2026-10-11 11:54:09 -03:00
waozi 4fcd59890b Build Pass with current Kryon and Ziran 2026-10-11 11:25:14 -03:00
waoziandClaude Opus 5.5 eecbb33f18 Introduce the purple asterisk and keyhole logo for Pass 0.2.10
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 19:10:13 -03:00
waozi 41587d7f0f Restore saved CLI profiles, vault unlocking and clipboard copying 2026-10-07 16:11:17 -03:00
waoziandClaude Opus 5.5 72fc32b970 Ignore the local Wrangler deploy cache
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 16:57:47 -03:00
waozi c6e7977396 Gate site deployments on browser and cache upgrade checks 2026-09-30 23:39:18 -03:00
waozi 7a5c147d64 Keep cached browser loaders paired with their Wasm build 2026-09-30 22:53:32 -03:00
waozi eceaa0380b Clarify full-version actions and expose verified downloads 2026-09-30 22:40:45 -03:00
waozi 9493b9e01d Keep the browser generator rendering when storage is unavailable 2026-09-30 22:40:01 -03:00
waozi 74d19b7cf8 Add Waozi palette for portfolio mini previews 2026-09-30 22:05:30 -03:00
waozi d092192325 Route native project commands through the Pass desktop host 2026-09-30 17:48:33 -03:00
waozi b9d1e1bd35 Port Pass GUI and CLI to native Plan 9 libdraw in Ziran 2026-09-30 01:40:23 -03:00
waozi 1818096275 Allow desktop test startup time and capture failure diagnostics 2026-09-29 21:49:13 -03:00
waozi 78fe91d184 Fix browser copying and verify generated passwords across platforms 2026-09-29 21:43:20 -03:00
waoziandClaude Opus 5.5 eed4c75706 Check the expected password and clipboard in browser and Android tests
The browser test now types a master password, checks the generated password
against the LessPass reference, and checks that Copy reaches the system
clipboard, is cleared later, and leaves other clipboard text alone. The
Android input test checks the same generated password.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-29 21:43:17 -03:00
waoziandClaude Opus 5.5 d4c0f367f9 Test desktop typing, generation, clipboard, and profiles on Xvfb
make gui-input-test drives the desktop app on a private Xvfb display: typing
into the fields, the expected LessPass password, the clipboard, and saving,
restarting with, and deleting a profile. e2e now runs it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-29 21:39:51 -03:00
waoziandClaude Opus 5.5 fdeea88672 Add a mini mode with only the generator
Pass opened with ?mini in the page address, or started with --mini on the
desktop, shows only the generator: site, login, master password, the
password, and Copy, without profiles, settings, or generation options. An
expand button in the top-right corner opens the full app: a page opens it
in a new tab without ?mini, and the phone-sized desktop window grows into
the full window in place.

Also update Kryon, which now opens desktop windows at a chosen size, and
add the MingCute icon package for the expand icon.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-29 21:29:34 -03:00
waozi cfa0b5c904 Render desktop smoke tests with private light and dark fixtures 2026-09-29 21:22:23 -03:00
waoziandClaude Opus 5.5 3e38257654 Show spinbox values in the dark theme
The theme styled spinboxes but not their value boxes, which kept Kryon's
white default fill under the theme's light text, so Length and Counter
were nearly invisible in dark mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-29 21:20:29 -03:00
waoziandClaude Opus 5.5 2bcccf0b12 Rebuild Pass as a Ziran app on Kryon
Pass's desktop, browser, Android, and command-line apps are now one Ziran
program on Kryon: src/app.zi draws the generator, profiles, and settings,
and thin hosts (desktop, browser canvas with a service worker for offline
use, Android, CLI) run it. The old .kry UI, the C core and hosts, the
Java activity, and the JavaScript web app are gone. Generation still
matches LessPass, and profiles and settings keep their storage formats.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-29 21:20:29 -03:00
waozi 720ad42405 Remove legacy vendored dependencies 2026-09-28 18:22:55 -03:00
waozi 88d2abba38 Use Ziran packages for Kryon 2026-09-28 17:25:29 -03:00
waozi 5349420989 Keep the Pass adapter portable to Plan 9 2026-09-28 11:42:23 -03:00
waozi 7758a9d3c0 Add a Ziran core compatibility adapter 2026-09-28 11:35:17 -03:00
waozi 133b4b08b9 Port Pass master emoji to Ziran 2026-09-28 11:21:08 -03:00
waozi e5ad25fbdd Build the Pass CLI from Ziran 2026-09-28 11:14:13 -03:00
waozi 1584763396 Generate Pass passwords in Ziran 2026-09-28 11:05:28 -03:00
waozi 7ef2e2726d Derive Pass keys in Ziran 2026-09-28 03:24:30 -03:00
waozi 99cba65af5 Start the Ziran Pass core migration 2026-09-28 03:05:43 -03:00
waozi 35e8120dbe Bump Kryon: plan9 fixes merged onto master 2026-09-22 18:15:20 -03:00
waozi bc8e59fb5a Give Pass an illustrated editorial website 2026-09-19 11:21:19 -03:00
waozi f9d721f179 Release Pass 0.2.9 2026-09-05 09:19:44 -03:00
waozi 7bb859f7df Keep Android builds aligned with the tested runtime and viewport 2026-09-05 09:19:44 -03:00
waozi 87df40db11 Use theme-aware icon tints and prevent taps through theme settings 2026-09-05 09:17:34 -03:00
waozi c0026b0b5f Redesign the Pass website around its vault mark 2026-09-02 17:24:47 -03:00
waozi 8c3e89368c Build with the shared plan9 rules 2026-08-31 17:50:54 -03:00
waozi 36e08df09e Move site deployment to Cloudflare Pages 2026-08-31 16:48:35 -03:00
waozi d930387758 Generate the Plan 9 build with k2c --plan9
The vendored Kryon compiler now emits 8c-safe C directly, so the
per-project rewriter script is gone: kry-c-plan9 runs k2c with --plan9,
writes the generated file list, and builds the embedded asset table
with the fonts. Bump vendor/kryon for the new k2c mode.
2026-08-31 15:26:04 -03:00
waozi 42bfe570e1 Define the app lifecycle hooks for the native Plan 9 entry
The k2c project host references CreateApp, DestroyApp, ApplyRoute, and
BeginScreenDraw weakly, and the native linker has no weak symbols.
The Plan 9 entry drives its own loop, so inert definitions satisfy the
host registry.
2026-08-31 13:08:39 -03:00
waozi e877f8d27d Expose the weak app lifecycle declarations for the Plan 9 rewrite
The native cpp does not define __GNUC__, so kryon_project.c's weak
declarations were compiled out and its lifecycle calls had no
prototypes for 8c. Drop the guard during the rewrite like Inbe does.
2026-08-31 12:44:54 -03:00
waozi 6d1a5ca1a5 Exit cleanly from the mkfile host-preparation check
A plan9 rc if whose condition is false and that has no else branch
returns failure, so the check rule failed exactly when the preparation
was present. Finish with an explicit exit 0.
2026-08-31 12:19:00 -03:00
waozi 5d92e65a92 Add a native Plan 9 port
- Host-side prepare script rewrites the k2c output for 8c (inferred
  declarations, compound literals, for-loop declarations) and generates
  the embedded asset table with the Noto Sans and emoji faces
- Native entry point mirrors the shared GUI main (window, Material
  theme, embedded fonts, shapes texture, frame loop) and switches to
  the user's home so profiles and app-storage settings land there
- plan9 mkfile builds and installs to /$objtype/bin against libkryon
2026-08-31 12:10:27 -03:00
waozi befbecb131 Bump Pass Kryon submodule to public master 2026-08-31 12:02:25 -03:00
waozi 3d27747a91 Move Pass Waozi return link 2026-08-31 11:56:44 -03:00
waozi b4d6a374d3 Adopt KryonActivity host and expand runtime test coverage
- Replace the custom MainActivity/TextInputBridge and android_bridge shim
  with kryon's KryonActivity and AndroidHost API; configure secure
  preferences via manifest meta-data
- Slim the pass_runtime surface: drop safe-area and biometric/master
  helpers that moved into the Android host
- Add pass_runtime_test, scripts/cli_test.sh, and a make coverage
  target; run runtime-test as part of make test
- Exclude the dom_ backend from web builds; bump vendor/kryon for the
  Android UI density scaling fix
- Refresh fastlane metadata and Linux packaging descriptions
2026-08-31 11:29:38 -03:00
waozi 42eb428c4c Package Pass HTML5 itch build 2026-08-31 11:01:51 -03:00
waozi 7a1ab6a48c Publish Pass web builds to itch 2026-08-31 10:48:43 -03:00
waozi 044024b549 Keep Pass web app on separate page 2026-08-30 00:14:16 -03:00
waozi 7b9de10d80 Refresh Pass website styling 2026-08-30 00:05:00 -03:00
waozi e527f83dd4 Use official F-Droid badge in README 2026-08-29 22:34:47 -03:00
waozi 1cffcde52d Add project README banners 2026-08-29 22:19:51 -03:00
waozi 06cd3a53ac Use Kryon Android window insets 2026-08-29 12:47:01 -03:00
waozi 45817b10e3 Bump Kryon for Android rotation fix 2026-08-29 11:21:19 -03:00
waozi 8220b3619d Update Kryon app framework 2026-08-27 19:46:13 -03:00
waozi 1e28b7e273 Fix web release backend selection 2026-08-26 16:23:03 -03:00
waozi 8db4e1b414 Prepare 0.2.8 release 2026-08-26 16:17:09 -03:00
waozi cafa4f9054 Add Sweet default theme and password output field 2026-08-26 15:38:43 -03:00
waozi 71ace783e2 Use Kryon secure store on Android 2026-08-26 15:32:09 -03:00
waozi d80b8e16f9 Version Android release APK assets 2026-08-26 15:18:08 -03:00
waozi 027b359ed7 Fix LessPass-compatible password generation 2026-08-26 15:11:06 -03:00
waozi 36e811bf74 Stabilize Android input CI emulator 2026-08-24 17:02:27 -03:00
waozi 41bb63baa7 Release Pass 0.2.7 2026-08-24 16:39:44 -03:00
waozi 423762d82f Fix Android input CI shell invocation 2026-08-24 16:33:27 -03:00
waozi 9f4f12f68a Release Pass 0.2.6 2026-08-24 16:14:56 -03:00
waozi 1497ecee17 Release Pass 0.2.5 2026-08-24 15:33:42 -03:00
waozi 3f4b8e43d5 Update desktop showcase banner 2026-08-23 23:26:13 -03:00
waozi a68e9fa3ee Bump Kryon submodule 2026-08-23 23:17:45 -03:00
waozi f70ade6adc Adopt Kryon #ui hierarchy syntax 2026-08-23 23:17:20 -03:00
waozi e636813590 Fix Android safe-area layout rotation 2026-08-23 22:46:36 -03:00
waozi 92ee741298 Add Kryon app smoke and Android rotation fixes 2026-08-23 22:30:28 -03:00
waozi 5c60cf8226 Optimize showcase banner 2026-08-23 22:29:53 -03:00
waozi 8f4121d921 Update showcase banner 2026-08-23 22:27:53 -03:00
waozi b0c7b2079a Update Kryon and expand E2E coverage 2026-08-22 20:03:28 -03:00
waozi 055d130bc3 android: tighten release changelog 2026-08-22 02:01:27 -03:00
waozi 57d52c6658 android: autosave generator defaults 2026-08-22 01:58:42 -03:00
waozi 8a601d6366 android: clear displayed secrets after timeout 2026-08-22 01:55:34 -03:00
waozi cc77006502 ci: install emscripten for release web app 2026-08-22 01:47:13 -03:00
waozi cb82a38b6a release: prepare pass 0.2.4 2026-08-22 01:45:45 -03:00
waozi d19d6edf7d Update pass logo assets 2026-08-22 01:10:18 -03:00
waozi f2eaed3c86 Add Kryon showcase metadata 2026-08-22 01:02:04 -03:00
waozi b6cdc32d52 site: full download channels with per-platform links
The Android card now offers the direct APK and the F-Droid package
page like the inbe site, the desktop card links the AppImage and
deb packages that releases already ship, and the CLI card covers
every platform. AppImage and deb asset names carry the version, so
build.sh templates it from version.go at build time. A SHA256SUMS
note closes the section now that releases publish checksums.
2026-08-21 09:12:16 -03:00
waozi 5047ce86b0 release: prepare pass 0.2.3 2026-08-21 09:04:01 -03:00
waozi 45f3f8dbc0 release: publish SHA256SUMS with the downloads
Every release now carries a SHA256SUMS file covering all published
artifacts, so the CLI, desktop, Android, and browser downloads can be
verified before use. The appcast already embedded digests for the
desktop update channels; this extends verification to every file.
2026-08-21 09:03:47 -03:00
waozi a52a4b6462 docs: describe installing the Android app
The APK has shipped since 0.2.2 but the README never mentioned it.
Document where to get it, the minimum Android version, and that the
app declares no Internet permission.
2026-08-21 09:03:47 -03:00
waozi b8bed150d0 release: push the tag only after the artifacts are ready
The tag used to be pushed before the appcast step ran, so any failure
there (v0.2.1 lost its release to a missing vendored script) orphaned
the version: later runs saw the tag and skipped publishing forever.
Publishing now happens in the safe order: build artifacts, appcast,
tag, release.
2026-08-21 09:03:33 -03:00
waozi 56be19e3a9 packaging: move the fdroiddata recipe to the fdroiddata fork
The F-Droid build recipe lives in fdroiddata, not in the app repository; the fastlane listing metadata stays because F-Droid reads it from the default branch.
2026-08-20 19:55:43 -03:00
waozi b256e9b9fd packaging: fix fdroiddata recipe from a local fdroidserver build
Point the 0.2.2 build at b4be990: the v0.2.2 tag does not survive fdroidserver signing-config stripping, and the binary scanner needs scandelete entries for unused vendored binaries in kryon submodules.
2026-08-20 19:44:04 -03:00
waozi b4be99002d droid: require the keystore password before signing release builds 2026-08-20 19:28:12 -03:00
waozi 9447c3a75c packaging: draft fdroiddata recipe for the F-Droid inclusion request 2026-08-20 19:17:34 -03:00
waozi 3deda78d54 fastlane: Android store listing metadata, changelogs, and screenshots 2026-08-20 19:17:34 -03:00
waozi c76f76ffb7 droid: build unsigned release APKs when no keystore is present 2026-08-20 19:17:34 -03:00
waozi c57006672a release: prepare pass 0.2.2 2026-08-20 18:48:29 -03:00
waozi 881a7336ec site: offer the Android APK download 2026-08-20 18:48:29 -03:00
waozi 11d0908325 ci: build and publish the Android APK 2026-08-20 18:48:29 -03:00
waozi b4d09eb632 droid: sign release builds and bump the version code 2026-08-20 18:48:29 -03:00
waozi d60269ca3d Restore pass CLI profile shorthand 2026-08-19 21:08:20 -03:00
waozi 7a40ebcce4 Clarify biometric setup requirement 2026-08-19 21:01:13 -03:00
waozi 9eeba9fe82 Fix Android master fingerprint and secure storage 2026-08-19 20:52:31 -03:00
waozi 7f06063bf5 Rename gopass to pass 2026-08-19 20:16:57 -03:00
waozi 664d981cb5 CI: gate on public-HTTPS submodule URLs
A guard job with a plain checkout fails the run when any .gitmodules
URL is not https:// — SSH URLs work only with a developer key and
break fresh clones and CI instead. The test job needs the guard.
2026-08-19 15:28:53 -03:00
waozi 03345a6304 Add desktop update checks and self-update to the GUI (0.2.1)
The GUI rides kryon's kry_update_flow through new kryui bindings: a
session-start appcast check, a toast plus an update row under the main
card, and for AppImage installs a verified download with one-click
restart (atomic swap + re-exec after secrets are cleared). Tarball and
deb installs show the release link. The release workflow publishes
appcast.json per arch (appimage-amd64/arm64) via kryon's
make_appcast.py.
2026-08-19 14:18:45 -03:00
waozi a237ff9a15 Follow the system theme by default
The GUI now uses the system palette and system light/dark mode by default, keeping Cobalt dark as the fallback palette when no system theme can be read. Includes the kryon bump that adds SetThemeSource/SetThemeMode bindings and defaults the platform theme source to SYSTEM everywhere.
2026-08-19 12:14:33 -03:00
waozi 57e229c13f ci: fix inverted polarity in the scanner self-test 2026-08-18 13:16:01 -03:00
waozi fb1188ac37 ci: privacy scan guard with a secret-fed deny-list
scripts/privacy_scan.sh scans git trees (or directories) for fixed-string
terms and redacts them from its own output; the deny-list never lives in
this repository — locally it is read from ~/.config/git/private-terms.txt
by the pre-push hook, in CI from the encrypted PRIVATE_TERMS secret. The
workflow self-test uses only a synthetic canary term.
2026-08-18 13:12:02 -03:00
waozi 9f3ea43414 privacy: scrub the vault filename from docs and tests
Docs and tests used the real vault filename as an example; replace it with
a generic name so published code says nothing about the private setup, and
isolate the CLI tests from the developer's real profiles file so local
configuration can never leak into test behavior.
2026-08-18 13:12:02 -03:00
218 changed files with 14185 additions and 21103 deletions

No files matched your search

+6 -11
View File
@@ -1,15 +1,10 @@
build-essential
cmake
pkg-config
libssl-dev
zlib1g-dev
libbrotli-dev
libzstd-dev
libsdl2-dev
libgl-dev
libx11-dev
libdrm-dev
libgbm-dev
libegl-dev
libgles-dev
libgtk-3-dev
libcairo2-dev
libfreetype6-dev
libfontconfig1-dev
libpango1.0-dev
xvfb
xauth
+143 -23
View File
@@ -15,30 +15,74 @@ concurrency:
cancel-in-progress: true
jobs:
test:
guard-package-urls:
name: Package URLs are public HTTPS
runs-on: ubuntu-latest
steps:
# Plain checkout on purpose: the guard validates URLs before fetching.
- name: Checkout Repository
uses: actions/checkout@v4
- name: Reject submodules and non-HTTPS package URLs
run: scripts/check_package_urls.sh
test:
runs-on: ubuntu-latest
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
- name: Install CLI test dependencies
run: |
sudo apt-get update
sudo apt-get install -y openssl xclip xvfb xauth
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Test Ziran CLI, core, and native/portable app runtime
run: make test
- uses: actions/setup-node@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: 1.25.x
cache: false
- name: Test CLI and generator
run: go test ./...
- name: Build browser app
run: make site
node-version: '22'
- name: Test browser input, storage, and offline launch
env:
WERK_WEB_BROWSER: google-chrome
run: make web-smoke
- name: Verify generated site
run: |
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/gopass.wasm
- name: Check formatting
run: test -z "$(find . -path ./vendor -prune -o -name '*.go' -type f -print | xargs gofmt -l)"
test -s build/site/app/index.wasm
- name: Check fastlane metadata
run: |
set -eu
meta=fastlane/metadata/android/en-US
limit() {
n=$(wc -m < "$1")
if [ "$n" -gt "$2" ]; then
echo "::error::$1 is $n characters (max $2)"
exit 1
fi
}
limit "$meta/title.txt" 30
limit "$meta/short_description.txt" 80
limit "$meta/full_description.txt" 4000
for f in "$meta"/changelogs/*.txt; do
limit "$f" 500
done
code=$(sed -n 's/^[[:space:]]*versionCode \([0-9][0-9]*\)$/\1/p' droid/app/build.gradle | head -n 1)
test -n "$code"
test -s "$meta/changelogs/$code.txt"
test -s "$meta/images/icon.png"
echo "fastlane metadata ok (versionCode $code)"
build-gui:
name: GUI (${{ matrix.arch }})
needs: guard-package-urls
strategy:
matrix:
include:
@@ -49,12 +93,6 @@ jobs:
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: 1.25.x
cache: false
- name: Install native dependencies
run: |
mapfile -t packages < .github/apt/gui-packages.txt
@@ -62,12 +100,94 @@ jobs:
sudo apt-get install -y "${packages[@]}"
- name: Build GUI
run: make gui
- name: Test GUI logic
run: cd gui && go test ./...
- name: Render GUI on private display
run: make gui-smoke
- name: Build Debian package
run: make package-deb
- uses: actions/upload-artifact@v4
with:
name: gopass-gui-linux-${{ matrix.arch }}
path: build/gopass-gui
name: werk-linux-${{ matrix.arch }}
path: |
build/werk
build/apps
build/pfp.png
if-no-files-found: error
build-android:
name: Android debug build
runs-on: ubuntu-latest
timeout-minutes: 60
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v3
- name: Cache Android SDK packages
uses: actions/cache@v4
with:
path: |
${{ env.ANDROID_HOME }}/platforms/android-36
${{ env.ANDROID_HOME }}/build-tools/34.0.0
${{ env.ANDROID_HOME }}/ndk/28.2.13676358
${{ env.ANDROID_HOME }}/cmake/3.22.1
key: android-sdk-${{ runner.os }}-${{ runner.arch }}-api36-bt34-ndk28-cmake322
restore-keys: |
android-sdk-${{ runner.os }}-${{ runner.arch }}-
- name: Cache Android native build
uses: actions/cache@v4
with:
path: |
droid/app/.cxx
droid/app/build/intermediates/cxx
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('src/*.zi', 'shared/*.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"
- name: Build debug APK
run: |
set -euo pipefail
chmod +x droid/gradlew
make android-debug
android-input-test:
name: Android NativeActivity input
runs-on: ubuntu-latest
timeout-minutes: 60
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v3
- name: Install Android SDK components
run: |
set -euo pipefail
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
yes | "$SDKMANAGER" --licenses >/dev/null || true
"$SDKMANAGER" "platforms;android-36" "build-tools;34.0.0" "ndk;28.2.13676358" "cmake;3.22.1"
- name: Run Android input tests
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 30
arch: x86_64
target: default
emulator-boot-timeout: 900
emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -no-metrics
script: make android-emulator android-input-test
- uses: actions/upload-artifact@v4
if: failure()
with:
name: android-input-test-reports
path: |
build/android-input/
if-no-files-found: ignore
+304 -51
View File
@@ -13,44 +13,19 @@ concurrency:
cancel-in-progress: false
jobs:
cli:
name: CLI (${{ matrix.os }}-${{ matrix.arch }})
guard-package-urls:
name: Package URLs are public HTTPS
runs-on: ubuntu-latest
strategy:
matrix:
os: [linux, darwin, windows, freebsd]
arch: [amd64, arm64]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.24.x
cache: false
- name: Build archive
env:
TARGET_OS: ${{ matrix.os }}
TARGET_ARCH: ${{ matrix.arch }}
run: |
set -euo pipefail
name="gopass-cli-${TARGET_OS}-${TARGET_ARCH}"
mkdir -p "build/release/$name"
suffix=""
[ "$TARGET_OS" = windows ] && suffix=".exe"
CGO_ENABLED=0 GOOS="$TARGET_OS" GOARCH="$TARGET_ARCH" go build -trimpath -ldflags='-s -w' -o "build/release/$name/gopass$suffix" ./cmd/gopass
cp LICENSE README.md "build/release/$name/"
if [ "$TARGET_OS" = windows ]; then
(cd build/release && zip -qr "$name.zip" "$name")
else
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
fi
- uses: actions/upload-artifact@v4
with:
name: cli-${{ matrix.os }}-${{ matrix.arch }}
path: build/release/gopass-cli-${{ matrix.os }}-${{ matrix.arch }}.*
if-no-files-found: error
- name: Checkout Repository
uses: actions/checkout@v4
gui:
name: GUI (${{ matrix.arch }})
- name: Reject submodules and non-HTTPS package URLs
run: scripts/check_package_urls.sh
cli:
name: CLI (${{ matrix.arch }})
needs: guard-package-urls
strategy:
matrix:
include:
@@ -61,12 +36,33 @@ jobs:
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
- name: Build archive
run: |
set -euo pipefail
make cli
name="pass-cli-linux-${{ matrix.arch }}"
mkdir -p "build/release/$name"
cp pass LICENSE README.md "build/release/$name/"
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
- uses: actions/upload-artifact@v4
with:
submodules: recursive
- uses: actions/setup-go@v5
with:
go-version: 1.25.x
cache: false
name: cli-linux-${{ matrix.arch }}
path: build/release/pass-cli-linux-${{ matrix.arch }}.tar.gz
if-no-files-found: error
gui:
name: GUI (${{ matrix.arch }})
needs: guard-package-urls
strategy:
matrix:
include:
- runner: ubuntu-22.04
arch: amd64
- runner: ubuntu-24.04-arm
arch: arm64
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
- name: Install native dependencies
run: |
mapfile -t packages < .github/apt/gui-packages.txt
@@ -75,9 +71,9 @@ jobs:
- run: make gui
- name: Package GUI tarball and Debian package
run: |
name="gopass-gui-linux-${{ matrix.arch }}"
name="werk-linux-${{ matrix.arch }}"
mkdir -p "build/release/$name"
cp build/gopass-gui LICENSE README.md "build/release/$name/"
cp -R build/werk build/apps build/pfp.png LICENSE README.md assets/app/icon.png "build/release/$name/"
tar -C build/release -czf "build/release/$name.tar.gz" "$name"
make package-deb
- name: Package AppImage
@@ -94,29 +90,156 @@ jobs:
with:
name: gui-linux-${{ matrix.arch }}
path: |
build/release/gopass-gui-linux-${{ matrix.arch }}.tar.gz
build/release/werk-linux-${{ matrix.arch }}.tar.gz
build/release/*.deb
build/release/*.AppImage
if-no-files-found: error
web:
android:
name: Android
runs-on: ubuntu-latest
timeout-minutes: 60
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
- uses: actions/setup-java@v4
with:
go-version: 1.24.x
cache: false
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v3
- name: Cache Android SDK packages
uses: actions/cache@v4
with:
path: |
${{ env.ANDROID_HOME }}/platforms/android-36
${{ env.ANDROID_HOME }}/build-tools/34.0.0
${{ env.ANDROID_HOME }}/ndk/28.2.13676358
${{ env.ANDROID_HOME }}/cmake/3.22.1
key: android-sdk-${{ runner.os }}-${{ runner.arch }}-api36-bt34-ndk28-cmake322
restore-keys: |
android-sdk-${{ runner.os }}-${{ runner.arch }}-
- name: Cache Android native build
uses: actions/cache@v4
with:
path: |
droid/app/.cxx
droid/app/build/intermediates/cxx
key: android-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('droid/app/src/main/cpp/CMakeLists.txt', 'droid/app/build.gradle', 'src/*.zi', 'shared/*.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"
- name: Prepare Android signing key
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
run: |
set -euo pipefail
test -n "$KEYSTORE_BASE64" || { echo "::error::KEYSTORE_BASE64 secret is empty or missing"; exit 1; }
mkdir -p "$HOME/.android"
printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$HOME/.android/pass-release.keystore"
- name: Build release APKs
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
set -euo pipefail
test -n "$KEYSTORE_PASSWORD" || { echo "::error::KEYSTORE_PASSWORD secret is empty or missing"; exit 1; }
test -n "$KEY_ALIAS" || { echo "::error::KEY_ALIAS secret is empty or missing"; exit 1; }
chmod +x droid/gradlew
export KRYON_DIR="$(./scripts/ziran.sh pkg path Kryon --locked)"
export ZIRAN_ROOT="$(./scripts/ziran.sh pkg path ziran --locked)"
export RAYLIB_DIR="$(./scripts/ziran.sh pkg path raylib --locked)/src"
export LIBOQS_DIR="$(./scripts/ziran.sh pkg path liboqs --locked)"
export MONOCYPHER_DIR="$(./scripts/ziran.sh pkg path monocypher --locked)"
./droid/gradlew -p droid assembleRelease \
-PsplitApks=true \
-Pkeystore.path="$HOME/.android/pass-release.keystore" \
-Pkeystore.alias="$KEY_ALIAS" \
-Pkeystore.password="$KEYSTORE_PASSWORD" \
--stacktrace
VERSION=$(sed -n '1p' VERSION)
mkdir -p build/release
cp droid/app/build/outputs/apk/release/app-universal-release.apk build/release/werk-android.apk
cp droid/app/build/outputs/apk/release/app-arm64-v8a-release.apk build/release/werk-android-arm64-v8a.apk
cp droid/app/build/outputs/apk/release/app-armeabi-v7a-release.apk build/release/werk-android-armeabi-v7a.apk
cp droid/app/build/outputs/apk/release/app-universal-release.apk "build/release/werk-$VERSION.apk"
cp droid/app/build/outputs/apk/release/app-arm64-v8a-release.apk "build/release/werk-$VERSION-arm64-v8a.apk"
cp droid/app/build/outputs/apk/release/app-armeabi-v7a-release.apk "build/release/werk-$VERSION-armeabi-v7a.apk"
python3 scripts/android_apk_check.py build/release/werk-android*.apk
test -s build/release/werk-android.apk
test -s build/release/werk-android-arm64-v8a.apk
test -s build/release/werk-android-armeabi-v7a.apk
test -s "build/release/werk-$VERSION.apk"
test -s "build/release/werk-$VERSION-arm64-v8a.apk"
test -s "build/release/werk-$VERSION-armeabi-v7a.apk"
- uses: actions/upload-artifact@v4
with:
name: android
path: build/release/*.apk
if-no-files-found: error
web:
runs-on: ubuntu-latest
needs: guard-package-urls
steps:
- uses: actions/checkout@v4
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- run: make site
- run: cd build/site && zip -qr ../gopass-web.zip .
- name: Package web site and HTML5 app
run: |
set -euo pipefail
cd build/site
zip -qr ../werk-web.zip .
mkdir -p ../werk-html5
cp app/index.html ../werk-html5/
cp app/index.js ../werk-html5/
cp app/index.wasm ../werk-html5/
cp app/sw.js ../werk-html5/
cp app/emoji-OFL.txt ../werk-html5/
cp manifest.webmanifest ../werk-html5/
cp -R icons ../werk-html5/icons
sed -i \
-e 's#href="/manifest.webmanifest"#href="manifest.webmanifest"#g' \
-e 's#href="/icons/#href="icons/#g' \
-e 's#src="/icons/#src="icons/#g' \
../werk-html5/index.html
python3 - <<'PY'
import json
from pathlib import Path
root = Path("../werk-html5")
manifest = json.loads((root / "manifest.webmanifest").read_text())
manifest["start_url"] = "."
manifest["scope"] = "."
for icon in manifest.get("icons", []):
icon["src"] = icon.get("src", "").lstrip("/")
(root / "manifest.webmanifest").write_text(json.dumps(manifest, indent=2) + "\n")
PY
cd ../werk-html5
zip -qr ../werk-html5.zip .
- uses: actions/upload-artifact@v4
with:
name: web
path: build/gopass-web.zip
path: |
build/werk-web.zip
build/werk-html5.zip
if-no-files-found: error
publish:
needs: [cli, gui, web]
needs: [cli, gui, web, android]
runs-on: ubuntu-latest
outputs:
released: ${{ steps.version.outputs.released }}
@@ -132,7 +255,7 @@ jobs:
name: Resolve release version
run: |
set -euo pipefail
version=$(sed -n 's/^const Version = "\([^"]*\)"/\1/p' version.go)
version=$(sed -n '1p' VERSION)
test -n "$version"
tag="v$version"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
@@ -141,6 +264,50 @@ jobs:
else
echo "released=true" >> "$GITHUB_OUTPUT"
fi
- name: Generate Update Appcast
if: steps.version.outputs.released == 'true'
run: |
set -euo pipefail
VERSION=$(sed -n '1p' VERSION)
TAG="v$VERSION"
BASE="https://github.com/${{ github.repository }}/releases/download/$TAG"
# appcast channel names use dpkg arch naming (amd64/arm64);
# the artifacts use uname -m naming (x86_64/aarch64)
arch_name() {
case "$1" in
x86_64) echo amd64 ;;
aarch64|arm64) echo arm64 ;;
*) echo "$1" ;;
esac
}
channels=()
for img in build/artifacts/*.AppImage; do
[ -e "$img" ] || continue
arch=$(basename "$img" | sed -n 's/^werk-.*-\([^-]*\)\.AppImage$/\1/p')
channels+=("--channel" "appimage-$(arch_name "$arch")=$img")
done
DEB="$(find build/artifacts -maxdepth 1 -name '*.deb' -print -quit || true)"
TAR="$(find build/artifacts -maxdepth 1 -name 'werk-linux-*.tar.gz' -print -quit || true)"
[ -n "$DEB" ] && channels+=("--channel" "deb=$DEB")
[ -n "$TAR" ] && channels+=("--channel" "tarball=$TAR")
if [ ${#channels[@]} -eq 0 ]; then
echo "no release artifacts found for the appcast"
exit 1
fi
python3 scripts/make_appcast.py \
--version "$VERSION" \
--base-url "$BASE" \
--notes-url "https://github.com/${{ github.repository }}/releases/tag/$TAG" \
--changelog CHANGELOG.md \
--out build/artifacts/appcast.json \
"${channels[@]}"
- name: Publish checksums
if: steps.version.outputs.released == 'true'
run: |
set -euo pipefail
cd build/artifacts
# The glob expands before the redirect creates SHA256SUMS itself.
sha256sum -- * > SHA256SUMS
- name: Create release tag
if: steps.version.outputs.released == 'true'
run: |
@@ -155,3 +322,89 @@ jobs:
tag_name: ${{ steps.version.outputs.tag }}
generate_release_notes: true
files: build/artifacts/*
publish-itch:
name: Publish itch.io
runs-on: ubuntu-latest
timeout-minutes: 45
continue-on-error: true
needs:
- web
- android
- gui
- publish
if: needs.publish.outputs.released == 'true'
env:
BUTLER_API_KEY: ${{ secrets.ITCH_API_KEY }}
steps:
- name: Check itch.io Secret
run: |
set -euo pipefail
if [ -z "${BUTLER_API_KEY:-}" ]; then
echo "ITCH_API_KEY secret is required to publish itch.io"
exit 1
fi
- name: Checkout Repository
uses: actions/checkout@v4
- name: Download Release Artifacts
uses: actions/download-artifact@v4
with:
path: build/artifacts
merge-multiple: true
- name: Install Butler
timeout-minutes: 15
run: |
set -euo pipefail
curl -fsSL \
https://broth.itch.zone/butler/linux-amd64/LATEST/archive/default \
-o "$RUNNER_TEMP/butler.zip"
mkdir -p "$RUNNER_TEMP/butler"
unzip -q "$RUNNER_TEMP/butler.zip" -d "$RUNNER_TEMP/butler"
chmod +x "$RUNNER_TEMP/butler/butler"
echo "$RUNNER_TEMP/butler" >> "$GITHUB_PATH"
- name: Publish Release Builds to itch.io
run: |
set -euo pipefail
VERSION="$(sed -n '1p' VERSION)"
html5_zip="build/artifacts/werk-html5.zip"
android_apk="build/artifacts/werk-android.apk"
linux_appimage="build/artifacts/werk-$VERSION-x86_64.AppImage"
test -f "$html5_zip"
test -f "$android_apk"
test -f "$linux_appimage"
butler_push() {
target="$1"
channel="$2"
attempt=1
log_file="$(mktemp)"
while [ "$attempt" -le 6 ]; do
if butler push "$target" "waozi/werk:$channel" --userversion "$VERSION" 2>&1 | tee "$log_file"; then
rm -f "$log_file"
return 0
fi
if ! grep -q "latest build is still processing" "$log_file"; then
rm -f "$log_file"
return 1
fi
echo "itch.io channel $channel is still processing; retrying in 60s ($attempt/6)"
sleep 60
attempt=$((attempt + 1))
done
rm -f "$log_file"
echo "itch.io channel $channel was still processing after retries"
return 1
}
butler_push "$html5_zip" html5
butler_push "$android_apk" android
butler_push "$linux_appimage" linux
+59
View File
@@ -0,0 +1,59 @@
name: Security
on:
push:
pull_request:
jobs:
privacy:
name: Privacy scan
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
# Prove the scanner works using only a synthetic term — the guard
# itself must never contain, or reveal, real private values.
- name: Self-test the scanner with a synthetic canary
run: |
canary=zzq-canary-7f3a
printf '%s\n' "$canary" > /tmp/canary-terms
mkdir /tmp/canary-dir
printf 'const token = "%s";\n' "$canary" > /tmp/canary-dir/leak.js
if scripts/privacy_scan.sh /tmp/canary-terms /tmp/canary-dir; then
echo "scanner failed to detect the canary" >&2
exit 1
fi
if ! scripts/privacy_scan.sh /tmp/canary-terms scripts; then
echo "scanner reported a false positive on its own source" >&2
exit 1
fi
rm -rf /tmp/canary-dir /tmp/canary-terms
# The deny-list comes from the encrypted PRIVATE_TERMS repository
# secret (one fixed-string term per line) so the private values are
# never part of this repository. Fork pull requests cannot read
# secrets; those runs skip with a warning and the scan re-runs on
# the push that lands the merge.
- name: Scan the repository for private terms
env:
PRIVATE_TERMS: ${{ secrets.PRIVATE_TERMS }}
run: |
if [ -z "$PRIVATE_TERMS" ]; then
echo "::warning::PRIVATE_TERMS secret is not set; privacy scan skipped"
exit 0
fi
printf '%s\n' "$PRIVATE_TERMS" > /tmp/terms
chmod 600 /tmp/terms
status=0
scripts/privacy_scan.sh /tmp/terms HEAD || status=1
if [ "$GITHUB_EVENT_NAME" = push ]; then
before="${{ github.event.before }}"
if [ "$before" != "0000000000000000000000000000000000000000" ]; then
for commit in $(git rev-list "$before..$GITHUB_SHA"); do
scripts/privacy_scan.sh /tmp/terms "$commit" || status=1
done
fi
fi
exit $status
+52 -53
View File
@@ -1,4 +1,4 @@
name: Netlify
name: Cloudflare Pages
on:
push:
@@ -10,28 +10,58 @@ permissions:
contents: read
concurrency:
group: netlify-${{ github.ref }}
group: pages-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
guard-package-urls:
name: Package URLs are public HTTPS
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Reject submodules and non-HTTPS package URLs
run: scripts/check_package_urls.sh
build:
needs: guard-package-urls
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
- uses: actions/setup-node@v4
with:
go-version: 1.24.x
cache: false
node-version: '22'
- name: Install Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Build Site
run: |
set -euo pipefail
make site
test -s build/site/index.html
test -s build/site/app/index.html
test -s build/site/app/gopass.wasm
test -s build/site/app/index.wasm
- name: Verify browser input, storage, cache upgrades, and offline launch
env:
WERK_WEB_BROWSER: google-chrome
run: bash scripts/web_smoke.sh
- name: Upload browser failure diagnostics
if: failure()
uses: actions/upload-artifact@v4
with:
name: werk-browser-diagnostics
path: build/web-test/*.png
if-no-files-found: ignore
- uses: actions/upload-artifact@v4
with:
name: gopass-site
name: werk-site
path: build/site
if-no-files-found: error
@@ -43,25 +73,14 @@ jobs:
steps:
- uses: actions/download-artifact@v4
with:
name: gopass-site
name: werk-site
path: build/site
- name: Install Netlify CLI
run: npm install --global netlify-cli
- name: Deploy Preview To Netlify
run: |
set -euo pipefail
auth_token="$(printf '%s' "$NETLIFY_AUTH_TOKEN" | tr -d '\r\n')"
site_id="$(printf '%s' "$NETLIFY_SITE_ID" | tr -d '\r\n')"
netlify deploy \
--dir build/site \
--no-build \
--alias "pr-${{ github.event.pull_request.number }}" \
--message "Preview ${{ github.event.pull_request.number }}" \
--auth "$auth_token" \
--site "$site_id"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
- name: Deploy Preview To Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build/site --project-name=pass --branch=${{ github.head_ref || github.ref_name }} --commit-hash=${{ github.sha }}
deploy-production:
name: Deploy Production
@@ -71,31 +90,11 @@ jobs:
steps:
- uses: actions/download-artifact@v4
with:
name: gopass-site
name: werk-site
path: build/site
- name: Package Site
run: |
set -euo pipefail
test -s build/site/index.html
cd build/site
zip -qr ../gopass-site.zip .
test -s ../gopass-site.zip
- name: Deploy Production To Netlify
run: |
set -euo pipefail
auth_token="$(printf '%s' "$NETLIFY_AUTH_TOKEN" | tr -d '\r\n')"
site_id="$(printf '%s' "$NETLIFY_SITE_ID" | tr -d '\r\n')"
test -n "$auth_token" || { echo "::error::NETLIFY_AUTH_TOKEN is empty or missing"; exit 1; }
test -n "$site_id" || { echo "::error::NETLIFY_SITE_ID is empty or missing"; exit 1; }
response="$(curl --fail-with-body --silent --show-error \
-X POST \
-H "Authorization: Bearer $auth_token" \
-H "Content-Type: application/zip" \
--data-binary "@build/gopass-site.zip" \
"https://api.netlify.com/api/v1/sites/$site_id/deploys")"
python3 -c 'import json, sys; deploy = json.loads(sys.argv[1]); state = deploy.get("state", ""); url = deploy.get("ssl_url") or deploy.get("url") or deploy.get("deploy_ssl_url") or deploy.get("deploy_url") or deploy.get("id"); print(f"Netlify deploy {state}: {url}"); raise SystemExit(1 if state in ("error", "failed") else 0)' "$response"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
- name: Deploy Production To Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build/site --project-name=pass --branch=master --commit-hash=${{ github.sha }}
+6 -2
View File
@@ -1,3 +1,7 @@
/build/
/gopass
/gui/gopass-gui
/pass
/ziran.local.toml
__pycache__/
*.pyc
.wrangler/
-3
View File
@@ -1,3 +0,0 @@
[submodule "vendor/kryon"]
path = vendor/kryon
url = https://github.com/kryonlabs/kryon.git
+43
View File
@@ -0,0 +1,43 @@
# Werkzeug repository rules
Werkzeug (formerly Pass) is a public repository. Read `~/Projects/AGENTS.md`
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.
- 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.
- Work the portable interpreter cannot do fast enough, such as Pass's
100,000 PBKDF2 rounds, is a native host capability, never a step-limit
increase.
## Data and secrets
- 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.
- Every file Werkzeug writes is private (0600 in 0700 folders).
## Platforms and tests
- Ziran only: C, Wasm and the browser loaders are compiler outputs. The
Android app has no Java (`hasCode=false`); it reaches the platform through
JNI from Ziran.
- Desktop tests run on private Xvfb displays (`make gui-smoke gui-test`),
the browser test in private headless Chromium (`make web-smoke`), and
Android tests only on a private emulator (`make android-input-test`),
never on a connected phone.
- Run `make test` and `ziran fmt --check` before committing.
- Releases follow `~/Projects/AGENTS.md`: add the numeric entry to
`CHANGELOG.md` and run `./update_version.sh`; only the release workflow
creates tags.
+90 -1
View File
@@ -1,5 +1,94 @@
# Changelog
## [0.3.0] - 2026-10-13
- Pass is now Werkzeug: a home screen of small private tools, each its own app and all preinstalled.
- A new logo: a wrench with a keyhole. The website moves to werk.waozi.xyz.
- Add Auth for two-factor sign-in codes from otpauth links or secret keys; copied codes clear after 30 seconds.
- Add Calculator, and Clock with a stopwatch.
- Add a profile with your name, a picture and the appearance every tool shares.
- Sync Auth's accounts between your devices from Profile → Sync: create an account, then connect another device with a 12-character code. Accounts are encrypted on the device; the server never sees them.
- Keep your Pass profiles, settings, theme and saved master password when updating.
- On Android, keep every screen clear of the navigation bar and the keyboard.
- Use Inbe's font, Noto Sans, in the browser and on phones older than Android 10.
## [0.2.10] - 2026-10-05
- Introduce the purple password asterisk and keyhole logo across Pass, website icons, Android launchers, and app listings.
## [0.2.9] - 2026-09-05
- Keep bottom navigation, password controls, and dialog icons readable with
dark tints in light mode and light tints in dark mode.
- Prevent taps in Theme Settings from reaching fields underneath or opening
the keyboard when saving the theme.
## [0.2.8] - 2026-08-26
- Match LessPass clients for the same site, login, master password, counter,
character classes, and length settings.
- Limit password length to LessPass's 5 to 35 character range.
- Require Android fingerprint unlock for saved master passwords and store them
with an authenticated Android Keystore key.
- Use the Sweet Material palette by default, with Sweet-Dark matched colors in
dark mode, and show generated passwords in a dedicated output field.
- Keep settings controls fully scrollable above the bottom navigation and use
the available form width while scrolling.
- Keep theme dropdowns from opening the Android soft keyboard.
## [0.2.7] - 2026-08-24
- Fix Android source builds in stricter environments such as F-Droid builders
while keeping Kry app source generation automatic.
## [0.2.6] - 2026-08-24
- Keep Android source builds self-contained so F-Droid and other source builds
generate the Kry app sources automatically.
## [0.2.5] - 2026-08-24
- Add Android appearance settings for following device colors, choosing
light or dark mode, selecting a color palette, and switching widget style.
- Use Android system Material colors for the app theme, with a stable Material
fallback instead of the bright pink accent some devices report.
- Recalculate the Android layout cleanly when rotating between portrait and
landscape, keeping controls clear of system bars and navigation insets.
## [0.2.4] - 2026-08-22
- Save and reuse Android master-password defaults, with fingerprint unlock
available from the generator and settings screens.
- Clear unlocked master-password text and generated passwords from the Android
screen after a short timeout.
- Autosave Android generator defaults when length, counter, character classes,
excluded characters, or biometric display settings change.
- Keep Android form fields visible while the keyboard is open, with better
spacing around settings and excluded-character controls.
- Run the real Pass app at pass.waozi.xyz/app through the Kryon canvas UI,
replacing the standalone browser form.
- Publish Android releases as a universal APK plus per-ABI APKs.
## [0.2.3] - 2026-08-21
- Verify every download: releases now ship a SHA256SUMS file covering the
command-line, desktop, Android, and browser downloads.
- The Android app now builds entirely from source with no developer signing
key, clearing the way for F-Droid distribution.
## [0.2.2] - 2026-08-20
- Install pass on Android: a signed APK is now downloadable from
pass.waozi.xyz alongside the desktop, terminal, and browser downloads.
- Fix the Android master-password fingerprint and secure storage so the
stored master password unlocks reliably across launches.
## [0.2.1] - 2026-08-19
- The desktop GUI now checks for new releases and can update itself: AppImage
builds download the checksum-verified update and restart straight into it,
while tarball and Debian package installs get a link to the release page.
## [0.2.0] - 2026-08-18
- Copy passwords through a built-in pure-Go X11 clipboard on Linux, with no
@@ -28,7 +117,7 @@
- Make keyboard navigation reliable: click a field, then use Tab and Shift+Tab
to move through the form.
- Keep one gopass window open by default; launching it again replaces the
- Keep one pass window open by default; launching it again replaces the
existing window.
- Keep long editing sessions responsive and stable.
+168 -52
View File
@@ -1,64 +1,180 @@
.PHONY: all cli gui native run test native-test web site install-gui uninstall-gui package-deb package-appimage android-debug
.DEFAULT_GOAL := all
ZIRAN ?= ./scripts/ziran.sh
# 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)
ZIRAN_ROOT = $(shell $(ZIRAN) pkg path ziran $(LOCK_FLAGS))
KRYON_DIR = $(shell $(ZIRAN) pkg path kryon $(LOCK_FLAGS))
RAYLIB_DIR = $(shell $(ZIRAN) pkg path raylib $(LOCK_FLAGS))/src
MINGCUTE_DIR = $(shell $(ZIRAN) pkg path mingcute $(LOCK_FLAGS))
# Account sync: ML-DSA-44 account keys from liboqs, and Ed25519, X25519,
# BLAKE2b and XChaCha20-Poly1305 from Monocypher.
LIBOQS_DIR = $(shell $(ZIRAN) pkg path liboqs $(LOCK_FLAGS))
MONOCYPHER_DIR = $(shell $(ZIRAN) pkg path monocypher $(LOCK_FLAGS))
LIBOQS_FLAGS := -DCMAKE_BUILD_TYPE=MinSizeRel -DBUILD_SHARED_LIBS=OFF -DOQS_BUILD_ONLY_LIB=ON \
-DOQS_USE_OPENSSL=OFF -DOQS_DIST_BUILD=OFF -DOQS_OPT_TARGET=generic -DOQS_MINIMAL_BUILD=SIG_ml_dsa_44
MONOCYPHER_SOURCES = $(MONOCYPHER_DIR)/src/monocypher.c $(MONOCYPHER_DIR)/src/optional/monocypher-ed25519.c
CC ?= cc
BIN_DIR ?= $(HOME)/bin
DATA_DIR ?= $(if $(XDG_DATA_HOME),$(XDG_DATA_HOME),$(HOME)/.local/share)
KRYON_ARCH ?= $(shell uname -m)
KRYON_BUILD_DIR := vendor/kryon/build/linux-$(KRYON_ARCH)
KRYON_RUNTIME_SOURCES := $(shell find vendor/kryon/src vendor/kryon/include -type f)
all: cli gui
cli:
go build -o gopass ./cmd/gopass
$(KRYON_BUILD_DIR)/libkryon.a: $(KRYON_RUNTIME_SOURCES) vendor/kryon/Makefile
$(MAKE) -C vendor/kryon -f Makefile all
gui: $(KRYON_BUILD_DIR)/libkryon.a
cd gui && go build -o ../build/gopass-gui .
native: all
run: gui
./build/gopass-gui
install-gui: gui
mkdir -p $(BIN_DIR) $(DATA_DIR)/applications $(DATA_DIR)/icons/hicolor/512x512/apps
cp build/gopass-gui $(BIN_DIR)/gopass-gui
cp packaging/linux/xyz.waozi.pass.desktop $(DATA_DIR)/applications/xyz.waozi.pass.desktop
cp assets/app/icon.png $(DATA_DIR)/icons/hicolor/512x512/apps/gopass.png
uninstall-gui:
rm -f $(BIN_DIR)/gopass-gui $(DATA_DIR)/applications/xyz.waozi.pass.desktop $(DATA_DIR)/icons/hicolor/512x512/apps/gopass.png
test:
go test ./...
cd gui && go test ./...
# Checks the C generator (used by the Android app) against the same fixed
# vectors as the Go tests.
native-test:
cc -Wall -Wextra -O2 -Inative native/gopass_core.c native/gopass_core_test.c -o build/gopass_core_test
./build/gopass_core_test
ANDROID_DIR := droid
# The tool bundles and Werkzeug's other files.
LIB_DIR ?= $(HOME)/.local/lib/werk
WEB_CC ?= $(if $(wildcard $(HOME)/emsdk/upstream/emscripten/emcc),$(HOME)/emsdk/upstream/emscripten/emcc,emcc)
SOURCES := $(wildcard src/*.zi shared/*.zi apps/*/*.zi)
LIBRARY_SOURCES = $(wildcard $(KRYON_DIR)/src/ui/*.zi $(KRYON_DIR)/src/ui/*/module.zi $(KRYON_DIR)/src/kss/*.zi $(KRYON_DIR)/src/backend/*.zi $(KRYON_DIR)/src/backend/*/module.zi $(ZIRAN_ROOT)/std/*.zi)
CFLAGS := -std=c99 -O2 -Wno-unused-variable -I$(ZIRAN_ROOT)/include
PROJECT := --project $(LOCK_FLAGS)
ANDROID_ABIS ?= armeabi-v7a,arm64-v8a
android-debug:
cd $(ANDROID_DIR) && ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS)
mkdir -p build
cp $(ANDROID_DIR)/app/build/outputs/apk/debug/app-debug.apk build/gopass-android-debug.apk
.PHONY: all apps cli gui native run test source-check core-test ziran-core-test cli-test pass-state-test app-logic-test lesspass-compat-test gui-smoke gui-test web web-canvas site web-smoke android-debug android-emulator android-release android-smoke android-input-test e2e check-package-urls install install-cli install-gui uninstall-cli uninstall-gui package-deb package-appimage plan9-c
all: cli gui
native: all
web:
build/generated/cli/.complete: $(SOURCES) ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --target=c --entry cli:main -o $(@D) apps/pass/cli.zi
touch $@
build/pass: build/generated/cli/.complete
$(CC) $(CFLAGS) -Ibuild/generated/cli build/generated/cli/*.c -o $@
cli: build/pass
cp build/pass pass
# Each app is its own bundle; Werkzeug runs them in one window.
APPS := pass auth calculator clock
APP_BUNDLES := $(APPS:%=build/apps/%.zib)
SHARED_SOURCES := $(wildcard shared/*.zi)
APP_MODULE_PATHS = --module-path shared --module-path $(KRYON_DIR)/src/ui --module-path $(MINGCUTE_DIR)/src --module-path $(ZIRAN_ROOT)/std
apps: $(APP_BUNDLES)
.SECONDEXPANSION:
build/apps/%.zib: $$(wildcard apps/$$*/*.zi apps/$$*/assets/*) $(SHARED_SOURCES) ziran.lock
mkdir -p $(@D)
$(ZIRAN) bundle --root . --module-path apps/$* $(APP_MODULE_PATHS) --define KRYON_HOSTED_UI --define WERK_APP \
$(if $(wildcard apps/$*/assets),--asset-dir assets=apps/$*/assets) --entry $*:Main -o $@ apps/$*/$*.zi
# The portable bundle runtime the host links, built from the locked Ziran.
build/ziran/libziran.a: ziran.lock
env -u DISPLAY -u WAYLAND_DISPLAY $(MAKE) -C $(ZIRAN_ROOT) BUILD_DIR=$(abspath build/ziran) $(abspath $@)
build/generated/desktop/.complete: $(wildcard src/*.zi) $(SHARED_SOURCES) $(LIBRARY_SOURCES) ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --target=c --entry desktop:main -o $(@D) src/desktop.zi
touch $@
build/liboqs/lib/liboqs.a: ziran.lock
cmake -S $(LIBOQS_DIR) -B build/liboqs $(LIBOQS_FLAGS) > /dev/null
cmake --build build/liboqs --target oqs > /dev/null
build/werk: build/generated/desktop/.complete build/ziran/libziran.a build/liboqs/lib/liboqs.a Makefile
$(CC) $(CFLAGS) -Ibuild/generated/desktop -I$(MONOCYPHER_DIR)/src -I$(MONOCYPHER_DIR)/src/optional \
build/generated/desktop/*.c $(MONOCYPHER_SOURCES) build/ziran/libziran.a build/liboqs/lib/liboqs.a \
$(shell pkg-config --libs sdl2 cairo freetype2 fontconfig pangocairo) -l:libcurl.so.4 -lm -lpthread -o $@
build/pfp.png: $(KRYON_DIR)/icons/pfp.png
cp $< $@
gui: build/werk build/pfp.png apps
run: gui
./build/werk
source-check:
python3 scripts/source_check.py
$(ZIRAN) fmt --check $(SOURCES) tests/*.zi
core-test ziran-core-test:
sh scripts/ziran_core_test.sh "$(ZIRAN)"
pass-state-test:
sh scripts/pass_state_test.sh "$(ZIRAN)"
app-logic-test:
sh scripts/app_logic_test.sh "$(ZIRAN)"
cli-test: cli
sh scripts/cli_test.sh ./pass
lesspass-compat-test: cli
python3 scripts/lesspass_compat_test.py --cli ./pass
test: source-check core-test pass-state-test app-logic-test cli-test lesspass-compat-test
gui-smoke: gui
sh scripts/gui_smoke.sh
gui-test: gui
sh scripts/werk_gui_test.sh
sh scripts/migration_test.sh
# 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) \
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
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --define PLATFORM_WEB --target=c -o $(@D) src/browser.zi
touch $@
build/web-app/index.js: build/generated/browser/.complete build/web-runtime/libziran.a $(APP_BUNDLES) build/pfp.png assets/app/icon.png assets/fonts/NotoSans-Regular.ttf
mkdir -p $(@D)
$(WEB_CC) -O2 -Wno-parentheses-equality -I$(ZIRAN_ROOT)/include -iquote build/generated/browser build/generated/browser/*.c \
build/web-runtime/libziran.a \
--js-library $(ZIRAN_ROOT)/web/ziran_web.js -sEXPORTED_RUNTIME_METHODS=FS,IDBFS -lidbfs.js \
-sASYNCIFY -sALLOW_MEMORY_GROWTH=1 -sSTACK_SIZE=16777216 -sASYNCIFY_STACK_SIZE=1048576 -sENVIRONMENT=web \
--embed-file assets/fonts/NotoSans-Regular.ttf@/kryon-font.ttf \
--embed-file build/apps@/apps --embed-file build/pfp.png@/pfp.png --embed-file assets/app/icon.png@/icon.png -o $@
build/web-app/index.html: build/web-app/index.js web/site/app/index.html
cp web/site/app/index.html $@
build/generated/worker/.complete: src/service_worker.zi ziran.toml ziran.lock
rm -rf $(@D)
mkdir -p $(@D)
$(ZIRAN) build $(PROJECT) --target=c -o $(@D) src/service_worker.zi
touch $@
build/web-app/sw.js: build/generated/worker/.complete
$(WEB_CC) -O2 -I$(ZIRAN_ROOT)/include -iquote build/generated/worker build/generated/worker/*.c \
--js-library $(ZIRAN_ROOT)/web/ziran_web.js -sENVIRONMENT=worker -sNO_EXIT_RUNTIME=1 \
-sSINGLE_FILE=1 -sWASM_ASYNC_COMPILATION=0 -o $@
web-canvas: build/web-app/index.html build/web-app/sw.js
web site: web-canvas
./web/build.sh
web-smoke: site
bash scripts/web_smoke.sh
site: web
test -f build/site/index.html
test -f build/site/app/gopass.wasm
# CMake emits JNI and foreign ABI types separately for each Android ABI.
android-debug: apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
mkdir -p build
cp droid/app/build/outputs/apk/debug/app-universal-debug.apk build/werk-android-debug.apk
python3 scripts/android_apk_check.py build/werk-android-debug.apk
cp droid/app/build/outputs/apk/debug/app-arm64-v8a-debug.apk build/werk-android-arm64-v8a-debug.apk
cp droid/app/build/outputs/apk/debug/app-armeabi-v7a-debug.apk build/werk-android-armeabi-v7a-debug.apk
android-emulator: apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=x86_64 $(GRADLE_ARGS)
mkdir -p build
cp droid/app/build/outputs/apk/debug/app-debug.apk build/werk-android-emulator.apk
python3 scripts/android_apk_check.py build/werk-android-emulator.apk
android-release: apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleRelease -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
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
check-package-urls:
bash scripts/check_package_urls.sh
e2e: check-package-urls test gui-smoke gui-test web-smoke android-debug
install: install-cli install-gui
install-cli: cli
mkdir -p $(BIN_DIR)
install -m 0755 pass $(BIN_DIR)/pass
install-gui: gui
mkdir -p $(BIN_DIR) $(LIB_DIR)/apps $(DATA_DIR)/applications $(DATA_DIR)/icons/hicolor/512x512/apps
install -m 0755 build/werk $(BIN_DIR)/werk
install -m 0644 $(APP_BUNDLES) $(LIB_DIR)/apps/
install -m 0644 build/pfp.png $(LIB_DIR)/pfp.png
cp packaging/linux/xyz.waozi.werk.desktop $(DATA_DIR)/applications/xyz.waozi.werk.desktop
cp assets/app/icon.png $(DATA_DIR)/icons/hicolor/512x512/apps/werk.png
uninstall-cli:
rm -f $(BIN_DIR)/pass
uninstall-gui:
rm -f $(BIN_DIR)/werk $(DATA_DIR)/applications/xyz.waozi.werk.desktop $(DATA_DIR)/icons/hicolor/512x512/apps/werk.png
rm -rf $(LIB_DIR)
package-deb: gui
./scripts/package-deb.sh
package-appimage: gui
./scripts/package-appimage.sh
+131 -110
View File
@@ -1,140 +1,161 @@
# gopass
<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>
</p>
Website and browser app: [pass.waozi.xyz](https://pass.waozi.xyz/)
# Werkzeug
`gopass` is a stateless password generator: the same site, login, master
password, and settings produce the same result without a password database.
It is a new, independently written implementation of the LessPass generation
algorithm. Compatibility does not imply endorsement by or affiliation with the
LessPass project.
Small private tools in one app. The home screen opens each one:
## Install
- **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 an authenticator's plain-text export, or by entering the
secret key. Tap a code to copy it; it is cleared from the clipboard after
30 seconds.
- **Calculator**: arithmetic with brackets, powers and percent, by keypad or
keyboard.
- **Clock**: the local time and date, and a stopwatch that keeps running
while the app is closed.
Prebuilt CLI and desktop downloads are available from
[pass.waozi.xyz](https://pass.waozi.xyz/#downloads).
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.
With Go 1.24 or newer:
Werkzeug was previously Pass. On its first start it moves Pass's saved
profiles, settings and theme into the new layout; the Android app keeps
Pass's package, so it updates in place and keeps a saved master password.
## Privacy
Everything is computed on the device. Werkzeug makes no network requests
unless you turn on sync. 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 → Sync keeps Auth's accounts on all your devices through a
[Daochi](https://github.com/kryonlabs/daochi) account, `api.waozi.xyz` by
default. Sync is off until you create or connect an account.
- Each record is sealed on the device with XChaCha20-Poly1305 under a random
vault key that never leaves your devices unencrypted. The seal covers the
account, the record and the time of the change, so the server can neither
read nor alter a record or a removal.
- The account key (ML-DSA-44) signs in and signs each sync together with
the device's own Ed25519 key.
- To connect another device, open Profile → Sync → Connect a device and enter
the 12-character code on the other device. The devices swap X25519 keys
through the server's link mailbox, and the account and vault keys travel
sealed with a key derived from that exchange and the code, so the server
cannot open or replace them. The code works for 10 minutes.
- The server can still withhold changes or serve an older copy to a device
that has not seen a newer one. A lost device keeps the keys it had: stop
syncing there if you can, and replace two-factor secrets you care about.
`scripts/sync_e2e_test.sh` runs two devices against a local Daochi node.
## 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 and Pango development packages; browser
builds need Emscripten; Android builds need JDK 21 and the SDK/NDK versions in
`droid/app/build.gradle`. Desktop tests use Xvfb, xdotool, xclip and
ImageMagick on private displays.
```sh
go install github.com/waozixyz/gopass/cmd/gopass@latest
make gui # build/werk and the app bundles in build/apps
make test # Pass core and CLI, Pass state, Auth codes, Calculator
make gui-smoke # light and dark home screens on a private Xvfb display
make gui-test # every tool, clipboard and profile on a private display
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-emulator # the x86_64 APK for a private emulator
```
Or build the command from a checkout:
For development with the real project repositories, create an ignored
`ziran.local.toml`:
```sh
go build ./cmd/gopass
```toml
[overrides]
kryon = "../../kryonlabs/kryon"
ziran = "../../ziranlang/ziran"
```
## Use
## The `pass` command
```text
gopass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
pass [OPTIONS] PROFILE SITE
```
The default password has 16 characters and includes lowercase letters,
uppercase letters, digits, and symbols. The default counter is 1.
`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: `gopass` first checks
`LESSPASS_MASTER_PASSWORD`, then reads from the controlling terminal or console
with echo disabled. Use `--prompt` to bypass the environment and always ask. For
example:
and shell history. Omitting it is safer: `pass` first checks
`LESSPASS_MASTER_PASSWORD`, then reads one line from standard input. Use
`--prompt` to bypass the environment and read from standard input:
```sh
gopass --prompt example.com alice
gopass --length 24 --counter 2 example.com alice
gopass --no-symbols --exclude '0O1Il' example.com alice
pass --prompt example.com alice
pass --length 24 --counter 2 example.com alice
pass --no-symbols --exclude '0O1Il' example.com alice
```
`--copy` sends the result to the clipboard without printing it. On Linux a
built-in pure-Go X11 clipboard is used when an X server (X.Org, Xlibre, or
XWayland) is reachable, so no external tool is needed; otherwise `gopass`
falls back to `wl-copy`, `xclip`, `xsel`, `pbcopy`, or `clip.exe` and reports
an error if none can be used. The copied password is served by a small
detached process and disappears when another application takes the clipboard;
`--clear-after 90s` releases it automatically after a delay (built-in X11
clipboard only), and `--read-clipboard` prints the current contents.
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.
## Profiles
`--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.
An optional configuration file at `$XDG_CONFIG_HOME/gopass/profiles.json`
(usually `~/.config/gopass/profiles.json`) can store named profiles — a login
plus default settings — so daily invocations shrink to one flag:
## Source layout
```sh
gopass --profile work example.com
```text
apps/pass/ Pass: LessPass core, settings and profiles, screens, CLI
apps/auth/ Auth: TOTP, otpauth links, accounts and screens
apps/calculator/ Calculator
apps/clock/ Clock and stopwatch
shared/ the app interface, protocol and SHA-256/PBKDF2
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
```
```json
{
"vault": "~/.secret_vault",
"copy": true,
"clear_after": "90s",
"profiles": {
"work": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
}
}
```
Profiles hold no secrets. Command-line flags always win over profile values,
and without a configuration file gopass behaves exactly as before.
## Master password from a vault
`--vault PATH` reads the master password from a file encrypted with OpenSSL:
```sh
printf 'master password' | openssl enc -aes-256-cbc -md sha512 -a \
-pbkdf2 -iter 100000 -salt -pass pass:... > ~/.secret_vault
gopass --vault ~/.secret_vault example.com alice
```
The vault passphrase is requested on the terminal with echo disabled, or read
from piped standard input, and the decrypted contents are used as the master
password — the master itself never appears in argv or the environment. The
vault path can also be set once in the profiles file.
## The `pass` shorthand
Copying or symlinking the binary as `pass` enables a compact personal mode
built on profiles:
```sh
ln -s gopass ~/bin/pass
pass work example.com
```
`pass PROFILE SITE` copies the password without printing it and clears the
clipboard after 90 seconds (`-timeout 30s` to change, `-timeout 0` to keep it
until another application takes over).
Run `gopass --help` for all flags.
## Desktop app
The optional desktop app is written in Go with Kryon and calls the same
generator package directly. It keeps the master password in process memory,
masks the master-password field, and clears copied passwords after 20 seconds
unless the clipboard has since been replaced.
```sh
git submodule update --init --recursive
make gui
./build/gopass-gui
```
## Library
```go
settings := gopass.DefaultOptions()
result, err := gopass.Generate("example.com", "alice", master, settings)
```
All inputs are interpreted as UTF-8 strings. Excluded characters are removed
from every enabled character class; generation fails if a class becomes empty,
all classes are disabled, or the requested length cannot include one character
from each class.
## License
Copyright © 2026 Waozi. Distributed under the BSD 3-Clause License. See
+1
View File
@@ -0,0 +1 @@
0.3.0
+534
View File
@@ -0,0 +1,534 @@
// 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 "werk_app"
#import "app_protocol"
#import "totp"
#import "sha256"
Icon :: #import "mingcute_regular_shield";
Remove :: #import "mingcute_regular_delete_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
FIELD_LINKS :: 1
FIELD_ISSUER :: 2
FIELD_NAME :: 3
FIELD_SECRET :: 4
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: [5]FieldState;
links: [16384]u8;
issuer: [64]u8;
name: [128]u8;
secret: [256]u8;
status: [128]u8;
// The account whose Remove was tapped once; a second tap removes it.
remove_pending: s32 = -1;
list_scroll: s32;
store: [LIST_LIMIT]u8;
session: Session;
SetStatus :: (text: string) {
unused CopyLimited(text, status[:])
}
Clear :: (bytes: []u8) {
index: s64 = 0
while index < bytes.count {
bytes[index] = cast(u8)0
index += 1
}
}
HexDigit :: (value: u8) -> u8 {
return ifx value < cast(u8)10 then cast(u8)48 + value else cast(u8)87 + value
}
// An account's record id comes from its link, so the same account added on
// two devices is one record.
SetRecordId :: (index: s32, link: string) {
digest := Sha256(link)
for at: 0..15 {
record_ids[index][at * 2] = HexDigit(digest[at] >> cast(u8)4)
record_ids[index][at * 2 + 1] = HexDigit(digest[at] & cast(u8)15)
}
record_ids[index][32] = cast(u8)0
for at: 0..31 {
digest[at] = cast(u8)0
}
}
// Writes the records of accounts added since the last save.
SaveAccounts :: () -> bool {
saved := true
index: s32 = 0
while index < account_count {
if !recorded[index] {
line: [1024]u8
{
link := LinkText(*accounts[index], line[:])
if link != "" {
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 AddLinks(TextView(store[0:count]), false)
if SaveAccounts() {
unused WriteStore("accounts.txt", "")
}
}
Clear(store[:])
while account_count > 0 {
account_count -= 1
accounts[account_count] = Account.{}
}
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
}
}
SameAccount :: (left: *Account, right: *Account) -> bool {
return TextUntilNul(left.issuer[:]) == TextUntilNul(right.issuer[:]) &&
TextUntilNul(left.name[:]) == TextUntilNul(right.name[:]) &&
TextUntilNul(left.secret[:]) == TextUntilNul(right.secret[:])
}
// Adds every otpauth link in text, separated by spaces or line breaks.
// Returns how many were new.
AddLinks :: (text: string, report: bool) -> s32 {
added: s32 = 0
refused: s32 = 0
start: s64 = 0
while start < text.count {
while start < text.count && text[start] <= cast(u8)32 {
start += 1
}
end := start
while end < text.count && text[end] > cast(u8)32 {
end += 1
}
if end > start {
account: Account
if ParseLink(text[start:end], *account) && account_count < ACCOUNT_LIMIT {
known := false
index: s32 = 0
while index < account_count {
if SameAccount(*accounts[index], *account) {
known = true
}
index += 1
}
if !known {
accounts[account_count] = account
codes[account_count] = CachedCode.{.step = -1}
recorded[account_count] = false
account_count += 1
added += 1
}
} else {
refused += 1
}
account = Account.{}
}
start = end
}
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[:]))
}
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}
recorded[account_count] = false
account_count += 1
account = Account.{}
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.{}
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)
}
// One account: its name, current code (tap to copy), the seconds left and
// Remove. True when Remove was confirmed.
DrawRow :: (index: s32, x: float32, y: float32, inner: float32, row: float32) -> bool {
account := *accounts[index]
Box(session, BoxProps.{.key = cast(u64)(1000 + index), .bounds = Rectangle.{x, y, inner, row - 8.0},
.radius = 10.0})
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
Label(cast(u64)(5000 + index), FormatInteger(remaining, number[:]),
Rectangle.{x + inner - 52.0, y + 24.0, 16.0, 18.0}, 12)
remove := ButtonProps.{.key = cast(u64)(6000 + index), .id = 6000 + index,
.label = ifx remove_pending == index then "Tap again to remove" else "Remove",
.bounds = Rectangle.{x + inner - 40.0, y + 16.0, 36.0, 36.0},
.icon_shape = Remove.Shape, .icon_only = true,
.tone = ButtonTone.ButtonToneNeutral, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}
if remove_pending == index {
remove.tone = ButtonTone.ButtonToneDanger
remove.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
if Button(session, remove) == 0 {
return false
}
if remove_pending == index {
return true
}
remove_pending = index
SetStatus("Tap the red button again to remove this account")
return false
}
ListView :: (area: Rectangle, left: float32, width: float32) {
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 {
y := scroll.content.y + cast(float32)index * row
if DrawRow(index, x, y, inner, row) {
remove_pending = -1
SetStatus(ifx RemoveAccount(index) then "Account removed" else "Could not remove the account")
break
}
index += 1
}
End(session)
}
}
AddView :: (area: Rectangle, left: float32, width: float32) {
y := area.y + 12.0
Label(cast(u64)20, "Paste otpauth:// links, one or many", Rectangle.{left, y, width, 20.0}, 14)
Field(FIELD_LINKS, "Links", "otpauth://totp/…", links[:], Rectangle.{left, y + 24.0, width, 40.0}, true)
y += 76.0
if Action(21, "Import links", Rectangle.{left, y, width, 40.0}, true) {
added := AddLinks(TextUntilNul(links[:]), true)
if added > 0 && !SaveAccounts() {
SetStatus("Could not save the accounts")
}
Clear(links[:])
fields[FIELD_LINKS] = FieldState.{}
if added > 0 {
view = VIEW_LIST
}
}
y += 64.0
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("")
}
}
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 {
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 {
AppDescribe("Auth", Icon.Shape)
return APP_PROTOCOL
}
// Records from another device replace the list.
if !loaded || RecordsVersion() != records_version {
LoadAccounts()
loaded = true
}
Draw()
return 0
}
+676
View File
@@ -0,0 +1,676 @@
// 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
}
Account :: struct {
issuer: [64]u8
name: [128]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
}
// 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
}
if equals < pair.count {
key := pair[0:equals]
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
}
}
}
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]))
if used < 0 {
return ""
}
return TextView(output[0:used])
}
+64
View File
@@ -0,0 +1,64 @@
// 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
}
+247
View File
@@ -0,0 +1,247 @@
// Evaluates calculator expressions: + − × ÷ (also - * /), ^ for powers,
// a postfix % for percent, unary signs and brackets. Brackets left open at
// the end are closed there.
#import "text_buffer"
#import "number_text"
Answer :: struct {
valid: bool
value: float64
error: string
}
source: string;
position: s32;
failure: string;
EvaluateExpression :: (text: string) -> Answer {
source = text
position = 0
failure = ""
value := ParseSum()
SkipSpaces()
if failure == "" && position < cast(s32)source.count {
failure = "Cannot read this expression"
}
if failure == "" && !Finite(value) {
failure = "Result is too large"
}
if failure != "" {
return Answer.{.error = failure}
}
return Answer.{.valid = true, .value = value}
}
Finite :: (value: float64) -> bool {
return value == value && value < 1.0e300 && value > -1.0e300
}
SkipSpaces :: () {
while position < cast(s32)source.count && source[position] == cast(u8)32 {
position += 1
}
}
// Whether the next character is the given one, consuming it when it is.
Take :: (symbol: string) -> bool {
SkipSpaces()
end := position + cast(s32)symbol.count
if end > cast(s32)source.count || source[position:end] != symbol {
return false
}
position = end
return true
}
ParseSum :: () -> float64 {
value := ParseProduct()
while failure == "" {
if Take("+") {
value += ParseProduct()
} else if Take("-") || Take("−") {
value -= ParseProduct()
} else {
return value
}
}
return value
}
ParseProduct :: () -> float64 {
value := ParseSigned()
while failure == "" {
if Take("×") || Take("*") {
value *= ParseSigned()
} else if Take("÷") || Take("/") {
divisor := ParseSigned()
if divisor == 0.0 {
failure = "Cannot divide by zero"
return 0.0
}
value /= divisor
} else {
return value
}
}
return value
}
ParseSigned :: () -> float64 {
if Take("-") || Take("−") {
return 0.0 - ParseSigned()
}
if Take("+") {
return ParseSigned()
}
return ParsePower()
}
ParsePower :: () -> float64 {
base := ParsePercent()
if failure == "" && Take("^") {
exponent := ParseSigned()
return Power(base, exponent)
}
return base
}
ParsePercent :: () -> float64 {
value := ParseAtom()
while failure == "" && Take("%") {
value /= 100.0
}
return value
}
ParseAtom :: () -> float64 {
if failure != "" {
return 0.0
}
if Take("(") {
value := ParseSum()
// A bracket still open at the end closes there.
SkipSpaces()
if !Take(")") && position < cast(s32)source.count {
failure = "Missing closing bracket"
}
return value
}
return ParseNumber()
}
ParseNumber :: () -> float64 {
SkipSpaces()
value: float64 = 0.0
digits: s32 = 0
while position < cast(s32)source.count && IsDigit(source[position]) {
value = value * 10.0 + cast(float64)(source[position] - cast(u8)48)
position += 1
digits += 1
}
if position < cast(s32)source.count && source[position] == cast(u8)46 {
position += 1
scale: float64 = 0.1
while position < cast(s32)source.count && IsDigit(source[position]) {
value += cast(float64)(source[position] - cast(u8)48) * scale
scale /= 10.0
position += 1
digits += 1
}
}
if digits == 0 {
failure = ifx position >= cast(s32)source.count then "Incomplete expression" else "Cannot read this expression"
}
return value
}
IsDigit :: (byte: u8) -> bool {
return byte >= cast(u8)48 && byte <= cast(u8)57
}
// Whole exponents multiply exactly; others are refused rather than
// approximated.
Power :: (base: float64, exponent: float64) -> float64 {
whole := cast(s64)exponent
if cast(float64)whole != exponent || whole > 4096 || whole < -4096 {
failure = "Powers must be whole numbers"
return 0.0
}
negative := whole < 0
if negative {
whole = 0 - whole
}
result: float64 = 1.0
factor := base
while whole > 0 {
if whole % 2 == 1 {
result *= factor
}
factor *= factor
whole /= 2
}
if negative {
if result == 0.0 {
failure = "Cannot divide by zero"
return 0.0
}
return 1.0 / result
}
return result
}
// Up to ten significant digits; very large and very small numbers use an
// exponent, such as 1.5e20.
FormatNumber :: (value: float64, output: []u8) -> string {
magnitude := ifx value < 0.0 then 0.0 - value else value
if magnitude != 0.0 && (magnitude >= 1.0e15 || magnitude < 1.0e-9) {
return FormatExponent(value, output)
}
whole_digits: s32 = 1
bound: float64 = 10.0
while magnitude >= bound && whole_digits < 15 {
bound *= 10.0
whole_digits += 1
}
places := 10 - whole_digits
if places < 0 {
places = 0
}
if places > 9 {
places = 9
}
return FormatDecimal(value, places, output)
}
FormatExponent :: (value: float64, output: []u8) -> string {
negative := value < 0.0
mantissa := ifx negative then 0.0 - value else value
exponent: s32 = 0
while mantissa >= 10.0 {
mantissa /= 10.0
exponent += 1
}
while mantissa < 1.0 {
mantissa *= 10.0
exponent -= 1
}
digits: [32]u8
text := FormatDecimal(ifx negative then 0.0 - mantissa else mantissa, 9, digits[:])
power: [24]u8
exponent_text := FormatInteger(cast(s64)exponent, power[:])
used: s32 = 0
used = AppendTo(output, used, text)
used = AppendTo(output, used, "e")
used = AppendTo(output, used, exponent_text)
return TextView(output[0:used])
}
AppendTo :: (output: []u8, used: s32, text: string) -> s32 {
index: s32 = 0
while index < cast(s32)text.count && used < cast(s32)output.count - 1 {
output[used] = text[index]
used += 1
index += 1
}
output[used] = cast(u8)0
return used
}
+35
View File
@@ -0,0 +1,35 @@
// The Calculator's expressions and number formatting.
#import "arithmetic"
Shows :: (expression: string, expected: string) -> bool {
answer := EvaluateExpression(expression)
if !answer.valid {
return false
}
output: [64]u8
return FormatNumber(answer.value, output[:]) == expected
}
Refuses :: (expression: string) -> bool {
return !EvaluateExpression(expression).valid
}
#program_export
Run :: () -> s32 {
if !Shows("12+30×2", "72") || !Shows("12+30*2", "72") || !Shows("(1+2)×3", "9") {
return 1
}
if !Shows("7÷2", "3.5") || !Shows("1÷3", "0.333333333") || !Shows("2^10", "1024") {
return 2
}
if !Shows("50%", "0.5") || !Shows("−4+1", "-3") || !Shows("2×(3+4", "14") {
return 3
}
if !Shows("0.1+0.2", "0.3") || !Shows("10^20", "1e20") || !Shows("2^-2", "0.25") {
return 4
}
if !Refuses("1÷0") || !Refuses("2^0.5") || !Refuses("3+") || !Refuses("4)") {
return 5
}
return 0
}
+239
View File
@@ -0,0 +1,239 @@
// Calculator: a keypad and keyboard calculator for ordinary arithmetic with
// brackets. It keeps the expression and the last result in memory only.
#import "session"
#import "geometry"
#import "text_props"
#import "text_align"
#import "text_widget"
#import "button_props"
#import "button_widget"
#import "control_props"
#import "box_props"
#import "box_widget"
#import "text_buffer"
#import "number_text"
#import "werk_app"
#import "app_protocol"
#import "arithmetic"
Icon :: #import "mingcute_regular_counter";
DeleteBack :: #import "mingcute_regular_delete_back";
using ButtonTone;
using ButtonEmphasis;
EXPRESSION_LIMIT :: 256
expression: [EXPRESSION_LIMIT]u8;
expression_length: s32;
result_text: [64]u8;
// The expression shows the last result, which typing a digit replaces.
showing_result: bool;
ExpressionText :: () -> string {
return TextView(expression[0:expression_length])
}
Clear :: () {
expression_length = 0
result_text[0] = cast(u8)0
showing_result = false
}
Append :: (text: string) {
starts_number := text[0] >= cast(u8)48 && text[0] <= cast(u8)57 || text[0] == cast(u8)46 ||
text[0] == cast(u8)40
if showing_result && starts_number {
expression_length = 0
}
showing_result = false
result_text[0] = cast(u8)0
if expression_length + cast(s32)text.count > EXPRESSION_LIMIT {
return
}
index: s32 = 0
while index < cast(s32)text.count {
expression[expression_length] = text[index]
expression_length += 1
index += 1
}
}
Backspace :: () {
showing_result = false
result_text[0] = cast(u8)0
if expression_length == 0 {
return
}
expression_length -= 1
// Remove a whole UTF-8 sequence, such as the multiplication sign.
while expression_length > 0 && (expression[expression_length] & cast(u8)0xC0) == cast(u8)0x80 {
expression_length -= 1
}
}
Evaluate :: () {
if expression_length == 0 {
return
}
answer := EvaluateExpression(ExpressionText())
if !answer.valid {
CopyResult(answer.error)
return
}
formatted: [64]u8
text := FormatNumber(answer.value, formatted[:])
expression_length = 0
Append(text)
showing_result = true
result_text[0] = cast(u8)0
}
CopyResult :: (text: string) {
index: s32 = 0
while index < cast(s32)text.count && index < 63 {
result_text[index] = text[index]
index += 1
}
result_text[index] = cast(u8)0
}
// Typed characters and keys act like the keypad.
Keyboard :: () {
key := AppKey()
if key == 257 || key == 335 {
Evaluate()
}
if key == 259 {
Backspace()
}
if key == 256 {
Clear()
}
typed := AppFieldInput().text
index: s32 = 0
while index < cast(s32)typed.count {
byte := typed[index]
if byte >= cast(u8)48 && byte <= cast(u8)57 || byte == cast(u8)46 || byte == cast(u8)40 ||
byte == cast(u8)41 || byte == cast(u8)43 || byte == cast(u8)45 || byte == cast(u8)37 ||
byte == cast(u8)94 {
Append(typed[index:index + 1])
}
if byte == cast(u8)42 {
Append("×")
}
if byte == cast(u8)47 {
Append("÷")
}
if byte == cast(u8)44 {
Append(".")
}
if byte == cast(u8)61 {
Evaluate()
}
index += 1
}
}
KEYS :: 20
Key :: struct {
label: string
input: string
accent: bool
}
KeyAt :: (index: s32) -> Key {
labels: [KEYS]string = .["C", "(", ")", "÷",
"7", "8", "9", "×",
"4", "5", "6", "−",
"1", "2", "3", "+",
"Delete", "0", ".", "="]
inputs: [KEYS]string = .["", "(", ")", "÷",
"7", "8", "9", "×",
"4", "5", "6", "-",
"1", "2", "3", "+",
"", "0", ".", ""]
return Key.{.label = labels[index], .input = inputs[index], .accent = index == 19}
}
Press :: (index: s32) {
if index == 0 {
Clear()
return
}
if index == 16 {
Backspace()
return
}
if index == 19 {
Evaluate()
return
}
Append(KeyAt(index).input)
}
Draw :: () {
session := AppSession()
area := AppBounds()
gap: float32 = 8.0
width := area.width - 32.0
if width > 420.0 {
width = 420.0
}
left := area.x + (area.width - width) * 0.5
top := area.y + 16.0
display := Rectangle.{left, top, width, 112.0}
Box(session, BoxProps.{.key = cast(u64)1, .bounds = display, .radius = 12.0})
shown := ExpressionText()
if shown == "" {
shown = "0"
}
Text(session, TextProps.{.key = cast(u64)2,
.bounds = Rectangle.{left + 16.0, top + 16.0, width - 32.0, 48.0},
.text = shown, .font = 32, .align = TextAlign.TextAlignEnd, .wrap = TextWrap.TextWrapEllipsis})
Text(session, TextProps.{.key = cast(u64)3,
.bounds = Rectangle.{left + 16.0, top + 72.0, width - 32.0, 24.0},
.text = TextUntilNul(result_text[:]), .font = 16, .align = TextAlign.TextAlignEnd})
pad_top := top + 112.0 + gap * 2.0
rows: float32 = 5.0
key_width := (width - gap * 3.0) / 4.0
key_height := (area.y + area.height - 16.0 - pad_top - gap * (rows - 1.0)) / rows
if key_height > 72.0 {
key_height = 72.0
}
if key_height < 36.0 {
key_height = 36.0
}
index: s32 = 0
while index < KEYS {
key := KeyAt(index)
column := cast(float32)(index % 4)
row := cast(float32)(index / 4)
bounds := Rectangle.{left + column * (key_width + gap), pad_top + row * (key_height + gap),
key_width, key_height}
props := ButtonProps.{.key = cast(u64)(100 + index), .id = 100 + index, .bounds = bounds,
.label = key.label,
.tone = cast(ButtonTone)(ifx key.accent then ButtonToneAccent else ButtonToneNeutral),
.emphasis = cast(ButtonEmphasis)(ifx key.accent then ButtonEmphasisFilled else ButtonEmphasisSoft)}
// Delete is an icon on a key as wide as the others.
if index == 16 {
props.icon_shape = DeleteBack.Shape
props.label = ""
}
if Button(session, props) != 0 {
Press(index)
}
index += 1
}
}
#program_export "CalculatorMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppDescribe("Calculator", Icon.Shape)
return APP_PROTOCOL
}
Keyboard()
Draw()
return 0
}
+271
View File
@@ -0,0 +1,271 @@
// Clock: the local time and date, and a stopwatch that keeps running while
// the app is closed.
#import "session"
#import "geometry"
#import "text_props"
#import "text_align"
#import "text_widget"
#import "button_props"
#import "button_widget"
#import "control_props"
#import "text_buffer"
#import "number_text"
#import "werk_app"
#import "app_protocol"
Icon :: #import "mingcute_regular_time";
VIEW_CLOCK :: 0
VIEW_STOPWATCH :: 1
Civil :: struct {
year: s64
month: s32
day: s32
weekday: s32
}
view: s32;
loaded: bool;
running: bool;
// While running, the wall time it started from; the time counted before
// that start is in elapsed.
started_at: float64;
elapsed: float64;
session: Session;
// The civil date of a day count since 1970-01-01 (proleptic Gregorian).
CivilFromDays :: (days: s64) -> Civil {
shifted := days + 719468
era := ifx shifted >= 0 then shifted / 146097 else (shifted - 146096) / 146097
day_of_era := shifted - era * 146097
year_of_era := (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146096) / 365
day_of_year := day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100)
month_index := (5 * day_of_year + 2) / 153
result: Civil
result.day = cast(s32)(day_of_year - (153 * month_index + 2) / 5 + 1)
result.month = cast(s32)(ifx month_index < 10 then month_index + 3 else month_index - 9)
result.year = year_of_era + era * 400 + (ifx result.month <= 2 then 1 else 0)
weekday := (days + 4) % 7
if weekday < 0 {
weekday += 7
}
result.weekday = cast(s32)weekday
return result
}
Append :: (output: []u8, used: s32, text: string) -> s32 {
index: s32 = 0
while index < cast(s32)text.count && used < cast(s32)output.count - 1 {
output[used] = text[index]
used += 1
index += 1
}
output[used] = cast(u8)0
return used
}
AppendTwoDigits :: (output: []u8, used: s32, value: s64) -> s32 {
digits: [3]u8
digits[0] = cast(u8)(48 + cast(s32)((value / 10) % 10))
digits[1] = cast(u8)(48 + cast(s32)(value % 10))
return Append(output, used, TextView(digits[0:2]))
}
AppendNumber :: (output: []u8, used: s32, value: s64) -> s32 {
number: [24]u8
return Append(output, used, FormatInteger(value, number[:]))
}
LocalSeconds :: () -> s64 {
now := AppNow()
seconds := cast(s64)now
if cast(float64)seconds > now {
seconds -= 1
}
return seconds + cast(s64)AppLocalOffset()
}
TimeText :: (output: []u8) -> string {
seconds := LocalSeconds()
of_day := seconds % 86400
if of_day < 0 {
of_day += 86400
}
used := AppendTwoDigits(output, 0, of_day / 3600)
used = Append(output, used, ":")
used = AppendTwoDigits(output, used, (of_day / 60) % 60)
used = Append(output, used, ":")
used = AppendTwoDigits(output, used, of_day % 60)
return TextView(output[0:used])
}
DateText :: (output: []u8) -> string {
seconds := LocalSeconds()
days := seconds / 86400
if seconds < 0 && seconds % 86400 != 0 {
days -= 1
}
date := CivilFromDays(days)
weekdays: [7]string = .["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
months: [12]string = .["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"]
used := Append(output, 0, weekdays[date.weekday])
used = Append(output, used, ", ")
used = AppendNumber(output, used, cast(s64)date.day)
used = Append(output, used, " ")
used = Append(output, used, months[date.month - 1])
used = Append(output, used, " ")
used = AppendNumber(output, used, date.year)
return TextView(output[0:used])
}
StopwatchSeconds :: () -> float64 {
total := elapsed
if running {
total += AppNow() - started_at
}
if total < 0.0 {
return 0.0
}
return total
}
// h:mm:ss.t, or m:ss.t under an hour.
StopwatchText :: (output: []u8) -> string {
tenths := cast(s64)(StopwatchSeconds() * 10.0)
seconds := tenths / 10
used: s32 = 0
if seconds >= 3600 {
used = AppendNumber(output, used, seconds / 3600)
used = Append(output, used, ":")
used = AppendTwoDigits(output, used, (seconds / 60) % 60)
} else {
used = AppendNumber(output, used, seconds / 60)
}
used = Append(output, used, ":")
used = AppendTwoDigits(output, used, seconds % 60)
used = Append(output, used, ".")
used = AppendNumber(output, used, tenths % 10)
return TextView(output[0:used])
}
// stopwatch.txt holds "running started_at elapsed" in milliseconds.
LoadStopwatch :: () {
buffer: [128]u8
count := ReadStore("stopwatch.txt", buffer[:])
if count <= 0 {
return
}
values: [3]s64
field: s32 = 0
index: s32 = 0
negative := false
while index < count && field < 3 {
byte := buffer[index]
if byte == cast(u8)32 {
if negative {
values[field] = 0 - values[field]
}
field += 1
negative = false
} else if byte == cast(u8)45 {
negative = true
} else if byte >= cast(u8)48 && byte <= cast(u8)57 {
values[field] = values[field] * 10 + cast(s64)(byte - cast(u8)48)
} else {
return
}
index += 1
}
if field < 3 && negative {
values[field] = 0 - values[field]
}
if field < 2 {
return
}
running = values[0] == 1
started_at = cast(float64)values[1] / 1000.0
elapsed = cast(float64)values[2] / 1000.0
}
SaveStopwatch :: () {
buffer: [128]u8
used := AppendNumber(buffer[:], 0, ifx running then 1 else 0)
used = Append(buffer[:], used, " ")
used = AppendNumber(buffer[:], used, cast(s64)(started_at * 1000.0))
used = Append(buffer[:], used, " ")
used = AppendNumber(buffer[:], used, cast(s64)(elapsed * 1000.0))
unused WriteStore("stopwatch.txt", TextView(buffer[0:used]))
}
Big :: (key: u64, text: string, area: Rectangle, y: float32, font: s32) {
Text(session, TextProps.{.key = key, .bounds = Rectangle.{area.x + 16.0, y, area.width - 32.0, cast(float32)(font + 16)},
.text = text, .font = font, .align = TextAlign.TextAlignCenter})
}
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
}
Draw :: () {
session = AppSession()
area := AppBounds()
width := area.width - 32.0
if width > 420.0 {
width = 420.0
}
left := area.x + (area.width - width) * 0.5
half := (width - 8.0) / 2.0
if Action(1, "Clock", Rectangle.{left, area.y + 16.0, half, 40.0}, view == VIEW_CLOCK) {
view = VIEW_CLOCK
}
if Action(2, "Stopwatch", Rectangle.{left + half + 8.0, area.y + 16.0, half, 40.0}, view == VIEW_STOPWATCH) {
view = VIEW_STOPWATCH
}
middle := area.y + area.height * 0.35
text: [64]u8
if view == VIEW_CLOCK {
Big(cast(u64)10, TimeText(text[:]), area, middle - 40.0, 56)
date: [96]u8
Big(cast(u64)11, DateText(date[:]), area, middle + 40.0, 18)
return
}
Big(cast(u64)20, StopwatchText(text[:]), area, middle - 40.0, 56)
buttons_y := middle + 56.0
if Action(21, ifx running then "Stop" else "Start", Rectangle.{left, buttons_y, half, 48.0}, true) {
now := AppNow()
if running {
elapsed += now - started_at
} else {
started_at = now
}
running = !running
SaveStopwatch()
}
if Action(22, "Reset", Rectangle.{left + half + 8.0, buttons_y, half, 48.0}, false) {
running = false
elapsed = 0.0
started_at = 0.0
SaveStopwatch()
}
}
#program_export "ClockMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppDescribe("Clock", Icon.Shape)
return APP_PROTOCOL
}
if !loaded {
LoadStopwatch()
loaded = true
}
Draw()
return 0
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

+230
View File
@@ -0,0 +1,230 @@
#import "pass_core"
#import "pass_text"
#import "byte_text_linux"
#import "version"
#import "c_string"
#import "text_buffer"
#if !#defined(PLAN9_BUILD) {
#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";
}
Usage :: #string END
Usage: pass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
pass [OPTIONS] PROFILE SITE
Derive a site-specific password.
Options:
-L, --length N password length (default 16, min 5, max 35)
-C, --counter N generation counter (default 1)
-l, --lowercase include lowercase letters
-u, --uppercase include uppercase letters
-d, --digits include digits
-s, --symbols include symbols
--no-lowercase exclude lowercase letters
--no-uppercase exclude uppercase letters
--no-digits exclude digits
--no-symbols exclude symbols
--exclude CHARS remove characters from all enabled classes
-p, --prompt read the master password from stdin
-P, --profile NAME use a saved login and generation settings
--vault PATH unlock an OpenSSL-encrypted master password
--clear-after TIME release copied password after e.g. 90s
-c, --copy copy the result to the X11 clipboard
--no-copy print instead of copying
-v, --version show version
-h, --help show this help
END;
Print :: (fd: s32, value: string) {
buffer: [4096]u8
offset: s32 = 0
while offset < cast(s32)value.count {
count: s32 = cast(s32)value.count - offset
if count > 4096 { count = 4096 }
index: s32 = 0
while index < count { buffer[index] = value[offset + index]; index += 1 }
written: s32 = 0
while written < count {
result: isize = Write(fd, *buffer[written], cast(usize)(count - written))
if result <= cast(isize)0 { return }
written += cast(s32)result
}
offset += count
}
}
Error :: (message: string) -> s32 {
Print(2, "pass: "); Print(2, message); Print(2, "\n")
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
options.length = 16; options.counter = cast(u64)1
options.lowercase = true; options.uppercase = true
options.digits = true; options.symbols = true
prompt: bool; copy: bool; no_copy: bool; version: bool
profile_name: string; vault_path: string; clear_after: string
explicit: u32
positional: [3]string
count: s32 = 0
index: s32 = 1
while index < argc {
arg := TextFromCString(argv[index])
if arg == "-h" || arg == "--help" { Print(1, Usage); return 0 }
if arg == "-v" || arg == "--version" { version = true }
else if arg == "-L" || arg == "--length" || arg == "-C" ||
arg == "--counter" || arg == "--exclude" || arg == "-P" ||
arg == "--profile" || arg == "--vault" || arg == "--clear-after" {
if index + 1 >= argc {
Print(2, "pass: "); Print(2, arg); Print(2, " requires a value\n")
Print(2, Usage); return 2
}
index += 1
value := TextFromCString(argv[index])
if arg == "--exclude" { options.exclude = value; explicit |= cast(u32)64 }
else if arg == "-P" || arg == "--profile" { profile_name = value }
else if arg == "--vault" { vault_path = value }
else if arg == "--clear-after" { clear_after = value }
else {
number := ParseNumber(value)
if !number.valid { Print(2, Usage); return 2 }
if arg == "-L" || arg == "--length" {
if number.value > 2147483647 || number.value < -2147483647 { Print(2, Usage); return 2 }
options.length = cast(s32)number.value
explicit |= cast(u32)1
} else {
if number.value < 0 { number.value = 0 }
options.counter = cast(u64)number.value
explicit |= cast(u32)2
}
}
} else {
handled: bool = true
if arg == "-l" || arg == "--lowercase" { options.lowercase = true; explicit |= cast(u32)4 }
else if arg == "-u" || arg == "--uppercase" { options.uppercase = true; explicit |= cast(u32)8 }
else if arg == "-d" || arg == "--digits" { options.digits = true; explicit |= cast(u32)16 }
else if arg == "-s" || arg == "--symbols" { options.symbols = true; explicit |= cast(u32)32 }
else if arg == "--no-lowercase" { options.lowercase = false; explicit |= cast(u32)4 }
else if arg == "--no-uppercase" { options.uppercase = false; explicit |= cast(u32)8 }
else if arg == "--no-digits" { options.digits = false; explicit |= cast(u32)16 }
else if arg == "--no-symbols" { options.symbols = false; explicit |= cast(u32)32 }
else if arg == "-p" || arg == "--prompt" { prompt = true }
else if arg == "-c" || arg == "--copy" { copy = true }
else if arg == "--no-copy" { no_copy = true }
else { handled = false }
if !handled {
if arg.count > 0 && arg[0] == cast(u8)45 { return Error("unknown option") }
if count >= 3 { return Error("too many positional arguments") }
positional[count] = arg; count += 1
}
}
index += 1
}
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
}
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]
}
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
defer { ClearBytes(master[:]) }
if count == 3 {
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 !unlocked {
name: [32]u8
CopyCString("LESSPASS_MASTER_PASSWORD", name[:])
environment: *u8 = GetEnv(*name[0])
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") }
}
}
}
}
generated := PassGenerate(site, login, TextUntilNul(master[:]), options)
defer { ClearBytes(generated.password[:]) }
ClearBytes(master[:])
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
}
}
Print(1, TextView(generated.password[0:generated.length])); Print(1, "\n")
return 0
}
+198
View File
@@ -0,0 +1,198 @@
#import "pass_text"
#import "std/c_string"
#import "std/text_buffer"
#import "std/byte_text_linux"
Capture :: #import "std/process_capture_linux";
Channel :: #import "std/process_channel_linux";
Socket :: #import "std/socket_linux";
Timer :: #import "std/timer_linux";
libc :: #system_library "libc";
NativeRead :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "read";
NativeWrite :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign libc "write";
NativeOpen :: (path: *u8, flags: s32) -> s32 #foreign libc "open";
NativeClose :: (fd: s32) -> s32 #foreign libc "close";
NativeEnv :: (name: *u8) -> *u8 #foreign libc "getenv";
NativeIsTty :: (fd: s32) -> s32 #foreign libc "isatty";
NativeGetTerminal :: (fd: s32, state: *void) -> s32 #foreign libc "tcgetattr";
NativeSetTerminal :: (fd: s32, action: s32, state: *void) -> s32 #foreign libc "tcsetattr";
NativeSession :: () -> s32 #foreign libc "setsid";
NativeShutdown :: (fd: s32, direction: s32) -> s32 #foreign libc "shutdown";
NativePipe :: (fds: *s32) -> s32 #foreign libc "pipe";
NativeFork :: () -> s32 #foreign libc "fork";
NativeDup :: (source: s32, destination: s32) -> s32 #foreign libc "dup2";
NativeExit :: (code: s32) -> void #foreign libc "_exit";
NativeWait :: (pid: s32, status: *s32, options: s32) -> s32 #foreign libc "waitpid";
SignalHandler :: #type (signal: s32) #c_call;
NativeSignal :: (signal: s32, handler: SignalHandler) -> SignalHandler #foreign libc "signal";
terminal_fd: s32 = -1;
terminal_state: [32]u64;
RestoreTerminalOnSignal :: (signal: s32) {
if terminal_fd >= 0 { unused NativeSetTerminal(terminal_fd, 0, cast(*void)*terminal_state[0]) }
NativeExit(128 + signal)
}
EnvironmentText :: (name: string) -> string {
bytes: [128]u8
if !CopyCString(name, bytes[:]) { return "" }
value := NativeEnv(*bytes[0])
if value == null { return "" }
return TextFromCString(value)
}
ExpandHomePath :: (value: string, output: []u8) -> bool {
if value == "~" || (value.count >= 2 && value[0:2] == "~/") {
home := EnvironmentText("HOME")
if home == "" { return false }
return AppendText(output, AppendText(output, 0, home), value[1:]) >= 0
}
return CopyCString(value, output)
}
// 0 means no file; -1 is an unreadable, oversized or invalid configuration.
ReadProfileDocument :: (output: []u8) -> s32 {
path: [4096]u8
base := EnvironmentText("XDG_CONFIG_HOME")
if base != "" { if !CopyCString(base, path[:]) { return -1 } }
else if !ExpandHomePath("~/.config", path[:]) { return 0 }
if AppendText(path[:], cast(s32)TextUntilNul(path[:]).count, "/pass/profiles.json") < 0 { return -1 }
fd := NativeOpen(*path[0], 0)
if fd < 0 { if Socket.LinuxErrno() == 2 { return 0 }; return -1 }
defer { unused NativeClose(fd) }
used: s32
while used < cast(s32)output.count - 1 {
count := NativeRead(fd, *output[used], cast(usize)(cast(s32)output.count - 1 - used))
if count < cast(isize)0 { return -1 }
if count == cast(isize)0 { output[used] = cast(u8)0; return used + 1 }
used += cast(s32)count
}
return -1
}
ReadSecret :: (buffer: []u8, prompt: string) -> bool {
fd: s32 = 0
terminal := NativeIsTty(fd) == 1
previous: [4]SignalHandler
signals: [4]s32 = .[1, 2, 3, 15]
if terminal {
if NativeGetTerminal(fd, cast(*void)*terminal_state[0]) != 0 { return false }
terminal_fd = fd
for i: 0..3 { previous[i] = NativeSignal(signals[i], RestoreTerminalOnSignal) }
}
defer {
if terminal {
unused NativeSetTerminal(fd, 0, cast(*void)*terminal_state[0])
terminal_fd = -1
restored: s32 = 0
while restored < 4 {
unused NativeSignal(signals[restored], previous[restored]); restored += 1
}
newline: [1]u8 = .[cast(u8)10]
unused NativeWrite(2, *newline[0], cast(usize)1)
}
}
if terminal {
// stty owns the platform-specific termios layout. The opaque saved
// state is restored even when input is cancelled with Ctrl-C.
ignored: [128]u8
args: [8]string = .["stty", "-echo", "-isig", "-icanon", "min", "1", "time", "0"]
changed := Capture.CaptureOutput(args[:], ignored[:])
if changed.error || changed.code != 0 { return false }
message: [128]u8
if CopyCString(prompt, message[:]) { unused NativeWrite(2, *message[0], cast(usize)prompt.count) }
}
used: s32
while used < cast(s32)buffer.count - 1 {
byte: u8
if NativeRead(fd, *byte, cast(usize)1) != cast(isize)1 { return used > 0 }
if byte == cast(u8)0 || byte == cast(u8)3 || byte == cast(u8)4 { return false }
if terminal && (byte == cast(u8)8 || byte == cast(u8)127) {
if used > 0 { used -= 1; buffer[used] = cast(u8)0 }
continue
}
if terminal && byte == cast(u8)21 { ClearBytes(buffer); used = 0; continue }
if byte == cast(u8)10 {
if used > 0 && buffer[used - 1] == cast(u8)13 { used -= 1 }
buffer[used] = cast(u8)0; return true
}
buffer[used] = byte; used += 1
}
return false
}
DecryptVault :: (vault: string, output: []u8) -> bool {
path: [4096]u8
if !ExpandHomePath(vault, path[:]) { return false }
passphrase: [1024]u8
defer { ClearBytes(passphrase[:]) }
if !ReadSecret(passphrase[:], "Vault passphrase: ") { return false }
args: [16]string = .["openssl", "enc", "-d", "-aes-256-cbc", "-md", "sha512", "-a", "-A", "-pbkdf2", "-iter", "100000", "-in", TextUntilNul(path[:]), "-pass", "stdin", "-salt"]
child := Channel.StartChannel(args[:], false)
if child.error != 0 { return false }
defer { unused Channel.CloseChannel(*child, 1000) }
length := cast(s32)TextUntilNul(passphrase[:]).count
passphrase[length] = cast(u8)10
if Channel.ChannelSend(child, passphrase[0:length + 1], 3000) < 0 { return false }
unused NativeShutdown(child.socket.fd, 1)
used: s32
while used < cast(s32)output.count - 1 {
count := Channel.ChannelReceive(child, output[used:cast(s32)output.count - 1], 10000)
if count < 0 { return false }
if count == 0 { break }
used += cast(s32)count
}
if used >= cast(s32)output.count - 1 || !Channel.WaitChannel(*child, 1000) || child.code != 0 { return false }
while used > 0 && output[used - 1] == cast(u8)10 { used -= 1 }
for i: 0..used - 1 { if output[i] == cast(u8)0 { return false } }
output[used] = cast(u8)0
return true
}
// A detached supervisor retains only its own clipboard child. Expiration
// releases that selection; it never clears a replacement owner's clipboard.
CopyPassword :: (value: string, clear_ms: s64) -> bool {
if EnvironmentText("DISPLAY") == "" { return false }
ready: [2]s32
if NativePipe(*ready[0]) != 0 { return false }
pid := NativeFork()
if pid < 0 { unused NativeClose(ready[0]); unused NativeClose(ready[1]); return false }
if pid == 0 {
unused NativeClose(ready[0]); unused NativeSession()
null_path: [16]u8; CopyCString("/dev/null", null_path[:])
null_fd := NativeOpen(*null_path[0], 2)
if null_fd >= 0 {
for i: 0..2 { unused NativeDup(null_fd, cast(s32)i) }
if null_fd > 2 { unused NativeClose(null_fd) }
}
args: [5]string = .["xclip", "-selection", "clipboard", "-in", "-quiet"]
child := Channel.StartChannel(args[:], false)
ok := child.error == 0
if ok {
payload: [36]u8
ok = CopyCString(value, payload[:])
if ok { ok = Channel.ChannelSend(child, payload[0:value.count], 3000) >= 0 }
ClearBytes(payload[:])
unused NativeShutdown(child.socket.fd, 1)
if Channel.WaitChannel(*child, 100) { ok = false }
}
answer: u8 = ifx ok then cast(u8)1 else cast(u8)0
unused NativeWrite(ready[1], *answer, cast(usize)1)
unused NativeClose(ready[1])
if ok {
started := Timer.MonotonicMilliseconds()
while !Channel.WaitChannel(*child, 100) {
if child.error != 0 || (clear_ms > 0 && Timer.MonotonicMilliseconds() - started >= clear_ms) { break }
}
}
unused Channel.CloseChannel(*child, 0)
NativeExit(0)
}
unused NativeClose(ready[1])
answer: u8
ok := NativeRead(ready[0], *answer, cast(usize)1) == cast(isize)1 && answer == cast(u8)1
unused NativeClose(ready[0])
if !ok { status: s32; unused NativeWait(pid, *status, 0) }
return ok
}
+106
View File
@@ -0,0 +1,106 @@
Json :: #import "std/json_scan";
#import "pass_core"
#import "pass_text"
#import "cli_native"
#import "std/text_buffer"
LegacyProfile :: struct {
found: bool
valid: bool
login: [1024]u8
vault: [4096]u8
exclude: [1024]u8
copy: bool
clear_ms: s64
}
profile_document: [65536]u8;
ProfileString :: (document: string, object: s32, name: string, output: []u8) -> bool {
at := Json.FieldAt(document, object, name)
if at < 0 || Json.MatchLiteral(document, at, "null") { return true }
return Json.ReadStringText(document, at, output) >= 0
}
ProfileBool :: (document: string, object: s32, name: string, value: *bool) -> bool {
at := Json.FieldAt(document, object, name)
if at < 0 || Json.MatchLiteral(document, at, "null") { return true }
if Json.MatchLiteral(document, at, "true") { <<value = true; return true }
if Json.MatchLiteral(document, at, "false") { <<value = false; return true }
return false
}
// The original CLI accepted Go-style durations; keep seconds, minutes, hours
// and fractional/composite values without placing any secrets in a command.
DurationMilliseconds :: (value: string) -> s64 {
if value == "0" { return 0 }
at: s32; total: float64
while at < cast(s32)value.count {
number := Json.ReadNumber(value, at)
if !number.valid || number.value < 0 { return -1 }
at = number.after
scale: float64
if at + 2 <= cast(s32)value.count && value[at:at + 2] == "ms" { scale = 1; at += 2 }
else if at < cast(s32)value.count && value[at] == cast(u8)115 { scale = 1000; at += 1 }
else if at < cast(s32)value.count && value[at] == cast(u8)109 { scale = 60000; at += 1 }
else if at < cast(s32)value.count && value[at] == cast(u8)104 { scale = 3600000; at += 1 }
else { return -1 }
total += number.value * scale
if total > 2147483647 { return -1 }
}
if at == 0 { return -1 }
return cast(s64)total
}
ProfileDefaults :: (document: string, object: s32, result: *LegacyProfile) -> bool {
if !ProfileString(document, object, "vault", result.vault[:]) ||
!ProfileBool(document, object, "copy", *result.copy) { return false }
duration: [128]u8
if !ProfileString(document, object, "clear_after", duration[:]) { return false }
if duration[0] != cast(u8)0 {
result.clear_ms = DurationMilliseconds(TextUntilNul(duration[:]))
if result.clear_ms < 0 { return false }
}
return true
}
LoadLegacyProfile :: (name: string, required: bool, options: *PassOptions,
explicit: u32) -> LegacyProfile {
result: LegacyProfile
loaded := ReadProfileDocument(profile_document[:])
if loaded < 0 { return result }
if loaded == 0 { result.valid = !required; return result }
document := TextUntilNul(profile_document[:])
start := Json.Space(document, 0)
end := Json.ValueEnd(document, start, 0)
if start >= cast(s32)document.count || document[start] != cast(u8)123 ||
end < 0 || Json.Space(document, end) != cast(s32)document.count { return result }
if !ProfileDefaults(document, start, *result) { return result }
profiles := Json.FieldAt(document, start, "profiles")
profile := Json.FieldAt(document, profiles, name)
if name == "" || profile < 0 { result.valid = !required; return result }
if document[profile] != cast(u8)123 ||
!ProfileString(document, profile, "login", result.login[:]) ||
result.login[0] == cast(u8)0 || !ProfileDefaults(document, profile, *result) { return result }
names: [2]string = .["length", "counter"]
for i: 0..1 {
at := Json.FieldAt(document, profile, names[i])
if at >= 0 && !Json.MatchLiteral(document, at, "null") {
after := Json.ValueEnd(document, at, 0)
number := ParseNumber(document[at:after])
if !number.valid || number.value < 0 { return result }
if i == 0 && number.value > 2147483647 { return result }
if number.value > 0 && (explicit & (cast(u32)1 << i)) == cast(u32)0 {
if i == 0 { options.length = cast(s32)number.value }
else { options.counter = cast(u64)number.value }
}
}
}
if (explicit & cast(u32)4) == cast(u32)0 && !ProfileBool(document, profile, "lowercase", *options.lowercase) { return result }
if (explicit & cast(u32)8) == cast(u32)0 && !ProfileBool(document, profile, "uppercase", *options.uppercase) { return result }
if (explicit & cast(u32)16) == cast(u32)0 && !ProfileBool(document, profile, "digits", *options.digits) { return result }
if (explicit & cast(u32)32) == cast(u32)0 && !ProfileBool(document, profile, "symbols", *options.symbols) { return result }
if !ProfileString(document, profile, "exclude", result.exclude[:]) { return result }
result.found = true; result.valid = true
return result
}
+487
View File
@@ -0,0 +1,487 @@
// Pass: a stateless password generator. The same site, login, master
// password and settings always give the same password, with no database.
#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 "checkbox_props"
#import "checkbox_widget"
#import "spinbox_props"
#import "spinbox_widget"
#import "box_props"
#import "box_widget"
#import "image_props"
#import "image_widget"
#import "scroll_props"
#import "scroll_widget"
#import "tree"
#import "text_buffer"
#import "utf8"
#import "werk_app"
#import "app_protocol"
#import "pass_core"
#import "pass_state"
#import "pass_text"
Icon :: #import "mingcute_regular_keyhole";
FieldState :: struct {
cursor: s32
anchor: s32
scroll_x: s32
}
initialized: bool;
view: s32;
focused: s32;
fields: [5]FieldState;
site: [256]u8;
login: [256]u8;
master: [1024]u8;
profile_name: [64]u8;
reveal: bool;
scroll_offsets: [3]s32;
emoji: [32]u8;
session: Session;
Label :: (value: string, x: float32, y: float32, width: float32, font: s32) {
props: TextProps
props.bounds = Rectangle.{x, y, width, cast(float32)(font + 8)}
props.text = value
props.font = font
Text(session, props)
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool, disabled: bool) -> bool {
props: ButtonProps
props.key = cast(u64)id
props.id = id
props.bounds = bounds
props.label = label
props.disabled = disabled
props.tone = ButtonTone.ButtonToneNeutral
props.emphasis = ButtonEmphasis.ButtonEmphasisSoft
if accent {
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button(session, props) == 1
}
ApplyEdit :: (buffer: []u8, edit: TextFieldEdit) -> bool {
if !edit.changed {
return false
}
length: s32 = 0
while length < cast(s32)buffer.count && buffer[length] != cast(u8)0 {
length += 1
}
if edit.start < 0 || edit.end < edit.start || edit.end > length {
return false
}
replacement: [1024]u8
used := length - (edit.end - edit.start) + cast(s32)edit.replacement.count
if used >= cast(s32)buffer.count || used >= 1024 {
return false
}
position: s32 = 0
while position < edit.start {
replacement[position] = buffer[position]
position += 1
}
index: s32 = 0
while index < cast(s32)edit.replacement.count {
replacement[position] = edit.replacement[index]
position += 1
index += 1
}
index = edit.end
while index < length {
replacement[position] = buffer[index]
position += 1
index += 1
}
index = 0
while index < cast(s32)buffer.count {
buffer[index] = ifx index < used then replacement[index] else cast(u8)0
index += 1
}
for wipe: 0..1023 {
replacement[wipe] = cast(u8)0
}
return true
}
Field :: (index: s32, label: string, buffer: []u8, bounds: Rectangle, secure: bool) {
snapshot: [1024]u8
mask: [1024]u8
// The views of the copies end with this block, before they are wiped.
{
props: TextFieldProps
position: s32 = 0
while position < cast(s32)buffer.count && position < 1023 {
snapshot[position] = buffer[position]
if buffer[position] == cast(u8)0 {
break
}
position += 1
}
props.key = cast(u64)(100 + index)
props.focus_id = 100 + index
props.bounds = bounds
props.label = label
props.value = TextUntilNul(snapshot[:])
props.cursor = fields[index].cursor
props.anchor = fields[index].anchor
props.scroll_x = fields[index].scroll_x
props.focused = focused == index + 1
props.max_bytes = cast(s32)buffer.count - 1
props.max_codepoints = props.max_bytes
props.secure = secure
if secure {
count := Codepoints(props.value)
if count > 1023 {
count = 1023
}
masked: s32 = 0
while masked < count {
mask[masked] = cast(u8)42
masked += 1
}
props.display_value = TextView(mask[0:count])
}
if props.focused {
props.input = AppFieldInput()
}
result := TextField(session, props)
fields[index].cursor = result.cursor
fields[index].anchor = result.anchor
fields[index].scroll_x = result.scroll_x
unused ApplyEdit(buffer, result.edit)
if result.focused {
focused = index + 1
}
if result.escaped && focused == index + 1 {
focused = 0
}
}
for wipe: 0..1023 {
snapshot[wipe] = cast(u8)0
mask[wipe] = cast(u8)0
}
}
// The number of characters in UTF-8 text.
Codepoints :: (text: string) -> s32 {
count: s32 = 0
index: s64 = 0
while index < text.count {
if (text[index] & cast(u8)0xC0) != cast(u8)0x80 {
count += 1
}
index += 1
}
return count
}
Check :: (id: s32, label: string, value: bool, bounds: Rectangle) -> bool {
props: CheckboxProps
props.key = cast(u64)id
props.id = id
props.label = label
props.bounds = bounds
props.checked = value
return Checkbox(session, props).checked
}
Integer :: (id: s32, label: string, value: s32, low: s32, high: s32, x: float32, y: float32, width: float32) -> s32 {
Label(label, x, y + 8.0, width - 160.0, 16)
props: SpinboxProps
props.key = cast(u64)id
props.id = id
props.label = label
props.bounds = Rectangle.{x + width - 150.0, y, 150.0, 38.0}
props.value = value
props.min = low
props.max = high
props.step = 1
return Spinbox(session, props).value
}
CurrentOptions :: () -> PassOptions {
options: PassOptions
options.length = runtime.settings.length
options.counter = cast(u64)runtime.settings.counter
options.lowercase = runtime.settings.lower
options.uppercase = runtime.settings.upper
options.digits = runtime.settings.digits
options.symbols = runtime.settings.symbols
options.exclude = TextUntilNul(runtime.settings.exclude[:])
return options
}
CurrentProfile :: () -> Profile {
profile: Profile
profile.name = profile_name
profile.site = site
profile.login = login
profile.exclude = runtime.settings.exclude
profile.length = runtime.settings.length
profile.counter = runtime.settings.counter
profile.lower = runtime.settings.lower
profile.upper = runtime.settings.upper
profile.digits = runtime.settings.digits
profile.symbols = runtime.settings.symbols
return profile
}
// The four fingerprint emoji that let you notice a mistyped master password.
Fingerprint :: (x: float32, y: float32) {
used := MasterEmoji(TextUntilNul(master[:]), emoji[:])
atlas := AppAssetPath("fingerprint.png")
position: s32 = 0
for index: 0..3 {
decoded := Decode(TextView(emoji[0:used]), position)
glyph: s32 = 0
while glyph < 63 && cast(u32)master_emoji_codepoints[glyph] != decoded.value {
glyph += 1
}
props: ImageProps
props.asset_path = atlas
props.alt_text = TextView(emoji[position:decoded.after])
props.bounds = Rectangle.{x + cast(float32)index * 28.0, y, 24.0, 24.0}
props.source = Rectangle.{cast(float32)(glyph % 8) * 64.0, cast(float32)(glyph / 8) * 64.0, 64.0, 64.0}
props.tint = ifx AppDark() then cast(u32)0xe8e8e8ff else cast(u32)0x202c29ff
Image(session, props)
position = decoded.after
}
}
MasterField :: (x: float32, y: float32, width: float32) -> float32 {
Label("Master password", x, y, width, 14)
Field(2, "Master password", master[:], Rectangle.{x, y + 24.0, width - 86.0, 40.0}, !reveal)
if Action(13, ifx reveal then "Hide" else "Show", Rectangle.{x + width - 78.0, y + 24.0, 78.0, 40.0}, false, false) {
reveal = !reveal
}
y += 76.0
if runtime.settings.show_fingerprint && master[0] != cast(u8)0 {
Fingerprint(x, y)
y += 34.0
}
if HasSavedMaster() {
if Action(14, "Unlock master password", Rectangle.{x, y, width, 38.0}, false, false) {
focused = 0
unused UnlockMaster()
}
y += 48.0
}
return y
}
OptionsForm :: (x: float32, y: float32, width: float32) -> float32 {
runtime.settings.length = Integer(20, "Length", runtime.settings.length, 5, 35, x, y, width)
y += 50.0
runtime.settings.counter = Integer(21, "Counter", runtime.settings.counter, 1, 999999, x, y, width)
y += 50.0
part := width / 4.0
runtime.settings.lower = Check(31, "a-z", runtime.settings.lower, Rectangle.{x, y, part, 36.0})
runtime.settings.upper = Check(32, "A-Z", runtime.settings.upper, Rectangle.{x + part, y, part, 36.0})
runtime.settings.digits = Check(33, "0-9", runtime.settings.digits, Rectangle.{x + part * 2.0, y, part, 36.0})
runtime.settings.symbols = Check(34, "#", runtime.settings.symbols, Rectangle.{x + part * 3.0, y, part, 36.0})
y += 48.0
Label("Exclude", x, y, width, 14)
Field(3, "Exclude", runtime.settings.exclude[:], Rectangle.{x, y + 24.0, width, 40.0}, false)
return y + 76.0
}
GenerateForm :: (x: float32, y: float32, width: float32) {
Label("Site", x, y, width, 14)
Field(0, "Site", site[:], Rectangle.{x, y + 24.0, width, 40.0}, false)
y += 76.0
Label("Login", x, y, width, 14)
Field(1, "Login", login[:], Rectangle.{x, y + 24.0, width, 40.0}, false)
y += 76.0
y = MasterField(x, y, width)
y = OptionsForm(x, y, width)
if Action(40, "Generate", Rectangle.{x, y, width, 44.0}, true, false) {
focused = 0
unused Generate(TextUntilNul(site[:]), TextUntilNul(login[:]), TextUntilNul(master[:]), CurrentOptions())
scroll_offsets[0] = 10000
}
y += 60.0
Label("Generated password", x, y, width, 14)
y += 28.0
props: BoxProps
props.key = cast(u64)42
props.bounds = Rectangle.{x, y, width, 54.0}
props.radius = 8.0
Box(session, props)
Label(ifx Generated() == "" then "Password will appear here" else Generated(), x + 10.0, y + 16.0, width - 20.0, 16)
y += 68.0
if Action(41, "Copy", Rectangle.{x, y, width, 40.0}, false, false) {
unused CopyPassword()
}
}
ProfilesForm :: (x: float32, y: float32, width: float32) {
Label("Profile name", x, y, width, 14)
Field(4, "Profile name", profile_name[:], Rectangle.{x, y + 24.0, width, 40.0}, false)
y += 76.0
if Action(210, "Save Current Profile", Rectangle.{x, y, width, 42.0}, true, false) {
unused SaveProfile(CurrentProfile())
}
y += 60.0
if runtime.profile_count == 0 {
Label("No saved profiles", x, y, width, 16)
}
index: s32 = 0
while index < runtime.profile_count {
Label(TextUntilNul(runtime.profiles[index].name[:]), x, y, width, 16)
Label(TextUntilNul(runtime.profiles[index].site[:]), x, y + 26.0, width, 12)
if Action(300 + index, "Generate", Rectangle.{x, y + 50.0, width * 0.6 - 4.0, 36.0}, false, false) {
unused GenerateProfile(index, TextUntilNul(master[:]))
view = 0
focused = 0
scroll_offsets[0] = 10000
}
if Action(400 + index, "Delete", Rectangle.{x + width * 0.6 + 4.0, y + 50.0, width * 0.4 - 4.0, 36.0}, false, false) {
unused DeleteProfile(index)
break
}
y += 102.0
index += 1
}
}
SettingsForm :: (x: float32, y: float32, width: float32) {
runtime.settings.auto_copy = Check(501, "Auto-copy after Generate", runtime.settings.auto_copy, Rectangle.{x, y, width, 36.0})
y += 48.0
runtime.settings.clear_seconds = Integer(502, "Clipboard seconds", runtime.settings.clear_seconds, 0, 3600, x, y, width)
y += 50.0
runtime.settings.show_fingerprint = Check(503, "Show master fingerprint", runtime.settings.show_fingerprint, Rectangle.{x, y, width, 36.0})
y += 54.0
Label("Generation defaults", x, y, width, 20)
y += 38.0
y = OptionsForm(x, y, width)
if Action(510, "Save Settings", Rectangle.{x, y, width, 42.0}, true, false) {
unused SaveSettings()
}
y += 60.0
Label("Secure master password", x, y, width, 20)
y += 38.0
y = MasterField(x, y, width)
Label(FingerprintStatus(), x, y, width, 12)
y += 36.0
if Action(520, "Save", Rectangle.{x, y, width / 2.0 - 4.0, 42.0}, true, !CanSaveMaster()) {
focused = 0
unused SaveMaster(TextUntilNul(master[:]))
}
if Action(522, "Forget", Rectangle.{x + width / 2.0 + 4.0, y, width / 2.0 - 4.0, 42.0}, false, !HasSavedMaster()) {
unused ForgetMaster()
}
}
// Tab moves between the fields of the current view.
FocusNext :: () {
if AppKey() != 258 {
return
}
if view == 0 {
if (AppModifiers() & 1) != 0 {
focused = ((focused + 2) % 4) + 1
} else {
focused = (focused % 4) + 1
}
}
if view == 1 {
focused = 5
}
if view == 2 {
focused = 3
}
}
Draw :: () {
session = AppSession()
area := AppBounds()
if runtime.has_unlocked_master {
master = runtime.unlocked_master
runtime.unlocked_master = .{}
runtime.has_unlocked_master = false
fields[2] = FieldState.{}
}
FocusNext()
pad: float32 = 18.0
width := area.width - pad * 2.0
if width > 480.0 {
width = 480.0
}
left := area.x + (area.width - width) * 0.5
height := area.height - 110.0
if height < 60.0 {
height = 60.0
}
content_height: s32 = 648
if runtime.settings.show_fingerprint && master[0] != cast(u8)0 {
content_height += 34
}
if HasSavedMaster() {
content_height += 48
}
if view == 1 {
content_height = 180 + runtime.profile_count * 102
}
if view == 2 {
content_height = 760
}
props: ScrollProps
props.key = cast(u64)(10 + view)
props.bounds = Rectangle.{left, area.y + 12.0, width, height}
props.content_height = content_height
props.scroll_offset = scroll_offsets[view]
props.scale = 1.0
scroll := Scroll(session, props)
scroll_offsets[view] = scroll.scroll_offset
if scroll.opened {
if view == 0 {
GenerateForm(scroll.content.x, scroll.content.y, scroll.content.width - 10.0)
}
if view == 1 {
ProfilesForm(scroll.content.x, scroll.content.y, scroll.content.width - 10.0)
}
if view == 2 {
SettingsForm(scroll.content.x, scroll.content.y, scroll.content.width - 10.0)
}
End(session)
}
Label(Status(), left, area.y + area.height - 88.0, width, 12)
labels: [3]string = .{"Generate", "Profiles", "Settings"}
for index: 0..2 {
tab := cast(s32)index
bounds := Rectangle.{left + cast(float32)index * width / 3.0, area.y + area.height - 58.0, width / 3.0 - 4.0, 46.0}
if Action(700 + tab, labels[index], bounds, view == tab, false) {
view = tab
focused = 0
}
}
AppKeyboard(focused != 0)
}
#program_export "PassMain"
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppDescribe("Pass", Icon.Shape)
return APP_PROTOCOL
}
if !initialized {
Initialize()
initialized = true
}
Tick()
Draw()
return 0
}
+330
View File
@@ -0,0 +1,330 @@
#import "sha256"
#if #defined(WERK_APP) {
#import "werk_app"
}
PassOptions :: struct {
length: s32
counter: u64
lowercase: bool
uppercase: bool
digits: bool
symbols: bool
exclude: string
}
PassClass :: struct {
bytes: [32]u8
count: s32
}
PassResult :: struct {
valid: bool
password: [36]u8
length: s32
error: string
}
EntropyState :: struct {
bytes: [32]u8
}
EntropyResult :: struct {
entropy: EntropyState
value: s32
}
master_emoji_codepoints: [64]s32 = .[
0x1F436, 0x1F431, 0x1F42D, 0x1F439, 0x1F430, 0x1F98A, 0x1F43B, 0x1F43C,
0x1F428, 0x1F42F, 0x1F981, 0x1F42E, 0x1F437, 0x1F438, 0x1F435, 0x1F414,
0x1F427, 0x1F989, 0x1F43A, 0x1F434, 0x1F984, 0x1F41D, 0x1F98B, 0x1F422,
0x1F34E, 0x1F34A, 0x1F34B, 0x1F349, 0x1F347, 0x1F353, 0x1F352, 0x1F351,
0x1F951, 0x1F33D, 0x1F355, 0x1F354, 0x1F35F, 0x1F369, 0x1F335, 0x1F332,
0x1F333, 0x1F334, 0x1F331, 0x1F33B, 0x1F338, 0x1F308, 0x2B50, 0x1F319,
0x1F525, 0x1F4A7, 0x26C4, 0x1F389, 0x1F3B8, 0x1F3AF, 0x1F3B2, 0x1F381,
0x1F680, 0x1F697, 0x2693, 0x1F3A8, 0x1F511, 0x1F4A1, 0x1F4DA, 0x1F3A7
];
// Whether the last DeriveKey failed; only the Werkzeug host can refuse.
derive_failed: bool;
DeriveKey :: (password: string, salt: string) -> [32]u8 {
derive_failed = false
// Inside Werkzeug the host derives the key natively; the portable
// interpreter would take minutes for 100,000 rounds.
#if #defined(WERK_APP) {
output: [32]u8
derive_failed = !AppPbkdf2Sha256(password, salt, 100000, output[:])
return output
} else {
return Pbkdf2Sha256(password, salt, 100000)
}
}
PassClassEmptyError :: (class_index: s32) -> string {
if class_index == 0 {
return "enabled lowercase character class is empty after exclusions"
}
if class_index == 1 {
return "enabled uppercase character class is empty after exclusions"
}
if class_index == 2 {
return "enabled digits character class is empty after exclusions"
}
return "enabled symbols character class is empty after exclusions"
}
PassFailure :: (message: string) -> PassResult {
result: PassResult
result.error = message
return result
}
PassFilterClass :: (characters: string, options: PassOptions) -> PassClass {
result: PassClass
character_index: s32 = 0
while character_index < cast(s32)characters.count {
excluded := false
exclude_index: s32 = 0
while exclude_index < cast(s32)options.exclude.count {
if options.exclude[exclude_index] == characters[character_index] {
excluded = true
break
}
exclude_index += 1
}
if !excluded && result.count < cast(s32)result.bytes.count {
result.bytes[result.count] = characters[character_index]
result.count += 1
}
character_index += 1
}
return result
}
PassAppendCounter :: (salt: []u8, offset: s32, counter: u64) -> s32 {
digits: [16]u8
digit_count: s32 = 0
value := counter
while value > cast(u64)0 {
nibble: u64 = value % cast(u64)16
if nibble < cast(u64)10 {
digits[digit_count] = cast(u8)(nibble + cast(u64)48)
} else {
digits[digit_count] = cast(u8)(nibble + cast(u64)87)
}
digit_count += 1
value /= cast(u64)16
}
if digit_count == 0 {
salt[offset] = cast(u8)48
return offset + 1
}
digit_index: s32 = digit_count - 1
while digit_index >= 0 {
salt[offset + (digit_count - digit_index - 1)] = digits[digit_index]
digit_index -= 1
}
return offset + digit_count
}
EntropyTake :: (entropy: EntropyState, divisor: s32) -> EntropyResult {
carry: u32 = 0
index: s32 = 0
while index < 32 {
current: u32 = carry * cast(u32)256 +
cast(u32)entropy.bytes[index]
entropy.bytes[index] = cast(u8)(current / cast(u32)divisor)
carry = current % cast(u32)divisor
index += 1
}
return EntropyResult.{entropy, cast(s32)carry}
}
PassGenerate :: (site: string, login: string, master: string,
options: PassOptions) -> PassResult {
if options.length < 5 || options.length > 35 {
return PassFailure(
"password length must be between 5 and 35")
}
class_sets: [4]string = .[
"abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
]
class_names: [4]string = .[
"lowercase", "uppercase", "digits", "symbols"
]
class_enabled: [4]bool = .[
options.lowercase, options.uppercase,
options.digits, options.symbols
]
classes: [4]PassClass
class_count: s32 = 0
alphabet: [128]u8
alphabet_count: s32 = 0
class_index: s32 = 0
while class_index < 4 {
if class_enabled[class_index] {
classes[class_count] = PassFilterClass(
class_sets[class_index], options)
if classes[class_count].count == 0 {
return PassFailure(PassClassEmptyError(class_index))
}
copy_index: s32 = 0
while copy_index < classes[class_count].count {
alphabet[alphabet_count] =
classes[class_count].bytes[copy_index]
alphabet_count += 1
copy_index += 1
}
class_count += 1
}
class_index += 1
}
if class_count == 0 {
return PassFailure("at least one character class must be enabled")
}
if options.length < class_count {
return PassFailure(
"password length is smaller than the enabled character classes")
}
if options.length == class_count {
return PassFailure(
"password length must leave room for generated characters")
}
salt: [640]u8
salt_length: s32 = 0
if cast(s32)site.count >= cast(s32)salt.count {
return PassFailure("site name is too long")
}
site_index: s32 = 0
while site_index < cast(s32)site.count {
salt[salt_length] = site[site_index]
salt_length += 1
site_index += 1
}
if cast(s64)salt_length + login.count + 16 > salt.count {
return PassFailure("login is too long")
}
login_index: s32 = 0
while login_index < cast(s32)login.count {
salt[salt_length] = login[login_index]
salt_length += 1
login_index += 1
}
salt_length = PassAppendCounter(salt[:], salt_length, options.counter)
entropy: EntropyState
entropy.bytes = DeriveKey(master, TextView(salt[0:salt_length]))
if derive_failed { return PassFailure("Could not derive the password") }
password_length := options.length - class_count
password: [36]u8
generated_index: s32 = 0
while generated_index < password_length {
taken := EntropyTake(entropy, alphabet_count)
entropy = taken.entropy
password[generated_index] = alphabet[taken.value]
generated_index += 1
}
required: [4]u8
required_index: s32 = 0
while required_index < class_count {
taken := EntropyTake(entropy, classes[required_index].count)
entropy = taken.entropy
required[required_index] = classes[required_index].bytes[taken.value]
required_index += 1
}
insertion_index: s32 = 0
while insertion_index < class_count {
taken := EntropyTake(entropy, password_length)
entropy = taken.entropy
position := taken.value
move_index := password_length
while move_index > position {
password[move_index] = password[move_index - 1]
move_index -= 1
}
password[position] = required[insertion_index]
password_length += 1
insertion_index += 1
}
result: PassResult
result.valid = true
result.length = password_length
result_index: s32 = 0
while result_index < password_length {
result.password[result_index] = password[result_index]
result_index += 1
}
return result
}
MasterEmojiAppendUtf8 :: (output: []u8, used: s32, codepoint: u32) -> s32 {
if used < 0 || used >= cast(s32)output.count { return used }
length: s32 = 0
if codepoint <= cast(u32)0x7f {
length = 1
} else if codepoint <= cast(u32)0x7ff {
length = 2
} else if codepoint <= cast(u32)0xffff {
length = 3
} else if codepoint <= cast(u32)0x10ffff {
length = 4
} else {
output[used] = cast(u8)0
return used
}
if used + length >= cast(s32)output.count {
output[used] = cast(u8)0
return used
}
if length == 1 {
output[used] = cast(u8)codepoint
} else if length == 2 {
output[used] = cast(u8)(cast(u32)0xc0 | (codepoint >> cast(u32)6))
output[used + 1] = cast(u8)(cast(u32)0x80 |
(codepoint & cast(u32)0x3f))
} else if length == 3 {
output[used] = cast(u8)(cast(u32)0xe0 | (codepoint >> cast(u32)12))
output[used + 1] = cast(u8)(cast(u32)0x80 |
((codepoint >> cast(u32)6) & cast(u32)0x3f))
output[used + 2] = cast(u8)(cast(u32)0x80 |
(codepoint & cast(u32)0x3f))
} else {
output[used] = cast(u8)(cast(u32)0xf0 | (codepoint >> cast(u32)18))
output[used + 1] = cast(u8)(cast(u32)0x80 |
((codepoint >> cast(u32)12) & cast(u32)0x3f))
output[used + 2] = cast(u8)(cast(u32)0x80 |
((codepoint >> cast(u32)6) & cast(u32)0x3f))
output[used + 3] = cast(u8)(cast(u32)0x80 |
(codepoint & cast(u32)0x3f))
}
used += length
output[used] = cast(u8)0
return used
}
MasterEmoji :: (master: string, output: []u8) -> s32 {
if output.count <= 0 { return 0 }
output[0] = cast(u8)0
digest := Sha256(master)
used: s32 = 0
for index: 0..3 {
codepoint: u32 = cast(u32)master_emoji_codepoints[
cast(s32)digest[index] & 63]
used = MasterEmojiAppendUtf8(output, used, codepoint)
}
return used
}
+160
View File
@@ -0,0 +1,160 @@
#import "pass_core"
#import "sha256"
#program_export
DigestMatches :: (left: [32]u8, right: [32]u8) -> bool {
for index: 0..31 {
if left[index] != right[index] { return false }
}
return true
}
#program_export
Answer :: () -> s32 {
empty := Sha256("")
abc := Sha256("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 }
expected: [32]u8 = .[
0x03, 0x94, 0xa2, 0xed, 0xe3, 0x32, 0xc9, 0xa1,
0x3e, 0xb8, 0x2e, 0x9b, 0x24, 0x63, 0x16, 0x04,
0xc3, 0x1d, 0xf9, 0x78, 0xb4, 0xe2, 0xf0, 0xfb,
0xd2, 0xc5, 0x49, 0x94, 0x4f, 0x9d, 0x79, 0xa5
]
if !DigestMatches(derived, expected) { return 3 }
long_password: [80]u8
for index: 0..79 { long_password[index] = cast(u8)97 }
long_derived := DeriveKey(TextView(long_password[0:80]), "salt")
long_password_expected: [32]u8 = .[
0x2f, 0xf0, 0x41, 0xc8, 0x08, 0x5d, 0xbc, 0xe4,
0x6f, 0x9d, 0xc5, 0xa4, 0xe8, 0xb9, 0xe5, 0xeb,
0x1d, 0x17, 0x27, 0x31, 0x8c, 0x54, 0x0f, 0x66,
0x97, 0xb5, 0xb0, 0xa3, 0x68, 0xe1, 0x58, 0xad
]
if !DigestMatches(long_derived, long_password_expected) { return 4 }
long_salt: [700]u8
for index: 0..699 { long_salt[index] = cast(u8)98 }
truncated_salt := DeriveKey("password", TextView(long_salt[0:700]))
truncated_salt_expected: [32]u8 = .[
0x3a, 0x4d, 0x1a, 0xf4, 0xf5, 0x39, 0x07, 0x0e,
0x6f, 0xb4, 0xb2, 0xa0, 0x70, 0x90, 0x71, 0xd0,
0x3e, 0x01, 0xc7, 0xfb, 0x6c, 0x26, 0x59, 0xf6,
0xa8, 0x48, 0x11, 0xea, 0xe8, 0x50, 0x15, 0x0b
]
if !DigestMatches(truncated_salt, truncated_salt_expected) { return 5 }
defaults := DefaultPassOptions()
generated := PassGenerate(
"example.com", "alice", "correct horse battery staple", defaults)
if !PassTextMatches(generated, "&Lf4'/-cSk4DPv_8") { return 6 }
excluded := defaults
excluded.length = 24
excluded.exclude = "0Ool1I!|"
generated = PassGenerate(
"example.com", "alice", "correct horse battery staple", excluded)
if !PassTextMatches(
generated, "7,.Cp}YnF'eeHHaqbX7#PQhg") { return 7 }
subset: PassOptions
subset.length = 12
subset.counter = 7
subset.lowercase = true
subset.digits = true
subset.exclude = ""
generated = PassGenerate(
"δοκιμή.example", "ユーザー", "pässword", subset)
if !PassTextMatches(generated, "oih5omhygh2v") { return 8 }
empty_subset: PassOptions
empty_subset.length = 5
empty_subset.uppercase = true
empty_subset.digits = true
generated = PassGenerate("x", "y", "", empty_subset)
if !PassTextMatches(generated, "C9O9I") { return 9 }
lesspass := PassGenerate(
"lesspass.com", "[email protected]", "password", defaults)
if !PassTextMatches(lesspass, "\\g-A1-.OHEwrXjT#") { return 10 }
counters := defaults
counters.counter = 10
generated = PassGenerate("site", "login", "test", counters)
if !PassTextMatches(generated, "XFt0F*,r619:+}[.") { return 11 }
counters.counter = 16
generated = PassGenerate("site", "login", "test", counters)
if !PassTextMatches(generated, "l:`nzj>S7+0#uL_d") { return 12 }
empty_inputs := PassGenerate("", "", "", defaults)
if !PassTextMatches(empty_inputs, "bb8^CBroRNj%4sP_") { return 13 }
invalid := defaults
invalid.digits = true
invalid.exclude = "0123456789"
if PassGenerate("", "", "", invalid).valid { return 14 }
emoji: [64]u8
emoji_length := MasterEmoji(
"correct horse battery staple", emoji[:])
if !TextMatches(TextView(emoji[0:emoji_length]),
"🐰🎨🐮🍑") { return 15 }
empty_emoji: [64]u8
empty_emoji_length := MasterEmoji("", empty_emoji[:])
if empty_emoji_length != 16 ||
!TextMatches(TextView(empty_emoji[0:empty_emoji_length]),
"🍔🔥🐰🐭") { return 16 }
tiny_emoji: [2]u8
tiny_emoji[0] = cast(u8)120
tiny_emoji_length := MasterEmoji(
"correct horse battery staple", tiny_emoji[:])
if tiny_emoji_length != 0 || tiny_emoji[0] != cast(u8)0 {
return 17
}
return 42
}
#program_export
PortableAnswer :: () -> s32 {
digest := HmacSha256("password", "salt")
if digest[0] != cast(u8)0xfc || digest[31] != cast(u8)0xd0 {
return 1
}
return 42
}
TextMatches :: (actual: string, expected: string) -> bool {
if actual.count != expected.count { return false }
index: s32 = 0
while index < cast(s32)actual.count {
if actual[index] != expected[index] { return false }
index += 1
}
return true
}
PassTextMatches :: (result: PassResult, expected: string) -> bool {
if !result.valid || result.length != cast(s32)expected.count {
return false
}
index: s32 = 0
while index < result.length {
if result.password[index] != expected[index] { return false }
index += 1
}
return true
}
DefaultPassOptions :: () -> PassOptions {
options: PassOptions
options.length = 16
options.counter = 1
options.lowercase = true
options.uppercase = true
options.digits = true
options.symbols = true
options.exclude = ""
return options
}
+345
View File
@@ -0,0 +1,345 @@
// Pass's settings, saved profiles and generation. Everything is computed on
// the device; the master password is never written unless the device keeps
// it behind its own authentication.
#import "pass_core"
#import "pass_text"
#import "text_buffer"
#import "number_text"
#import "werk_app"
Profile :: struct {
name: [64]u8
site: [256]u8
login: [256]u8
exclude: [128]u8
length: s32
counter: s32
lower: bool
upper: bool
digits: bool
symbols: bool
}
Settings :: struct {
auto_copy: bool
clear_seconds: s32
show_fingerprint: bool
length: s32
counter: s32
lower: bool
upper: bool
digits: bool
symbols: bool
exclude: [128]u8
}
Runtime :: struct {
settings: Settings
profiles: [64]Profile
profile_count: s32
generated: [36]u8
status: [256]u8
unlocked_master: [1024]u8
has_unlocked_master: bool
secure_action: s32
}
runtime: Runtime;
store_buffer: [65536]u8;
SetStatus :: (value: string) { CopyText(value, runtime.status[:]) }
Status :: () -> string { return TextUntilNul(runtime.status[:]) }
Generated :: () -> string { return TextUntilNul(runtime.generated[:]) }
Clamp :: (value: s32, low: s32, high: s32) -> s32 {
if value < low { return low }
if value > high { return high }
return value
}
DefaultSettings :: () -> Settings {
settings: Settings
settings.length = 16; settings.counter = 1; settings.clear_seconds = 20
settings.show_fingerprint = true
settings.lower = true; settings.upper = true
settings.digits = true; settings.symbols = true
return settings
}
StoreName :: (key: string, output: []u8) -> string {
used := AppendText(output, 0, ".kryon_pass_")
used = AppendText(output, used, key)
used = AppendText(output, used, ".txt")
if used < 0 { return "" }
return TextUntilNul(output)
}
ReadSetting :: (key: string, output: []u8) -> bool {
name: [256]u8
return ReadStore(StoreName(key, name[:]), output) >= 0
}
WriteSetting :: (key: string, value: string) -> bool {
name: [256]u8
return WriteStore(StoreName(key, name[:]), value)
}
ReadInteger :: (key: string, fallback: s32) -> s32 {
buffer: [64]u8
if !ReadSetting(key, buffer[:]) { return fallback }
number := ParseNumber(TextUntilNul(buffer[:]))
if !number.valid || number.value > 2147483647 || number.value < -2147483647 { return fallback }
return cast(s32)number.value
}
WriteInteger :: (key: string, value: s32) -> bool {
buffer: [32]u8
return WriteSetting(key, FormatInteger(cast(s64)value, buffer[:]))
}
ApplySetting :: (key: string, value: string) {
number := ParseNumber(value)
if key == "exclude" { CopyText(value, runtime.settings.exclude[:]); return }
if !number.valid || number.value > 2147483647 || number.value < -2147483647 { return }
integer := cast(s32)number.value
if key == "auto_copy" { runtime.settings.auto_copy = integer != 0 }
if key == "clear_after_seconds" { runtime.settings.clear_seconds = integer }
if key == "show_fingerprint" { runtime.settings.show_fingerprint = integer != 0 }
if key == "length" { runtime.settings.length = integer }
if key == "counter" { runtime.settings.counter = integer }
if key == "lower" { runtime.settings.lower = integer != 0 }
if key == "upper" { runtime.settings.upper = integer != 0 }
if key == "digits" { runtime.settings.digits = integer != 0 }
if key == "symbols" { runtime.settings.symbols = integer != 0 }
}
LoadSettings :: () {
count := ReadStore("settings.cfg", store_buffer[:])
if count > 0 {
text := TextView(store_buffer[0:count])
start: s32 = 0
index: s32 = 0
separator: s32 = -1
while index <= count {
if index == count || text[index] == cast(u8)10 {
end := index
if end > start && text[end - 1] == cast(u8)13 { end -= 1 }
if separator >= start { ApplySetting(text[start:separator], text[separator + 1:end]) }
start = index + 1; separator = -1
} else {
if text[index] == cast(u8)61 && separator < 0 { separator = index }
}
index += 1
}
}
keys: [10]string = .{"auto_copy", "clear_after_seconds", "show_fingerprint", "length", "counter", "lower", "upper", "digits", "symbols", "exclude"}
for index: 0..9 {
buffer: [256]u8
if ReadSetting(keys[index], buffer[:]) { ApplySetting(keys[index], TextUntilNul(buffer[:])) }
}
runtime.settings.length = Clamp(runtime.settings.length, 5, 35)
runtime.settings.counter = Clamp(runtime.settings.counter, 1, 999999)
runtime.settings.clear_seconds = Clamp(runtime.settings.clear_seconds, 0, 3600)
}
SaveSettings :: () -> bool {
settings := runtime.settings
ok := WriteInteger("auto_copy", cast(s32)settings.auto_copy)
ok = WriteInteger("clear_after_seconds", settings.clear_seconds) && ok
ok = WriteInteger("show_fingerprint", cast(s32)settings.show_fingerprint) && ok
ok = WriteInteger("length", settings.length) && ok
ok = WriteInteger("counter", settings.counter) && ok
ok = WriteInteger("lower", cast(s32)settings.lower) && ok
ok = WriteInteger("upper", cast(s32)settings.upper) && ok
ok = WriteInteger("digits", cast(s32)settings.digits) && ok
ok = WriteInteger("symbols", cast(s32)settings.symbols) && ok
ok = WriteSetting("exclude", TextUntilNul(runtime.settings.exclude[:])) && ok
if ok { SetStatus("Settings saved") } else { SetStatus("Could not save settings") }
return ok
}
ProfileOptions :: (profile: Profile) -> PassOptions {
options: PassOptions
options.length = profile.length
options.counter = cast(u64)Clamp(profile.counter, 0, 2147483647)
options.lowercase = profile.lower; options.uppercase = profile.upper
options.digits = profile.digits; options.symbols = profile.symbols
return options
}
Generate :: (site: string, login: string, master: string, options: PassOptions) -> bool {
result := PassGenerate(site, login, master, options)
runtime.generated = result.password
if !result.valid { SetStatus(result.error); return false }
SetStatus("Password generated locally")
if runtime.settings.auto_copy { CopyPassword() }
return true
}
CopyPassword :: () -> bool {
value := Generated()
if value == "" { SetStatus("Generate a password first"); return false }
if !ClipboardCopy(value, runtime.settings.clear_seconds) { SetStatus("Clipboard is unavailable"); return false }
SetStatus("Copied")
return true
}
LoadProfiles :: () {
runtime.profile_count = 0
count := ReadStore("profiles.tsv", store_buffer[:])
if count <= 0 { return }
text := TextView(store_buffer[0:count])
start: s32 = 0
index: s32 = 0
while index <= count && runtime.profile_count < 64 {
if index == count || text[index] == cast(u8)10 {
end := index
if end > start && text[end - 1] == cast(u8)13 { end -= 1 }
line := text[start:end]
fields: [10]string
field: s32 = 0
position: s32 = 0
previous: s32 = 0
while position <= cast(s32)line.count && field < 10 {
if position == cast(s32)line.count || line[position] == cast(u8)9 {
fields[field] = line[previous:position]
field += 1; previous = position + 1
}
position += 1
}
if field >= 9 {
profile: Profile
valid := CopyText(fields[0], profile.name[:]) && CopyText(fields[1], profile.site[:]) && CopyText(fields[2], profile.login[:]) && CopyText(fields[9], profile.exclude[:])
numbers: [6]s32
for number_index: 0..5 {
number := ParseNumber(fields[number_index + 3])
if !number.valid || number.value > 2147483647 || number.value < -2147483647 { valid = false }
numbers[number_index] = cast(s32)number.value
}
profile.length = Clamp(numbers[0], 5, 35); profile.counter = numbers[1]
profile.lower = numbers[2] != 0; profile.upper = numbers[3] != 0
profile.digits = numbers[4] != 0; profile.symbols = numbers[5] != 0
if valid && profile.name[0] != cast(u8)0 {
runtime.profiles[runtime.profile_count] = profile
runtime.profile_count += 1
}
}
start = index + 1
}
index += 1
}
}
WriteProfiles :: () -> bool {
used: s32 = 0
index: s32 = 0
while index < runtime.profile_count {
profile := runtime.profiles[index]
used = AppendText(store_buffer[:], used, TextUntilNul(profile.name[:]))
used = AppendText(store_buffer[:], used, "\t")
used = AppendText(store_buffer[:], used, TextUntilNul(profile.site[:]))
used = AppendText(store_buffer[:], used, "\t")
used = AppendText(store_buffer[:], used, TextUntilNul(profile.login[:]))
values: [6]s32 = .{profile.length, profile.counter, cast(s32)profile.lower, cast(s32)profile.upper, cast(s32)profile.digits, cast(s32)profile.symbols}
for number_index: 0..5 {
buffer: [32]u8
used = AppendText(store_buffer[:], used, "\t")
used = AppendText(store_buffer[:], used, FormatInteger(cast(s64)values[number_index], buffer[:]))
}
used = AppendText(store_buffer[:], used, "\t")
used = AppendText(store_buffer[:], used, TextUntilNul(profile.exclude[:]))
used = AppendText(store_buffer[:], used, "\n")
if used < 0 { SetStatus("Could not save profiles"); return false }
index += 1
}
if !WriteStore("profiles.tsv", TextView(store_buffer[0:used])) { SetStatus("Could not save profiles"); return false }
return true
}
SaveProfile :: (profile: Profile) -> bool {
candidate := profile
name := TextUntilNul(candidate.name[:])
if name == "" { SetStatus("Profile name required"); return false }
if !SafeField(name) || !SafeField(TextUntilNul(candidate.site[:])) || !SafeField(TextUntilNul(candidate.login[:])) || !SafeField(TextUntilNul(candidate.exclude[:])) { SetStatus("Profile fields cannot contain tabs or newlines"); return false }
index: s32 = 0
while index < runtime.profile_count {
if TextUntilNul(runtime.profiles[index].name[:]) == name { break }
index += 1
}
if index >= 64 { SetStatus("Profile limit reached"); return false }
original := runtime.profiles[index]
original_count := runtime.profile_count
runtime.profiles[index] = candidate
if index == runtime.profile_count { runtime.profile_count += 1 }
if !WriteProfiles() { runtime.profiles[index] = original; runtime.profile_count = original_count; return false }
SetStatus("Profile saved"); return true
}
DeleteProfile :: (index: s32) -> bool {
if index < 0 || index >= runtime.profile_count { SetStatus("Profile not found"); return false }
original := runtime.profiles
count := runtime.profile_count
position := index
while position + 1 < runtime.profile_count { runtime.profiles[position] = runtime.profiles[position + 1]; position += 1 }
runtime.profile_count -= 1
if !WriteProfiles() { runtime.profiles = original; runtime.profile_count = count; return false }
runtime.profiles[runtime.profile_count] = Profile.{}
SetStatus("Profile deleted"); return true
}
GenerateProfile :: (index: s32, master: string) -> bool {
if index < 0 || index >= runtime.profile_count { SetStatus("Profile not found"); return false }
profile := runtime.profiles[index]
options := ProfileOptions(profile)
options.exclude = TextUntilNul(profile.exclude[:])
return Generate(TextUntilNul(profile.site[:]), TextUntilNul(profile.login[:]), master, options)
}
SaveMaster :: (master: string) -> bool {
if master == "" { SetStatus("Enter master password first"); return false }
if !SecureAvailable() { SetStatus("Device authentication unavailable"); return false }
if !SecureRequest(master, true) { SetStatus("Secure master failed"); return false }
runtime.secure_action = 1; SetStatus("Saving master"); return true
}
UnlockMaster :: () -> bool {
if !SecureSaved() { SetStatus("No saved master password"); return false }
if !SecureRequest("", false) { SetStatus("Secure master failed"); return false }
runtime.secure_action = 2; SetStatus("Unlock requested"); return true
}
ForgetMaster :: () -> bool {
if !SecureForget() { SetStatus("Could not forget saved master"); return false }
runtime.unlocked_master = .{}
runtime.has_unlocked_master = false; runtime.secure_action = 0
SetStatus("Saved master forgotten"); return true
}
FingerprintStatus :: () -> string {
if !SecureAvailable() { return "Device authentication is not available" }
if SecureSaved() { return "Saved master uses device authentication" }
return "No saved master password"
}
HasSavedMaster :: () -> bool { return SecureSaved() }
CanSaveMaster :: () -> bool { return SecureAvailable() }
Tick :: () {
buffer: [1024]u8
result := SecurePoll(buffer[:])
if result == 2 {
if runtime.secure_action == 2 {
runtime.unlocked_master = buffer
runtime.has_unlocked_master = true
SetStatus("Master unlocked")
} else {
SetStatus("Master password saved")
}
runtime.secure_action = 0
}
if result == 3 { SetStatus("Secure master failed or cancelled"); runtime.secure_action = 0 }
for index: 0..1023 { buffer[index] = cast(u8)0 }
}
Initialize :: () {
runtime = Runtime.{}
runtime.settings = DefaultSettings()
SetStatus("Ready")
LoadSettings(); LoadProfiles()
}
Shutdown :: () {
runtime.generated = .{}; runtime.unlocked_master = .{}
runtime.has_unlocked_master = false
}
+57
View File
@@ -0,0 +1,57 @@
#import "c_string"
#import "text_buffer"
ClearBytes :: (bytes: []u8) {
at: s32 = 0
while at < cast(s32)bytes.count { bytes[at] = cast(u8)0; at += 1 }
}
CopyText :: (value: string, output: []u8) -> bool {
if output.count == 0 { return false }
if value.count >= output.count { return false }
return CopyCString(value, output)
}
AppendText :: (output: []u8, used: s32, value: string) -> s32 {
if used < 0 || cast(s64)used + cast(s64)value.count >= cast(s64)output.count { return -1 }
index: s32 = 0
while index < cast(s32)value.count {
output[used + index] = value[index]
index += 1
}
used += cast(s32)value.count
output[used] = cast(u8)0
return used
}
Number :: struct { valid: bool; value: s64; }
ParseNumber :: (text: string) -> Number {
result: Number
if text.count == 0 { return result }
index: s32 = 0
negative: bool = text[0] == cast(u8)45
if negative || text[0] == cast(u8)43 { index = 1 }
if index == cast(s32)text.count { return result }
while index < cast(s32)text.count {
byte: u8 = text[index]
if byte < cast(u8)48 || byte > cast(u8)57 { return result }
digit: s64 = cast(s64)(byte - cast(u8)48)
if result.value > (9223372036854775807 - digit) / 10 { return Number.{} }
result.value = result.value * 10 + digit
index += 1
}
if negative { result.value = 0 - result.value }
result.valid = true
return result
}
SafeField :: (value: string) -> bool {
index: s32 = 0
while index < cast(s32)value.count {
if value[index] == cast(u8)0 || value[index] == cast(u8)9 ||
value[index] == cast(u8)10 || value[index] == cast(u8)13 { return false }
index += 1
}
return true
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<title>Werkzeug — a wrench with a keyhole</title>
<g fill="#8254ff" fill-rule="evenodd" transform="translate(-10 10)">
<path d="M425.9 145.5A118 118 0 1 1 366.5 86.1L288.5 164.1A42 42 0 0 0 347.9 223.5Z"/>
<path d="M239.0 202.3L309.7 273.0L181.0 401.7A50 50 0 0 1 110.3 331.0ZM159.8 324.2a21 21 0 0 0 -11.2 38.7l-5.2 23.0h32.8l-5.2 -23.0a21 21 0 0 0 -11.2 -38.7Z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 482 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

File renamed without changes.
Binary file not shown.
+94
View File
@@ -0,0 +1,94 @@
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/)
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.
File renamed without changes.
-63
View File
@@ -1,63 +0,0 @@
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"time"
)
type clipboardCommand struct {
program string
args []string
}
func copyToClipboard(value string, clearAfter time.Duration) error {
// The built-in pure-Go X11 clipboard doubles as the only backend that can
// auto-clear: it owns the selection from a daemon and releases it on time.
if handled, err := copyViaX11(value, clearAfter); handled {
return err
}
if clearAfter > 0 {
fmt.Fprintln(os.Stderr, "warning: --clear-after needs the built-in X11 clipboard; copying without auto-clear")
}
commands := clipboardCommands()
var failures []error
for _, candidate := range commands {
path, err := exec.LookPath(candidate.program)
if err != nil {
continue
}
command := exec.Command(path, candidate.args...)
command.Stdin = strings.NewReader(value)
if output, err := command.CombinedOutput(); err == nil {
return nil
} else if len(output) > 0 {
failures = append(failures, fmt.Errorf("%s: %w: %s", candidate.program, err, output))
} else {
failures = append(failures, fmt.Errorf("%s: %w", candidate.program, err))
}
}
if len(failures) > 0 {
return fmt.Errorf("clipboard command failed: %w", errors.Join(failures...))
}
return errors.New("clipboard unavailable: install wl-copy, xclip, xsel, pbcopy, or clip.exe")
}
func clipboardCommands() []clipboardCommand {
switch runtime.GOOS {
case "darwin":
return []clipboardCommand{{program: "pbcopy"}}
case "windows":
return []clipboardCommand{{program: "clip.exe"}}
default:
return []clipboardCommand{
{program: "wl-copy"},
{program: "xclip", args: []string{"-selection", "clipboard", "-in"}},
{program: "xsel", args: []string{"--clipboard", "--input"}},
}
}
}
-23
View File
@@ -1,23 +0,0 @@
//go:build !linux
package main
import (
"errors"
"time"
)
// The built-in X11 clipboard is Linux-only; other platforms always fall back
// to external clipboard tools.
func copyViaX11(text string, clearAfter time.Duration) (bool, error) {
return false, nil
}
func runClipboardDaemon(timeout time.Duration) error {
return errors.New("the built-in clipboard daemon is Linux-only")
}
func readClipboardSelection() (string, error) {
return "", errors.New("reading the clipboard is Linux-only")
}
-318
View File
@@ -1,318 +0,0 @@
//go:build linux
package main
import (
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/xproto"
)
// Pure-Go X11 clipboard. Xlibre is protocol-compatible with X.Org, so the
// regular CLIPBOARD selection works there too. No xclip/xsel/wl-copy needed.
const (
selClipboard = "CLIPBOARD"
atomUTF8 = "UTF8_STRING"
atomString = "STRING"
atomText = "TEXT"
atomTextPlain = "text/plain"
atomPlainUTF8 = "text/plain;charset=utf-8"
atomTargets = "TARGETS"
atomMultiple = "MULTIPLE"
propName = "GOPASS_SELECTION"
)
type xAtoms map[string]xproto.Atom
func allAtomNames() []string {
return []string{selClipboard, atomUTF8, atomString, atomText, atomTextPlain,
atomPlainUTF8, atomTargets, atomMultiple, propName}
}
func internAtoms(c *xgb.Conn, names ...string) (xAtoms, error) {
m := make(xAtoms, len(names))
for _, n := range names {
rep, err := xproto.InternAtom(c, false, uint16(len(n)), n).Reply()
if err != nil {
return nil, err
}
m[n] = rep.Atom
}
return m, nil
}
// serveClipboard takes ownership of the X11 CLIPBOARD selection and answers
// paste requests until another client takes ownership or timeout elapses
// (timeout <= 0 means "until replaced"). If ready is non-nil it is closed once
// ownership has been confirmed.
func serveClipboard(text string, timeout time.Duration, ready chan<- struct{}) error {
c, err := xgb.NewConn()
if err != nil {
return fmt.Errorf("cannot connect to X server: %v", err)
}
defer c.Close()
atoms, err := internAtoms(c, allAtomNames()...)
if err != nil {
return err
}
screen := xproto.Setup(c).DefaultScreen(c)
wid, err := c.NewId()
if err != nil {
return err
}
err = xproto.CreateWindowChecked(c, 0, xproto.Window(wid), screen.Root,
-1, -1, 1, 1, 0, 0, 0, 0, nil).Check()
if err != nil {
return err
}
xproto.SetSelectionOwner(c, xproto.Window(wid), atoms[selClipboard], xproto.TimeCurrentTime)
rep, err := xproto.GetSelectionOwner(c, atoms[selClipboard]).Reply()
if err != nil {
return err
}
if rep.Owner != xproto.Window(wid) {
return errors.New("failed to acquire CLIPBOARD ownership")
}
if ready != nil {
close(ready)
}
done := make(chan error, 1)
go func() { done <- selectionEventLoop(c, text, atoms) }()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sig)
if timeout > 0 {
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case err := <-done:
return err
case <-timer.C:
return nil
case <-sig:
return nil
}
}
select {
case err := <-done:
return err
case <-sig:
return nil
}
}
func selectionEventLoop(c *xgb.Conn, text string, atoms xAtoms) error {
for {
ev, err := c.WaitForEvent()
if err != nil { // connection closed or protocol error
return err
}
switch e := ev.(type) {
case xproto.SelectionClearEvent:
return nil // another client owns the clipboard now
case xproto.DestroyNotifyEvent:
return nil
case xproto.SelectionRequestEvent:
handleSelectionRequest(c, e, text, atoms)
}
}
}
func handleSelectionRequest(c *xgb.Conn, e xproto.SelectionRequestEvent, text string, atoms xAtoms) {
prop := e.Property
if prop == xproto.AtomNone {
prop = e.Target
}
ok := false
switch e.Target {
case atoms[atomTargets]:
targets := []xproto.Atom{
atoms[atomTargets], atoms[atomMultiple],
atoms[atomUTF8], atoms[atomPlainUTF8],
atoms[atomText], atoms[atomTextPlain], atoms[atomString],
}
buf := make([]byte, 4*len(targets))
for i, t := range targets {
binary.LittleEndian.PutUint32(buf[i*4:], uint32(t))
}
ok = changeProperty(c, e.Requestor, prop, xproto.AtomAtom, 32, buf)
case atoms[atomUTF8], atoms[atomPlainUTF8], atoms[atomText], atoms[atomTextPlain], atoms[atomString]:
// Generated passwords are plain ASCII, so serving the same bytes for
// STRING (Latin-1) and TEXT targets is safe.
ok = changeProperty(c, e.Requestor, prop, e.Target, 8, []byte(text))
}
if !ok {
prop = xproto.AtomNone // refuse this target
}
// Reply with a SelectionNotify event (event code 31).
b := make([]byte, 32)
b[0] = 31
binary.LittleEndian.PutUint32(b[4:], uint32(e.Time))
binary.LittleEndian.PutUint32(b[8:], uint32(e.Requestor))
binary.LittleEndian.PutUint32(b[12:], uint32(e.Selection))
binary.LittleEndian.PutUint32(b[16:], uint32(e.Target))
binary.LittleEndian.PutUint32(b[20:], uint32(prop))
xproto.SendEvent(c, false, e.Requestor, 0, string(b))
}
func changeProperty(c *xgb.Conn, win xproto.Window, prop, typ xproto.Atom, format byte, data []byte) bool {
units := uint32(len(data))
if format == 32 {
units /= 4
}
return xproto.ChangePropertyChecked(c, xproto.PropModeReplace, win, prop,
typ, format, units, data).Check() == nil
}
// copyViaX11 copies through the built-in clipboard server. It reports false
// when no X server is reachable, so the caller can fall back to external
// clipboard tools.
func copyViaX11(text string, clearAfter time.Duration) (bool, error) {
if os.Getenv("DISPLAY") == "" {
return false, nil
}
probe, err := xgb.NewConn()
if err != nil {
return false, nil
}
probe.Close()
return true, spawnClipboardDaemon(text, clearAfter)
}
// spawnClipboardDaemon re-executes this binary detached (new session) so the
// clipboard keeps working after the terminal is closed. The password travels
// over a pipe; it is never in argv or the environment.
func spawnClipboardDaemon(text string, timeout time.Duration) error {
r, w, err := os.Pipe()
if err != nil {
return err
}
cmd := exec.Command(selfPath(), "--serve-clipboard", "--clear-after="+timeout.String())
cmd.ExtraFiles = []*os.File{r}
cmd.Env = os.Environ() // keep DISPLAY for the child
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
r.Close()
w.Close()
return err
}
if _, err := io.WriteString(w, text); err != nil {
return err
}
w.Close()
r.Close()
return nil
}
// selfPath returns the absolute path of this running executable, so the
// detached clipboard daemon can re-exec itself reliably.
func selfPath() string {
if p, err := os.Executable(); err == nil {
return p
}
return os.Args[0]
}
// runClipboardDaemon is the detached child process: it receives the password
// over the pipe passed as fd 3 and serves the X11 clipboard until it is
// replaced or the timeout elapses.
func runClipboardDaemon(timeout time.Duration) error {
f := os.NewFile(uintptr(3), "pipe")
if f == nil {
return errors.New("no pipe on fd 3")
}
data := make([]byte, 0, 64)
buf := make([]byte, 64)
for {
n, err := f.Read(buf)
data = append(data, buf[:n]...)
if err != nil {
break
}
}
f.Close()
if len(data) == 0 {
return errors.New("empty clipboard payload")
}
return serveClipboard(string(data), timeout, nil)
}
// readClipboardSelection requests the current CLIPBOARD contents as
// UTF8_STRING (equivalent of "xclip -o -selection clipboard").
func readClipboardSelection() (string, error) {
c, err := xgb.NewConn()
if err != nil {
return "", fmt.Errorf("cannot connect to X server: %v", err)
}
defer c.Close()
atoms, err := internAtoms(c, allAtomNames()...)
if err != nil {
return "", err
}
screen := xproto.Setup(c).DefaultScreen(c)
wid, err := c.NewId()
if err != nil {
return "", err
}
if err := xproto.CreateWindowChecked(c, 0, xproto.Window(wid), screen.Root,
-1, -1, 1, 1, 0, 0, 0, 0, nil).Check(); err != nil {
return "", err
}
xproto.ConvertSelection(c, xproto.Window(wid), atoms[selClipboard],
atoms[atomUTF8], atoms[propName], xproto.TimeCurrentTime)
// Wait for the SelectionNotify reply.
var prop xproto.Atom
found := false
deadline := time.Now().Add(5 * time.Second)
for !found {
if time.Now().After(deadline) {
return "", errors.New("timed out waiting for the clipboard owner")
}
ev, err := c.WaitForEvent()
if err != nil {
return "", err
}
if sn, ok := ev.(xproto.SelectionNotifyEvent); ok {
if sn.Selection != atoms[selClipboard] {
continue
}
if sn.Property == xproto.AtomNone {
return "", errors.New("clipboard owner refused the request")
}
prop = sn.Property
found = true
}
}
rep, err := xproto.GetProperty(c, false, xproto.Window(wid), prop,
xproto.GetPropertyTypeAny, 0, 1<<20).Reply()
if err != nil {
return "", err
}
return string(rep.Value), nil
}
-44
View File
@@ -1,44 +0,0 @@
//go:build linux
package main
import (
"os"
"testing"
"time"
)
// Live X11 round trip: take ownership of the CLIPBOARD selection, then read
// it back as a separate X client.
func TestClipboardRoundTrip(t *testing.T) {
if os.Getenv("DISPLAY") == "" {
t.Skip("no X11 display available")
}
text := "TestPassword123"
ready := make(chan struct{})
done := make(chan error, 1)
go func() { done <- serveClipboard(text, 10*time.Second, ready) }()
select {
case <-ready:
case err := <-done:
t.Fatalf("clipboard server exited early: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for clipboard ownership")
}
// Reading immediately can race with clipboard managers stealing the
// selection; poll briefly for the expected content.
deadline := time.Now().Add(5 * time.Second)
for {
got, err := readClipboardSelection()
if err == nil && got == text {
return // success
}
if time.Now().After(deadline) {
t.Fatalf("clipboard round trip failed: last read = %q, err = %v", got, err)
}
time.Sleep(100 * time.Millisecond)
}
}
-324
View File
@@ -1,324 +0,0 @@
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
password "github.com/waozixyz/gopass"
"github.com/waozixyz/gopass/vault"
)
const environmentVariable = "LESSPASS_MASTER_PASSWORD"
// promptVaultPassphrase asks for the vault passphrase on the terminal, or
// reads it from standard input when stdin is piped ("echo pw | gopass ...").
func promptVaultPassphrase() (string, error) {
if info, err := os.Stdin.Stat(); err == nil && info.Mode()&os.ModeCharDevice == 0 {
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && line == "" {
return "", err
}
return strings.TrimRight(line, "\r\n"), nil
}
return readPassword("Vault passphrase: ")
}
// readVaultPassphrase is the hook tests replace to decrypt a synthetic vault.
var readVaultPassphrase = promptVaultPassphrase
func main() {
arguments := os.Args[1:]
if filepath.Base(os.Args[0]) == "pass" {
translated, ok := translatePassArguments(arguments)
if !ok {
os.Exit(2)
}
arguments = translated
}
if err := run(arguments, os.Stdout, os.Stderr); err != nil {
fmt.Fprintf(os.Stderr, "gopass: %v\n", err)
os.Exit(1)
}
}
func run(arguments []string, stdout, stderr io.Writer) error {
config, err := loadConfig()
if err != nil {
return err
}
options := password.DefaultOptions()
flags := flag.NewFlagSet("gopass", flag.ContinueOnError)
flags.SetOutput(stderr)
flags.Usage = func() { printHelp(stderr) }
flags.IntVar(&options.Length, "L", options.Length, "password length")
flags.IntVar(&options.Length, "length", options.Length, "password length")
flags.Uint64Var(&options.Counter, "C", options.Counter, "generation counter")
flags.Uint64Var(&options.Counter, "counter", options.Counter, "generation counter")
flags.BoolVar(&options.Lowercase, "l", options.Lowercase, "include lowercase letters")
flags.BoolVar(&options.Lowercase, "lowercase", options.Lowercase, "include lowercase letters")
flags.BoolVar(&options.Uppercase, "u", options.Uppercase, "include uppercase letters")
flags.BoolVar(&options.Uppercase, "uppercase", options.Uppercase, "include uppercase letters")
flags.BoolVar(&options.Digits, "d", options.Digits, "include digits")
flags.BoolVar(&options.Digits, "digits", options.Digits, "include digits")
flags.BoolVar(&options.Symbols, "s", options.Symbols, "include symbols")
flags.BoolVar(&options.Symbols, "symbols", options.Symbols, "include symbols")
var noLowercase, noUppercase, noDigits, noSymbols bool
flags.BoolVar(&noLowercase, "no-lowercase", false, "exclude lowercase letters")
flags.BoolVar(&noUppercase, "no-uppercase", false, "exclude uppercase letters")
flags.BoolVar(&noDigits, "no-digits", false, "exclude digits")
flags.BoolVar(&noSymbols, "no-symbols", false, "exclude symbols")
flags.StringVar(&options.Exclude, "exclude", "", "characters to exclude")
var forcePrompt, copyPassword, noCopy, showVersion, readClipboard, serveClipboard bool
flags.BoolVar(&forcePrompt, "p", false, "prompt for the master password")
flags.BoolVar(&forcePrompt, "prompt", false, "prompt for the master password")
flags.BoolVar(&copyPassword, "c", false, "copy the password to the clipboard")
flags.BoolVar(&copyPassword, "copy", false, "copy the password to the clipboard")
flags.BoolVar(&noCopy, "no-copy", false, "print instead of copying when the profile says to copy")
flags.BoolVar(&showVersion, "v", false, "show version")
flags.BoolVar(&showVersion, "version", false, "show version")
var profileName, vaultFlag string
var clearAfter time.Duration
flags.StringVar(&profileName, "P", "", "use a named profile from the configuration file")
flags.StringVar(&profileName, "profile", "", "use a named profile from the configuration file")
flags.StringVar(&vaultFlag, "vault", "", "read the master password from an OpenSSL-encrypted vault")
flags.DurationVar(&clearAfter, "clear-after", 0, "clear the clipboard after this long; 0 keeps it until replaced (built-in X11 clipboard only)")
flags.BoolVar(&readClipboard, "read-clipboard", false, "print the current clipboard contents")
flags.BoolVar(&serveClipboard, "serve-clipboard", false, "") // internal: detached clipboard daemon mode
if err := flags.Parse(normalizeArguments(arguments)); err != nil {
if errors.Is(err, flag.ErrHelp) {
return nil
}
return err
}
explicit := map[string]bool{}
flags.Visit(func(f *flag.Flag) { explicit[f.Name] = true })
if noLowercase {
options.Lowercase = false
}
if noUppercase {
options.Uppercase = false
}
if noDigits {
options.Digits = false
}
if noSymbols {
options.Symbols = false
}
if showVersion {
fmt.Fprintf(stdout, "gopass %s\n", password.Version)
return nil
}
if serveClipboard {
return runClipboardDaemon(clearAfter)
}
if readClipboard {
text, err := readClipboardSelection()
if err != nil {
return err
}
fmt.Fprintln(stdout, text)
return nil
}
var profile Profile
if profileName != "" {
if config == nil {
return fmt.Errorf("unknown profile %q: no configuration file at %s", profileName, configPath())
}
found, ok := config.Profiles[profileName]
if !ok {
return fmt.Errorf("unknown profile %q", profileName)
}
if found.Login == "" {
return fmt.Errorf("profile %q has no login", profileName)
}
profile = found
profile.apply(&options, explicit)
}
positional := flags.Args()
if profileName != "" {
if len(positional) != 1 {
printHelp(stderr)
return errors.New("expected SITE with --profile")
}
} else if len(positional) < 2 || len(positional) > 3 {
printHelp(stderr)
return errors.New("expected SITE LOGIN and an optional MASTER_PASSWORD")
}
if forcePrompt && len(positional) == 3 {
return errors.New("MASTER_PASSWORD cannot be supplied together with --prompt")
}
site, login := positional[0], ""
if profileName != "" {
login = profile.Login
} else {
login = positional[1]
}
// A vault from the configuration is the least authoritative master
// password source: anything the user spells out for this invocation
// (--vault, the environment, --prompt, a positional password) wins.
vaultPath := vaultFlag
if vaultPath == "" {
_, envSet := os.LookupEnv(environmentVariable)
if !envSet && !forcePrompt && len(positional) < 3 {
switch {
case profile.Vault != "":
vaultPath = expandHome(profile.Vault)
case config != nil && config.Vault != "":
vaultPath = expandHome(config.Vault)
}
}
}
if !noCopy && !anySet(explicit, "c", "copy") {
switch {
case profile.Copy != nil:
copyPassword = *profile.Copy
case config != nil && config.Copy != nil:
copyPassword = *config.Copy
}
}
if noCopy {
copyPassword = false
}
if !anySet(explicit, "clear-after") {
setting := profile.ClearAfter
if setting == "" && config != nil {
setting = config.ClearAfter
}
if setting != "" {
duration, err := time.ParseDuration(setting)
if err != nil {
return fmt.Errorf("clear_after: %w", err)
}
clearAfter = duration
}
}
master, err := masterPassword(positional, forcePrompt, vaultPath)
if err != nil {
return err
}
generated, err := password.Generate(site, login, master, options)
if err != nil {
return err
}
if copyPassword {
if err := copyToClipboard(generated, clearAfter); err != nil {
return err
}
if clearAfter > 0 {
fmt.Fprintf(stderr, "Password copied to the clipboard (auto-clears in %s).\n", clearAfter)
} else {
fmt.Fprintln(stderr, "Password copied to the clipboard.")
}
return nil
}
fmt.Fprintln(stdout, generated)
return nil
}
// normalizeArguments lets callers place options before or after SITE and
// LOGIN. The standard flag package stops at the first positional argument,
// while command wrappers naturally append profile options after the site.
func normalizeArguments(arguments []string) []string {
valueFlags := map[string]bool{
"-L": true, "--length": true,
"-C": true, "--counter": true,
"--exclude": true,
"-P": true, "--profile": true,
"--vault": true, "--clear-after": true,
}
options := make([]string, 0, len(arguments))
positional := make([]string, 0, 3)
for i := 0; i < len(arguments); i++ {
argument := arguments[i]
if argument == "--" {
positional = append(positional, arguments[i+1:]...)
break
}
if strings.HasPrefix(argument, "-") && argument != "-" {
options = append(options, argument)
if valueFlags[argument] && i+1 < len(arguments) {
i++
options = append(options, arguments[i])
}
continue
}
positional = append(positional, argument)
}
return append(options, positional...)
}
func masterPassword(positional []string, forcePrompt bool, vaultPath string) (string, error) {
if vaultPath != "" {
if forcePrompt {
return "", errors.New("--vault cannot be combined with --prompt")
}
if len(positional) == 3 {
return "", errors.New("--vault cannot be combined with MASTER_PASSWORD")
}
passphrase, err := readVaultPassphrase()
if err != nil {
return "", err
}
return vault.Decrypt(vaultPath, passphrase)
}
if !forcePrompt && len(positional) == 3 {
return positional[2], nil
}
if !forcePrompt {
if value, exists := os.LookupEnv(environmentVariable); exists {
return value, nil
}
}
return readPassword("Master password: ")
}
func printHelp(output io.Writer) {
fmt.Fprintln(output, `Usage: gopass [OPTIONS] SITE LOGIN [MASTER_PASSWORD]
Derive a site-specific password. If MASTER_PASSWORD is omitted, gopass reads
LESSPASS_MASTER_PASSWORD or asks for it on the controlling terminal. With
--vault it instead decrypts an OpenSSL-encrypted vault and uses its contents
as the master password. With --profile, a named profile from the
configuration file supplies the login and default settings and only SITE is
passed on the command line.
Options:
-L, --length N password length (default 16)
-C, --counter N generation counter (default 1)
-l, --lowercase include lowercase letters
-u, --uppercase include uppercase letters
-d, --digits include digits
-s, --symbols include symbols
--no-lowercase exclude lowercase letters
--no-uppercase exclude uppercase letters
--no-digits exclude digits
--no-symbols exclude symbols
--exclude CHARS remove characters from all enabled classes
-p, --prompt always ask for the master password
-c, --copy copy result without printing it
--no-copy print instead of copying when the profile says to copy
-P, --profile NAME use a named profile from the configuration file
--vault PATH read the master password from an OpenSSL-encrypted vault
--clear-after DUR clear the clipboard after DUR; 0 keeps it until replaced
--read-clipboard print the current clipboard contents
-v, --version show version
-h, --help show this help`)
}
-89
View File
@@ -1,89 +0,0 @@
package main
import (
"bytes"
"strings"
"testing"
password "github.com/waozixyz/gopass"
)
func TestRunWithArgument(t *testing.T) {
var output, diagnostics bytes.Buffer
err := run([]string{"example.com", "alice", "correct horse battery staple"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got, want := output.String(), "&vLf44D'/cSkP-_8\n"; got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestRunUsesEnvironmentAndFlags(t *testing.T) {
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"--length", "10", "--no-symbols", "--exclude", "aA0", "example.com", "alice"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(output.String())
if len(got) != 10 {
t.Fatalf("output length = %d, want 10", len(got))
}
if strings.ContainsAny(got, "aA0"+"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
t.Fatalf("output %q contains a disabled character", got)
}
}
func TestRunAcceptsFlagsAfterSiteAndLogin(t *testing.T) {
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"example.com", "alice", "-C", "9", "-L", "23", "--no-symbols"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); len(got) != 23 {
t.Fatalf("output length = %d, want 23", len(got))
}
}
func TestRunInformationOptions(t *testing.T) {
for _, test := range []struct {
argument string
want string
}{
{"--version", "gopass " + password.Version},
{"--help", "Usage: gopass"},
} {
var output, diagnostics bytes.Buffer
if err := run([]string{test.argument}, &output, &diagnostics); err != nil {
t.Errorf("run(%s): %v", test.argument, err)
}
combined := output.String() + diagnostics.String()
if !strings.Contains(combined, test.want) {
t.Errorf("run(%s) output %q does not contain %q", test.argument, combined, test.want)
}
}
}
func TestRunRejectsConflictingPasswordSources(t *testing.T) {
var output, diagnostics bytes.Buffer
err := run([]string{"--prompt", "example.com", "alice", "master"}, &output, &diagnostics)
if err == nil || !strings.Contains(err.Error(), "cannot be supplied") {
t.Fatalf("error = %v, want source conflict", err)
}
}
func TestClipboardCommandsDoNotCarryPasswordData(t *testing.T) {
secret := "this must travel only over standard input"
for _, command := range clipboardCommands() {
if command.program == secret {
t.Fatal("secret appeared as clipboard executable")
}
for _, argument := range command.args {
if strings.Contains(argument, secret) {
t.Fatal("secret appeared in clipboard command arguments")
}
}
}
}
-82
View File
@@ -1,82 +0,0 @@
package main
import (
"errors"
"flag"
"fmt"
"io"
"os"
"strconv"
"time"
)
const passUsage = `pass - generate a LessPass password and copy it to the clipboard
Usage:
pass [flags] <profile> <site>
The profile name selects a login and settings from the gopass profiles file.
You will be prompted (hidden input) for the passphrase of your OpenSSL
secret vault when one is configured. The password is copied to the
CLIPBOARD selection; it is never displayed.
Flags:
`
// translatePassArguments rewrites the legacy two-argument `pass PROFILE SITE`
// command line into the equivalent gopass arguments, so a copy or symlink of
// the gopass binary named "pass" keeps working as the personal shorthand.
// It reports false (after printing usage) on a malformed legacy invocation.
func translatePassArguments(arguments []string) ([]string, bool) {
flags := flag.NewFlagSet("pass", flag.ContinueOnError)
flags.SetOutput(io.Discard) // report errors through reportPassUsage instead
vaultPath := flags.String("vault", "", "path to an OpenSSL-encrypted vault holding the master password")
counter := flags.Int64("counter", -1, "LessPass counter")
length := flags.Int("length", 0, "password length")
symbols := flags.Bool("symbols", false, "include symbols in the generated password")
timeout := flags.Duration("timeout", 90*time.Second, "clipboard auto-clear timeout; 0 keeps it until overwritten")
read := flags.Bool("read", false, "print the current clipboard contents")
if err := flags.Parse(arguments); err != nil {
if errors.Is(err, flag.ErrHelp) {
reportPassUsage(os.Stdout, flags)
os.Exit(0)
}
reportPassUsage(os.Stderr, flags)
fmt.Fprintf(os.Stderr, "\nerror: %v\n", err)
return nil, false
}
translated := []string{"--copy", "--clear-after=" + timeout.String()}
if *vaultPath != "" {
translated = append(translated, "--vault", *vaultPath)
}
if *counter >= 0 {
translated = append(translated, "-C", strconv.FormatInt(*counter, 10))
}
if *length > 0 {
translated = append(translated, "-L", strconv.Itoa(*length))
}
if *symbols {
translated = append(translated, "-s")
}
if *read {
return append(translated, "--read-clipboard"), true
}
rest := flags.Args()
if len(rest) != 2 {
reportPassUsage(os.Stderr, flags)
return nil, false
}
return append(translated, "--profile", rest[0], rest[1]), true
}
// reportPassUsage prints the legacy usage block, the way the original pass
// tool reported a bad command line.
func reportPassUsage(output io.Writer, flags *flag.FlagSet) {
fmt.Fprint(output, passUsage)
flags.SetOutput(output)
flags.PrintDefaults()
}
-58
View File
@@ -1,58 +0,0 @@
package main
import (
"reflect"
"testing"
)
func TestTranslatePassArguments(t *testing.T) {
tests := []struct {
name string
in []string
want []string
}{
{
name: "plain",
in: []string{"w", "example.org"},
want: []string{"--copy", "--clear-after=1m30s", "--profile", "w", "example.org"},
},
{
name: "all flags",
in: []string{"-vault", "/v", "-counter", "5", "-length", "20", "-symbols", "n", "s.org"},
want: []string{"--copy", "--clear-after=1m30s", "--vault", "/v", "-C", "5", "-L", "20", "-s", "--profile", "n", "s.org"},
},
{
name: "zero timeout keeps the clipboard",
in: []string{"-timeout", "0", "w", "example.org"},
want: []string{"--copy", "--clear-after=0s", "--profile", "w", "example.org"},
},
{
name: "read mode",
in: []string{"-read"},
want: []string{"--copy", "--clear-after=1m30s", "--read-clipboard"},
},
}
for _, test := range tests {
got, ok := translatePassArguments(test.in)
if !ok {
t.Errorf("%s: translatePassArguments(%v) rejected the arguments", test.name, test.in)
continue
}
if !reflect.DeepEqual(got, test.want) {
t.Errorf("%s: got %v, want %v", test.name, got, test.want)
}
}
}
func TestTranslatePassArgumentsRejectsBadUsage(t *testing.T) {
for _, arguments := range [][]string{
{},
{"w"},
{"w", "example.org", "extra"},
{"-length", "notanumber", "w", "example.org"},
} {
if got, ok := translatePassArguments(arguments); ok {
t.Errorf("translatePassArguments(%v) = %v, want rejection", arguments, got)
}
}
}
-119
View File
@@ -1,119 +0,0 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
password "github.com/waozixyz/gopass"
)
// Profile holds the saved settings for one named identity: a login plus the
// generator options and clipboard behavior to use with it. Profiles contain
// no secrets — the master password always comes from a prompt, the
// environment, or an encrypted vault referenced by path.
type Profile struct {
Login string `json:"login"`
Counter uint64 `json:"counter,omitempty"`
Length int `json:"length,omitempty"`
Lowercase *bool `json:"lowercase,omitempty"`
Uppercase *bool `json:"uppercase,omitempty"`
Digits *bool `json:"digits,omitempty"`
Symbols *bool `json:"symbols,omitempty"`
Exclude string `json:"exclude,omitempty"`
Vault string `json:"vault,omitempty"`
Copy *bool `json:"copy,omitempty"`
ClearAfter string `json:"clear_after,omitempty"`
}
// Config is the optional profiles file. Every field is a default that flags
// and profile entries override; a missing file leaves gopass fully stateless.
type Config struct {
Vault string `json:"vault,omitempty"`
Copy *bool `json:"copy,omitempty"`
ClearAfter string `json:"clear_after,omitempty"`
Profiles map[string]Profile `json:"profiles"`
}
// configPath is a variable so tests can point it at a temporary file.
var configPath = defaultConfigPath
func defaultConfigPath() string {
if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" {
return filepath.Join(dir, "gopass", "profiles.json")
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".config", "gopass", "profiles.json")
}
// loadConfig reads the profiles file. A missing file is not an error: the
// feature is simply off and gopass behaves as a plain stateless generator.
func loadConfig() (*Config, error) {
path := configPath()
if path == "" {
return nil, nil
}
raw, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var config Config
if err := json.Unmarshal(raw, &config); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return &config, nil
}
// apply fills the option fields that were not set explicitly on the command
// line, so the precedence is always flag > profile > built-in default.
func (p Profile) apply(options *password.Options, explicit map[string]bool) {
if p.Length > 0 && !anySet(explicit, "L", "length") {
options.Length = p.Length
}
if p.Counter > 0 && !anySet(explicit, "C", "counter") {
options.Counter = p.Counter
}
if p.Lowercase != nil && !anySet(explicit, "l", "lowercase", "no-lowercase") {
options.Lowercase = *p.Lowercase
}
if p.Uppercase != nil && !anySet(explicit, "u", "uppercase", "no-uppercase") {
options.Uppercase = *p.Uppercase
}
if p.Digits != nil && !anySet(explicit, "d", "digits", "no-digits") {
options.Digits = *p.Digits
}
if p.Symbols != nil && !anySet(explicit, "s", "symbols", "no-symbols") {
options.Symbols = *p.Symbols
}
if p.Exclude != "" && !anySet(explicit, "exclude") {
options.Exclude = p.Exclude
}
}
func anySet(explicit map[string]bool, names ...string) bool {
for _, name := range names {
if explicit[name] {
return true
}
}
return false
}
// expandHome resolves a leading ~ so config entries stay portable.
func expandHome(path string) string {
if path == "~" || strings.HasPrefix(path, "~/") {
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, strings.TrimPrefix(path, "~"))
}
}
return path
}
-234
View File
@@ -1,234 +0,0 @@
package main
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
password "github.com/waozixyz/gopass"
)
// withConfig points the config loader at a temporary file for one test.
func withConfig(t *testing.T, content string) {
t.Helper()
path := filepath.Join(t.TempDir(), "profiles.json")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
original := configPath
configPath = func() string { return path }
t.Cleanup(func() { configPath = original })
}
func withVaultPassphrase(t *testing.T, passphrase string) {
t.Helper()
original := readVaultPassphrase
readVaultPassphrase = func() (string, error) { return passphrase, nil }
t.Cleanup(func() { readVaultPassphrase = original })
}
func TestRunWithProfileSettings(t *testing.T) {
withConfig(t, `{
"vault": "/nonexistent/vault",
"copy": true,
"clear_after": "90s",
"profiles": {
"w": {"login": "alice", "counter": 9, "length": 23, "symbols": false}
}
}`)
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
want, err := password.Generate("example.com", "alice", "correct horse battery staple", password.Options{
Length: 23, Counter: 9, Lowercase: true, Uppercase: true, Digits: true, Symbols: false,
})
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestProfileSettingsDoNotOverrideExplicitFlags(t *testing.T) {
withConfig(t, `{"profiles": {"w": {"login": "alice", "length": 23, "symbols": false}}}`)
t.Setenv(environmentVariable, "correct horse battery staple")
var output, diagnostics bytes.Buffer
err := run([]string{"-P", "w", "-L", "10", "example.com"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); len(got) != 10 {
t.Fatalf("output length = %d, want 10 (flag must beat profile)", len(got))
}
}
func TestRunRejectsBadProfileNames(t *testing.T) {
withConfig(t, `{"profiles": {"w": {"login": "alice"}, "n": {}}}`)
t.Setenv(environmentVariable, "x")
var output, diagnostics bytes.Buffer
if err := run([]string{"-P", "x", "example.com"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "unknown profile") {
t.Fatalf("error = %v, want unknown profile", err)
}
if err := run([]string{"-P", "n", "example.com"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "has no login") {
t.Fatalf("error = %v, want missing login", err)
}
// A profile without a configuration file at all.
original := configPath
configPath = func() string { return filepath.Join(t.TempDir(), "absent.json") }
defer func() { configPath = original }()
if err := run([]string{"-P", "w", "example.com"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "no configuration file") {
t.Fatalf("error = %v, want missing configuration", err)
}
}
func TestRunRejectsInvalidConfig(t *testing.T) {
withConfig(t, `{"profiles":`)
var output, diagnostics bytes.Buffer
if err := run([]string{"example.com", "alice", "master"}, &output, &diagnostics); err == nil {
t.Fatal("expected error for malformed configuration")
}
}
func TestRunRejectsInvalidClearAfter(t *testing.T) {
withConfig(t, `{"clear_after": "not-a-duration", "profiles": {"w": {"login": "alice"}}}`)
t.Setenv(environmentVariable, "x")
var output, diagnostics bytes.Buffer
err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics)
if err == nil || !strings.Contains(err.Error(), "clear_after") {
t.Fatalf("error = %v, want clear_after parse failure", err)
}
}
func TestVaultMasterPasswordBeatsEnvironmentAndPositional(t *testing.T) {
if _, err := exec.LookPath("openssl"); err != nil {
t.Skip("openssl not available")
}
vaultFile := filepath.Join(t.TempDir(), ".secret_vault")
encrypt := `printf 'my-top-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
}
withVaultPassphrase(t, "masterpw")
t.Setenv(environmentVariable, "environment-must-be-ignored")
var output, diagnostics bytes.Buffer
err := run([]string{"--vault", vaultFile, "example.com", "alice"}, &output, &diagnostics)
if err != nil {
t.Fatal(err)
}
want, err := password.Generate("example.com", "alice", "my-top-secret", password.DefaultOptions())
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); got != want {
t.Fatalf("output = %q, want %q", got, want)
}
if err := run([]string{"--vault", vaultFile, "example.com", "alice", "master"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "cannot be combined") {
t.Fatalf("error = %v, want source conflict with MASTER_PASSWORD", err)
}
if err := run([]string{"--vault", vaultFile, "--prompt", "example.com", "alice"}, &output, &diagnostics); err == nil ||
!strings.Contains(err.Error(), "cannot be combined") {
t.Fatalf("error = %v, want source conflict with --prompt", err)
}
}
func TestConfigVaultIsUsedForProfile(t *testing.T) {
if _, err := exec.LookPath("openssl"); err != nil {
t.Skip("openssl not available")
}
vaultFile := filepath.Join(t.TempDir(), ".secret_vault")
encrypt := `printf 'cfg-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
}
withConfig(t, `{"vault": "`+vaultFile+`", "profiles": {"w": {"login": "alice"}}}`)
withVaultPassphrase(t, "masterpw")
var output, diagnostics bytes.Buffer
if err := run([]string{"-P", "w", "--no-copy", "example.com"}, &output, &diagnostics); err != nil {
t.Fatal(err)
}
want, err := password.Generate("example.com", "alice", "cfg-secret", password.DefaultOptions())
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(output.String()); got != want {
t.Fatalf("output = %q, want %q", got, want)
}
}
func TestExpandHome(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil {
t.Skip("no home directory")
}
for _, test := range []struct{ in, want string }{
{"~", home},
{"~/bin/.secret_vault", filepath.Join(home, "bin", ".secret_vault")},
{"/abs/path", "/abs/path"},
{"relative", "relative"},
} {
if got := expandHome(test.in); got != test.want {
t.Errorf("expandHome(%q) = %q, want %q", test.in, got, test.want)
}
}
}
func TestVaultPassphraseFromPipedStdin(t *testing.T) {
if _, err := exec.LookPath("openssl"); err != nil {
t.Skip("openssl not available")
}
vaultFile := filepath.Join(t.TempDir(), ".secret_vault")
encrypt := `printf 'piped-secret' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:masterpw > ` + vaultFile
if out, err := exec.Command("sh", "-c", encrypt).CombinedOutput(); err != nil {
t.Fatalf("openssl encrypt failed: %v: %s", err, out)
}
for _, test := range []struct {
name string
contents string
}{
{"newline", "masterpw\n"},
{"crlf", "masterpw\r\n"},
{"no trailing newline", "masterpw"},
} {
t.Run(test.name, func(t *testing.T) {
input, err := os.CreateTemp(t.TempDir(), "stdin")
if err != nil {
t.Fatal(err)
}
if _, err := input.WriteString(test.contents); err != nil {
t.Fatal(err)
}
if _, err := input.Seek(0, 0); err != nil {
t.Fatal(err)
}
previous := os.Stdin
os.Stdin = input
defer func() { os.Stdin = previous }()
got, err := promptVaultPassphrase()
if err != nil {
t.Fatal(err)
}
if got != "masterpw" {
t.Fatalf("passphrase = %q, want %q", got, "masterpw")
}
})
}
}
-53
View File
@@ -1,53 +0,0 @@
//go:build linux
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
)
func readPassword(label string) (string, error) {
terminal, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a controlling terminal: %w", err)
}
defer terminal.Close()
state, err := terminalState(terminal.Fd(), syscall.TCGETS, nil)
if err != nil {
return "", fmt.Errorf("cannot read terminal settings: %w", err)
}
noEcho := *state
noEcho.Lflag &^= syscall.ECHO
if _, err := terminalState(terminal.Fd(), syscall.TCSETS, &noEcho); err != nil {
return "", fmt.Errorf("cannot disable terminal echo: %w", err)
}
defer func() { _, _ = terminalState(terminal.Fd(), syscall.TCSETS, state) }()
if _, err := fmt.Fprint(terminal, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(terminal).ReadString('\n')
fmt.Fprintln(terminal)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func terminalState(fd uintptr, request uintptr, replacement *syscall.Termios) (*syscall.Termios, error) {
state := replacement
if state == nil {
state = new(syscall.Termios)
}
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, request, uintptr(unsafe.Pointer(state)))
if errno != 0 {
return nil, errno
}
return state, nil
}
-9
View File
@@ -1,9 +0,0 @@
//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !windows
package main
import "errors"
func readPassword(_ string) (string, error) {
return "", errors.New("secure terminal prompting is not supported on this operating system; use LESSPASS_MASTER_PASSWORD")
}
-50
View File
@@ -1,50 +0,0 @@
//go:build darwin || dragonfly || freebsd || netbsd || openbsd || solaris
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
)
func readPassword(label string) (string, error) {
terminal, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a controlling terminal: %w", err)
}
defer terminal.Close()
stty, err := exec.LookPath("stty")
if err != nil {
return "", fmt.Errorf("cannot securely prompt because stty is unavailable: %w", err)
}
original, err := runStty(stty, terminal, "-g")
if err != nil {
return "", fmt.Errorf("cannot read terminal settings: %w", err)
}
if _, err := runStty(stty, terminal, "-echo"); err != nil {
return "", fmt.Errorf("cannot disable terminal echo: %w", err)
}
defer func() { _, _ = runStty(stty, terminal, strings.TrimSpace(original)) }()
if _, err := fmt.Fprint(terminal, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(terminal).ReadString('\n')
fmt.Fprintln(terminal)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func runStty(path string, terminal *os.File, argument string) (string, error) {
command := exec.Command(path, argument)
command.Stdin = terminal
command.Stderr = terminal
output, err := command.Output()
return string(output), err
}
-63
View File
@@ -1,63 +0,0 @@
//go:build windows
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
)
const enableEchoInput = 0x0004
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
getConsoleMode = kernel32.NewProc("GetConsoleMode")
setConsoleMode = kernel32.NewProc("SetConsoleMode")
)
func readPassword(label string) (string, error) {
input, err := os.OpenFile("CONIN$", os.O_RDWR, 0)
if err != nil {
return "", fmt.Errorf("cannot securely prompt without a console: %w", err)
}
defer input.Close()
output, err := os.OpenFile("CONOUT$", os.O_WRONLY, 0)
if err != nil {
return "", fmt.Errorf("cannot open the console for prompting: %w", err)
}
defer output.Close()
var original uint32
if err := windowsCall(getConsoleMode, input.Fd(), uintptr(unsafe.Pointer(&original))); err != nil {
return "", fmt.Errorf("cannot read console settings: %w", err)
}
if err := windowsCall(setConsoleMode, input.Fd(), uintptr(original&^enableEchoInput)); err != nil {
return "", fmt.Errorf("cannot disable console echo: %w", err)
}
defer func() { _ = windowsCall(setConsoleMode, input.Fd(), uintptr(original)) }()
if _, err := fmt.Fprint(output, label); err != nil {
return "", err
}
line, readErr := bufio.NewReader(input).ReadString('\n')
fmt.Fprintln(output)
if readErr != nil && len(line) == 0 {
return "", fmt.Errorf("cannot read master password: %w", readErr)
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
func windowsCall(procedure *syscall.LazyProc, arguments ...uintptr) error {
result, _, callErr := procedure.Call(arguments...)
if result != 0 {
return nil
}
if callErr != nil && callErr != syscall.Errno(0) {
return callErr
}
return syscall.EINVAL
}
+67 -5
View File
@@ -7,17 +7,43 @@ android {
compileSdk 36
ndkVersion "28.2.13676358"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
def keystorePropsFile = rootProject.file("local.properties")
def keystoreProps = new Properties()
if (keystorePropsFile.exists()) {
keystoreProps.load(new FileInputStream(keystorePropsFile))
}
def getKeystorePath = { -> project.findProperty('keystore.path') ?: keystoreProps['keystore.path'] ?: System.getenv("HOME") + "/.android/pass-release.keystore" }
def getKeystoreAlias = { -> project.findProperty('keystore.alias') ?: keystoreProps['keystore.alias'] ?: "pass-key" }
def releasePassword = project.findProperty('keystore.password') ?: ""
def releaseKeystorePath = getKeystorePath()
def releaseKeystore = releaseKeystorePath ? file(releaseKeystorePath) : null
// Sign release builds only when a keystore is actually available: CI and
// local release builds pass -Pkeystore.* properties, while clean checkouts
// (for example an F-Droid builder) produce an unsigned APK instead.
def signRelease = !project.hasProperty('fDroidBuild') \
&& releaseKeystore != null && releaseKeystore.exists() \
&& releasePassword != ""
signingConfigs {
release {
if (signRelease) {
storeFile releaseKeystore
storePassword releasePassword
keyAlias getKeystoreAlias()
keyPassword releasePassword
}
}
}
defaultConfig {
applicationId 'xyz.waozi.pass'
minSdk 21
targetSdk 36
versionCode 2
versionName "0.2.0"
versionCode 12
versionName "0.3.0"
// Default to the two realistic phone targets; override with
// -Pabi=x86_64 etc. for emulator builds.
def abis = project.findProperty('abi') ?: 'armeabi-v7a,arm64-v8a'
@@ -26,8 +52,18 @@ android {
}
}
splits {
abi {
enable = (project.findProperty('splitApks') ?: 'false').toString().toBoolean()
reset()
include 'armeabi-v7a', 'arm64-v8a'
universalApk true
}
}
buildTypes {
release {
signingConfig signRelease ? signingConfigs.release : null
minifyEnabled false
}
debug {
@@ -51,3 +87,29 @@ android {
}
}
}
// Bundle fonts without adding app or host Java code.
def prepareFonts = tasks.register('prepareFonts', Copy) {
into layout.buildDirectory.dir('generated/passAssets/fonts')
from('../../assets/fonts/NotoSans-Regular.ttf') { rename { 'ui.ttf' } }
from('../../assets/fonts/NotoSans-OFL.txt')
from('../../assets/fonts/emoji.ttf')
from('../../assets/fonts/emoji-OFL.txt')
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('generated/passAssets'))
tasks.named('preBuild').configure { dependsOn prepareFonts }
// The tool apps are portable bundles, built once for every ABI.
def makeApps = tasks.register('makeApps', Exec) {
workingDir '../..'
commandLine 'make', 'apps'
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('generated/appAssets'))
def prepareImages = tasks.register('prepareImages', Copy) {
dependsOn makeApps
from('../../assets/app/icon.png')
from("${System.getenv('KRYON_DIR')}/icons/pfp.png")
from('../../build/apps') { include '*.zib'; into 'apps' }
into layout.buildDirectory.dir('generated/appAssets')
}
tasks.named('preBuild').configure { dependsOn prepareImages }
+8 -3
View File
@@ -1,17 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- gopass generates passwords entirely offline; no permissions needed. -->
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<!-- Only for sync, which is off until the owner sets up an account. -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:hasCode="true"
android:hasCode="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:allowBackup="false">
<activity
android:name="xyz.waozi.pass.MainActivity"
android:name="android.app.NativeActivity"
android:configChanges="keyboardHidden|orientation|screenSize|smallestScreenSize|uiMode"
android:exported="true"
android:launchMode="singleTask"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
android:windowSoftInputMode="adjustResize"
android:windowLayoutInDisplayCutoutMode="never">
<meta-data
android:name="android.app.lib_name"
+79 -123
View File
@@ -1,124 +1,80 @@
cmake_minimum_required(VERSION 3.22)
project(Gopass C)
set(REPO_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../..")
set(KRYON_DIR "${REPO_ROOT}/vendor/kryon")
set(RAYLIB_DIR "${KRYON_DIR}/vendor/raylib/src")
set(GOPASS_NATIVE_DIR "${REPO_ROOT}/native")
set(NATIVE_APP_GLUE_DIR "${ANDROID_NDK}/sources/android/native_app_glue")
file(GLOB_RECURSE KRYON_SOURCES CONFIGURE_DEPENDS "${KRYON_DIR}/src/*.c")
# The src/backend/ software renderer implements raylib-named functions for
# no-raylib hosts; Android links real raylib, so compiling both is a
# duplicate-symbol link error.
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/backend/.*")
# gopass uses no 2D physics; mirror the desktop Makefile's physics filter.
list(REMOVE_ITEM KRYON_SOURCES
"${KRYON_DIR}/src/scene/physics_world.c"
"${KRYON_DIR}/src/scene/node_body2d.c"
"${KRYON_DIR}/src/scene/node_area2d.c"
"${KRYON_DIR}/src/scene/node_collision_shape2d.c")
# Ksync account crypto requires liboqs and gopass never syncs; runtime asset
# downloads need an Android download backend gopass does not provide.
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/ksync/.*")
list(FILTER KRYON_SOURCES EXCLUDE REGEX "${KRYON_DIR}/src/runtime_assets/.*")
list(REMOVE_ITEM KRYON_SOURCES "${KRYON_DIR}/src/file_dialog/file_dialog.c")
set(GOPASS_FONT_ASSET "vendor/kryon/fonts/noto/NotoSans-Regular.ttf")
set(GOPASS_EMBEDDED_ASSETS_C "${CMAKE_BINARY_DIR}/gopass_embedded_assets.c")
add_custom_command(
OUTPUT "${GOPASS_EMBEDDED_ASSETS_C}"
COMMAND sh "${KRYON_DIR}/scripts/embed-assets.sh" "${GOPASS_EMBEDDED_ASSETS_C}" "${GOPASS_FONT_ASSET}"
DEPENDS "${KRYON_DIR}/scripts/embed-assets.sh" "${KRYON_DIR}/fonts/noto/NotoSans-Regular.ttf"
WORKING_DIRECTORY "${REPO_ROOT}"
VERBATIM
)
add_library(raylib STATIC
"${RAYLIB_DIR}/rcore.c"
"${RAYLIB_DIR}/rshapes.c"
"${RAYLIB_DIR}/rtextures.c"
"${RAYLIB_DIR}/rtext.c"
"${RAYLIB_DIR}/raudio.c"
)
target_compile_definitions(raylib PRIVATE
PLATFORM_ANDROID
GRAPHICS_API_OPENGL_ES2
SUPPORT_SCREEN_CAPTURE=0
SUPPORT_COMPRESSION_API=0
SUPPORT_AUTOMATION_EVENTS=0
SUPPORT_CLIPBOARD_IMAGE=0
SUPPORT_FILEFORMAT_BMP=0
SUPPORT_FILEFORMAT_GIF=0
SUPPORT_FILEFORMAT_QOI=0
SUPPORT_FILEFORMAT_DDS=0
SUPPORT_FILEFORMAT_TTF=1
SUPPORT_FILEFORMAT_JPG=1
SUPPORT_FILEFORMAT_PNG=1
SUPPORT_FILEFORMAT_OGG=1
SUPPORT_MODULE_RAUDIO=1
)
target_compile_options(raylib PRIVATE
-Os
-ffunction-sections
-fdata-sections
)
target_include_directories(raylib PUBLIC
"${RAYLIB_DIR}"
"${NATIVE_APP_GLUE_DIR}"
)
add_library(main SHARED
main.c
gopass_app.c
android_bridge.c
"${GOPASS_NATIVE_DIR}/gopass_core.c"
"${GOPASS_EMBEDDED_ASSETS_C}"
${KRYON_SOURCES}
"${NATIVE_APP_GLUE_DIR}/android_native_app_glue.c"
)
target_include_directories(main PRIVATE
"${KRYON_DIR}/include"
"${KRYON_DIR}/src"
"${GOPASS_NATIVE_DIR}"
"${NATIVE_APP_GLUE_DIR}"
)
target_compile_definitions(main PRIVATE
PLATFORM_ANDROID
ANDROID_BUILD=1
_DEFAULT_SOURCE
_GNU_SOURCE
_FILE_OFFSET_BITS=64
UI_EMBEDDED_ONLY=1
KRYON_WITH_PHYSICS=0
)
target_compile_options(main PRIVATE
-Os
-ffunction-sections
-fdata-sections
-fvisibility=hidden
)
target_link_options(main PRIVATE
-Wl,--gc-sections
-Wl,--strip-all
-Wl,--wrap=fopen
-Wl,-z,max-page-size=16384
-Wl,-z,common-page-size=16384
)
target_link_libraries(main
raylib
android
log
OpenSLES
EGL
GLESv2
m
)
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}")
endif()
set(GENERATED "${CMAKE_BINARY_DIR}/ziran")
set(DEFINES --define ANDROID_BUILD)
if(ANDROID_ABI STREQUAL "arm64-v8a")
list(APPEND DEFINES --define __aarch64__)
elseif(ANDROID_ABI STREQUAL "armeabi-v7a")
list(APPEND DEFINES --define __arm__)
elseif(ANDROID_ABI STREQUAL "x86_64")
list(APPEND DEFINES --define __x86_64__)
elseif(ANDROID_ABI STREQUAL "x86")
list(APPEND DEFINES --define __i386__)
else()
message(FATAL_ERROR "Unsupported Android ABI: ${ANDROID_ABI}")
endif()
set(LOCK_FLAGS --locked)
if(EXISTS "${REPO_ROOT}/ziran.local.toml")
set(LOCK_FLAGS)
endif()
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")
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
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.
foreach(candidate "${ZIRAN_ROOT}/build/bin/zi2c" "${REPO_ROOT}/build/ziran-bootstrap/build/bin/zi2c")
if(NOT ZI2C_BIN AND EXISTS "${candidate}")
set(ZI2C_BIN "${candidate}")
endif()
endforeach()
include("${KRYON_DIR}/cmake/KryonAndroid.cmake")
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 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"
"FRAMEFLAGS=-Wframe-larger-than=16384" "${BUNDLE_RUNTIME_DIR}/libziran.a"
COMMAND_ERROR_IS_FATAL ANY)
# Account sync: liboqs for ML-DSA-44 account keys, Monocypher for the rest.
set(OQS_BUILD_ONLY_LIB ON CACHE BOOL "" FORCE)
set(OQS_USE_OPENSSL OFF CACHE BOOL "" FORCE)
set(OQS_MINIMAL_BUILD "SIG_ml_dsa_44" CACHE STRING "" FORCE)
set(OQS_DIST_BUILD OFF CACHE BOOL "" FORCE)
set(OQS_OPT_TARGET generic CACHE STRING "" FORCE)
foreach(oqs_x86_feature
ADX AES AVX AVX2 AVX512 AVX512BW AVX512DQ AVX512F
BMI1 BMI2 FMA PCLMULQDQ POPCNT SSE SSE2 SSE3 VPCLMULQDQ)
set(OQS_USE_${oqs_x86_feature}_INSTRUCTIONS OFF CACHE BOOL "" FORCE)
endforeach()
add_subdirectory("${LIBOQS_DIR}" "${CMAKE_BINARY_DIR}/liboqs")
add_library(main SHARED ${GENERATED_SOURCES}
"${MONOCYPHER_DIR}/src/monocypher.c" "${MONOCYPHER_DIR}/src/optional/monocypher-ed25519.c")
target_include_directories(main PRIVATE "${GENERATED}" "${ZIRAN_ROOT}/include"
"${MONOCYPHER_DIR}/src" "${MONOCYPHER_DIR}/src/optional")
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)
# 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.
-205
View File
@@ -1,205 +0,0 @@
/* Minimal JNI bridge for the gopass Android app: safe-area insets, display
* density, soft-keyboard visibility, and soft-keyboard text input. Modeled
* on inbe's android_device.c / android_insets.c. */
#include "android_bridge.h"
#if ANDROID_BUILD
#include "kryon.h"
#include "ui_dpi.h"
#include <android/log.h>
#include <android_native_app_glue.h>
#include <jni.h>
#include <pthread.h>
extern struct android_app *GetAndroidApp(void);
#ifndef JNI_VERSION_1_6
#define JNI_VERSION_1_6 0x10060000
#endif
#define LOG_TAG "GOPASS_JNI"
static pthread_mutex_t bridge_mutex = PTHREAD_MUTEX_INITIALIZER;
static int insets_status_bar = 0;
static int insets_nav_bar = 0;
static int insets_cutout_top = 0;
static int insets_cutout_bottom = 0;
static int insets_ready = 0;
static float device_density = 0.0f;
static int
scaled_inset(int java_px, float density)
{
if(density <= 0.0f)
density = 1.0f;
return (int)(java_px / density + 0.5f);
}
void
android_bridge_init(void)
{
pthread_mutex_lock(&bridge_mutex);
insets_status_bar = 0;
insets_nav_bar = 0;
insets_cutout_top = 0;
insets_cutout_bottom = 0;
insets_ready = 0;
device_density = 0.0f;
pthread_mutex_unlock(&bridge_mutex);
}
int
android_bridge_top_reserved(void)
{
int status, cutout, top, ready;
float density;
pthread_mutex_lock(&bridge_mutex);
status = insets_status_bar;
cutout = insets_cutout_top;
density = device_density;
ready = insets_ready;
pthread_mutex_unlock(&bridge_mutex);
if(!ready)
return 28; /* conservative status-bar guess until Java reports */
top = status > cutout ? status : cutout;
return scaled_inset(top, density);
}
int
android_bridge_bottom_reserved(void)
{
int nav, cutout, bottom, ready;
float density;
pthread_mutex_lock(&bridge_mutex);
nav = insets_nav_bar;
cutout = insets_cutout_bottom;
density = device_density;
ready = insets_ready;
pthread_mutex_unlock(&bridge_mutex);
if(!ready)
return 48; /* conservative nav-bar guess until Java reports */
bottom = nav > cutout ? nav : cutout;
return scaled_inset(bottom, density);
}
void
android_bridge_set_soft_keyboard(int visible)
{
struct android_app *app = GetAndroidApp();
JavaVM *jvm;
JNIEnv *env = NULL;
jobject activity;
jclass activity_class;
jmethodID method;
int attached = 0;
if(app == NULL || app->activity == NULL || app->activity->vm == NULL ||
app->activity->clazz == NULL)
return;
jvm = app->activity->vm;
activity = app->activity->clazz;
if((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) {
if((*jvm)->AttachCurrentThread(jvm, &env, NULL) != JNI_OK || env == NULL)
return;
attached = 1;
}
activity_class = (*env)->GetObjectClass(env, activity);
if(activity_class == NULL)
goto done;
method = (*env)->GetMethodID(env, activity_class, "setSoftKeyboardVisible", "(Z)V");
if(method == NULL) {
__android_log_write(ANDROID_LOG_ERROR, LOG_TAG, "setSoftKeyboardVisible not found");
goto done;
}
(*env)->CallVoidMethod(env, activity, method, visible ? JNI_TRUE : JNI_FALSE);
done:
if((*env)->ExceptionCheck(env)) {
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
if(attached)
(*jvm)->DetachCurrentThread(jvm);
}
/* ---- Java -> C natives (exported JNI symbols; RegisterNatives from
* JNI_OnLoad resolves through the boot loader here and does not bind to the
* activity's class, so we rely on standard dlsym resolution instead) ---- */
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeSetInsets(JNIEnv *env, jobject thiz,
jint status_bar, jint nav_bar,
jint cutout_left, jint cutout_top,
jint cutout_right, jint cutout_bottom)
{
(void)env;
(void)thiz;
(void)cutout_left;
(void)cutout_right;
pthread_mutex_lock(&bridge_mutex);
insets_status_bar = status_bar;
insets_nav_bar = nav_bar;
insets_cutout_top = cutout_top;
insets_cutout_bottom = cutout_bottom;
insets_ready = 1;
pthread_mutex_unlock(&bridge_mutex);
}
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeSetDeviceDensity(JNIEnv *env, jobject thiz, jfloat density)
{
(void)env;
(void)thiz;
if(density <= 0.0f)
return;
pthread_mutex_lock(&bridge_mutex);
device_density = density;
pthread_mutex_unlock(&bridge_mutex);
SetUIDeviceDensity(density);
}
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeTextInputCommit(JNIEnv *env, jobject thiz, jint codepoint)
{
(void)env;
(void)thiz;
QueueUITextInputCodepoint((int)codepoint);
}
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeTextInputBackspace(JNIEnv *env, jobject thiz)
{
(void)env;
(void)thiz;
QueueUITextInputBackspace();
}
JNIEXPORT void JNICALL
Java_xyz_waozi_pass_MainActivity_nativeTextInputEnter(JNIEnv *env, jobject thiz)
{
(void)env;
(void)thiz;
QueueUITextInputEnter();
}
#else /* !ANDROID_BUILD */
void android_bridge_init(void) {}
int android_bridge_top_reserved(void) { return 0; }
int android_bridge_bottom_reserved(void) { return 0; }
void android_bridge_set_soft_keyboard(int visible) { (void)visible; }
#endif
-24
View File
@@ -1,24 +0,0 @@
#ifndef GOPASS_ANDROID_BRIDGE_H
#define GOPASS_ANDROID_BRIDGE_H
#if defined(__cplusplus)
extern "C" {
#endif
/* Call once before InitWindow. */
void android_bridge_init(void);
/* Safe-area insets converted to UI units (java px / density). Returns 0
* until Java has reported real values; callers should treat 0 as "unknown"
* and keep a conservative margin. */
int android_bridge_top_reserved(void);
int android_bridge_bottom_reserved(void);
/* Shows or hides the soft keyboard through the activity. */
void android_bridge_set_soft_keyboard(int visible);
#if defined(__cplusplus)
}
#endif
#endif
-521
View File
@@ -1,521 +0,0 @@
/* C port of the gopass desktop GUI (gui/main.go) for the Android build.
* The desktop branch keeps the Go layout; this port adds a narrow-screen
* layout for phones: single column, two-abreast rules, scrollable card. */
#include "gopass_app.h"
#include "gopass_core.h"
#include "kryon.h"
#include "embedded_assets.h"
#include "ui_scroll.h"
#include "ui_scaling.h"
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define CLIPBOARD_LIFETIME_MS 20000
typedef struct {
char buffer[1024];
int cursor;
int focused;
int commit;
int focus_id;
int max_codepoints;
int secure;
} Field;
static void
field_init(Field *f, int focus_id, int capacity_codepoints)
{
memset(f, 0, sizeof(*f));
f->focus_id = focus_id;
f->max_codepoints = capacity_codepoints;
}
static const char *
field_text(const Field *f)
{
return f->buffer;
}
static void
field_clear(Field *f)
{
memset(f->buffer, 0, sizeof(f->buffer));
f->cursor = 0;
}
struct GopassApp {
Field site, login, master, exclude;
int length, counter;
int lower, upper, digits, symbols;
int reveal;
char generated[136];
char message[160];
/* clipboard lease */
char clip_value[136];
int64_t clip_expires_ms;
int clip_has_value;
int scroll_offset;
};
static int64_t
now_ms(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
static void
clipboard_copy(GopassApp *a, const char *value)
{
SetClipboardText(value);
snprintf(a->clip_value, sizeof(a->clip_value), "%s", value);
a->clip_expires_ms = now_ms() + CLIPBOARD_LIFETIME_MS;
a->clip_has_value = 1;
}
static void
clipboard_tick(GopassApp *a)
{
const char *current;
if(!a->clip_has_value || now_ms() < a->clip_expires_ms)
return;
current = GetClipboardText();
if(current != NULL && strcmp(current, a->clip_value) == 0)
SetClipboardText("");
a->clip_has_value = 0;
a->clip_value[0] = '\0';
}
static void
clipboard_clear(GopassApp *a)
{
const char *current;
if(a->clip_has_value) {
current = GetClipboardText();
if(current != NULL && strcmp(current, a->clip_value) == 0)
SetClipboardText("");
}
a->clip_has_value = 0;
a->clip_value[0] = '\0';
}
static void
generate(GopassApp *a)
{
GopassOptions options;
char err[160];
memset(&options, 0, sizeof(options));
options.length = a->length;
options.counter = (uint64_t)a->counter;
options.lowercase = a->lower;
options.uppercase = a->upper;
options.digits = a->digits;
options.symbols = a->symbols;
options.exclude = a->exclude.buffer;
if(gopass_generate(field_text(&a->site), field_text(&a->login),
field_text(&a->master), &options,
a->generated, sizeof(a->generated),
err, sizeof(err)) != 0) {
a->generated[0] = '\0';
snprintf(a->message, sizeof(a->message), "%s", err);
return;
}
snprintf(a->message, sizeof(a->message), "%s", "Password generated locally");
}
static UITextInputStyle
input_style(void)
{
UIMaterialScheme s = GetUIMaterialScheme();
UITextInputStyle style;
memset(&style, 0, sizeof(style));
style.background = s.surface_container;
style.border = s.outline;
style.focus_border = s.primary;
style.text = s.on_surface;
style.cursor = s.primary;
style.radius = 6.0f;
style.padding_x = 10;
style.padding_y = 8;
return style;
}
static int
draw_field(Field *f, Rectangle bounds, int font, UITextInputStyle style)
{
TextFieldProps props;
memset(&props, 0, sizeof(props));
props.bounds = bounds;
props.text = f->buffer;
props.text_size = sizeof(f->buffer);
props.cursor_position = &f->cursor;
props.focused = &f->focused;
props.max_codepoints = f->max_codepoints;
props.font = font;
props.focus_id = f->focus_id;
props.style = style;
props.commit_pressed = &f->commit;
props.secure = f->secure;
return DrawUITextField(props);
}
static int
button(int x, int y, int w, int h, const char *label, UIButtonStyle style, int disabled)
{
int hover = 0;
return DrawUIGenericButton(x, y, w, h, label, style, disabled, &hover);
}
static void
checkbox(int x, int y, const char *label, int *value)
{
DrawUICheckboxToggle(x, y, label, value);
}
static Rectangle
scaled_rect(float x, float y, float w, float h)
{
Rectangle r;
r.x = (float)ScaleUIPx((int)x);
r.y = (float)ScaleUIPx((int)y);
r.width = (float)ScaleUIPx((int)w);
r.height = (float)ScaleUIPx((int)h);
return r;
}
static void
label_text(const char *text, int x, int y, int font, Color color)
{
Text(text, ScaleUIPx(x), ScaleUIPx(y), font, color);
}
GopassApp *
gopass_app(void)
{
static GopassApp app;
static int initialized;
if(!initialized) {
initialized = 1;
field_init(&app.site, 101, 256);
field_init(&app.login, 102, 256);
field_init(&app.master, 103, 1024);
field_init(&app.exclude, 104, 128);
app.length = 16;
app.counter = 1;
app.lower = app.upper = app.digits = app.symbols = 1;
}
return &app;
}
/* ------------------------------------------------------------------ */
/* Wide layout: mirrors gui/main.go */
/* ------------------------------------------------------------------ */
static void
draw_wide(GopassApp *a, int width, int height, int top_reserved)
{
UIMaterialScheme scheme = GetUIMaterialScheme();
Color text = GetThemeText();
UITextInputStyle style = input_style();
int content_w = width - 64;
int x, y;
if(content_w > 720)
content_w = 720;
x = (width - content_w) / 2;
y = 22 + top_reserved;
DrawRectangleRounded(scaled_rect((float)x, (float)y, 48, 48), 0.22f, 10, scheme.primary);
label_text("g", x + 15, y + 7, 32, scheme.on_primary);
label_text("gopass", x + 64, y + 2, 32, text);
label_text("Private by design - generated on this device",
x + 64, y + 38, 14, scheme.on_surface_variant);
y += 70;
DrawRectangleRounded(scaled_rect((float)x, (float)y, (float)content_w, 550), 0.035f, 10, scheme.surface);
DrawRectangleLinesEx(scaled_rect((float)x, (float)y, (float)content_w, 550), 1.0f, scheme.outline);
label_text("PASSWORD DETAILS", x + 24, y + 24, 12, scheme.primary);
y += 54;
label_text("Site", x + 24, y, 14, text);
draw_field(&a->site, scaled_rect((float)x + 24, (float)y + 24, (float)content_w - 48, 38), 16, style);
y += 76;
label_text("Login", x + 24, y, 14, text);
draw_field(&a->login, scaled_rect((float)x + 24, (float)y + 24, (float)content_w - 48, 38), 16, style);
y += 76;
label_text("Master password", x + 24, y, 14, text);
a->master.secure = !a->reveal;
draw_field(&a->master, scaled_rect((float)x + 24, (float)y + 24, (float)content_w - 150, 38), 16, style);
if(button(ScaleUIPx(x + content_w - 112), ScaleUIPx(y + 24), ScaleUIPx(88), ScaleUIPx(38),
a->reveal ? "Hide" : "Reveal", UI_BUTTON_STYLE_SECONDARY, 0))
a->reveal = !a->reveal;
y += 76;
label_text("PASSWORD RULES", x + 24, y - 10, 12, scheme.primary);
y += 14;
label_text("Length", x + 24, y, 14, text);
{
SpinboxProps props;
memset(&props, 0, sizeof(props));
props.bounds = scaled_rect((float)x + 24, (float)y + 24, 130, 38);
props.id = 301;
props.min = 1;
props.max = 128;
props.step = 1;
props.value = &a->length;
Spinbox(props);
}
label_text("Counter", x + 182, y, 14, text);
{
SpinboxProps props;
memset(&props, 0, sizeof(props));
props.bounds = scaled_rect((float)x + 182, (float)y + 24, 130, 38);
props.id = 302;
props.min = 1;
props.max = 999999;
props.step = 1;
props.value = &a->counter;
Spinbox(props);
}
draw_field(&a->exclude, scaled_rect((float)x + 340, (float)y + 24, (float)content_w - 364, 38), 16, style);
label_text("Excluded characters", x + 340, y, 14, text);
y += 76;
checkbox(ScaleUIPx(x + 24), ScaleUIPx(y), "Lowercase", &a->lower);
checkbox(ScaleUIPx(x + 174), ScaleUIPx(y), "Uppercase", &a->upper);
checkbox(ScaleUIPx(x + 324), ScaleUIPx(y), "Digits", &a->digits);
checkbox(ScaleUIPx(x + 444), ScaleUIPx(y), "Symbols", &a->symbols);
y += 48;
if(button(ScaleUIPx(x + 24), ScaleUIPx(y), ScaleUIPx(150), ScaleUIPx(42),
"Generate", UI_BUTTON_STYLE_PRIMARY, 0))
generate(a);
if(button(ScaleUIPx(x + 190), ScaleUIPx(y), ScaleUIPx(150), ScaleUIPx(42),
"Copy for 20s", UI_BUTTON_STYLE_SECONDARY, a->generated[0] == '\0')) {
clipboard_copy(a, a->generated);
snprintf(a->message, sizeof(a->message), "%s", "Copied; clipboard clears in 20 seconds");
}
if(button(ScaleUIPx(x + 356), ScaleUIPx(y), ScaleUIPx(120), ScaleUIPx(42),
"Clear", UI_BUTTON_STYLE_SECONDARY, 0)) {
field_clear(&a->master);
a->generated[0] = '\0';
snprintf(a->message, sizeof(a->message), "%s", "Cleared");
}
y += 56;
DrawRectangleRounded(scaled_rect((float)x + 24, (float)y, (float)content_w - 48, 72), 0.08f, 10, scheme.surface_container);
if(a->generated[0] != '\0')
label_text(a->generated, x + 42, y + 15, 20, text);
else
label_text("Your generated password appears here", x + 42, y + 17, 16, scheme.on_surface_variant);
if(a->message[0] != '\0')
label_text(a->message, x + 42, y + 45, 12, scheme.on_surface_variant);
}
/* ------------------------------------------------------------------ */
/* Narrow phone layout: single column inside a scrollable card */
/* ------------------------------------------------------------------ */
static void
draw_narrow(GopassApp *a, int width, int height, int top_reserved, int bottom_reserved)
{
UIMaterialScheme scheme = GetUIMaterialScheme();
Color text = GetThemeText();
UITextInputStyle style = input_style();
UIScrollArea area;
UIScrollView view;
int margin = 12;
int card_x = margin;
int card_y = top_reserved + 62;
int card_w = width - margin * 2;
int card_h = height - bottom_reserved - margin - card_y;
int pad = 18;
int inner_x = card_x + pad;
int inner_w = card_w - pad * 2;
int half_w = (inner_w - 12) / 2;
int content_h;
int x, y, cx, cy;
Rectangle card;
if(card_h < 200)
card_h = 200;
/* compact header */
DrawRectangleRounded(scaled_rect((float)margin, (float)top_reserved + 8, 40, 40), 0.22f, 10, scheme.primary);
label_text("g", margin + 13, top_reserved + 15, 24, scheme.on_primary);
label_text("gopass", margin + 52, top_reserved + 6, 24, text);
label_text("Private by design \xc2\xb7 generated on this device",
margin + 52, top_reserved + 36, 12, scheme.on_surface_variant);
/* content height (UI units): sections and rows below */
content_h = 20 /* section label */
+ 3 * 66 /* site, login, master rows */
+ 20 + 62 /* rules label + spinbox row */
+ 66 /* excluded characters */
+ 2 * 36 /* checkbox rows */
+ 50 /* generate */
+ 50 /* copy/clear row */
+ 78 /* result box */
+ pad;
card = scaled_rect((float)card_x, (float)card_y, (float)card_w, (float)card_h);
DrawRectangleRounded(card, 0.035f, 10, scheme.surface);
DrawRectangleLinesEx(card, 1.0f, scheme.outline);
memset(&area, 0, sizeof(area));
area.bounds = card;
area.content_height = ScaleUIPx(content_h);
area.content_x = ScaleUIPx(inner_x);
area.content_width = ScaleUIPx(inner_w);
area.scroll_offset = &a->scroll_offset;
view = BeginUIScrollContainer(area);
cx = view.content_x;
cy = view.content_y;
/* positions in UI units relative to content origin */
x = 0;
y = 0;
label_text("PASSWORD DETAILS", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 12, scheme.primary);
y += 20;
label_text("Site", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
draw_field(&a->site, (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 22)),
(float)ScaleUIPx(inner_w), (float)ScaleUIPx(38)}, 16, style);
y += 66;
label_text("Login", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
draw_field(&a->login, (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 22)),
(float)ScaleUIPx(inner_w), (float)ScaleUIPx(38)}, 16, style);
y += 66;
label_text("Master password", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
a->master.secure = !a->reveal;
{
int field_w = inner_w - 80;
draw_field(&a->master, (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 22)),
(float)ScaleUIPx(field_w), (float)ScaleUIPx(38)}, 16, style);
if(button(cx + ScaleUIPx(x + field_w + 8), cy + ScaleUIPx(y + 22), ScaleUIPx(72), ScaleUIPx(38),
a->reveal ? "Hide" : "Reveal", UI_BUTTON_STYLE_SECONDARY, 0))
a->reveal = !a->reveal;
}
y += 66;
label_text("PASSWORD RULES", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 12, scheme.primary);
y += 18;
label_text("Length", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
{
SpinboxProps props;
memset(&props, 0, sizeof(props));
props.bounds = (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 20)),
(float)ScaleUIPx(half_w), (float)ScaleUIPx(38)};
props.id = 301;
props.min = 1;
props.max = 128;
props.step = 1;
props.value = &a->length;
Spinbox(props);
}
label_text("Counter", cx + ScaleUIPx(x + half_w + 12), cy + ScaleUIPx(y), 14, text);
{
SpinboxProps props;
memset(&props, 0, sizeof(props));
props.bounds = (Rectangle){(float)(cx + ScaleUIPx(x + half_w + 12)), (float)(cy + ScaleUIPx(y + 20)),
(float)ScaleUIPx(half_w), (float)ScaleUIPx(38)};
props.id = 302;
props.min = 1;
props.max = 999999;
props.step = 1;
props.value = &a->counter;
Spinbox(props);
}
y += 62;
label_text("Excluded characters", cx + ScaleUIPx(x), cy + ScaleUIPx(y), 14, text);
draw_field(&a->exclude, (Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y + 22)),
(float)ScaleUIPx(inner_w), (float)ScaleUIPx(38)}, 16, style);
y += 66;
checkbox(cx + ScaleUIPx(x), cy + ScaleUIPx(y), "Lowercase", &a->lower);
checkbox(cx + ScaleUIPx(x + half_w + 12), cy + ScaleUIPx(y), "Uppercase", &a->upper);
y += 36;
checkbox(cx + ScaleUIPx(x), cy + ScaleUIPx(y), "Digits", &a->digits);
checkbox(cx + ScaleUIPx(x + half_w + 12), cy + ScaleUIPx(y), "Symbols", &a->symbols);
y += 44;
if(button(cx + ScaleUIPx(x), cy + ScaleUIPx(y), ScaleUIPx(inner_w), ScaleUIPx(42),
"Generate", UI_BUTTON_STYLE_PRIMARY, 0))
generate(a);
y += 50;
if(button(cx + ScaleUIPx(x), cy + ScaleUIPx(y), ScaleUIPx(half_w), ScaleUIPx(42),
"Copy for 20s", UI_BUTTON_STYLE_SECONDARY, a->generated[0] == '\0')) {
clipboard_copy(a, a->generated);
snprintf(a->message, sizeof(a->message), "%s", "Copied; clipboard clears in 20 seconds");
}
if(button(cx + ScaleUIPx(x + half_w + 12), cy + ScaleUIPx(y), ScaleUIPx(half_w), ScaleUIPx(42),
"Clear", UI_BUTTON_STYLE_SECONDARY, 0)) {
field_clear(&a->master);
a->generated[0] = '\0';
snprintf(a->message, sizeof(a->message), "%s", "Cleared");
}
y += 50;
DrawRectangleRounded((Rectangle){(float)(cx + ScaleUIPx(x)), (float)(cy + ScaleUIPx(y)),
(float)ScaleUIPx(inner_w), (float)ScaleUIPx(72)}, 0.08f, 10,
scheme.surface_container);
if(a->generated[0] != '\0')
DrawUITextInRect(a->generated,
(Rectangle){(float)(cx + ScaleUIPx(x + 14)), (float)(cy + ScaleUIPx(y + 8)),
(float)ScaleUIPx(inner_w - 28), (float)ScaleUIPx(40)},
16, text);
else
label_text("Your generated password appears here", x + 14, y + 14, 14, scheme.on_surface_variant);
if(a->message[0] != '\0')
label_text(a->message, x + 14, y + 50, 11, scheme.on_surface_variant);
EndUIScrollContainer(area, view);
}
void
gopass_app_draw(GopassApp *a, int surface_w, int surface_h, float dpi,
int top_reserved, int bottom_reserved)
{
int ui_w = (int)(surface_w / (dpi > 0.0f ? dpi : 1.0f) + 0.5f);
int ui_h = (int)(surface_h / (dpi > 0.0f ? dpi : 1.0f) + 0.5f);
(void)ui_h;
Background(GetThemeBackground());
clipboard_tick(a);
if(ui_w >= 560)
draw_wide(a, ui_w, ui_h, top_reserved);
else
draw_narrow(a, ui_w, ui_h, top_reserved, bottom_reserved);
}
void
gopass_app_shutdown(GopassApp *a)
{
if(a == NULL)
return;
field_clear(&a->master);
clipboard_clear(a);
a->generated[0] = '\0';
}
-16
View File
@@ -1,16 +0,0 @@
#ifndef GOPASS_APP_H
#define GOPASS_APP_H
typedef struct GopassApp GopassApp;
GopassApp *gopass_app(void);
/* Draws one frame. Surface sizes are physical pixels; dpi is the display
* scale. top/bottom_reserved are safe-area insets in UI units (dp). */
void gopass_app_draw(GopassApp *app, int surface_w, int surface_h, float dpi,
int top_reserved, int bottom_reserved);
/* Clears secrets held in memory. */
void gopass_app_shutdown(GopassApp *app);
#endif
-107
View File
@@ -1,107 +0,0 @@
/* Android entry point for gopass. Raylib's Android backend provides
* android_main and calls main(); this file owns window, theme, fonts, and
* the frame loop. */
#include "kryon.h"
#include "embedded_assets.h"
#include "ui_dpi.h"
#include "ui_core.h"
#include "ui_scaling.h"
#include "android_bridge.h"
#include "gopass_app.h"
#include <stdio.h>
#include <string.h>
#if ANDROID_BUILD
#include <android/log.h>
#include <unistd.h>
#endif
static const char *const FONT_ASSET_PATH = "vendor/kryon/fonts/noto/NotoSans-Regular.ttf";
/* Kryon's shape drawing rides on a 1x1 white texture so rectangles tint
* cleanly on the GL ES surface (same setup inbe performs on Android). */
static void
setup_shapes_texture(void)
{
Image white = GenImageColor(1, 1, WHITE);
Texture2D texture = LoadTextureFromImage(white);
UnloadImage(white);
if(texture.id == 0)
return;
SetTextureFilter(texture, TEXTURE_FILTER_POINT);
SetShapesTexture(texture, (Rectangle){0.0f, 0.0f, 1.0f, 1.0f});
}
static int
setup_ui_font(void)
{
const EmbeddedAsset *asset = GetEmbeddedAsset(FONT_ASSET_PATH);
if(asset == NULL || asset->data == NULL || asset->size == 0) {
TraceLog(LOG_WARNING, "GOPASS: missing embedded font asset");
return 0;
}
if(!RegisterUIFontSource("ui", GetEmbeddedAssetExtension(FONT_ASSET_PATH),
asset->data, asset->size, NULL, 0)) {
TraceLog(LOG_WARNING, "GOPASS: RegisterUIFontSource failed");
return 0;
}
if(!UseUIFont("ui")) {
TraceLog(LOG_WARNING, "GOPASS: UseUIFont failed");
return 0;
}
return 1;
}
int
main(int argc, char **argv)
{
GopassApp *app;
(void)argc;
(void)argv;
#if ANDROID_BUILD
__android_log_write(ANDROID_LOG_INFO, "GOPASS_MAIN", "main start");
android_bridge_init();
if(chdir("/data/user/0/xyz.waozi.pass/files") != 0)
TraceLog(LOG_WARNING, "GOPASS: failed to switch to files directory");
#endif
InitWindow(0, 0, "gopass");
if(!IsWindowReady()) {
TraceLog(LOG_ERROR, "GOPASS: InitWindow failed");
return 1;
}
InitUIDPI();
SetThemeStyle(THEME_STYLE_MATERIAL);
SetCurrentTheme(11, 1); /* Cobalt dark, same as the desktop GUI */
setup_ui_font();
setup_shapes_texture();
SetUITextInputPlatformCallback(android_bridge_set_soft_keyboard);
SetTargetFPS(60);
app = gopass_app();
while(!WindowShouldClose()) {
int width = GetScreenWidth();
int height = GetScreenHeight();
Vector2 scale = GetWindowScaleDPI();
float dpi = scale.x > 0.0f ? scale.x : 1.0f;
BeginDrawing();
BeginUIFrame(width, height, dpi);
gopass_app_draw(app, width, height, dpi,
android_bridge_top_reserved(),
android_bridge_bottom_reserved());
EndUIFrame();
EndDrawing();
}
gopass_app_shutdown(app);
CloseWindow();
return 0;
}
@@ -1,170 +0,0 @@
package xyz.waozi.pass;
import android.app.NativeActivity;
import android.graphics.Insets;
import android.os.Build;
import android.os.Bundle;
import android.view.DisplayCutout;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.inputmethod.InputMethodManager;
import android.content.Context;
/**
* NativeActivity glue for the kryon UI: routes soft-keyboard input and
* window insets to the native side. Modeled on inbe's MainActivity.
*/
public class MainActivity extends NativeActivity {
static {
// Associate libmain with this class's loader so ART can resolve the
// native methods below (NativeActivity loads it via the boot loader).
System.loadLibrary("main");
}
private int lastDeleteRepeatCount = -1;
private native void nativeSetInsets(int status, int nav,
int cutoutLeft, int cutoutTop, int cutoutRight, int cutoutBottom);
private native void nativeSetDeviceDensity(float density);
private native void nativeTextInputCommit(int codepoint);
private native void nativeTextInputBackspace();
private native void nativeTextInputEnter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupInsetsListener();
}
public void setSoftKeyboardVisible(final boolean visible) {
runOnUiThread(new Runnable() {
@Override
public void run() {
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
View view = getWindow() != null ? getWindow().getDecorView() : null;
if (imm == null || view == null) return;
if (visible) {
view.requestFocus();
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
} else {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_DEL) {
int repeatCount = event.getRepeatCount();
int deleteCount = lastDeleteRepeatCount < 0
? 1
: Math.max(1, repeatCount - lastDeleteRepeatCount);
lastDeleteRepeatCount = repeatCount;
for (int i = 0; i < deleteCount; i++) {
nativeTextInputBackspace();
}
} else if (keyCode == KeyEvent.KEYCODE_ENTER ||
keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) {
lastDeleteRepeatCount = -1;
nativeTextInputEnter();
} else {
lastDeleteRepeatCount = -1;
int unicode = event.getUnicodeChar();
if (unicode >= 32) {
nativeTextInputCommit(unicode);
}
}
} else if (event != null && event.getAction() == KeyEvent.ACTION_UP) {
if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
lastDeleteRepeatCount = -1;
}
} else if (event != null && event.getAction() == KeyEvent.ACTION_MULTIPLE &&
event.getCharacters() != null) {
lastDeleteRepeatCount = -1;
String chars = event.getCharacters();
for (int i = 0; i < chars.length();) {
int codepoint = chars.codePointAt(i);
if (codepoint >= 32) {
nativeTextInputCommit(codepoint);
}
i += Character.charCount(codepoint);
}
}
return super.dispatchKeyEvent(event);
}
private void setupInsetsListener() {
final View decorView = getWindow().getDecorView();
nativeSetDeviceDensity(getResources().getDisplayMetrics().density);
decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
updateInsets(insets);
return insets;
}
});
// Startup safety net: catch the initial layout pass.
decorView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
WindowInsets insets = decorView.getRootWindowInsets();
if (insets != null) {
updateInsets(insets);
}
}
decorView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
decorView.post(new Runnable() {
@Override
public void run() {
decorView.requestApplyInsets();
}
});
}
private void updateInsets(WindowInsets insets) {
if (insets == null) return;
nativeSetDeviceDensity(getResources().getDisplayMetrics().density);
int statusBar = 0;
int navBar = 0;
int cLeft = 0, cTop = 0, cRight = 0, cBottom = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Insets systemBars = insets.getInsetsIgnoringVisibility(
WindowInsets.Type.systemBars());
statusBar = systemBars.top;
navBar = systemBars.bottom;
} else {
statusBar = insets.getSystemWindowInsetTop();
navBar = insets.getSystemWindowInsetBottom();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
DisplayCutout cutout = insets.getDisplayCutout();
if (cutout != null) {
cLeft = cutout.getSafeInsetLeft();
cTop = cutout.getSafeInsetTop();
cRight = cutout.getSafeInsetRight();
cBottom = cutout.getSafeInsetBottom();
}
}
nativeSetInsets(statusBar, navBar, cLeft, cTop, cRight, cBottom);
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 842 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

+1 -1
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">gopass</string>
<string name="app_name">Werkzeug</string>
</resources>
+1 -1
View File
@@ -13,5 +13,5 @@ dependencyResolutionManagement {
}
}
rootProject.name = "gopass"
rootProject.name = "werk"
include ':app'
@@ -0,0 +1 @@
Initial release: deterministic, LessPass-compatible password generation with configurable length, counter, character classes, and excluded characters. Everything is computed locally; nothing is stored or uploaded.
@@ -0,0 +1,2 @@
- Keep bottom navigation, password controls, and dialog icons readable with dark tints in light mode and light tints in dark mode.
- Prevent taps in Theme Settings from reaching fields underneath or opening the keyboard when saving the theme.
@@ -0,0 +1 @@
- Introduce the purple password asterisk and keyhole logo across Pass, website icons, Android launchers, and app listings.
@@ -0,0 +1,5 @@
- Pass is now Werkzeug: a home screen of small private tools, each its own app and all preinstalled.
- A new logo: a wrench with a keyhole. The website moves to werk.waozi.xyz.
- Add Auth for two-factor sign-in codes from otpauth links or secret keys; copied codes clear after 30 seconds.
- Add Calculator, and Clock with a stopwatch.
- Add a profile with your name, a picture and the appearance every tool shares.
@@ -0,0 +1 @@
New clipboard handling, vault support, and named profiles in the CLI, plus self-update checks in the desktop app. Android keeps the same local, stateless generator.
@@ -0,0 +1,2 @@
- Install pass on Android: a signed APK is now downloadable from pass.waozi.xyz alongside the desktop, terminal, and browser downloads.
- Fix the Android master-password fingerprint and secure storage so the stored master password unlocks reliably across launches.
@@ -0,0 +1,2 @@
- Verify every download: releases now ship a SHA256SUMS file covering the command-line, desktop, Android, and browser downloads.
- The Android app now builds entirely from source with no developer signing key, clearing the way for F-Droid distribution.
@@ -0,0 +1,6 @@
- Save and reuse Android master-password defaults with fingerprint unlock.
- Clear unlocked master text and generated passwords after a timeout.
- Autosave length, counter, character classes, excluded characters, and biometric display settings.
- Keep Android fields visible while the keyboard is open.
- Run the real Pass app at pass.waozi.xyz/app.
- Publish universal and per-ABI Android APKs.
@@ -0,0 +1,3 @@
- Add Android appearance settings for following device colors, choosing light or dark mode, selecting a color palette, and switching widget style.
- Use Android system Material colors for the app theme, with a stable Material fallback instead of the bright pink accent some devices report.
- Recalculate the Android layout cleanly when rotating between portrait and landscape, keeping controls clear of system bars and navigation insets.
@@ -0,0 +1 @@
- Keep Android source builds self-contained so F-Droid and other source builds generate the Kry app sources automatically.
@@ -0,0 +1 @@
- Fix Android source builds in stricter environments such as F-Droid builders while keeping Kry app source generation automatic.
@@ -0,0 +1,4 @@
- Match LessPass clients for the same site, login, master password, counter, character classes, and length settings.
- Limit password length to LessPass's 5 to 35 character range.
- Require Android fingerprint unlock for saved master passwords and store them with an authenticated Android Keystore key.
- Use the Sweet Material palette by default, with Sweet-Dark matched colors in dark mode, and show generated passwords in a dedicated output field.
@@ -0,0 +1,15 @@
Werkzeug holds small private tools in one app. Everything is computed on your device and nothing is tracked. It makes no network requests unless you turn on sync.
• Pass derives strong, repeatable passwords. The same site, login, master password, and settings always produce the same result, so there is no password database to back up, sync, or lose. It is LessPass-compatible, with configurable length, counter, character classes and excluded characters, and an optional master password kept behind device authentication.
• Auth shows two-factor sign-in codes (TOTP with SHA-1, SHA-256 or SHA-512). Add accounts from otpauth links, including an authenticator's plain-text export, or by secret key. Copied codes are cleared from the clipboard after 30 seconds. Optional sync keeps them on all your devices, encrypted on the device so the server never sees them.
• Calculator handles everyday arithmetic with brackets, powers and percent.
• Clock shows the local time and date and has a stopwatch.
A profile with your name and picture sets the appearance every tool shares. Werkzeug was previously called Pass; updating keeps your profiles, settings and saved master password.
Pass is an independent implementation of the LessPass algorithm. Compatibility does not imply endorsement by or affiliation with the LessPass project.
Source code: https://github.com/waozixyz/werk
Website: https://werk.waozi.xyz
Licensed under BSD-3-Clause.
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

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

Before

Width:  |  Height:  |  Size: 125 KiB

-182
View File
@@ -1,182 +0,0 @@
package main
import (
_ "embed"
"time"
password "github.com/waozixyz/gopass"
"github.com/waozixyz/kryon/go/kryui"
)
const clipboardLifetime = 20 * time.Second
//go:embed icon.png
var appIconPNG []byte
//go:embed assets/emoji.ttf
var emojiFontTTF []byte
type app struct {
site, login, master, exclude *kryui.TextFieldState
length, counter int32
lower, upper, digits, symbols bool
reveal bool
generated, message, fingerprint string
clipboard clipboardLease
}
func newApp() *app {
return &app{
site: kryui.NewTextField(101, 256), login: kryui.NewTextField(102, 256),
master: kryui.NewPasswordField(103, 1024), exclude: kryui.NewTextField(104, 128),
length: 16, counter: 1, lower: true, upper: true, digits: true, symbols: true,
clipboard: clipboardLease{read: kryui.GetClipboardText, write: kryui.SetClipboardText, now: time.Now},
}
}
func main() {
kryui.SetConfigFlags(kryui.FlagWindowResizable)
kryui.InitWindow(720, 690, "gopass")
defer kryui.CloseWindow()
icon := kryui.LoadImageFromMemory(".png", appIconPNG)
kryui.SetWindowIcon(icon)
kryui.UnloadImage(icon)
kryui.SetThemeStyle(kryui.ThemeStyleMaterial)
kryui.SetCurrentTheme(11, true) // Cobalt dark
kryui.EnsureUIDefaultFont()
// The emoji fingerprint font serves only the master-password emoji
// codepoints; all other glyphs keep coming from the theme font.
kryui.RegisterUIFixedFontData("gopass-emoji", ".ttf", emojiFontTTF, password.MasterEmojiCodepoints())
kryui.SetWindowMinSize(560, 620)
kryui.EnableEventWaiting()
a := newApp()
defer func() { a.master.Clear(); a.clipboard.clear() }()
for !kryui.WindowShouldClose() {
a.clipboard.tick()
kryui.BeginDrawing()
w := kryui.GetScreenWidth()
kryui.BeginUI(kryui.Key("gopass/main"))
a.draw(w)
kryui.EndUI()
a.handleUIEvents()
kryui.EndDrawing()
}
}
func (a *app) draw(width int32) {
bg, text := kryui.GetThemeBackground(), kryui.GetThemeText()
scheme := kryui.GetUIMaterialScheme()
kryui.ClearBackground(bg)
contentW := width - 64
if contentW > 720 {
contentW = 720
}
x := (width - contentW) / 2
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x), 22, 48, 48), .22, 10, scheme.Primary)
kryui.DrawUIText("g", x+15, 29, kryui.UIText32, scheme.OnPrimary)
kryui.DrawUIText("gopass", x+64, 24, kryui.UIText32, text)
kryui.DrawUIText("Private by design · generated on this device", x+64, 60, kryui.UIText14, scheme.OnSurfaceVariant)
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x), 92, float32(contentW), 550), .035, 10, scheme.Surface)
kryui.DrawRectangleLinesEx(kryui.NewRectangle(float32(x), 92, float32(contentW), 550), 1, scheme.Outline)
kryui.DrawUIText("PASSWORD DETAILS", x+24, 116, kryui.UIText12, scheme.Primary)
style := inputStyle()
y := int32(146)
a.field("Site", a.site, x+24, y, contentW-48, style)
y += 76
a.field("Login", a.login, x+24, y, contentW-48, style)
y += 76
kryui.DrawUIText("Master password", x+24, y, kryui.UIText14, text)
a.master.SetSecure(!a.reveal)
kryui.TextField(a.master, kryui.FieldProps{Bounds: kryui.NewRectangle(float32(x+24), float32(y+24), float32(contentW-150), 38), Font: kryui.UIText16, Style: style})
if a.fingerprint != "" {
fontToken := kryui.PushUIFont("gopass-emoji")
width := kryui.MeasureText(a.fingerprint, kryui.UIText16)
kryui.DrawUIText(a.fingerprint, x+contentW-24-width, y, kryui.UIText16, scheme.OnSurfaceVariant)
kryui.PopUIFont(fontToken)
}
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+contentW-112), float32(y+24), 88, 38), Label: map[bool]string{true: "Hide", false: "Reveal"}[a.reveal], Style: kryui.UIButtonStyleSecondary, ID: 205})
y += 76
kryui.DrawUIText("PASSWORD RULES", x+24, y-10, kryui.UIText12, scheme.Primary)
y += 14
kryui.DrawUIText("Length", x+24, y, kryui.UIText14, text)
kryui.Spinbox(kryui.SpinboxProps{Bounds: kryui.NewRectangle(float32(x+24), float32(y+24), 130, 38), ID: 301, Min: 1, Max: 128, Step: 1, Value: &a.length})
kryui.DrawUIText("Counter", x+182, y, kryui.UIText14, text)
kryui.Spinbox(kryui.SpinboxProps{Bounds: kryui.NewRectangle(float32(x+182), float32(y+24), 130, 38), ID: 302, Min: 1, Max: 999999, Step: 1, Value: &a.counter})
kryui.TextField(a.exclude, kryui.FieldProps{Bounds: kryui.NewRectangle(float32(x+340), float32(y+24), float32(contentW-364), 38), Font: kryui.UIText16, Style: style})
kryui.DrawUIText("Excluded characters", x+340, y, kryui.UIText14, text)
y += 76
kryui.DrawUICheckboxToggle(x+24, y, "Lowercase", &a.lower)
kryui.DrawUICheckboxToggle(x+174, y, "Uppercase", &a.upper)
kryui.DrawUICheckboxToggle(x+324, y, "Digits", &a.digits)
kryui.DrawUICheckboxToggle(x+444, y, "Symbols", &a.symbols)
y += 48
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+24), float32(y), 150, 42), Label: "Generate", Style: kryui.UIButtonStylePrimary, ID: 401})
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+190), float32(y), 150, 42), Label: "Copy for 20s", Style: kryui.UIButtonStyleSecondary, ID: 402, Disabled: a.generated == ""})
kryui.Button(kryui.ButtonProps{Bounds: kryui.NewRectangle(float32(x+356), float32(y), 120, 42), Label: "Clear", Style: kryui.UIButtonStyleSecondary, ID: 403})
y += 56
kryui.DrawRectangleRounded(kryui.NewRectangle(float32(x+24), float32(y), float32(contentW-48), 72), .08, 10, scheme.SurfaceContainer)
if a.generated != "" {
kryui.SelectableText(a.generated, x+42, y+15, kryui.UIText20, text)
} else {
kryui.DrawUIText("Your generated password appears here", x+42, y+17, kryui.UIText16, scheme.OnSurfaceVariant)
}
if a.message != "" {
kryui.DrawUIText(a.message, x+42, y+45, kryui.UIText12, scheme.OnSurfaceVariant)
}
}
func (a *app) field(label string, field *kryui.TextFieldState, x, y, width int32, style kryui.UITextInputStyle) {
kryui.DrawUIText(label, x, y, kryui.UIText14, kryui.GetThemeText())
kryui.TextField(field, kryui.FieldProps{Bounds: kryui.NewRectangle(float32(x), float32(y+24), float32(width), 38), Font: kryui.UIText16, Style: style})
}
func (a *app) handleUIEvents() {
for event, ok := kryui.NextUIEvent(); ok; event, ok = kryui.NextUIEvent() {
switch event.Kind {
case kryui.EventTextChanged:
if event.Key == 103 {
if master := a.master.Text(); master != "" {
a.fingerprint = password.MasterPasswordEmojiString(master)
} else {
a.fingerprint = ""
}
}
case kryui.EventClick:
switch event.Key {
case 205:
a.reveal = !a.reveal
case 401:
a.generate()
case 402:
if a.generated != "" {
a.clipboard.copy(a.generated, clipboardLifetime)
a.message = "Copied; clipboard clears in 20 seconds"
}
case 403:
a.master.Clear()
a.fingerprint = ""
a.generated = ""
a.message = "Cleared"
}
}
}
}
func (a *app) generate() {
result, err := password.Generate(a.site.Text(), a.login.Text(), a.master.Text(), password.Options{Length: int(a.length), Counter: uint64(a.counter), Lowercase: a.lower, Uppercase: a.upper, Digits: a.digits, Symbols: a.symbols, Exclude: a.exclude.Text()})
if err != nil {
a.generated = ""
a.message = err.Error()
return
}
a.generated, a.message = result, "Password generated locally"
}
func inputStyle() kryui.UITextInputStyle {
s := kryui.GetUIMaterialScheme()
return kryui.UITextInputStyle{Background: s.SurfaceContainer, Border: s.Outline, FocusBorder: s.Primary, Text: s.OnSurface, Cursor: s.Primary, Radius: 6, PaddingX: 10, PaddingY: 8}
}
-54
View File
@@ -1,54 +0,0 @@
package gopass
import "crypto/sha256"
// masterEmojiTable is the fixed alphabet for the master-password fingerprint.
// Entries are single-codepoint emoji with distinct silhouettes so a wrong
// master password is obvious at a glance. The order is part of the public
// derivation: never reorder or extend without treating it as a format change.
var masterEmojiTable = []rune{
// animals
'🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼',
'🐨', '🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🐔',
'🐧', '🦉', '🐺', '🐴', '🦄', '🐝', '🦋', '🐢',
// food
'🍎', '🍊', '🍋', '🍉', '🍇', '🍓', '🍒', '🍑',
'🥑', '🌽', '🍕', '🍔', '🍟', '🍩',
// nature
'🌵', '🌲', '🌳', '🌴', '🌱', '🌻', '🌸', '🌈',
'⭐', '🌙',
// objects
'🔥', '💧', '⛄', '🎉', '🎸', '🎯', '🎲', '🎁',
'🚀', '🚗', '⚓', '🎨', '🔑', '💡', '📚', '🎧',
}
// MasterEmojiCount is the number of emoji shown for one master password.
const MasterEmojiCount = 4
// MasterPasswordEmoji derives a short emoji fingerprint from a master
// password: the first bytes of its SHA-256 select MasterEmojiCount emoji from
// masterEmojiTable. The same master password always produces the same emoji,
// so a user can recognise a correctly typed master password across sessions
// without the password ever being stored or displayed. The fingerprint leaks
// only 24 bits of the hash, which does not help recover a strong master.
func MasterPasswordEmoji(master string) []rune {
sum := sha256.Sum256([]byte(master))
emoji := make([]rune, MasterEmojiCount)
for i := range emoji {
emoji[i] = masterEmojiTable[int(sum[i])%len(masterEmojiTable)]
}
return emoji
}
// MasterPasswordEmojiString is MasterPasswordEmoji as a display string.
func MasterPasswordEmojiString(master string) string {
return string(MasterPasswordEmoji(master))
}
// MasterEmojiCodepoints lists the table's codepoints. Registration with a
// font subset needs exactly these glyphs.
func MasterEmojiCodepoints() []rune {
codepoints := make([]rune, len(masterEmojiTable))
copy(codepoints, masterEmojiTable)
return codepoints
}
-63
View File
@@ -1,63 +0,0 @@
package gopass
import "testing"
func TestMasterPasswordEmojiIsDeterministic(t *testing.T) {
first := MasterPasswordEmojiString("correct horse battery staple")
for i := 0; i < 8; i++ {
if got := MasterPasswordEmojiString("correct horse battery staple"); got != first {
t.Fatalf("fingerprint changed between calls: %q vs %q", got, first)
}
}
if got := MasterPasswordEmojiString(""); got == "" || len([]rune(got)) != MasterEmojiCount {
t.Fatalf("empty master fingerprint = %q, want %d emoji", got, MasterEmojiCount)
}
}
func TestMasterPasswordEmojiDiffersForDifferentMasters(t *testing.T) {
seen := map[string]string{
MasterPasswordEmojiString("test"): "test",
MasterPasswordEmojiString("test2"): "test2",
MasterPasswordEmojiString("tset"): "tset",
MasterPasswordEmojiString("hunter2"): "hunter2",
MasterPasswordEmojiString("correct horse battery staple"): "correct horse battery staple",
}
// Five distinct short masters colliding on a 24-bit space would be
// itself a sha256 anomaly; a single collision here means a table bug.
if len(seen) != 5 {
t.Fatalf("expected distinct fingerprints, got %d unique for 5 masters", len(seen))
}
}
func TestMasterPasswordEmojiUsesTableAlphabet(t *testing.T) {
inTable := func(r rune) bool {
for _, candidate := range masterEmojiTable {
if candidate == r {
return true
}
}
return false
}
if len(masterEmojiTable) != 64 {
t.Fatalf("table has %d emoji, want 64", len(masterEmojiTable))
}
for _, master := range []string{"a", "b", "ab", "🔐", "фыв"} {
for _, r := range MasterPasswordEmoji(master) {
if !inTable(r) {
t.Fatalf("master %q produced rune %U outside the table", master, r)
}
}
}
}
func TestMasterEmojiCodepointsMatchTable(t *testing.T) {
codepoints := MasterEmojiCodepoints()
if len(codepoints) != len(masterEmojiTable) {
t.Fatalf("got %d codepoints, want %d", len(codepoints), len(masterEmojiTable))
}
for i := range codepoints {
if codepoints[i] != masterEmojiTable[i] {
t.Fatalf("codepoint %d = %U, want %U", i, codepoints[i], masterEmojiTable[i])
}
}
}
+20
View File
@@ -0,0 +1,20 @@
</$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
-407
View File
@@ -1,407 +0,0 @@
/* C port of the gopass Go generator (gopass.go, pbkdf2.go). The output is
* byte-identical to the Go implementation; native/gopass_core_test.c checks
* the same fixed vectors the Go tests use. */
#include "gopass_core.h"
#include <stdio.h>
#include <string.h>
static const char LOWERCASE_CHARACTERS[] = "abcdefghijklmnopqrstuvwxyz";
static const char UPPERCASE_CHARACTERS[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char DIGIT_CHARACTERS[] = "0123456789";
static const char SYMBOL_CHARACTERS[] = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
/* ------------------------------------------------------------------ */
/* SHA-256 */
/* ------------------------------------------------------------------ */
typedef struct {
uint32_t state[8];
uint64_t bitlen;
uint8_t buffer[64];
size_t buffer_len;
} Sha256;
static const uint32_t SHA256_K[64] = {
0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu,
0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u, 0xd807aa98u, 0x12835b01u,
0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u,
0xc19bf174u, 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu,
0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, 0x983e5152u,
0xa831c66du, 0xb00327c8u, 0xbf597fc7u, 0xc6e00bf3u, 0xd5a79147u,
0x06ca6351u, 0x14292967u, 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu,
0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u,
0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u,
0xd6990624u, 0xf40e3585u, 0x106aa070u, 0x19a4c116u, 0x1e376c08u,
0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu,
0x682e6ff3u, 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u,
0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u
};
static uint32_t
rotr32(uint32_t value, unsigned bits)
{
return (value >> bits) | (value << (32 - bits));
}
static void
sha256_init(Sha256 *ctx)
{
ctx->state[0] = 0x6a09e667u;
ctx->state[1] = 0xbb67ae85u;
ctx->state[2] = 0x3c6ef372u;
ctx->state[3] = 0xa54ff53au;
ctx->state[4] = 0x510e527fu;
ctx->state[5] = 0x9b05688cu;
ctx->state[6] = 0x1f83d9abu;
ctx->state[7] = 0x5be0cd19u;
ctx->bitlen = 0;
ctx->buffer_len = 0;
}
static void
sha256_block(Sha256 *ctx, const uint8_t block[64])
{
uint32_t w[64];
uint32_t a, b, c, d, e, f, g, h;
uint32_t t1, t2;
int i;
for(i = 0; i < 16; i++)
w[i] = ((uint32_t)block[i * 4] << 24) |
((uint32_t)block[i * 4 + 1] << 16) |
((uint32_t)block[i * 4 + 2] << 8) |
(uint32_t)block[i * 4 + 3];
for(i = 16; i < 64; i++) {
uint32_t s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >> 3);
uint32_t s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
a = ctx->state[0];
b = ctx->state[1];
c = ctx->state[2];
d = ctx->state[3];
e = ctx->state[4];
f = ctx->state[5];
g = ctx->state[6];
h = ctx->state[7];
for(i = 0; i < 64; i++) {
uint32_t s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25);
uint32_t ch = (e & f) ^ (~e & g);
t1 = h + s1 + ch + SHA256_K[i] + w[i];
uint32_t s0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22);
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
t2 = s0 + maj;
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
ctx->state[0] += a;
ctx->state[1] += b;
ctx->state[2] += c;
ctx->state[3] += d;
ctx->state[4] += e;
ctx->state[5] += f;
ctx->state[6] += g;
ctx->state[7] += h;
}
static void
sha256_update(Sha256 *ctx, const void *data, size_t len)
{
const uint8_t *p = (const uint8_t *)data;
ctx->bitlen += (uint64_t)len * 8u;
while(len > 0) {
size_t take = 64 - ctx->buffer_len;
if(take > len)
take = len;
memcpy(ctx->buffer + ctx->buffer_len, p, take);
ctx->buffer_len += take;
p += take;
len -= take;
if(ctx->buffer_len == 64) {
sha256_block(ctx, ctx->buffer);
ctx->buffer_len = 0;
}
}
}
static void
sha256_final(Sha256 *ctx, uint8_t out[32])
{
uint64_t bitlen = ctx->bitlen;
int i;
ctx->buffer[ctx->buffer_len++] = 0x80u;
if(ctx->buffer_len > 56) {
while(ctx->buffer_len < 64)
ctx->buffer[ctx->buffer_len++] = 0;
sha256_block(ctx, ctx->buffer);
ctx->buffer_len = 0;
}
while(ctx->buffer_len < 56)
ctx->buffer[ctx->buffer_len++] = 0;
for(i = 7; i >= 0; i--)
ctx->buffer[ctx->buffer_len++] = (uint8_t)(bitlen >> (i * 8));
sha256_block(ctx, ctx->buffer);
for(i = 0; i < 8; i++) {
out[i * 4] = (uint8_t)(ctx->state[i] >> 24);
out[i * 4 + 1] = (uint8_t)(ctx->state[i] >> 16);
out[i * 4 + 2] = (uint8_t)(ctx->state[i] >> 8);
out[i * 4 + 3] = (uint8_t)ctx->state[i];
}
}
static void
sha256(const void *data, size_t len, uint8_t out[32])
{
Sha256 ctx;
sha256_init(&ctx);
sha256_update(&ctx, data, len);
sha256_final(&ctx, out);
}
/* ------------------------------------------------------------------ */
/* HMAC-SHA256 */
/* ------------------------------------------------------------------ */
static void
hmac_sha256(const void *key, size_t key_len,
const void *message, size_t message_len,
uint8_t out[32])
{
uint8_t block_key[64];
uint8_t pad[64];
uint8_t inner[32];
Sha256 ctx;
size_t i;
memset(block_key, 0, sizeof(block_key));
if(key_len > 64) {
sha256(key, key_len, block_key);
} else {
memcpy(block_key, key, key_len);
}
for(i = 0; i < 64; i++)
pad[i] = block_key[i] ^ 0x36u;
sha256_init(&ctx);
sha256_update(&ctx, pad, 64);
sha256_update(&ctx, message, message_len);
sha256_final(&ctx, inner);
for(i = 0; i < 64; i++)
pad[i] = block_key[i] ^ 0x5cu;
sha256_init(&ctx);
sha256_update(&ctx, pad, 64);
sha256_update(&ctx, inner, 32);
sha256_final(&ctx, out);
}
/* ------------------------------------------------------------------ */
/* PBKDF2 (single block, dkLen = 32) */
/* ------------------------------------------------------------------ */
void
gopass_derive_key(const char *password, size_t password_len,
const char *salt, size_t salt_len,
uint8_t out[32])
{
uint8_t block_input[512];
uint8_t previous[32];
size_t input_len;
int round;
/* salt || INT(32, big-endian) == salt || 00 00 00 01 */
input_len = salt_len;
if(input_len > sizeof(block_input) - 4)
input_len = sizeof(block_input) - 4;
if(input_len > 0)
memcpy(block_input, salt, input_len);
block_input[input_len] = 0;
block_input[input_len + 1] = 0;
block_input[input_len + 2] = 0;
block_input[input_len + 3] = 1;
input_len += 4;
hmac_sha256(password, password_len, block_input, input_len, previous);
memcpy(out, previous, 32);
for(round = 1; round < GOPASS_DERIVATION_ROUNDS; round++) {
hmac_sha256(password, password_len, previous, 32, previous);
for(int i = 0; i < 32; i++)
out[i] ^= previous[i];
}
memset(block_input, 0, sizeof(block_input));
}
/* ------------------------------------------------------------------ */
/* Entropy draws (big-endian 256-bit value, successive remainders) */
/* ------------------------------------------------------------------ */
static int
entropy_take_remainder(uint8_t entropy[32], int divisor)
{
unsigned carry = 0;
int i;
for(i = 0; i < 32; i++) {
unsigned current = carry * 256u + entropy[i];
entropy[i] = (uint8_t)(current / (unsigned)divisor);
carry = current % (unsigned)divisor;
}
return (int)carry;
}
/* ------------------------------------------------------------------ */
/* Generator */
/* ------------------------------------------------------------------ */
static int
set_error(char *err, size_t err_size, const char *message)
{
if(err != NULL && err_size > 0)
snprintf(err, err_size, "%s", message);
return 1;
}
static int
class_filtered(const char *characters, const char *exclude, char *out, int out_size)
{
int count = 0;
for(const char *c = characters; *c != '\0'; c++) {
int excluded = 0;
if(exclude != NULL) {
for(const char *e = exclude; *e != '\0'; e++) {
if(*e == *c) {
excluded = 1;
break;
}
}
}
if(!excluded && count < out_size)
out[count++] = *c;
}
return count;
}
int
gopass_generate(const char *site, const char *login, const char *master,
const GopassOptions *options,
char *out, size_t out_size,
char *err, size_t err_size)
{
static const char *class_names[4] = {"lowercase", "uppercase", "digits", "symbols"};
static const char *class_sets[4] = {
LOWERCASE_CHARACTERS, UPPERCASE_CHARACTERS, DIGIT_CHARACTERS, SYMBOL_CHARACTERS
};
const int class_enabled[4] = {
options->lowercase != 0, options->uppercase != 0,
options->digits != 0, options->symbols != 0
};
char classes[4][32];
int class_lengths[4];
int class_count = 0;
char alphabet[128];
int alphabet_length = 0;
char salt[640];
size_t salt_len;
uint8_t entropy[32];
char password[136];
int password_length;
char required[4];
char message[192];
int i;
if(options->length < 1)
return set_error(err, err_size, "password length must be positive");
for(i = 0; i < 4; i++) {
if(!class_enabled[i])
continue;
class_lengths[class_count] =
class_filtered(class_sets[i], options->exclude,
classes[class_count], (int)sizeof(classes[class_count]));
if(class_lengths[class_count] == 0) {
snprintf(message, sizeof(message),
"enabled %s character class is empty after exclusions", class_names[i]);
return set_error(err, err_size, message);
}
memcpy(alphabet + alphabet_length, classes[class_count],
(size_t)class_lengths[class_count]);
alphabet_length += class_lengths[class_count];
class_count++;
}
if(class_count == 0)
return set_error(err, err_size, "at least one character class must be enabled");
if(options->length < class_count) {
snprintf(message, sizeof(message),
"password length %d is smaller than the %d enabled character classes",
options->length, class_count);
return set_error(err, err_size, message);
}
if((size_t)options->length + 1 > out_size || options->length + 1 > (int)sizeof(password))
return set_error(err, err_size, "password length exceeds the output buffer");
salt_len = 0;
if(site != NULL) {
size_t site_len = strlen(site);
if(salt_len + site_len >= sizeof(salt))
return set_error(err, err_size, "site name is too long");
memcpy(salt + salt_len, site, site_len);
salt_len += site_len;
}
if(login != NULL) {
size_t login_len = strlen(login);
if(salt_len + login_len >= sizeof(salt))
return set_error(err, err_size, "login is too long");
memcpy(salt + salt_len, login, login_len);
salt_len += login_len;
}
salt_len += (size_t)snprintf(salt + salt_len, sizeof(salt) - salt_len,
"%llu", (unsigned long long)options->counter);
gopass_derive_key(master != NULL ? master : "", master != NULL ? strlen(master) : 0,
salt, salt_len, entropy);
password_length = options->length - class_count;
for(i = 0; i < password_length; i++)
password[i] = alphabet[entropy_take_remainder(entropy, alphabet_length)];
for(i = 0; i < class_count; i++)
required[i] = classes[i][entropy_take_remainder(entropy, class_lengths[i])];
for(i = 0; i < class_count; i++) {
int position = entropy_take_remainder(entropy, password_length + 1);
memmove(password + position + 1, password + position,
(size_t)(password_length - position));
password[position] = required[i];
password_length++;
}
memcpy(out, password, (size_t)password_length);
out[password_length] = '\0';
memset(password, 0, sizeof(password));
memset(required, 0, sizeof(required));
return 0;
}
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff. Show more