10 Commits
Author SHA1 Message Date
waozi 18bdfcb7be Use Mesh identity and signed referrals in Dew 2026-11-17 16:56:57 -03:00
waozi 954a72b167 Use the current Kryon widget API
Migrate the top-up page and web runtime to the .Draw and .Props widget
API and CanvasInputTake. Pin Kryon 1be70904, Entity 126dbd8 and Ziran
665fbbca and regenerate the lock.
2026-11-14 09:56:01 -03:00
waozi 207e474c3d Test the site against its own build made with the test driver
Kryon no longer compiles its test driver into ordinary builds. The browser
test drives the page through that driver, so make web-test now builds its
own copy of the site in build/web-test with KRYON_TEST_DRIVER set. The site
directory is the WEB variable, and the published build/web has no driver.
2026-11-14 01:57:25 -03:00
waozi 908a66fafd Add referral invitations and explicit no-purchase acceptance 2026-11-03 01:07:57 -03:00
waozi 11812ea201 Update the Ziran toolchain for the current Kryon 2026-11-02 11:08:04 -03:00
waozi a063c64ba1 Pin Entity and Kryon to exact revisions so the locked fetch resolves 2026-11-02 10:55:49 -03:00
waozi 5096a1613d Update Entity and Kryon with passphrase backups 2026-11-02 10:41:48 -03:00
waozi 4401493259 Use the current Ziran setup action
It links the standard modules where the locked compiler looks, which the
prebuilt build tree needs outside a project.
2026-10-27 19:10:15 -03:00
waozi 57e42f9fa2 Install the site build tools from the canonical Ubuntu archive
The Ziran setup action now installs them, avoiding the runner mirror that
sometimes stalls package setup for many minutes.
2026-10-27 18:48:03 -03:00
waozi 916e5768dc Set up the prebuilt Ziran and cached packages in CI
The site build no longer builds the locked compiler and fetches every
package from scratch; the Ziran setup action downloads the prebuilt
compiler and reuses the cached package checkouts.
2026-10-27 18:20:44 -03:00
17 changed files with 1102 additions and 226 deletions

No files matched your search

+8 -14
View File
@@ -28,36 +28,30 @@ jobs:
with:
path: waozixyz/dew
persist-credentials: false
- name: Read the locked toolchain and release version
- name: Read the release version
id: version
run: |
python3 - <<'PY' >> "$GITHUB_OUTPUT"
import json
from pathlib import Path
print('compiler=' + json.loads(Path('ziran.lock').read_text())['toolchain']['commit'])
print('version=' + json.loads(Path('version.json').read_text())['version'])
PY
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
# The locked compiler comes prebuilt, the package checkouts cached, and
# Ubuntu packages from the canonical archive.
- name: Set up the locked Ziran, its packages and the build tools
uses: ziranlang/ziran/.github/actions/setup@979159a55bcf1f9edb9eb8f26ea10aca421412e2
with:
repository: ziranlang/ziran
ref: ${{ steps.version.outputs.compiler }}
project: waozixyz/dew
path: ziranlang/ziran
persist-credentials: false
fetch: true
packages: build-essential cmake pkg-config
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Install build dependencies
working-directory: .
run: sh ziranlang/ziran/scripts/ci_packages.sh build-essential cmake pkg-config
- uses: mymindstorm/setup-emsdk@v14
with:
version: '6.0.6'
actions-cache-folder: emsdk-cache
- name: Build the locked compiler and fetch packages
run: |
make -j2 -C "$GITHUB_WORKSPACE/ziranlang/ziran"
echo "$GITHUB_WORKSPACE/ziranlang/ziran/build/bin" >> "$GITHUB_PATH"
"$GITHUB_WORKSPACE/ziranlang/ziran/build/bin/ziran" fetch --locked
- name: Test and build the site
run: |
make test ZIRAN="$GITHUB_WORKSPACE/ziranlang/ziran/build/bin/ziran"
+1
View File
@@ -2,3 +2,4 @@ build/
backup/
ziran.local.toml
__pycache__/
work/
+10
View File
@@ -1,5 +1,15 @@
# Changelog
## [Unreleased]
- Use Mesh naming and its canonical local referral fixture for integration tests.
- The top-up page and web runtime use Kryon's current widget API (`Text`, `Button`, `Box`, `TextField`, `Scroll` and `SvgIcon` with `.Draw` and `.Props`) and take keys through `CanvasInputTake`. Dew builds with Kryon 1be70904, Entity 126dbd8 and Ziran 665fbbca.
- `make web-test` builds its own copy of the site with Kryon's test driver in `build/web-test`; the published `build/web` is built without it.
- Sign-in uses the latest Entity, with passphrase-only account backups.
## [0.2.3] - 2026-10-27
- Payments now show under Activity at the bottom of the page, with the day each one arrived and what became of it. The section stays hidden until there is a payment.
+15 -7
View File
@@ -5,11 +5,15 @@ ENTITY = $(shell $(ZIRAN) pkg path entity $(LOCK_FLAGS))
PORT ?= 8095
.PHONY: all test web web-test serve
# Where the site is built; the browser test builds its own copy elsewhere.
WEB ?= build/web
all: web
test: build/model-test/test
env -u DISPLAY -u WAYLAND_DISPLAY build/model-test/test
$(ZIRAN) fmt --check src/*.zi src/web/*.zi tests/*.zi
python3 tests/web_site_test.py --landing-only
build/model-test/test: src/topup_model.zi tests/topup_model_test.zi ziran.lock
rm -rf build/model-test
@@ -21,18 +25,22 @@ build/model-test/test: src/topup_model.zi tests/topup_model_test.zi ziran.lock
# build/web is the whole site; version.json names the source it came from.
web:
$(MAKE) -C '$(ENTITY)' build/entity.zx ZIRAN='$(TOOLCHAIN)/build/bin/ziran'
rm -rf build/web
rm -rf $(WEB)
ZIRAN='$(TOOLCHAIN)/build/bin/ziran' python3 '$(ENTITY)/scripts/build-web.py' \
--profile '$(ENTITY)/build/entity.zx' --output build/web/runtime.html
rm -f build/web/runtime.html
cp site/index.html site/_headers site/icon.svg site/manifest.webmanifest site/og.jpg site/icon-512.png site/apple-touch-icon.png build/web/
--profile '$(ENTITY)/build/entity.zx' --output $(WEB)/runtime.html
rm -f $(WEB)/runtime.html
cp site/index.html site/_headers site/_redirects site/icon.svg site/manifest.webmanifest site/og.jpg site/icon-512.png site/apple-touch-icon.png $(WEB)/
cp src/web/referral.js $(WEB)/
printf '{"version":"%s","revision":"%s"}\n' \
"$$(python3 -c 'import json; print(json.load(open("version.json"))["version"])')" \
"$$(git rev-parse HEAD)" > build/web/version.json
"$$(git rev-parse HEAD)" > $(WEB)/version.json
# Opens the built site in a private headless browser.
# Opens the site in a private headless browser. The test drives the page
# through Kryon's test driver, which only a build made with KRYON_TEST_DRIVER
# set includes, so it builds its own copy and leaves build/web as published.
web-test:
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS node tests/web_site_test.mjs build/web
KRYON_TEST_DRIVER=1 $(MAKE) web WEB=build/web-test
python3 tests/web_site_test.py build/web-test
serve:
python3 -m http.server $(PORT) --bind 127.0.0.1 --directory build/web
+59 -3
View File
@@ -19,21 +19,77 @@ The page never grants Dew. The node sets the rate and credits deposits;
the page reads the balance and address through Entity's shared Profile,
whose provider is the only code that touches account keys.
## Referrals
`https://dew.waozi.xyz/invite/CODE` prefills an invitation in Entity's shared
**My referrals** page. `?ref=CODE` and manual code entry work too. Landing on
a link never binds an account: sign in, review the code and disclosure, then explicitly
confirm. [Mesh](https://mesh.ziran-lang.org) binds the account and credits the once-only 20 Dew welcome
gift together, immediately, without a purchase or minimum spend. The UI
confirms a gift only after the server returns its receipt.
My referrals uses the same Entity account and signed provider as other apps.
It shows the server-issued sharing code/link, aggregate earnings and paginated
accepted friends, including people who never bought Dew. The inviter sees
each friend's public name/alias or account ID and acceptance date; that
disclosure appears before acceptance. Invitations are unlimited, and the
inviter earns 5% in Dew on the friend's paid purchases on an ongoing basis.
Each account can have only one inviter across participating apps.
An unaccepted code is kept in the URL and this tab's session storage across
reloads and sign-in. There is no claim timer or automatic acceptance. Keep
the displayed code to enter manually if installation or another device loses
the link. Dismiss link removes the tab's suggestion; the shared UI lets you edit
its saved manual code. Private account keys,
binding policy, balances, receipts and the accepted list stay with Entity and
the authoritative Mesh service; the web shell stores none of those.
`/referrals` opens the dashboard. The canonical waozi.xyz and
account.waozi.xyz `/invite/CODE`, `/invite` and `/referrals` routes forward
to Dew while retaining the query. Optional `app` and `platform` hints travel
with the pending code. Direct/web/desktop/F-Droid invitations use this flow.
Play, Apple, Amazon and unknown platform hints open only the referral/profile
flow: valid signed-in welcome claims remain available, while web top-up and
payment controls stay disabled. For paid Dew the user returns to the originating
app's payment options. A source hint never proves store provenance or chooses
a credit allocation; the server owns those decisions.
The integration uses `EntityHostReferrals(code)` (prefill only), not a second
web identity/signing implementation. Entity's `entity.referrals` service
calls Mesh's authenticated `/api/v1/referrals/me`, `/claim` and
`/accepted?cursor=…&limit=50` endpoints. Account changes discard old results.
## Build
Dependencies use `ziran.toml` and `ziran.lock`; local overrides belong in
the ignored `ziran.local.toml`. The browser build needs Emscripten.
```sh
make test # conversions, minimum and payment links
make web # the whole site in build/web
make web-test # opens build/web in a private headless Chromium
build-queue -- make test # model tests + offline referral landing browser tests
build-queue -- make web # the whole site in build/web
build-queue -- make web-test # generated site in Chromium on private Xvfb
make serve # http://127.0.0.1:8095
```
`src/topup.zi` draws the page with Kryon widgets, `src/topup_model.zi` holds
the arithmetic and links, and `src/web/runtime.zi` is the browser host. The
site shell is in `site/`; `design/og.svg` is the source of `site/og.jpg`.
`src/web/referral.js` owns only pending-code attribution and platform routing.
The Python stdlib CDP harness in `tests/browser.py` needs Chromium and Xvfb,
uses a disposable profile under ignored `work/web-test`, scrubs inherited
display/session variables, disables desktop recovery and touches only its own
processes. No Node is used by the browser tests. The Emscripten web builder
also supports an existing Bun runtime through
`EM_NODE_JS=/absolute/path/to/bun`. Set that variable in sessions that prohibit
Node; it selects Bun directly, without a Node shim.
`python3 tests/referral_integration_test.py` additionally uses Mesh's compiled
test-only `work/referral-fixture.test`. It starts and stops a disposable local
server, creates real accounts through Entity, and tests explicit acceptance,
the immediate server receipt without a purchase, accepted nonpurchasers,
pagination, public-ID fallback and switching accounts through the real shared
account hub. Its private fixture report and logs stay under ignored
`work/referral`; browser traffic never reaches production.
## Releases
+4
View File
@@ -0,0 +1,4 @@
# Referral paths load the same app. Absolute asset URLs work at every depth.
/invite/* /index.html 200
/invite /index.html 200
/referrals /index.html 200
+27 -7
View File
@@ -7,9 +7,9 @@
<meta name="description" content="Dew is the one currency for every Waozi app. Sign in with your profile and top up with Monero or almost any other coin.">
<meta name="theme-color" content="#0e1a20">
<link rel="canonical" href="https://dew.waozi.xyz/">
<link rel="icon" href="icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="manifest.webmanifest">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="manifest" href="/manifest.webmanifest">
<meta property="og:type" content="website">
<meta property="og:url" content="https://dew.waozi.xyz/">
<meta property="og:title" content="Dew">
@@ -33,26 +33,41 @@
#loading .status { width: min(520px, 100%); margin: 14px 0 0; color: #ffd8a8; }
#loading .retry { margin-top: 14px; padding: 10px 22px; border: 0; border-radius: 999px; background: #2f9fc4; color: #fff; font: 600 16px system-ui, sans-serif; cursor: pointer; }
#loading { flex-direction: column; }
#referral-landing { position: fixed; inset: 0; z-index: 2; overflow: auto; padding: 32px max(20px, calc((100vw - 560px)/2)); background: #0e1a20; font: 17px/1.6 system-ui, sans-serif; }
#referral-landing h1 { font-size: 30px; }
#referral-code { display: block; overflow-wrap: anywhere; font-size: 24px; user-select: all; }
#referral-landing button { margin: 8px 8px 8px 0; padding: 12px 20px; border: 1px solid #2f9fc4; border-radius: 24px; background: #223a45; color: #e8f3f7; font: inherit; cursor: pointer; }
#referral-landing[hidden], #loading[hidden], #canvas[hidden], #referral-landing button[hidden] { display: none; }
</style>
</head>
<body>
<canvas id="canvas" tabindex="0"></canvas>
<section id="referral-landing" hidden aria-labelledby="referral-title">
<h1 id="referral-title"></h1>
<p id="referral-gift"></p>
<p id="referral-code-label"></p>
<code id="referral-code"></code>
<p id="referral-manual"></p>
<p id="referral-terms"></p>
<button id="referral-open" type="button"></button>
<button id="referral-forget" type="button"></button>
</section>
<div id="loading" role="status" aria-live="polite">
<div class="intro" lang="en">
<header><img src="icon.svg" alt=""><h1>Dew</h1></header>
<header><img src="/icon.svg" alt=""><h1>Dew</h1></header>
<p class="lede">One currency for every Waozi app.</p>
<p>Dew follows your profile into Inner Breeze, Arcade, Shovey and Apfelwurm. Unlock practices and storage, dress up your worm, and earn it by playing.</p>
<p>Top up with Monero in any amount, or from 100 Dew with Bitcoin, Ethereum, USDT and hundreds of other coins.</p>
<noscript><p>Dew needs JavaScript and WebAssembly to run.</p></noscript>
</div>
<div class="intro" lang="de" hidden>
<header><img src="icon.svg" alt=""><h1>Dew</h1></header>
<header><img src="/icon.svg" alt=""><h1>Dew</h1></header>
<p class="lede">Eine Währung für alle Waozi-Apps.</p>
<p>Dew begleitet dein Profil in Inner Breeze, Arcade, Shovey und Apfelwurm. Schalte Übungen und Speicher frei, kleide deinen Wurm ein und verdiene es beim Spielen.</p>
<p>Lade es mit Monero in beliebiger Höhe auf oder ab 100 Dew mit Bitcoin, Ethereum, USDT und Hunderten anderer Coins.</p>
</div>
<div class="intro" lang="es" hidden>
<header><img src="icon.svg" alt=""><h1>Dew</h1></header>
<header><img src="/icon.svg" alt=""><h1>Dew</h1></header>
<p class="lede">Una moneda para todas las apps de Waozi.</p>
<p>Dew acompaña a tu perfil en Inner Breeze, Arcade, Shovey y Apfelwurm. Desbloquea prácticas y almacenamiento, viste a tu gusano y gánalo jugando.</p>
<p>Recárgalo con Monero en cualquier cantidad, o desde 100 Dew con Bitcoin, Ethereum, USDT y cientos de monedas más.</p>
@@ -61,6 +76,7 @@
<p class="status" hidden></p>
<button type="button" class="retry" hidden></button>
</div>
<script src="/referral.js"></script>
<script>
(function () {
var loading = document.getElementById('loading');
@@ -110,11 +126,15 @@
clearTimeout(slow);
remember(0);
loading.classList.add('done');
if (window.DewReferral) DewReferral.ready();
return;
}
if (!ended) requestAnimationFrame(watch);
}
window.Module = {
referralOnly: !!(window.DewReferral && !DewReferral.fundingAllowed),
referralCode: window.DewReferral ? DewReferral.code : '',
referralRequested: !!(window.DewReferral && DewReferral.requested),
canvas: document.getElementById('canvas'),
setStatus: function (text) {
var match = /\((\d+(?:\.\d+)?)\/(\d+)\)/.exec(text || '');
@@ -125,7 +145,7 @@
};
function start() {
var script = document.createElement('script');
script.src = 'runtime.js';
script.src = '/runtime.js';
script.onerror = failed;
document.body.appendChild(script);
watch();
+34 -33
View File
@@ -10,23 +10,17 @@
#import "qrcode/qrcode"
#import "kryon/session"
#import "kryon/geometry"
#import "kryon/text_props"
Text :: #import "kryon/text";
#import "kryon/text_align"
#import "kryon/text_widget"
#import "kryon/text_measure"
#import "kryon/text_input_props"
#import "kryon/text_field_widget"
#import "kryon/button_props"
#import "kryon/button_widget"
TextField :: #import "kryon/text_field";
Button :: #import "kryon/button";
#import "kryon/control_props"
#import "kryon/scroll_props"
#import "kryon/scroll_widget"
Scroll :: #import "kryon/scroll";
#import "kryon/tree"
#import "kryon/box_props"
#import "kryon/box_widget"
Box :: #import "kryon/box";
#import "kryon/drawing_props"
#import "kryon/svg_icon_props"
#import "kryon/svg_icon_widget"
SvgIcon :: #import "kryon/svg_icon";
#import "kryon/widget_palette"
#import "kryon/system_clipboard"
#import "kryon/open_uri"
@@ -39,6 +33,7 @@
TOPUP_NONE :: 0
TOPUP_SIGN_IN :: 1
TOPUP_PROFILE :: 2
TOPUP_REFERRALS :: 3
DEW_BACKGROUND :: 0x0e1a20ff
DEW_CARD :: 0x172a33ff
@@ -243,7 +238,7 @@ TopupGuestPump :: (now: float64) {
// Draws the page; returns TOPUP_SIGN_IN or TOPUP_PROFILE when the Profile
// should open.
TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now: float64) -> s32 {
TopupFrame :: (session: Session, viewport: Rectangle, input: TextField.Input, now: float64) -> s32 {
copy := topup_copy
action: s32 = TOPUP_NONE
status := EntityHostDewStatus()
@@ -259,8 +254,8 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
minimum := DewAtLeast(TROCADOR_MINIMUM_ATOMIC, rate)
filled: [512]u8
Box(session, BoxProps.{.key = cast(u64)60000, .bounds = viewport, .fill = ColorFromPacked(cast(u32)DEW_BACKGROUND)})
scroll := Scroll(session, ScrollProps.{.key = cast(u64)60001, .bounds = viewport,
Box.Draw(session, Box.Props.{.key = cast(u64)60000, .bounds = viewport, .fill = ColorFromPacked(cast(u32)DEW_BACKGROUND)})
scroll := Scroll.Draw(session, Scroll.Props.{.key = cast(u64)60001, .bounds = viewport,
.content_height = cast(s32)topup_content_height, .scroll_offset = topup_scroll})
topup_scroll = scroll.scroll_offset
if !scroll.opened { return action }
@@ -272,13 +267,13 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
top := y
// Title row: the drop, "Dew", and the Profile.
Box(session, BoxProps.{.key = cast(u64)60002, .bounds = Rectangle.{x, y, 48.0, 48.0},
Box.Draw(session, Box.Props.{.key = cast(u64)60002, .bounds = Rectangle.{x, y, 48.0, 48.0},
.fill = ColorFromPacked(cast(u32)DEW_ACCENT), .radius = 24.0})
SvgIcon(session, SvgIconProps.{.shape = DROP_SHAPE, .color = Color.{255, 255, 255, 255},
SvgIcon.Draw(session, SvgIcon.Props.{.shape = DROP_SHAPE, .color = Color.{255, 255, 255, 255},
.bounds = Rectangle.{x + 12.0, y + 11.0, 24.0, 26.0}})
Text(session, TextProps.{.key = cast(u64)60003, .text = "Dew", .font = 32,
Text.Draw(session, Text.Props.{.key = cast(u64)60003, .text = "Dew", .size = 32,
.bounds = Rectangle.{x + 62.0, y + 4.0, column - 220.0, 40.0}})
if Button(session, ButtonProps.{.key = cast(u64)60004, .id = 60004,
if Button.Draw(session, Button.Props.{.key = cast(u64)60004, .id = 60004,
.label = ifx status.ready then copy.profile else copy.sign_in,
.bounds = Rectangle.{x + column - 140.0, y + 4.0, 140.0, 40.0},
.tone = ButtonTone.ButtonToneAccent, .emphasis = ButtonEmphasis.ButtonEmphasisSoft}) != 0 {
@@ -286,6 +281,12 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
}
y += 62.0
Line(session, 60005, copy.tagline, x, *y, column, 17, 26.0)
if Button.Draw(session, Button.Props.{.key = cast(u64)60006, .id = 60006, .label = copy.referrals,
.bounds = Rectangle.{x, y, column, 44.0}, .tone = ButtonTone.ButtonToneAccent,
.emphasis = ButtonEmphasis.ButtonEmphasisSoft}) != 0 {
action = TOPUP_REFERRALS
}
y += 58.0
// Whose Dew, and the balance.
inner := column - 36.0
@@ -311,7 +312,7 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
Line(session, 60011, copy.sign_in_title, x + 18.0, *y, inner, 18, 10.0)
Line(session, 60012, copy.sign_in_hint, x + 18.0, *y, inner, 14, 14.0)
}
if Button(session, ButtonProps.{.key = cast(u64)60013, .id = 60013, .label = copy.sign_in,
if Button.Draw(session, Button.Props.{.key = cast(u64)60013, .id = 60013, .label = copy.sign_in,
.bounds = Rectangle.{x + 18.0, y, inner, 48.0}, .tone = ButtonTone.ButtonToneAccent}) != 0 {
action = TOPUP_SIGN_IN
}
@@ -334,7 +335,7 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
seconds: [24]u8
Line(session, 60018, ifx topup_retry_at > now then Fill(copy.node_retry, FormatInteger(wait, seconds[:]), "", "", filled[:]) else copy.node_error,
x + 18.0, *y, inner, 14, 8.0)
if topup_retry_at > now && Button(session, ButtonProps.{.key = cast(u64)60008, .id = 60008, .label = copy.retry_now,
if topup_retry_at > now && Button.Draw(session, Button.Props.{.key = cast(u64)60008, .id = 60008, .label = copy.retry_now,
.bounds = Rectangle.{x + 18.0, y, 180.0, 40.0}, .tone = ButtonTone.ButtonToneAccent,
.emphasis = ButtonEmphasis.ButtonEmphasisSoft}) != 0 {
TopupRetry()
@@ -355,7 +356,7 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
chip := (inner - gap * 3.0) / 4.0
for index: 0..3 {
label: [24]u8
if Button(session, ButtonProps.{.key = cast(u64)(60022 + index), .id = 60022 + cast(s32)index,
if Button.Draw(session, Button.Props.{.key = cast(u64)(60022 + index), .id = 60022 + cast(s32)index,
.label = FormatInteger(DEW_PRESETS[index], label[:]),
.bounds = Rectangle.{x + 18.0 + cast(float32)index * (chip + gap), y, chip, 46.0},
.selected = topup_preset == cast(s32)index, .tone = ButtonTone.ButtonToneAccent,
@@ -387,7 +388,7 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
if side > 0.0 { y += side + 14.0 }
Line(session, 60035, address, x + 18.0, *y, inner, 15, 12.0)
copied := now < topup_copied_until
if Button(session, ButtonProps.{.key = cast(u64)60036, .id = 60036, .label = ifx copied then copy.copied else copy.copy_address,
if Button.Draw(session, Button.Props.{.key = cast(u64)60036, .id = 60036, .label = ifx copied then copy.copied else copy.copy_address,
.bounds = Rectangle.{x + 18.0, y, inner, 46.0}, .tone = ButtonTone.ButtonToneAccent,
.emphasis = ButtonEmphasis.ButtonEmphasisSoft}) != 0 {
if SystemClipboardSet(address) { topup_copied_until = now + 2000.0 }
@@ -417,7 +418,7 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
digits: [24]u8
pay: [128]u8
pay_label := ifx dew > 0 then Fill(copy.pay_other, FormatInteger(dew, digits[:]), "", "", pay[:]) else copy.other_coin
if Button(session, ButtonProps.{.key = cast(u64)60043, .id = 60043, .label = pay_label,
if Button.Draw(session, Button.Props.{.key = cast(u64)60043, .id = 60043, .label = pay_label,
.bounds = Rectangle.{x + 18.0, y, inner, 48.0}, .tone = ButtonTone.ButtonToneAccent,
.disabled = link == ""}) != 0 && link != "" {
unused OpenUri(link)
@@ -455,7 +456,7 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
}
Line(session, 60050, copy.footer, x, *y, column, 15, 10.0)
if Button(session, ButtonProps.{.key = cast(u64)60051, .id = 60051, .label = "waozi.xyz",
if Button.Draw(session, Button.Props.{.key = cast(u64)60051, .id = 60051, .label = "waozi.xyz",
.bounds = Rectangle.{x, y, 140.0, 40.0}, .tone = ButtonTone.ButtonToneAccent,
.emphasis = ButtonEmphasis.ButtonEmphasisGhost}) != 0 {
unused OpenUri("https://waozi.xyz/")
@@ -466,31 +467,31 @@ TopupFrame :: (session: Session, viewport: Rectangle, input: TextFieldInput, now
}
Card :: (session: Session, key: u64, x: float32, y: float32, width: float32, height: float32) {
Box(session, BoxProps.{.key = key, .bounds = Rectangle.{x, y, width, height},
Box.Draw(session, Box.Props.{.key = key, .bounds = Rectangle.{x, y, width, height},
.fill = ColorFromPacked(cast(u32)DEW_CARD), .radius = 16.0})
}
// Wrapped text that moves y below itself and the gap after it.
Line :: (session: Session, key: u64, text: string, x: float32, y: *float32, width: float32, font: s32, gap: float32) {
if text == "" { return }
props := TextProps.{.key = key, .text = text, .font = font, .wrap = TextWrap.TextWrapAuto,
props := Text.Props.{.key = key, .text = text, .size = font, .wrap = Text.Wrap.TextWrapAuto,
.bounds = Rectangle.{x, y.*, width, 0.0}}
height := cast(float32)TextHeight(session, props)
props.bounds.height = height
Text(session, props)
Text.Draw(session, props)
y.* += height + gap
}
AmountInput :: (session: Session, bounds: Rectangle, input: TextFieldInput, copy: TopupCopy) -> bool {
AmountInput :: (session: Session, bounds: Rectangle, input: TextField.Input, copy: TopupCopy) -> bool {
snapshot: [16]u8
snapshot = topup_typed
props := TextFieldProps.{.key = cast(u64)60026, .focus_id = 60026, .bounds = bounds,
props := TextField.Props.{.key = cast(u64)60026, .focus_id = 60026, .bounds = bounds,
.label = copy.other_amount, .placeholder = copy.other_amount_hint,
.value = TextUntilNul(snapshot[:]), .cursor = topup_field.cursor, .anchor = topup_field.anchor,
.scroll_x = topup_field.scroll_x, .focused = topup_field.focused,
.max_bytes = 7, .max_codepoints = 7, .numeric = true}
if topup_field.focused { props.input = input }
result := TextField(session, props)
result := TextField.Draw(session, props)
changed := false
if result.edit.changed {
edit := result.edit
@@ -527,11 +528,11 @@ DrawQr :: (session: Session, text: string, x: float32, y: float32, width: float3
side := cell * modules
left := cast(s32)(x + (width - cast(float32)side) * 0.5)
top := cast(s32)y
Box(session, BoxProps.{.key = cast(u64)61000, .radius = 10.0,
Box.Draw(session, Box.Props.{.key = cast(u64)61000, .radius = 10.0,
.bounds = Rectangle.{cast(float32)left, y, cast(float32)side, cast(float32)side}, .fill = Color.{255, 255, 255, 255}})
for index: 0..topup_qr_count - 1 {
rect := topup_qr_rects[index]
Box(session, BoxProps.{.key = cast(u64)(61001 + index),
Box.Draw(session, Box.Props.{.key = cast(u64)(61001 + index),
.bounds = Rectangle.{cast(float32)(left + (rect.column + 4) * cell), cast(float32)(top + (rect.row + 4) * cell),
cast(float32)(rect.width * cell), cast(float32)(rect.height * cell)}, .fill = Color.{0, 0, 0, 255}})
}
+4
View File
@@ -5,6 +5,7 @@ TopupCopy :: struct {
tagline: string
sign_in: string
profile: string
referrals: string
back: string
sign_in_title: string
sign_in_hint: string
@@ -53,6 +54,7 @@ TopupEnglish :: () -> TopupCopy {
.tagline = "One currency for every Waozi app. Top it up here with Monero or almost any other coin.",
.sign_in = "Sign in",
.profile = "Profile",
.referrals = "My referrals · accept an invitation",
.back = "Back",
.sign_in_title = "Sign in with your profile to see your Dew and top it up.",
.sign_in_hint = "Use the same profile as in Inner Breeze, Arcade or Shovey: link this browser from the app, or import your key.",
@@ -101,6 +103,7 @@ TopupGerman :: () -> TopupCopy {
.tagline = "Eine Währung für alle Waozi-Apps. Lade sie hier mit Monero oder fast jedem anderen Coin auf.",
.sign_in = "Anmelden",
.profile = "Profil",
.referrals = "Meine Empfehlungen · Einladung annehmen",
.back = "Zurück",
.sign_in_title = "Melde dich mit deinem Profil an, um dein Dew zu sehen und aufzuladen.",
.sign_in_hint = "Nutze dasselbe Profil wie in Inner Breeze, Arcade oder Shovey: Verknüpfe diesen Browser in der App oder importiere deinen Schlüssel.",
@@ -149,6 +152,7 @@ TopupSpanish :: () -> TopupCopy {
.tagline = "Una moneda para todas las apps de Waozi. Recárgala aquí con Monero o casi cualquier otra moneda.",
.sign_in = "Iniciar sesión",
.profile = "Perfil",
.referrals = "Mis referidos · aceptar una invitación",
.back = "Atrás",
.sign_in_title = "Inicia sesión con tu perfil para ver tu Dew y recargarlo.",
.sign_in_hint = "Usa el mismo perfil que en Inner Breeze, Arcade o Shovey: vincula este navegador desde la app o importa tu clave.",
+66
View File
@@ -0,0 +1,66 @@
// Attribution is a suggestion, never an account binding or a balance grant.
// Entity owns sign-in, explicit acceptance, signed requests and all receipts.
(function () {
'use strict';
var storageKey = 'dew-pending-referral-v1';
var query = new URLSearchParams(location.search);
var match = /^\/invite\/([^/]+)\/?$/.exec(location.pathname);
var supplied = match || ['ref', 'code', 'referral'].some(function (key) { return query.has(key); });
var pending = {};
try { pending = JSON.parse(sessionStorage.getItem(storageKey) || '{}') || {}; } catch (_) {}
if (typeof pending !== 'object' || Array.isArray(pending)) pending = {};
if (supplied) {
var code = match ? match[1] : query.get('ref') || query.get('code') || query.get('referral') || '';
try { code = decodeURIComponent(code); } catch (_) { code = ''; }
pending = { code: code.trim(), app: query.get('app') || '', platform: query.get('platform') || query.get('source_platform') || 'web' };
}
// Source hints persist with the code; losing a hint must never turn a store
// invitation into a web purchase flow after a reload or sign-in.
if (!supplied && (query.has('platform') || query.has('source_platform')))
pending.platform = query.get('platform') || query.get('source_platform');
if (!supplied && query.has('app')) pending.app = query.get('app');
var code = typeof pending.code === 'string' ? pending.code : '';
if (!/^[A-Za-z0-9_-]{1,128}$/.test(code)) code = '';
var platform = String(pending.platform || 'web').toLowerCase();
var direct = ['web', 'direct', 'desktop', 'fdroid', 'f-droid', 'linux', 'windows', 'macos'].indexOf(platform) !== -1;
pending = { code: code, app: typeof pending.app === 'string' ? pending.app.slice(0, 128) : '', platform: platform };
try { sessionStorage.setItem(storageKey, JSON.stringify(pending)); } catch (_) {}
var language = (query.get('lang') || navigator.language || 'en').slice(0, 2).toLowerCase();
var translations = {
en: { title: 'Your Dew invitation', code: 'Invitation code', gift: 'Sign in, then accept your invitation to receive 20 Dew immediately. No purchase or minimum is required.', terms: 'You can have one inviter across Waozi apps. Your public name, alias or account ID and acceptance date appear in their referrals list. They earn 5% Dew on your paid Dew purchases, with no invitation limit or end date.', manual: 'Keep this code. If a download or sign-in loses the link, enter it in My referrals after signing in.', open: 'Sign in / accept invitation', dashboard: 'My referrals', restricted: 'Accept your invitation here to receive the welcome gift. To buy Dew, return to the app that sent this invitation and use its own payment options. This page will not open web top-up for that edition.', unknown: 'The invitation link has no valid code. You can enter a code manually in My referrals.', forget: 'Dismiss this link', return: 'Return to Dew' },
de: { title: 'Deine Dew-Einladung', code: 'Einladungscode', gift: 'Melde dich an und nimm die Einladung an, um sofort 20 Dew zu erhalten. Kein Kauf und kein Mindestbetrag nötig.', terms: 'Du kannst in allen Waozi-Apps zusammen einen Einladenden haben. Dein öffentlicher Name, Alias oder deine Konto-ID und das Annahmedatum erscheinen in dessen Empfehlungsliste. Die Person erhält dauerhaft 5 % Dew auf deine bezahlten Dew-Käufe. Einladungen sind unbegrenzt.', manual: 'Bewahre diesen Code auf. Geht der Link beim Herunterladen oder Anmelden verloren, gib ihn nach der Anmeldung unter Meine Empfehlungen ein.', open: 'Anmelden / Einladung annehmen', dashboard: 'Meine Empfehlungen', restricted: 'Nimm deine Einladung hier an, um das Willkommensgeschenk zu erhalten. Kehre für Dew-Käufe zu der App zurück, die diese Einladung gesendet hat, und nutze deren Zahlungsmöglichkeiten. Diese Seite öffnet für diese Ausgabe keine Web-Aufladung.', unknown: 'Der Einladungslink enthält keinen gültigen Code. Du kannst unter Meine Empfehlungen einen Code von Hand eingeben.', forget: 'Diesen Link schließen', return: 'Zurück zu Dew' },
es: { title: 'Tu invitación de Dew', code: 'Código de invitación', gift: 'Inicia sesión y acepta la invitación para recibir 20 Dew de inmediato. No se requiere compra ni importe mínimo.', terms: 'Solo puedes tener una persona que te invite entre todas las apps de Waozi. Tu nombre público, alias o ID de cuenta y la fecha de aceptación aparecen en su lista de referidos. Recibe un 5 % de Dew por tus compras pagadas de Dew, sin límite de invitaciones ni fecha de finalización.', manual: 'Guarda este código. Si una descarga o el inicio de sesión pierde el enlace, introdúcelo en Mis referidos después de iniciar sesión.', open: 'Iniciar sesión / aceptar invitación', dashboard: 'Mis referidos', restricted: 'Acepta tu invitación aquí para recibir el regalo de bienvenida. Para comprar Dew, vuelve a la app que envió la invitación y usa sus opciones de pago. Esta página no abrirá la recarga web para esa edición.', unknown: 'El enlace no contiene un código válido. Puedes introducir uno manualmente en Mis referidos.', forget: 'Descartar este enlace', return: 'Volver a Dew' }
};
if (!translations[language]) language = 'en';
var words = translations[language];
var requested = !!supplied || /^\/(invite|referrals)\/?$/.test(location.pathname) || query.get('view') === 'referrals' || !!code || !direct;
var panel = document.getElementById('referral-landing');
function text(id, value) { document.getElementById(id).textContent = value; }
text('referral-title', words.title);
text('referral-code-label', words.code);
text('referral-code', code);
text('referral-gift', words.gift + (direct ? '' : ' ' + words.restricted));
text('referral-terms', words.terms);
text('referral-manual', code ? words.manual : words.unknown);
text('referral-open', code ? words.open : words.dashboard);
text('referral-forget', words.forget);
panel.lang = language;
panel.hidden = !requested;
document.getElementById('referral-code-label').hidden = !code;
document.getElementById('referral-forget').onclick = function () {
try { sessionStorage.removeItem(storageKey); } catch (_) {}
location.href = '/?lang=' + language + (direct ? '' : '&platform=' + encodeURIComponent(platform));
};
window.DewReferral = {
code: code, requested: requested, fundingAllowed: direct,
// No opaque install attribution or private account material is retained.
sourceApp: pending.app,
ready: function () { panel.hidden = true; },
open: function () {
if (!window.Module) return;
Module.referralCode = code;
Module.referralRequested = true;
}
};
document.getElementById('referral-open').onclick = window.DewReferral.open;
})();
+31 -18
View File
@@ -12,13 +12,9 @@ using Canvas :: #import "kryon/Canvas";
#import "kryon/Frame"
#import "kryon/ScrollDevice"
#import "kryon/key_input"
#import "kryon/text_input_props"
#import "kryon/text_props"
#import "kryon/text_widget"
#import "kryon/button_props"
#import "kryon/button_widget"
#import "kryon/box_props"
#import "kryon/box_widget"
Text :: #import "kryon/text";
Button :: #import "kryon/button";
Box :: #import "kryon/box";
#import "kryon/drawing_props"
#import "kryon/widget_palette"
#import "kryon/TestDriver"
@@ -28,6 +24,7 @@ using Canvas :: #import "kryon/Canvas";
#import "std/c_string"
#import "std/byte_text_linux"
#import "entity/native_host"
#import "entity/referral_native"
#import "topup"
#import "topup_copy"
@@ -54,32 +51,45 @@ main :: () -> s32 {
if !found || !EntityHostOpen(profile_bytes, "/kryon-apps/profile", "dew", true) { return 1 }
// This page is the top-up: the Profile's Top up comes back here.
EntityHostTopUpUrl("")
// This host is the direct web edition. Link hints only hide purchase UI;
// they never become the provider's trusted app/edition identity.
unused EntityReferralsSource("direct", "dew")
referral_only := WebAsBool(WebGet(WebGetObject(WebGlobal, WebName("Module")), WebName("referralOnly")))
if referral_only { EntityHostAllowFunding(false) }
language: [64]u8
TopupStart(TextFromCString(GetRouteQuery()), BrowserLanguage(language[:]))
EntityHostReferralsLocale(topup_copy.language)
defer { unused EntityHostClose(); unused BundleStorageSync(false) }
session := SessionOpen()
if !SessionValid(session) { return 1 }
defer { unused SessionClose(session) }
palette := DewPalette()
unused WidgetPaletteUse(session, palette)
profile := false
profile := referral_only
saved := PageNow()
WebSet(WebGetObject(WebGlobal, WebName("Module")), WebName("profileReady"), WebBool(true))
while PollCanvas() {
scope := WebScope()
module := WebGetObject(WebGlobal, WebName("Module"))
if WebAsBool(WebGet(module, WebName("referralRequested"))) {
code: [129]u8
handle := WebAsObject(WebGet(module, WebName("referralCode")))
length := WebCopyString(handle, code[:])
if length < 0 || length >= cast(s32)code.count { length = 0 }
if EntityHostReferrals(TextFromBytes(code[:length])) { profile = true }
WebSet(module, WebName("referralRequested"), WebBool(false))
}
WebSet(WebGetObject(WebGlobal, WebName("Module")), WebName("profileVisible"), WebBool(profile))
BeginCanvasFrame()
viewport := CanvasViewport()
pointer := PollPointer()
key := CanvasPressedKey()
modifiers := CanvasModifiers()
// Keys and typed text arrive in the order the page received them.
key, modifiers := CanvasInputTake(session)
wheel := CanvasWheelMove()
point := CanvasTypedCodepoint()
while point != 0 { unused TypedCodepointSend(session, point); point = CanvasTypedCodepoint() }
typed: [1024]u8
text := TypedTextTake(session, typed[:])
EntityHostPump()
TopupPump(PageNow())
if !referral_only { TopupPump(PageNow()) }
TreePointerUpdate(session, pointer)
TreeSecondaryPointerUpdate(session, PollSecondaryPointer())
PointerWheelSend(session, pointer.x, pointer.y, wheel)
@@ -92,22 +102,25 @@ main :: () -> s32 {
input := TextFieldInputFor(key, modifiers, text)
if profile {
// The Profile sits under the page's own title bar and Back.
Box(session, BoxProps.{.key = cast(u64)49003, .bounds = Rectangle.{viewport.x, viewport.y, viewport.width, 56.0},
Box.Draw(session, Box.Props.{.key = cast(u64)49003, .bounds = Rectangle.{viewport.x, viewport.y, viewport.width, 56.0},
.fill = ColorFromPacked(palette.background)})
bounds := Rectangle.{viewport.x, viewport.y + 56.0, viewport.width, viewport.height - 56.0}
if !EntityHostFrame(session, bounds, key, modifiers, input, true) { return 1 }
Text(session, TextProps.{.key = cast(u64)49002, .text = topup_copy.profile, .font = 20,
Text.Draw(session, Text.Props.{.key = cast(u64)49002, .text = topup_copy.profile, .size = 20,
.bounds = Rectangle.{100.0, 12.0, viewport.width - 200.0, 36.0}})
if Button(session, ButtonProps.{.key = cast(u64)49001, .id = 49001, .label = topup_copy.back,
if Button.Draw(session, Button.Props.{.key = cast(u64)49001, .id = 49001, .label = topup_copy.back,
.bounds = Rectangle.{8.0, 6.0, 92.0, 44.0}}) != 0 || key == 256 {
if !EntityHostBack() && EntityHostSave() { profile = false }
if !EntityHostBack() && EntityHostSave() {
if referral_only { unused EntityHostReferrals("") } else { profile = false }
}
}
if EntityHostTopUpRequested() && EntityHostSave() { profile = false }
if EntityHostTopUpRequested() && EntityHostSave() && !referral_only { profile = false }
} else {
action := TopupFrame(session, viewport, input, PageNow())
if action != TOPUP_NONE {
EntityHostReload()
if action == TOPUP_SIGN_IN { unused EntityHostAccount() }
if action == TOPUP_REFERRALS { unused EntityHostReferrals("") }
profile = true
}
}
+243
View File
@@ -0,0 +1,243 @@
"""Small stdlib CDP client; owns only its private Xvfb and Chromium processes."""
import base64
import hashlib
import json
import os
from pathlib import Path
import shutil
import signal
import socket
import struct
import subprocess
import tempfile
import time
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import HTTPError
from urllib.parse import urlsplit
ROOT = Path(__file__).resolve().parents[1]
PROJECTS = next((parent for parent in ROOT.parents if (parent / 'harness/waozi/account').is_dir()),
ROOT.parents[2])
class Browser:
def __enter__(self):
scratch = ROOT / 'work/web-test'
scratch.mkdir(parents=True, exist_ok=True)
self.profile = Path(tempfile.mkdtemp(prefix='b-', dir=scratch))
env = {key: value for key, value in os.environ.items() if key not in
{'DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS', 'SESSION_MANAGER'}}
# Chromium's temporary Unix socket paths have a short kernel limit.
env.update(YUE_DESKTOP_RECOVERY='0', TMPDIR=str(ROOT / 'work'))
self.log = (self.profile / 'chromium.log').open('w+')
self.process = subprocess.Popen([
'xvfb-run', '-a', '--server-args=-screen 0 1280x900x24 -nolisten tcp',
os.environ.get('CHROMIUM') or shutil.which('chromium') or 'google-chrome', '--headless=new', '--no-sandbox',
'--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--disable-dev-shm-usage',
'--no-first-run', '--no-default-browser-check', '--disable-background-networking',
'--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1', '--mute-audio',
'--remote-debugging-port=0', f'--user-data-dir={self.profile}', 'about:blank'],
env=env, stdin=subprocess.DEVNULL, stdout=self.log, stderr=self.log, start_new_session=True)
self.ws = None
self.sequence = 0
self.events = []
self.responses = {}
self.request_handler = None
self.referral_replies = []
self.api_paths = []
self.api_statuses = []
try:
self.wait(lambda: (self.profile / 'DevToolsActivePort').exists(), 30, 'Chromium start')
port = (self.profile / 'DevToolsActivePort').read_text().splitlines()[0]
with urlopen(f'http://127.0.0.1:{port}/json/list', timeout=5) as response:
targets = json.load(response)
address = urlsplit(next(target['webSocketDebuggerUrl'] for target in targets if target['type'] == 'page'))
self.ws = socket.create_connection((address.hostname, address.port), timeout=15)
key = base64.b64encode(os.urandom(16)).decode()
self.ws.sendall((f'GET {address.path} HTTP/1.1\r\nHost: {address.netloc}\r\n'
f'Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n'
'Sec-WebSocket-Version: 13\r\n\r\n').encode())
headers = bytearray()
while not headers.endswith(b'\r\n\r\n'):
headers.extend(self._read(1))
if len(headers) > 16384:
raise RuntimeError('Oversized WebSocket handshake')
expected = base64.b64encode(hashlib.sha1((key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode()).digest())
assert b' 101 ' in headers and expected in headers, 'CDP WebSocket handshake refused'
self.command('Runtime.enable')
self.command('Page.enable')
self.command('Emulation.setDeviceMetricsOverride', {
'width': 1280, 'height': 900, 'deviceScaleFactor': 1, 'mobile': False})
return self
except BaseException:
self.__exit__(None, None, None)
raise
def _read(self, length):
data = bytearray()
while len(data) < length:
part = self.ws.recv(length - len(data))
if not part:
raise RuntimeError('CDP socket closed')
data.extend(part)
return bytes(data)
def _send(self, payload, opcode=1):
mask = os.urandom(4)
count = len(payload)
header = bytes([0x80 | opcode, 0x80 | (count if count < 126 else 126 if count < 65536 else 127)])
if count >= 65536:
header += struct.pack('!Q', count)
elif count >= 126:
header += struct.pack('!H', count)
self.ws.sendall(header + mask + bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload)))
def _receive(self):
fragments = bytearray()
while True:
first, second = self._read(2)
count = second & 127
if count == 126:
count = struct.unpack('!H', self._read(2))[0]
elif count == 127:
count = struct.unpack('!Q', self._read(8))[0]
if count > 4 * 1024 * 1024:
raise RuntimeError('CDP frame exceeds test limit')
mask = self._read(4) if second & 128 else None
payload = self._read(count)
if mask:
payload = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload))
opcode = first & 15
if opcode == 9:
self._send(payload, 10)
continue
if opcode == 8:
raise RuntimeError('CDP closed WebSocket')
fragments.extend(payload)
if first & 128:
return json.loads(fragments)
def command(self, method, params=None):
self.sequence += 1
serial = self.sequence
self._send(json.dumps({'id': serial, 'method': method, 'params': params or {}}).encode())
while True:
if serial in self.responses:
result = self.responses.pop(serial)
if 'error' in result:
raise RuntimeError(f'{method}: {result["error"]}')
return result.get('result', {})
result = self._receive()
if 'id' in result:
self.responses[result['id']] = result
continue
if result.get('method') == 'Fetch.requestPaused' and self.request_handler:
self.request_handler(result['params'])
if result.get('method') in {'Runtime.consoleAPICalled', 'Runtime.exceptionThrown'}:
self.events = (self.events + [result])[-30:]
def route_api(self, origin):
"""Route real product API requests to a disposable Mesh HTTP fixture.
This changes only test transport. Entity still signs its normal auth
handshake, and the local server still validates it and owns all credits.
"""
self.route_origins({'https://api.waozi.xyz': origin})
def route_origins(self, origins):
"""Keep secure product origins while serving only local test fixtures."""
assert all(urlsplit(value).hostname == '127.0.0.1' for value in origins.values())
def handle(event):
request = event['request']
source = urlsplit(request['url'])
origin = origins.get(source.scheme + '://' + source.netloc)
if origin is None:
self.command('Fetch.failRequest', {'requestId': event['requestId'], 'errorReason': 'BlockedByClient'})
return
headers = {key: value for key, value in request['headers'].items()
if key.lower() not in {'host', 'content-length'}}
body = request.get('postData')
forwarded = Request(origin.rstrip('/') + source.path + ('?' + source.query if source.query else ''),
data=body.encode() if body is not None else None,
headers=headers, method=request['method'])
try:
response = urlopen(forwarded, timeout=15)
except HTTPError as error:
response = error
with response:
# Generated Wasm is larger than JSON. Keep both explicitly
# bounded, and never print binary response bodies.
limit = 1024 * 1024 if source.hostname == 'api.waozi.xyz' else 32 * 1024 * 1024
payload = response.read(limit + 1)
assert len(payload) <= limit, 'fixture response exceeds test bound'
if source.hostname == 'api.waozi.xyz':
self.api_paths.append((request['method'], source.path))
self.api_statuses.append((request['method'], source.path, response.status))
if source.path.startswith('/api/v1/referrals/') and request['method'] != 'OPTIONS':
self.referral_replies.append({'path': source.path, 'status': response.status,
'body': json.loads(payload) if payload else {}})
response_headers = [{'name': key, 'value': value} for key, value in response.headers.items()
if key.lower() not in {'transfer-encoding', 'content-length', 'content-encoding'}]
self.command('Fetch.fulfillRequest', {'requestId': event['requestId'],
'responseCode': response.status, 'responseHeaders': response_headers,
'body': base64.b64encode(payload).decode()})
self.request_handler = handle
self.command('Fetch.enable', {'patterns': [{'urlPattern': 'https://*.waozi.xyz/*', 'requestStage': 'Request'}]})
def evaluate(self, expression, await_promise=False):
response = self.command('Runtime.evaluate', {
'expression': expression, 'returnByValue': True, 'awaitPromise': await_promise})
if 'exceptionDetails' in response:
raise RuntimeError(str(response['exceptionDetails']))
return response.get('result', {}).get('value')
def navigate(self, url):
self.command('Page.navigate', {'url': url})
self.wait(lambda: self.evaluate('location.href') == url and self.evaluate('document.readyState') == 'complete', 30, 'page load')
@staticmethod
def wait(callback, seconds=15, label='condition'):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
value = callback()
if value:
return value
time.sleep(.05)
raise AssertionError(f'Timed out waiting for {label}')
def click(self, x, y):
for kind in ['mouseMoved', 'mousePressed', 'mouseReleased']:
self.command('Input.dispatchMouseEvent', {
'type': kind, 'x': x, 'y': y, 'button': 'left', 'clickCount': 1})
time.sleep(.08)
def __exit__(self, *unused):
if self.ws:
try:
self.command('Browser.close')
except (OSError, RuntimeError):
pass
self.ws.close()
try:
os.killpg(self.process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
if self.process.poll() is None:
try:
self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
os.killpg(self.process.pid, signal.SIGKILL)
self.process.wait(timeout=5)
self.log.close()
for attempt in range(20):
try:
shutil.rmtree(self.profile)
break
except FileNotFoundError:
break
except OSError:
if attempt == 19:
raise
time.sleep(.1)
+259
View File
@@ -0,0 +1,259 @@
#!/usr/bin/env python3
"""Real generated UI + shared account hub + Mesh ML-DSA/referral HTTP routes.
Requires the backend worker's compiled, test-only referral browser fixture.
Every account and browser profile is disposable; no production traffic occurs.
"""
from contextlib import contextmanager
from http.server import ThreadingHTTPServer
import json
import os
from pathlib import Path
import signal
import subprocess
import tempfile
import threading
import time
from urllib.request import Request, urlopen
from browser import Browser, PROJECTS, ROOT
from web_site_test import Handler, driver
BACKEND = PROJECTS / 'ziranlang/mesh'
@contextmanager
def fixture():
scratch = ROOT / 'work/referral'
scratch.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='fixture-', dir=scratch) as directory:
report = Path(directory) / 'report.json'
log = (scratch / 'integration-server.log').open('w+')
env = {key: value for key, value in os.environ.items() if key not in
{'DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS', 'SESSION_MANAGER'}}
env.update(MESH_REFERRAL_FIXTURE_REPORT=str(report), YUE_DESKTOP_RECOVERY='0', TMPDIR=directory)
binary = Path(os.environ.get('MESH_REFERRAL_FIXTURE_BIN', BACKEND / 'work/referral-fixture.test'))
process = subprocess.Popen([str(binary),
'-test.run', '^TestReferralBrowserFixture$', '-test.v', '-test.timeout=10m'],
cwd=BACKEND, env=env, stdin=subprocess.DEVNULL, stdout=log,
stderr=log, start_new_session=True)
metadata = None
try:
Browser.wait(report.exists, 30, 'real-auth fixture startup')
metadata = json.loads(report.read_text())
assert metadata['synthetic'] and metadata['real_mldsa']
assert metadata['authority'] == 'https://api.waozi.xyz'
def control(path, body=None):
request = Request(metadata['url'] + '/fixture/' + path,
data=json.dumps(body or {}).encode(), method='POST',
headers={'X-Fixture-Key': metadata['control_key'], 'Content-Type': 'application/json'})
with urlopen(request, timeout=20) as response:
return json.load(response)
yield metadata['url'], control
finally:
if metadata:
try:
control('stop')
except OSError:
pass
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=5)
log.close()
if process.returncode:
raise RuntimeError(f'Referral fixture exited with {process.returncode}; see {log.name}')
def tree(browser):
return driver(browser, 'tree')['nodes']
def click_widget(browser, key):
for attempt in range(24):
nodes = driver(browser, 'find\tkey=' + str(key))['nodes']
if not nodes:
if attempt >= 3:
browser.command('Input.dispatchMouseEvent', {'type': 'mouseMoved', 'x': 850, 'y': 700})
browser.command('Input.dispatchMouseEvent', {'type': 'mouseWheel', 'x': 850, 'y': 700,
'deltaX': 0, 'deltaY': 650})
time.sleep(.1)
continue
node = nodes[0]
if node['enabled'] and node['visible'] and node['visible_height'] > 10:
browser.click(node['visible_x'] + node['visible_width'] / 2,
node['visible_y'] + node['visible_height'] / 2)
return
direction = 1 if node['y'] > 450 else -1
browser.command('Input.dispatchMouseEvent', {'type': 'mouseMoved', 'x': 850, 'y': 700})
browser.command('Input.dispatchMouseEvent', {'type': 'mouseWheel', 'x': 850, 'y': 700,
'deltaX': 0, 'deltaY': direction * 650})
time.sleep(.1)
labels = [node['label'] for node in tree(browser) if node['visible']]
raise AssertionError(f'Widget {key} unavailable; visible labels: {labels}')
def ready(browser):
Browser.wait(lambda: browser.evaluate('!!(window.Module && Module.profileReady && Module.profileVisible)'),
90, 'generated referral UI')
def fill_code(browser, value):
click_widget(browser, 107)
browser.command('Input.dispatchKeyEvent', {'type': 'keyDown', 'key': 'Control', 'code': 'ControlLeft',
'windowsVirtualKeyCode': 17, 'modifiers': 2})
browser.command('Input.dispatchKeyEvent', {'type': 'keyDown', 'key': 'a', 'code': 'KeyA',
'windowsVirtualKeyCode': 65, 'modifiers': 2})
time.sleep(.15)
browser.command('Input.dispatchKeyEvent', {'type': 'keyUp', 'key': 'a', 'code': 'KeyA',
'windowsVirtualKeyCode': 65, 'modifiers': 2})
browser.command('Input.dispatchKeyEvent', {'type': 'keyUp', 'key': 'Control', 'code': 'ControlLeft',
'windowsVirtualKeyCode': 17})
time.sleep(.1)
for character in value:
browser.command('Input.dispatchKeyEvent', {'type': 'char', 'text': character, 'key': character})
try:
Browser.wait(lambda: any(node['key'] == 107 and node['value'] == value for node in tree(browser)),
10, 'manual code edit')
except AssertionError:
raise AssertionError('Manual code edit state: ' + json.dumps([node for node in tree(browser)
if node['key'] == 107])) from None
def wait_api(browser, predicate, label):
# CDP requests must keep being pumped while waiting for intercepted HTTP.
try:
Browser.wait(lambda: browser.evaluate('true') and predicate(), 30, label)
except AssertionError as error:
observed = [(reply['path'], reply['status'], reply['body'].get('error', ''))
for reply in browser.referral_replies]
labels = [node['label'] for node in tree(browser) if node['visible']]
raise AssertionError(f'{error}; API: {observed}; requests: {browser.api_statuses}; UI: {labels}') from None
def create_account(browser):
click_widget(browser, 78005)
click_widget(browser, 820)
Browser.wait(lambda: browser.evaluate('!!(Module.sharedAccountOwner && Module.sharedAccountOwner.length === 64)'),
30, 'actual account creation and hub handoff')
owner = browser.evaluate('Module.sharedAccountOwner')
# Opaque fixture account material from the real provider is retained only
# inside this test process, never printed, decoded or used to sign anything.
key = browser.evaluate('Module.sharedAccountKey')
for _ in range(4):
if any(node['key'] == 78003 for node in tree(browser)):
break
browser.click(54, 28)
time.sleep(.15)
wait_api(browser, lambda: any(reply['path'].endswith('/me') and reply['status'] == 200 and
reply['body'].get('account_id') == owner for reply in browser.referral_replies),
'signed referral summary')
return owner, key
def switch_shared_account(browser, owner, key):
previous = browser.evaluate('performance.timeOrigin')
browser.evaluate('void WaoziAccount.share(' + json.dumps(key) + ', ' + json.dumps(owner) + ', false); true')
Browser.wait(lambda: browser.evaluate('performance.timeOrigin') != previous, 20, 'actual shared-account reload')
ready(browser)
Browser.wait(lambda: browser.evaluate('Module.sharedAccountOwner') == owner, 15, 'shared account selection')
def integration(browser, control):
browser.navigate('https://dew.waozi.xyz/referrals')
ready(browser)
inviter, inviter_key = create_account(browser)
seeded = control('seed', {'account_id': inviter, 'count': 51})
code = seeded['code']
click_widget(browser, 78009)
Browser.wait(lambda: 'fixture-referral-049' in json.dumps(tree(browser)), 30, 'accepted nonpurchasers first page')
first_page = tree(browser)
assert 'fixture-referral-000' in json.dumps(first_page)
assert any(node['key'] == 78101 and node['label'] for node in first_page), 'acceptance date missing'
click_widget(browser, 78027)
Browser.wait(lambda: 'fixture-referral-050' in json.dumps(tree(browser)), 30, 'accepted next page')
assert 'fixture-referral-000' not in json.dumps(tree(browser)), 'pagination retained stale page'
print('Local integration: real signup, signed summary and nonpurchaser pagination passed', flush=True)
# Sign out through the real account UI, then create a fresh account.
browser.click(54, 28)
click_widget(browser, 830)
click_widget(browser, 8808)
Browser.wait(lambda: browser.evaluate('!Module.sharedAccountOwner'), 20, 'actual sign-out')
browser.navigate('https://dew.waozi.xyz/invite/' + code + '?platform=play&app=shovey')
ready(browser)
friend, friend_key = create_account(browser)
assert friend != inviter
assert 'fixture-referral-' not in json.dumps(tree(browser)), 'previous account referrals leaked'
assert not any(reply['path'].endswith('/claim') for reply in browser.referral_replies), 'landing silently claimed'
fill_code(browser, 'BAD_MANUAL')
print('Local integration: fresh friend account and manual code edit passed', flush=True)
saved = browser.evaluate("['referral-pending.txt','referral-suggestion.txt'].map(name => { try { return Module.FS.readFile('/kryon-apps/profile/' + name, {encoding:'utf8'}); } catch (_) { return 'missing'; } })")
assert saved == ['BAD_MANUAL', code], 'Shared referral files before reload: ' + json.dumps(saved)
browser.evaluate('new Promise((resolve,reject) => Module.FS.syncfs(false, error => error ? reject(error) : resolve(true)))', True)
previous = browser.evaluate('performance.timeOrigin')
browser.command('Page.reload')
Browser.wait(lambda: browser.evaluate('performance.timeOrigin') != previous, 15, 'safe reload')
ready(browser)
try:
Browser.wait(lambda: any(node['key'] == 107 and node['value'] == 'BAD_MANUAL' for node in tree(browser)),
30, 'manual code survives reload over URL suggestion')
except AssertionError:
fields = [node for node in tree(browser) if node['key'] == 107]
raise AssertionError('Manual reload state: ' + json.dumps(fields)) from None
print('Local integration: manual code survived generated-app reload', flush=True)
fill_code(browser, code)
click_widget(browser, 78024)
assert not any(reply['path'].endswith('/claim') for reply in browser.referral_replies), 'review silently claimed'
click_widget(browser, 78022)
wait_api(browser, lambda: any(reply['path'].endswith('/claim') and reply['status'] == 200
for reply in browser.referral_replies), 'authoritative claim receipt')
claim = next(reply['body'] for reply in browser.referral_replies if reply['path'].endswith('/claim') and reply['status'] == 200)
assert claim['status'] == 'bound' and claim['welcome_units'] == 20_000_000 and claim['welcome_receipt_id']
Browser.wait(lambda: any(node['key'] == 78006 for node in tree(browser)), 15, 'immediate welcome gift confirmation')
assert not any(method == 'POST' and 'purchase' in path for method, path in browser.api_paths), 'welcome gift required a purchase'
assert not any(node['key'] in {60020, 60030, 60040} for node in tree(browser)), 'store-source claim exposed web payment'
switch_shared_account(browser, inviter, inviter_key)
Browser.wait(lambda: 'fixture-referral-049' in json.dumps(tree(browser)), 30, 'restored inviter list')
click_widget(browser, 78027)
Browser.wait(lambda: friend in json.dumps(tree(browser)), 30, 'real nonpurchaser public-ID fallback')
fresh = len(browser.referral_replies)
switch_shared_account(browser, friend, friend_key)
wait_api(browser, lambda: any(reply['path'].endswith('/me') and reply['body'].get('account_id') == friend
for reply in browser.referral_replies[fresh:] if reply['status'] == 200), 'friend summary after switch')
wait_api(browser, lambda: any(reply['path'].endswith('/accepted') and reply['body'].get('accepted') == []
for reply in browser.referral_replies[fresh:] if reply['status'] == 200), 'friend owner-scoped empty list')
assert 'fixture-referral-' not in json.dumps(tree(browser)), 'old-owner rows survived shared account switch'
assert any(node['key'] == 78018 for node in tree(browser)), 'permanent inviter binding not shown after reload'
assert sum(reply['path'].endswith('/claim') for reply in browser.referral_replies) == 1, 'reload repeated claim'
print('Local real-auth browser integration passed: explicit signed claim, immediate20 without purchase, nonpurchaser name/date/ID fallback, pagination, shared-account isolation')
def main():
Handler.site = ROOT / 'build/web'
Handler.landing_only = False
Handler.shared_account = True
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
with fixture() as (api, control), Browser() as browser:
local = f'http://127.0.0.1:{server.server_port}'
browser.route_origins({'https://dew.waozi.xyz': local,
'https://account.waozi.xyz': local + '/__account',
'https://api.waozi.xyz': api})
integration(browser, control)
finally:
server.shutdown()
server.server_close()
if __name__ == '__main__':
main()
-105
View File
@@ -1,105 +0,0 @@
// Open dew.waozi.xyz's build in a private headless browser: the page must draw
// without a failed frame, and its Sign in button must open the shared Profile.
// Usage: node tests/web_site_test.mjs SITE_DIR|URL
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { access, mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { extname, join, normalize } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
// SITE_DIR is served locally; an https URL tests the deployed site instead.
const site = process.argv[2];
if (!site) throw new Error('Usage: node tests/web_site_test.mjs SITE_DIR|URL');
const live = /^https:\/\//.test(site);
const types = { '.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.webmanifest': 'application/manifest+json' };
const server = createServer(async (request, response) => {
const path = normalize(decodeURIComponent(new URL(request.url, 'http://x').pathname)).replace(/^\/+/, '') || 'index.html';
try {
const body = await readFile(join(site, path));
response.writeHead(200, { 'Content-Type': types[extname(path)] || 'application/octet-stream' });
response.end(body);
} catch { response.writeHead(404); response.end(); }
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const profile = await mkdtemp(join(process.env.TMPDIR || tmpdir(), 'dew-web-'));
const env = { ...process.env };
for (const key of ['DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS']) delete env[key];
const browser = spawn(process.env.CHROMIUM || 'chromium', ['--headless=new', '--no-sandbox', '--use-gl=swiftshader',
'--enable-unsafe-swiftshader', '--no-first-run', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'],
{ env, detached: true, stdio: 'ignore' });
let socket, sequence = 0;
const pending = new Map(), console_lines = [];
const command = (method, params = {}) => new Promise((resolve, reject) => {
const id = ++sequence; pending.set(id, { resolve, reject }); socket.send(JSON.stringify({ id, method, params }));
});
let failure = '';
try {
const started = Date.now();
while (true) {
try { await access(join(profile, 'DevToolsActivePort')); break; } catch {}
if (Date.now() - started > 15000) throw new Error('the browser did not start');
await delay(50);
}
const port = (await readFile(join(profile, 'DevToolsActivePort'), 'utf8')).split('\n')[0];
const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
socket = new WebSocket(targets.find(target => target.type === 'page').webSocketDebuggerUrl);
await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; });
socket.onmessage = event => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.consoleAPICalled')
console_lines.push(message.params.args.map(arg => arg.value ?? arg.description ?? '').join(' '));
const request = pending.get(message.id);
if (!request) return;
pending.delete(message.id);
message.error ? request.reject(new Error(JSON.stringify(message.error))) : request.resolve(message.result);
};
await command('Runtime.enable'); await command('Page.enable');
await command('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false });
await command('Page.navigate', { url: live ? site : `http://127.0.0.1:${server.address().port}/` });
let ready = false;
const deadline = Date.now() + 60000;
while (!ready && Date.now() < deadline) {
// The page may still be loading; it answers once its status element exists.
const state = await command('Runtime.evaluate', {
expression: 'JSON.stringify({ready: !!(window.Module && Module.profileReady), error: !!document.getElementById("loading")?.classList.contains("error")})',
returnByValue: true });
if (typeof state.result?.value !== 'string') { await delay(250); continue; }
const value = JSON.parse(state.result.value);
if (value.error) { failure = 'the page reported that Dew could not start'; break; }
ready = value.ready;
if (!ready) await delay(250);
}
if (!ready && !failure) failure = 'the page never became ready';
// Let the page draw several frames before judging them.
await delay(3000);
if (!failure) {
// The title row's Sign in button: the right end of the centred 560-pixel column.
const click = { x: 1280 / 2 + 280 - 60, y: 28 + 4 + 20, button: 'left', clickCount: 1 };
await command('Input.dispatchMouseEvent', { type: 'mouseMoved', ...click });
await command('Input.dispatchMouseEvent', { type: 'mousePressed', ...click });
await delay(100);
await command('Input.dispatchMouseEvent', { type: 'mouseReleased', ...click });
let profile = false;
const opened = Date.now() + 10000;
while (!profile && Date.now() < opened) {
const state = await command('Runtime.evaluate', { expression: '!!Module.profileVisible', returnByValue: true });
profile = state.result?.value === true;
if (!profile) await delay(200);
}
if (!profile) failure = 'Sign in did not open the Profile';
await delay(1500);
}
const failed = console_lines.find(line => /frame failed|portable execution failed/.test(line));
if (!failure && failed) failure = failed;
} finally {
try { process.kill(-browser.pid, 'SIGTERM'); } catch {}
server.close();
await rm(profile, { recursive: true, force: true }).catch(() => {});
}
if (failure) {
console.error(console_lines.slice(-20).join('\n'));
throw new Error(failure);
}
console.log('Dew drew its page and opened the Profile in the browser');
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""Exercise actual browser attribution and generated Dew/Entity Wasm without Node."""
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import argparse
import json
from pathlib import Path
import threading
from urllib.parse import urlsplit
from browser import Browser, PROJECTS, ROOT
class Handler(SimpleHTTPRequestHandler):
site = ROOT / 'site'
landing_only = False
shared_account = False
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(self.site), **kwargs)
def log_message(self, *unused):
pass
def do_GET(self):
path = urlsplit(self.path).path
if path.startswith('/__account/'):
name = path.removeprefix('/__account/')
if name == 'hub':
name = 'hub.html'
if name not in {'share.js', 'hub.html'}:
return self.send_error(404)
public_file = PROJECTS / 'harness/waozi/account' / name
return self.answer(public_file.read_bytes(), 'text/javascript' if name.endswith('.js') else 'text/html')
if path == '/referral.js' and self.landing_only:
return self.answer((ROOT / 'src/web/referral.js').read_bytes(), 'text/javascript')
if path == '/runtime.js' and self.landing_only:
return self.answer(b'window.runtimeStarted = (window.runtimeStarted || 0) + 1;', 'text/javascript')
if path in {'/', '/invite', '/referrals'} or path.startswith('/invite/'):
page = (self.site / 'index.html').read_text()
# The test is entirely offline: no production hub/account/network.
if not self.shared_account:
page = page.replace("shared.src = 'https://account.waozi.xyz/share.js';",
"shared.src = '/test-share.js';")
if not self.landing_only:
page = page.replace('window.Module = {', "window.Module = { preRun: [function () { ENV.KRYON_TEST_DRIVER = '/test'; Module.FS.mkdir('/test'); }],")
return self.answer(page.encode(), 'text/html')
if path == '/test-share.js':
return self.answer(b'window.WaoziAccount = {attach: function () {return Promise.resolve();}};', 'text/javascript')
return super().do_GET()
def answer(self, body, content_type):
self.send_response(200)
self.send_header('Content-Type', content_type + '; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(body)
def do_POST(self):
if self.path != '/__transport_test':
return self.send_error(404)
body = self.rfile.read(int(self.headers.get('Content-Length', 0)))
self.answer(json.dumps({'received': body.decode()}).encode(), 'application/json')
def landing(browser, origin):
browser.navigate(origin + '/invite/TEST_CODE?app=shovey&lang=de')
assert browser.evaluate('DewReferral.code') == 'TEST_CODE'
assert browser.evaluate('DewReferral.requested') is True
assert browser.evaluate('document.querySelector("#referral-gift").textContent.includes("sofort 20 Dew")')
assert browser.evaluate('Module.referralRequested') is True
browser.navigate(origin + '/?lang=es')
assert browser.evaluate('DewReferral.code') == 'TEST_CODE', 'code lost across sign-in/reload'
assert browser.evaluate('DewReferral.sourceApp') == 'shovey'
assert browser.evaluate('document.querySelector("#referral-manual").textContent.includes("Guarda")')
browser.navigate(origin + '/?ref=%3Cscript%3E&lang=en')
assert browser.evaluate('DewReferral.code') == '', 'invalid link must not recover older code'
assert browser.evaluate('document.querySelector("#referral-manual").textContent.includes("manually")')
browser.navigate(origin + '/invite/STORE_CODE?platform=gplay&app=shovey')
assert browser.evaluate('DewReferral.fundingAllowed') is False
assert browser.evaluate('Module.referralOnly') is True, 'store link opened payment flow'
assert browser.evaluate('document.querySelector("#referral-code").textContent') == 'STORE_CODE'
browser.navigate(origin + '/')
assert browser.evaluate('DewReferral.fundingAllowed') is False, 'reload lost store source restriction'
assert browser.evaluate('document.querySelector("#referral-open").hidden') is False, 'store hint blocked welcome claim'
for platform in ['apple', 'amazon', 'unrecognized']:
browser.navigate(origin + '/invite/STORE_CODE?platform=' + platform)
assert browser.evaluate('DewReferral.fundingAllowed') is False
browser.navigate(origin + '/invite/DIRECT_CODE?platform=fdroid&lang=fr')
assert browser.evaluate('DewReferral.fundingAllowed') is True
assert browser.evaluate('document.querySelector("#referral-landing").lang') == 'en'
browser.evaluate('document.querySelector("#referral-forget").click()')
browser.wait(lambda: browser.evaluate('location.pathname + location.search') == '/?lang=en')
browser.wait(lambda: browser.evaluate('typeof DewReferral !== "undefined" && DewReferral.code === ""'))
assert browser.evaluate('DewReferral.requested') is False
# A privacy-restricted browser still keeps the original link available.
browser.command('Page.addScriptToEvaluateOnNewDocument', {'source':
"Storage.prototype.getItem = Storage.prototype.setItem = function () {throw Error('disabled')};"})
browser.navigate(origin + '/?ref=MANUAL_CODE&view=referrals')
assert browser.evaluate('DewReferral.code') == 'MANUAL_CODE'
browser.route_api(origin)
response = browser.evaluate("fetch('https://api.waozi.xyz/__transport_test', {method:'POST',body:'fixture'}).then(r => r.json())", True)
assert response == {'received': 'fixture'}, 'local-only API routing changed request bytes'
print('Local browser tests: link/manual fallback, reload, EN/DE/ES, invalid code, storage denial, source routing passed')
def driver(browser, verb):
serial = browser.evaluate('(window.testSerial = (window.testSerial || 0) + 1)')
command = json.dumps(str(serial) + '\t' + verb + '\n')
browser.evaluate(f'Module.FS.writeFile("/test/next", {command}); Module.FS.rename("/test/next", "/test/command")')
Browser.wait(lambda: browser.evaluate('Module.FS.analyzePath("/test/reply").exists'), 15, verb)
response = browser.evaluate('JSON.parse(Module.FS.readFile("/test/reply", {encoding:"utf8"}))')
browser.evaluate('Module.FS.unlink("/test/reply")')
assert response['ok'], response
return response
def generated(browser, origin):
browser.navigate(origin + '/')
browser.wait(lambda: browser.evaluate('!!(window.Module && Module.profileReady)'), 90, 'generated app startup')
assert browser.evaluate('Module.sharedAccountReady') is True, 'actual shared account hub did not complete handoff'
tree = driver(browser, 'tree')
assert 'My referrals' in json.dumps(tree), 'topup has no referrals entry'
button = driver(browser, 'find\tkey=60006')['nodes'][0]
browser.click(button['x'] + button['width'] / 2, button['y'] + button['height'] / 2)
browser.wait(lambda: browser.evaluate('!!Module.profileVisible'), 15, 'referrals entry')
browser.navigate(origin + '/invite/MANUAL_CODE')
browser.wait(lambda: browser.evaluate('!!(window.Module && Module.profileReady && Module.profileVisible)'), 90, 'referral landing')
tree = driver(browser, 'tree')
assert 'My referrals' in json.dumps(tree), 'Entity referral route did not open'
assert browser.evaluate('Module.referralCode') == 'MANUAL_CODE', 'landing lost prefill'
assert 'MANUAL_CODE' in json.dumps(tree), 'signed-out flow hides the manual fallback code'
signin = driver(browser, 'find\tkey=78005')['nodes'][0]
browser.click(signin['visible_x'] + signin['visible_width'] / 2,
signin['visible_y'] + signin['visible_height'] / 2)
browser.wait(lambda: any(node['key'] == 820 for node in driver(browser, 'tree')['nodes']),
10, 'referral sign-in opens actual account choices')
browser.navigate(origin + '/invite/STORE_CODE?platform=play&app=shovey')
browser.wait(lambda: browser.evaluate('!!(window.Module && Module.profileReady && Module.profileVisible)'), 90, 'store-source referral route')
tree = driver(browser, 'tree')
assert 'STORE_CODE' in json.dumps(tree)
assert any(node['key'] == 78005 for node in tree['nodes']), 'store hint blocked sign-in/welcome claim'
assert not any(node['key'] in {60020, 60030, 60040} for node in tree['nodes']), 'store route exposed web purchase'
for _ in range(2):
browser.click(54, 28)
tree = driver(browser, 'tree')
assert not any(node['key'] in {60020, 60030, 60040} for node in tree['nodes']), 'Back exposed web purchase'
for locale, title in [('de', 'Meine Empfehlungen'), ('es', 'Mis referidos')]:
browser.navigate(origin + '/referrals?lang=' + locale)
browser.wait(lambda: browser.evaluate('!!(window.Module && Module.profileReady && Module.profileVisible)'),
90, 'translated shared referrals')
assert any(node['key'] == 78003 and node['label'] == title for node in driver(browser, 'tree')['nodes'])
assert 'frame failed' not in json.dumps(browser.events), browser.events
print('Local generated-app browser tests: Dew entry, shared Entity referral route and landing prefill passed')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('site', nargs='?', default='build/web', type=Path)
parser.add_argument('--landing-only', action='store_true')
args = parser.parse_args()
Handler.site = ROOT / 'site' if args.landing_only else args.site.resolve()
Handler.landing_only = args.landing_only
Handler.shared_account = not args.landing_only
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
with Browser() as browser:
if args.landing_only:
landing(browser, f'http://127.0.0.1:{server.server_port}')
else:
local = f'http://127.0.0.1:{server.server_port}'
browser.route_origins({'https://dew.waozi.xyz': local,
'https://account.waozi.xyz': local + '/__account'})
generated(browser, 'https://dew.waozi.xyz')
finally:
server.shutdown()
server.server_close()
if __name__ == '__main__':
main()
+157 -36
View File
@@ -1,6 +1,24 @@
{
"format": 1,
"packages": [
{
"commit": "907e90ddd4c78f02e0d49e90384e4197f7dcdf26",
"dependencies": {},
"id": "p002f6ed23e3a3576",
"name": "monocypher",
"ref": "master",
"source": true,
"url": "https://github.com/LoupVaillant/Monocypher.git"
},
{
"commit": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7",
"dependencies": {},
"id": "p0dd67588478f9a3e",
"name": "libsamplerate",
"ref": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7",
"source": true,
"url": "https://github.com/libsndfile/libsamplerate.git"
},
{
"commit": "2944b2e668e735438d8ce24e47a39be3f5c36af5",
"dependencies": {},
@@ -10,54 +28,147 @@
"url": "https://github.com/ziranlang/qrcode.git"
},
{
"commit": "0931212f92d5f1a3f8b1be80abab7a9695bda50e",
"dependencies": {"raylib": "p5a77c9c35110e925"},
"id": "p3127065409ca96f6",
"name": "kryon",
"ref": "master",
"url": "https://github.com/kryonlabs/kryon.git"
"commit": "829a65d769d935c4852f8159e964312c0957260a",
"dependencies": {},
"id": "p16cd0434af3dff7b",
"name": "sdl3",
"ref": "829a65d769d935c4852f8159e964312c0957260a",
"source": true,
"url": "https://github.com/libsdl-org/SDL.git"
},
{
"commit": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"commit": "3a88f21f962928fc4a92fcdabc99f89be1588623",
"dependencies": {},
"id": "p5a77c9c35110e925",
"name": "raylib",
"ref": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"id": "p2567a9faecca698d",
"name": "liboqs",
"ref": "main",
"source": true,
"url": "https://github.com/raysan5/raylib.git"
"url": "https://github.com/open-quantum-safe/liboqs.git"
},
{
"commit": "ec6ed304767e10c125ab2820f3b01d6fd773e147",
"dependencies": {"image_codec": "p69c0e968ae5735d9", "libwebp": "p3b3c785a0e17e605"},
"dependency_refs": {"image_codec": "360553150917f352e49e1beb78917370792ccaef", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339"},
"id": "p2af20e0c835b1c63",
"name": "webp",
"ref": "ec6ed304767e10c125ab2820f3b01d6fd773e147",
"url": "https://github.com/ziranlang/webp.git"
},
{
"commit": "1844042d1ca751e62e61df7617dba19c98588339",
"dependencies": {},
"id": "p3b3c785a0e17e605",
"name": "libwebp",
"ref": "1844042d1ca751e62e61df7617dba19c98588339",
"source": true,
"url": "https://github.com/webmproject/libwebp.git"
},
{
"commit": "1aadfad932c98c069a1204261b1856f81f3bc199",
"dependencies": {},
"id": "p57c0272208aae8db",
"name": "libavif",
"ref": "1aadfad932c98c069a1204261b1856f81f3bc199",
"source": true,
"url": "https://github.com/AOMediaCodec/libavif.git"
},
{
"commit": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2",
"dependencies": {"libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e"},
"dependency_refs": {"libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7"},
"id": "p59deb49c7f103127",
"name": "audio",
"ref": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2",
"url": "https://github.com/ziranlang/audio.git"
},
{
"commit": "bd278217e2bac754d868b3d6502eac4257658d4b",
"dependencies": {"dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa"},
"dependency_refs": {"dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937"},
"id": "p5d7d12505a42f7b3",
"name": "av1",
"ref": "bd278217e2bac754d868b3d6502eac4257658d4b",
"url": "https://github.com/ziranlang/av1.git"
},
{
"commit": "360553150917f352e49e1beb78917370792ccaef",
"dependencies": {},
"id": "p69c0e968ae5735d9",
"name": "image-codec",
"ref": "360553150917f352e49e1beb78917370792ccaef",
"url": "https://github.com/ziranlang/image-codec.git"
},
{
"commit": "22d2ddbdc236796953c905a05a2cebf5ab1b4ff3",
"dependencies": {"liboqs": "pe86510e9fb3fef51"},
"dependencies": {"liboqs": "p2567a9faecca698d"},
"dependency_refs": {"liboqs": "main"},
"id": "p7098ac9cd92f7e5f",
"name": "Oqs",
"ref": "master",
"url": "https://github.com/ziranlang/oqs.git"
},
{
"commit": "f5f0a19a5dc6c14a49adb3cd63ea79a60f6ba77b",
"commit": "b141d9c45db236335351c8a4b2a14b3ade27c937",
"dependencies": {},
"id": "p809b4d31a48625a3",
"name": "monocypher",
"ref": "master",
"id": "p74ab3cb6eb3b86fa",
"name": "libaom",
"ref": "b141d9c45db236335351c8a4b2a14b3ade27c937",
"source": true,
"url": "https://github.com/LoupVaillant/Monocypher.git"
"url": "https://aomedia.googlesource.com/aom"
},
{
"commit": "25d9f649c43a8de44a5fea602d2835e33e6ca999",
"commit": "c1ac6095d01bcfdd4c5ae49c4636aaf9a0303449",
"dependencies": {"crypto": "pc23fbf455e97614d", "oqs": "p7098ac9cd92f7e5f"},
"id": "p9972fcdd2d5ba999",
"name": "DaochiClient",
"ref": "master",
"url": "https://github.com/ziranlang/daochi-client.git"
"dependency_refs": {"crypto": "master", "oqs": "master"},
"id": "p8204ae87a845c1c3",
"name": "mesh_client",
"ref": "c1ac6095d01bcfdd4c5ae49c4636aaf9a0303449",
"url": "https://github.com/ziranlang/mesh-client.git"
},
{
"commit": "7d37be6e1f0643c01b35545e42e48c633f19a90d",
"dependencies": {"daochi_client": "p9972fcdd2d5ba999", "kryon": "p3127065409ca96f6", "monocypher": "p809b4d31a48625a3", "qrcode": "p0dfa70137405b096"},
"id": "p6feeecb5bfff3686",
"name": "Entity",
"ref": "master",
"url": "https://github.com/waozixyz/entity.git"
"commit": "51b7f2abdade71cd9bb0e7a373ef2610ec6f9daf",
"dependencies": {},
"id": "p82dbc05081cd4d96",
"name": "zlib",
"ref": "51b7f2abdade71cd9bb0e7a373ef2610ec6f9daf",
"source": true,
"url": "https://github.com/madler/zlib.git"
},
{
"commit": "03016057afa1c695f6e24f32e5be5df761475220",
"dependencies": {"audio": "p59deb49c7f103127", "avif": "pb203529d803e73a4", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"},
"dependency_refs": {"audio": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2", "avif": "2611e727e226a2af22dfb7f10bf224bd2f1a3d30", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"},
"id": "p83b7422cf506dc6a",
"name": "kryon",
"ref": "1be70904a388db11ef5fb3938cd2d37ab7dd8eb5",
"url": "https://github.com/kryonlabs/kryon.git"
},
{
"commit": "19b299005fbe2d895f4ad525cfdae62a2220c3ea",
"dependencies": {},
"id": "p8da229d15597ab5c",
"name": "curl",
"ref": "19b299005fbe2d895f4ad525cfdae62a2220c3ea",
"source": true,
"url": "https://github.com/curl/curl.git"
},
{
"commit": "2611e727e226a2af22dfb7f10bf224bd2f1a3d30",
"dependencies": {"av1": "p5d7d12505a42f7b3", "dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db"},
"dependency_refs": {"av1": "bd278217e2bac754d868b3d6502eac4257658d4b", "dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199"},
"id": "pb203529d803e73a4",
"name": "avif",
"ref": "2611e727e226a2af22dfb7f10bf224bd2f1a3d30",
"url": "https://github.com/ziranlang/avif.git"
},
{
"commit": "54706fc6bc0cdecab7e9593974a4039cc038fca7",
"dependencies": {},
"id": "pb24767b9eb34d961",
"name": "dav1d",
"ref": "54706fc6bc0cdecab7e9593974a4039cc038fca7",
"source": true,
"url": "https://github.com/videolan/dav1d.git"
},
{
"commit": "944826f70779a6b6cd53f6b06a75b36f4d8a2558",
@@ -68,22 +179,32 @@
"url": "https://github.com/ziranlang/crypto.git"
},
{
"commit": "48955d1117ed6207a12d2a4c9e4162283d3420a5",
"commit": "3c7df0daa0cfb12fff67dfaac34aac736687a59e",
"dependencies": {"curl": "p8da229d15597ab5c", "kryon": "p83b7422cf506dc6a", "mesh_client": "p8204ae87a845c1c3", "monocypher": "p002f6ed23e3a3576", "oqs": "p7098ac9cd92f7e5f", "qrcode": "p0dfa70137405b096", "zlib": "p82dbc05081cd4d96"},
"dependency_refs": {"curl": "19b299005fbe2d895f4ad525cfdae62a2220c3ea", "kryon": "3f72441949d4e16094834fa9220e5d7fa77a0ac0", "mesh_client": "c1ac6095d01bcfdd4c5ae49c4636aaf9a0303449", "monocypher": "master", "oqs": "master", "qrcode": "master", "zlib": "51b7f2abdade71cd9bb0e7a373ef2610ec6f9daf"},
"id": "pd380d4bff37de135",
"name": "Entity",
"ref": "3c7df0daa0cfb12fff67dfaac34aac736687a59e",
"url": "https://github.com/waozixyz/entity.git"
},
{
"commit": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
"dependencies": {},
"id": "pe86510e9fb3fef51",
"name": "liboqs",
"ref": "main",
"id": "pe1fe9bbe80bf1d6d",
"name": "libopus",
"ref": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
"source": true,
"url": "https://github.com/open-quantum-safe/liboqs.git"
"url": "https://github.com/xiph/opus.git"
}
],
"root": {
"dependencies": {"entity": "p6feeecb5bfff3686", "kryon": "p3127065409ca96f6", "qrcode": "p0dfa70137405b096"},
"dependencies": {"entity": "pd380d4bff37de135", "kryon": "p83b7422cf506dc6a", "qrcode": "p0dfa70137405b096"},
"dependency_refs": {"entity": "3c7df0daa0cfb12fff67dfaac34aac736687a59e", "kryon": "1be70904a388db11ef5fb3938cd2d37ab7dd8eb5", "qrcode": "master"},
"name": "Dew"
},
"toolchain": {
"commit": "6c952032c6f337fba5a6b41bd1acbf114ed84fb4",
"ref": "master",
"commit": "398bd43d9c68ed57f34e837fca7785dd77b85762",
"ref": "665fbbca60ccf1e3823741d727af9af6c6552958",
"url": "https://github.com/ziranlang/ziran.git"
}
}
+3 -3
View File
@@ -4,15 +4,15 @@ module_roots = ["src", "tests"]
[toolchain]
git = "https://github.com/ziranlang/ziran.git"
ref = "master"
ref = "665fbbca60ccf1e3823741d727af9af6c6552958"
[dependencies.kryon]
git = "https://github.com/kryonlabs/kryon.git"
ref = "master"
ref = "1be70904a388db11ef5fb3938cd2d37ab7dd8eb5"
[dependencies.entity]
git = "https://github.com/waozixyz/entity.git"
ref = "master"
ref = "3c7df0daa0cfb12fff67dfaac34aac736687a59e"
[dependencies.qrcode]
git = "https://github.com/ziranlang/qrcode.git"