Design System Master File
LOGIC: When building a specific page, first check
design-system/pages/[page-name].md. If that file exists, its rules override this Master file. If not, strictly follow the rules below.
Project: Zalo Rust Desktop Generated: 2026-10-21 19:23:18 Category: Chat & Messaging App Design Dials: Variance 4/10 (Balanced / Modern) | Motion 3/10 (Subtle) | Density 7/10 (Standard)
Global Rules
Color Palette
| Role | Hex | CSS Variable |
|---|---|---|
| Primary | #2563EB | --color-primary |
| On Primary | #FFFFFF | --color-on-primary |
| Secondary | #6366F1 | --color-secondary |
| On Secondary | #000000 | --color-on-secondary |
| Accent/CTA | #059669 | --color-accent |
| On Accent/CTA | #000000 | --color-on-accent |
| Background | #FFFFFF | --color-background |
| Foreground | #0F172A | --color-foreground |
| Card | #FFFFFF | --color-card |
| Card Foreground | #0F172A | --color-card-foreground |
| Muted | #F1F5FD | --color-muted |
| Muted Foreground | #475569 | --color-muted-foreground |
| Border | #E4ECFC | --color-border |
| Destructive | #DC2626 | --color-destructive |
| On Destructive | #FFFFFF | --color-on-destructive |
| Ring | #2563EB | --color-ring |
Color Notes: Messenger blue + online green
Typography
- Heading Font: Inter
- Body Font: Inter
- Mood: minimal, clean, swiss, functional, neutral, professional
- Google Fonts: Inter + Inter
CSS Import:
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap");
Spacing Variables
Density: 7/10 — Standard
| Token | Value | Usage |
|---|---|---|
--space-xs | 4px / 0.25rem | Tight gaps |
--space-sm | 8px / 0.5rem | Icon gaps, inline spacing |
--space-md | 16px / 1rem | Standard padding |
--space-lg | 24px / 1.5rem | Section padding |
--space-xl | 32px / 2rem | Large gaps |
--space-2xl | 48px / 3rem | Section margins |
--space-3xl | 64px / 4rem | Hero padding |
Shadow Depths
| Level | Value | Usage |
|---|---|---|
--shadow-sm | 0 1px 2px rgba(0,0,0,0.05) | Subtle lift |
--shadow-md | 0 4px 6px rgba(0,0,0,0.1) | Cards, buttons |
--shadow-lg | 0 10px 15px rgba(0,0,0,0.1) | Modals, dropdowns |
--shadow-xl | 0 20px 25px rgba(0,0,0,0.15) | Hero images, featured cards |
Component Specs
Buttons
/* Primary Button */
.btn-primary {
background: #059669;
color: white;
padding: 12px 24px;
border-radius: 8px;
font-weight: 600;
transition: all 200ms ease;
cursor: pointer;
}
.btn-primary:hover {
opacity: 0.9;
transform: translateY(-1px);
}
/* Secondary Button */
.btn-secondary {
background: transparent;
color: #2563eb;
border: 2px solid #2563eb;
padding: 12px 24px;
border-radius: 8px;
font-weight: 600;
transition: all 200ms ease;
cursor: pointer;
}
Cards
.card {
background: #ffffff;
border-radius: 12px;
padding: 24px;
box-shadow: var(--shadow-md);
transition: all 200ms ease;
cursor: pointer;
}
.card:hover {
box-shadow: var(--shadow-lg);
transform: translateY(-2px);
}
Inputs
.input {
padding: 12px 16px;
border: 1px solid #e2e8f0;
border-radius: 8px;
font-size: 16px;
transition: border-color 200ms ease;
}
.input:focus {
border-color: #2563eb;
outline: none;
box-shadow: 0 0 0 3px #2563eb20;
}
Modals
.modal-overlay {
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
}
.modal {
background: white;
border-radius: 16px;
padding: 32px;
box-shadow: var(--shadow-xl);
max-width: 500px;
width: 90%;
}
Style Guidelines
Style: Minimalism & Swiss Style
Keywords: Clean, simple, spacious, functional, white space, high contrast, geometric, sans-serif, grid-based, essential
Best For: Enterprise apps, dashboards, documentation sites, SaaS platforms, professional tools
Key Effects: Subtle hover (200-250ms), smooth transitions, sharp shadows if any, clear type hierarchy, fast loading
Page Pattern
Pattern Name: Product Demo + Features
- Conversion Strategy: Use an interactive demo only when it explains value better than static media. Provide captions, transcript, visible play/pause controls, and a non-video fallback; do not autoplay under reduced motion. Pause media when offscreen or hidden and keep the final product state available as static content.
- CTA Placement: Video center + CTA right/bottom
- Section Order: Hero > Product video/mockup (center) > Feature breakdown per section > Comparison (optional) > CTA
Motion
Scroll Reveal (Subtle) — Trigger: scroll (viewport enter) | Duration: 300-400ms | Easing: power1.out
gsap.from(el, {
opacity: 0,
y: 12,
duration: 0.35,
ease: "power1.out",
scrollTrigger: { trigger: el, start: "top 90%", toggleActions: "play none none reverse" },
});
Framework notes: Requires the ScrollTrigger plugin registered once via gsap.registerPlugin(ScrollTrigger); Use matchMedia(‘(prefers-reduced-motion: reduce)’) to skip non-essential motion and render the final state immediately
- ✅ Keep the y offset small (8-16px) so it reads as a fade, not a slide
- ❌ Don’t reveal below-the-fold content needed for SEO/crawlers as invisible-by-default without a no-JS fallback
- ⚡ toggleActions ‘play none none reverse’ avoids re-triggering on every scroll direction change
Anti-Patterns (Do NOT Use)
- ❌ Excessive decoration
Additional Forbidden Patterns
- ❌ Emojis as icons — Strictly use
lucide::...icon constants. Never use raw keyboard emojis as UI icons (prevents missing-glyph tofu boxes□). - ❌ Missing cursor:pointer — All clickable elements must have cursor:pointer
- ❌ Layout-shifting hovers — Avoid scale transforms that shift layout
- ❌ Low contrast text — Maintain 4.5:1 minimum contrast ratio
- ❌ Instant state changes — Always use transitions (150-300ms)
- ❌ Invisible focus states — Focus states must be visible for a11y
Pre-Delivery Checklist
Before delivering any UI code, verify:
- Strictly use
lucide::...icon constants, never raw keyboard emojis. - All icons from embedded Lucide vector set (
src/gui/theme.rs). -
cursor-pointeron all clickable elements - Hover states with smooth transitions (150-300ms)
- Light mode: text contrast 4.5:1 minimum
- Focus states visible for keyboard navigation
-
prefers-reduced-motionrespected - Responsive: 375px, 768px, 1024px, 1440px
- No content hidden behind fixed navbars
- No horizontal scroll on mobile
ROADMAP: AloLite (Minimal Native Messaging Client)
Objective: Build a minimal, ultra-lightweight, native Linux messaging client in Rust that starts instantaneously, uses minimal system resources, and eliminates Electron, Node.js, and out-of-scope non-core features (VoIP, Video Feed, Multi-platform bloat).
1. Layered Architecture & Separation of Concerns
The protocol layer is isolated in an independent module to ensure modularity, clean maintenance, and independent testability:
src/
├── main.rs # Single Linux CLI/GUI entrypoint
├── lib.rs # Crate root & module re-exports
├── protocol/ # [FEATURE 1] Pure network protocol, auth & crypto
│ ├── mod.rs, crypto.rs, session.rs, login.rs, qr.rs, chat.rs, socket.rs, ...
├── storage/ # [FEATURE 2] Local SQLite persistence (messages, threads)
│ └── mod.rs
├── gui/ # [FEATURE 3] Native egui desktop GUI (Wayland & X11)
│ ├── mod.rs, workspace.rs, messages.rs, modals.rs, theme.rs, stickers.rs, worker.rs
├── common/ # [SHARED] Shared utilities (clock, data_dir, logger, ui)
│ └── mod.rs, clock.rs, data_dir.rs, logger.rs, ui.rs
└── legacy/ # [QUARANTINED] Out-of-scope modules (VoIP, Feed, Scheduler)
2. Feature Scope Boundaries
✅ In Scope (Core Linux MVP):
- Authentication: QR code scanning, persistent session and cookie storage, automatic session restore on startup.
- Conversations: Friend list, group list, and recent conversation threads.
- Messaging:
- Real-time text, basic sticker, and image receipt via long-lived WebSocket connection.
- Text message, basic emoji, and image transmission via HTTP endpoints.
- Local Persistence: SQLite local message and thread caching, enabling offline message reading.
- Platform: Native Linux execution on Wayland and X11, compatible with Vietnamese input methods (ibus, fcitx5).
❌ Out of Scope (Explicit Non-Goals):
- VoIP / Audio & Video Calls: Omit WebRTC signaling, FFmpeg camera probing, and Opus streaming (
src/call.rs,src/audio.rs). - Zalo Video & Social Feed: Omit timeline feed, video stories, and social profiles (
src/feed.rs). - TUI Terminal Interface: Completely deleted (
src/tui.rsremoved,ratatuiandcrosstermdropped). - Multi-Account Management: Focus on a single reliable, hardened user session.
- Windows / macOS Legacy: Remove Windows PE resource compilation, manifests, Inno Setup scripts, and macOS notification helpers.
3. Execution Roadmap (4 Phases)
Phase 1: Codebase Pruning & Linux Build Simplification [COMPLETED]
- Empirical Verification: Validated
ParamCipher v2andreqqrauthentication against live servers (code: 0). - Protocol Decoupling: Extracted all protocol logic into the isolated
src/protocol/module. - Build Script Cleanup: Stripped 250+ lines of Windows PE COFF
.resgenerator frombuild.rs. - UI Streamlining: Hid feed navigation from the left sidebar; removed Windows console attachment from
src/main.rs. - TUI Deletion: Completely removed
src/tui.rs, droppedratatuiandcrosstermdependencies, streamlined client to pureeguidesktop. - Verification: Confirmed
cargo check --all-targets(0 warnings) and all 204 unit tests passing.
Phase 2: QR Authentication & Persistent Session Management [COMPLETED]
- XDG Standard Compliance: Standardized session and database storage at
~/.local/share/alolite/(or$XDG_DATA_HOME/alolite) with private0700directory and0600file permissions (src/common/data_dir.rs). - Seamless Session Restore: Validated instant session resume from
session.jsonon startup without blocking the UI thread; non-expired sessions navigate directly into chat workspace. - Graceful Expiration & Re-authentication: Handled token expiry (
zpw_sekinvalidation / error code 600 / -102) by marking expiration, notifying UI (GuiEvent::SessionExpired), and generating fresh QR without application crash. - QR Lifecycle & Timeout Handling: Added
GuiEvent::QrExpiredwhen long-poll scan or confirmation times out, clearly updating the login UI state and providing manual and automatic refresh options.
Phase 3: Core Messaging & WebSocket Synchronization
- Fetch recent conversations (
get_friends,get_groups) and persist into SQLitestore.rs. - Sync conversation message history (
get_group_history/ 1-1 chats). - Implement text message sending (
/api/message/sms) with optimistic UI update. - Maintain a stable long-lived WebSocket connection (
socket.rs) for push notifications and unread badge updates. - Implement basic image viewing and photo sending.
Phase 4: Linux Polish & Packaging
- Validate font rendering (
BeVietnamPro) and Vietnamese input methods (ibus, fcitx5) inegui. - Polish UI with responsive dark/light themes.
- Produce standalone Linux distribution artifacts: stripped binary,
alolite.desktopentry, and.debpackage.
Legal Notice & Compliance Policy — AloLite
1. Trademark Notice & Nominative Fair Use
- “Zalo” is a registered trademark of VNG Corporation in the Socialist Republic of Vietnam and internationally.
- AloLite is an entirely independent, third-party open-source project. This software is NOT affiliated with, endorsed by, sponsored by, or officially associated with VNG Corporation or any of its subsidiaries.
- Any references to “Zalo” within this repository, source code identifiers, commit history, or technical documentation are made solely for Nominative Fair Use purposes: to accurately identify and describe the network protocol and technical compatibility target. The project name, public releases, and logos do not use VNG Corporation’s trademarks as brand identifiers.
2. Copyright & Clean-Room Interoperability
AloLite is implemented as an independent, clean-room software client designed for technical research and platform interoperability on Linux operating systems.
2.1 Statutory Basis for Interoperability
- Socialist Republic of Vietnam — Law on Intellectual Property (Articles 20 & 50a): Explicitly permits decompilation, reverse engineering, and technical analysis of computer programs strictly to achieve interoperability between independently created software programs, provided it does not prejudice the normal exploitation of the work.
- United States — 17 U.S.C. § 1201(f) (Reverse Engineering Exemption): Permits reverse engineering of technological protection measures solely for the purpose of enabling interoperability of an independently created computer program with other programs.
- European Union — Directive 2009/24/EC (Article 6 - Decompilation): Authorizes decompilation without the owner’s authorization where reproduction of the code and translation of its form are indispensable to obtain the information necessary to achieve the interoperability of an independently created computer program with other programs.
2.2 Clean-Room Engineering Invariants
- Zero Source Code Infringement: No decompiled C/C++ source code, disassembly dumps, proprietary headers, or extracted JavaScript bundles from official packages are committed to this repository.
- Independent Rust Implementation: All cryptographic routines (
ParamCipher v2,AES-CBC,AES-GCM,signkey), frame codecs, data models, and network state machines are independently authored in pure Rust. - Zero Bundled Copyrighted Media: No proprietary artwork, official application icons, copyrighted sticker sets, audio notification files, or font binaries belonging to VNG Corporation or third parties may be distributed in this Git repository. All media must be loaded dynamically by the client at runtime under the user’s authenticated session.
3. Naming & Branding Policy
To eliminate any potential for consumer confusion and fully comply with trademark protection standards:
- Product Name: The application is branded exclusively as AloLite (display name). Binary packages, desktop entries, and public distribution metadata must strictly use
aloliteoralolite-desktop. - Internal Module Structure: Protocol implementation layers are named with neutral technical terminology (
src/protocol/) rather than trademarked commercial brands. - Application Artwork: All icons, branding assets, and graphical UI elements must be original works authored for AloLite or sourced from permissive open-source licenses (e.g., Lucide icons, SIL OFL fonts). Official brand logos (such as the Zalo rounded square “Z” logo) are strictly prohibited.
4. Acceptable Use Policy (AUP)
Users and contributors of AloLite agree to the following terms:
- Personal & Legitimate Use: AloLite is designed solely for individual users accessing their own lawful personal accounts on non-supported platforms (such as Linux desktop environments).
- No Automated Spamming or Harassment: Using this software for automated unsolicited bulk messaging, automated calling, or harassment is strictly prohibited.
- No Data Scraping: Using this software to harvest, scrape, or extract personal information from other users without consent is strictly prohibited.
- No Denial of Service: Circumventing rate limits, exploiting vulnerabilities, or overloading service infrastructure is strictly prohibited.
- Non-Commercial Nature: AloLite is distributed free of charge under the Alolite Source-Available & Non-Commercial License (see
LICENSE). It contains no advertisements, telemetry tracking, premium tiers, or commercial monetization mechanisms.
5. Disclaimer of Warranties & Limitation of Liability
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ADR-0001: Pure-Rust Trusted Device Protocol Implementation
- Status: Accepted
- Date: 2026-11-07
- Author: ngxc
- Deciders: Alolite Core Engineering
1. Context & Problem Statement
To support direct 1-1 end-to-end messaging and resolve Zalo server error_code: 10002 (Group not found / Companion authorization required), Alolite requires the Trusted Device Protocol.
The official Zalo client ships this logic inside an isolated WebAssembly binary:
- File:
trusted_device_protocol_bg.97af2bf51fb002cefc5a888e932bcab2.wasm(SHA-256:716f0a0637...) - Size: 346 KB, 331 functions, stripped symbols.
- Analysis across official Linux, Windows (
Zalo-Win-26.11.10.7z), and macOS Universal (Zalo 26.11.10.dmg) packages revealed that no native binary library exists; all desktop platforms run this protocol via WebAssembly.
Per Alolite core principles (Zero Node.js, Zero Electron, pure native Rust executable) and Clean-Room IP Standards (docs/standards/compliance-and-ip.md), Alolite cannot bundle or execute proprietary WASM runtimes or embed proprietary WASM blobs.
2. Decision
Re-implement the entire Trusted Device Protocol in clean-room pure Rust under src/protocol/auth/trust/ without external code generators or runtime WASM dependencies:
- Curve25519 & XEdDSA: Use
curve25519-dalek 4(withdigestfeature) andsha2to implement Signal-compatible 33-byte Curve25519 public keys (0x05Djb type) and 64-byte XEdDSA signatures ($R \parallel s$) with the Edwards sign-bit packed into bit 7 of the last byte. - Protobuf Codec: Implement a zero-dependency, zero-allocation-where-possible protobuf reader and writer in
wire.rsstrictly matching the wire semantics observed via differential fuzzing against the reference WASM. - basE91: Pure Rust implementation of the standard basE91 text codec for the
"Z1@"QR payload inbase91.rs. - Security & Zeroization: All private scalars and linking secrets implement
ZeroizeandZeroizeOnDrop. Constant-time comparison (subtle::ConstantTimeEq) is mandatory for MAC and signature checks. - Testing & Verification: Keep deterministic known-answer test vectors in
tests/fixtures/trusted_device_kat.jsonand integration tests intests/protocol_trusted_device.rs.
3. Consequences
Positive
- Zero WASM / JS Dependency: Native execution speed, instant startup, zero runtime memory overhead from WASM interpreters.
- Strict Clean-Room: Clean implementation derived exclusively from black-box differential testing and wire observations.
- Portability: Seamless compilation across Linux (x86_64, aarch64), Windows, and macOS without extra native C dependencies.
Negative / Trade-offs
- Future protocol updates from upstream Zalo require re-verifying against updated official packages using the established REA harness (
re-notes/11-trusted-device-protocol.md).
4. Compliance & Invariants
- INV-1: All companion public keys must start with byte
0x05and measure 33 bytes. - INV-2: Private keys must be clamped per RFC 7748 before scalar operations.
- INV-3: Linking MACs must be verified in constant time before parsing inner metadata keys.
- INV-4: Device list companions are strictly ordered by
companion_idascending; duplicates are resolved as last-write-wins. - INV-5: The QR2 companion flow MUST only be offered when the login-time server flag
getServerInfo→setttings.authen.trusted_device.qr_format_trust_deviceis1; with0(all live auth hosts, 2026-11-07) the client MUST fall back to plain QR1, matching the reference client.ZALO_QR_TRUSTED=1|0is the only sanctioned override, for protocol experiments.
5. Deployment Status (2026-11-07)
The module is complete and offline-verified (KAT + integration tests), but inactive in production:
Zalo’s servers report qr_format_trust_device = 0, so the companion-linking QR (and the mobile
biometric authorization it triggers) cannot be exercised end to end. Evidence and the probe matrix:
re-notes/10-trusted-device-and-bio-sync.md §1.2.1.
ADR-0002: Single-Responsibility Protocol & Storage Module Boundaries
- Status: Accepted
- Date: 2026-11-08
- Author: ngxc
- Deciders: Alolite Core Engineering
1. Context & Problem Statement
Before this refactoring, three monolithic files (src/protocol/chat.rs at 8,275 lines / 95 pub items, src/protocol/history_sync.rs at 2,281 lines, and src/protocol/session.rs at 2,191 lines) accumulated ~70% of the entire src/protocol/ directory. This created three structural defects:
- Broken Layering:
src/protocol/history_sync.rsopenedrusqlite::ConnectionandMessageStoredirectly, whilesrc/protocol/chat.rsread/wrotethreads_cache.json(load_threads_cache/save_threads_cache), violating the pure-protocol boundary inAGENTS.md. - Split Domain Ownership: Reaction sending (
send_reaction) and seen/mute REST calls (send_seen_v2,set_unread_mark,set_mute_conversation) lived inchat.rsalongside separatereactions.rsandunread.rsmodules. - Duplicated Wire Helpers: Identical JSON unwrapping (
unwrap_data,pick_str),group_prefix stripping, control-event flattening (controls/content/ stringifieddata), monotonicclientIdgeneration, and MD5/timestamp helpers were duplicated across multiple files.
2. Decision
Decompose the protocol and persistence layers into cohesive single-responsibility modules without maintaining legacy re-export shims:
-
Shared Foundation (
src/protocol/wire.rs+src/protocol/registry/):wire.rsis the single source of truth forrequire_login,obj,unwrap_data,pick_str,val_i64,val_u64,wire_identity,is_group_flag,strip_group_prefix,iter_control_items,parse_control_data,next_client_message_id, and host helpersdomain_or/chat_send_host.registry/splits intoregistry/mod.rs(ApiDomain,CommandSpec,lookup_command, domain command constants),registry/http_table.rs(437-entry sortedCOMMAND_REGISTRY), andregistry/ws.rs(complete WebSocketcmdand close-code catalog).
-
Session Transport (
src/protocol/session/):session/mod.rs:SessionHTTP transport (reqwest,ParamCipher, candidate failover,api_get/api_post).session/domains.rs:Domainsrouting table,heal_from_verified,apply_service_map, candidate ranking.session/persistence.rs:SavedSession,LoginInfo,DeviceIdentity,save_to_file/load_from_file,official_imei.session/privacy.rs: Privacy Guard toggles (block_typing/block_delivered/block_seen),redact_*,urlencode,truncate.session/status.rs:SessionError,SessionStatus,AUTH_ERROR_CODES.
-
Domain-Grouped Protocol Subdirectories (
src/protocol/{auth,social,messaging}/):auth/:login.rs(password & server/login info),qr.rs(QR1/QR2 flow),trust/*(Curve25519/XEdDSA Trusted Companion Device crypto).social/:friends.rs(get_friends,FriendshipStatus,PhoneLookupResult,find_user_by_phone, friend requests, online status),groups.rs(get_groups,fetch_group_profiles,get_mini_profiles,get_group_history*,resolve_thread_names).messaging/:model.rs(WireMessageRef,MessageKind,DeliveryState,UnreadPolicy),threads.rs(ChatMessage,Thread,SidebarPresentation,MessageIdentityIndex,merge_thread_into,deduplicate_threads, pin/hide/delete conversation ops),send.rs(outbound text/RTF/quote/forward/recall/delete/typing),polling.rs(PollState,QueueCursor,lp_chat,get_last_msgs,get_cloud_messages,merge_previews,merge_group_history,parse_chat_message),attachments.rs(chunked image/asyncfile uploads,FileDoneRegistry, CDN URL/filename helpers),links.rs(LinkMetadata,extract_first_url,/api/message/parselink, OpenGraph HTML fallback),stickers.rs(sticker store, category detail, Vietnamese keyword search,send_sticker*),reactions.rs(send_reaction,icon_to_emoji,reaction_code_and_type),unread.rs(send_seen_v2,set_unread_mark,set_mute_conversation,get_mute_conversations,MuteControlEvent,extract_mute_controls).
-
Pure Sync vs. SQLite Storage Boundary (
src/protocol/sync/vs.src/storage/):src/protocol/sync/contains zerorusqliteorMessageStoreimports:sync/mod.rs(sync key/status state & cursor helper),sync/controls.rs(pull_mobile_msg,cancel_phone_sync,clean_sync,/api/znoise,MobileSyncControlEvent),sync/zdb4.rs(RSA-2048 sync keys &ZDB4.0decryptor),sync/bin_net.rs(BinNetTLV decoder),sync/v2_proto.rs(proto.Sync2chunk parser),sync/history.rs(thread history cloud fetch loop),sync/phone.rs(pure phone message sync & polling queue drain),sync/container.rs(mobile backup container & Sync V2 chunk download/crypto).src/storage/sync_ingest.rsandsrc/storage/thread_cache.rsown all pure SQLite archive ingestion (extract_conv_archives_from_entries,commit_conv_archives_to_store,commit_mobile_backup_to_store,commit_sync_v2_messages_to_store,commit_phone_sync_to_store,persist_thread_snapshot) andthreads_cache.jsonpersistence (load_threads_cache,save_threads_cache), free ofSessionor HTTP transport.CoreEnginecomposes protocol fetch with storage persistence.
-
Typed Protocol Boundary & UI-Free
CoreEngine(src/core/):- Public endpoints in
src/protocol/return typed structs (SendMessageReceipt,ActionAck,PollBatch,CloudMessagesPage,LastMsgsBatch,MuteSnapshot,QrScannedProfile,QrConfirmResult) instead of rawserde_json::Value. src/core/(CoreEngine,CoreEvent,CoreImageData) contains zeroeguiimports and drives both the GUI worker adapter (src/gui/worker/) and MCP/REST (src/mcp/).
- Public endpoints in
3. Mandatory Module & Boundary Rules Going Forward
- No
rusqliteor local disk cache I/O insidesrc/protocol/(exception: explicit credential persistence insession/persistence.rsand read-only media cache lookup inmessaging/stickers.rs). All SQLite queries, migrations, andthreads_cache.jsonwrites belong insrc/storage/. - All service hosts live exclusively in
src/protocol/endpoints.rs; outbound HTTP endpoints should be declared insrc/protocol/registry/and dispatched viaSession::api_get/Session::api_post. - One cohesive responsibility per file under domain subdirectories: New protocol features must join
auth/,social/,messaging/,session/,registry/, orsync/rather than adding root-level files or expandingsend.rs/threads.rs. Internal helpers shared across siblings staypub(super). - No duplicate wire/JSON helpers: Reuse
crate::protocol::wire::*(includingstrip_vn_diacritics),crate::clock::now_ms, andcrate::crypto::md5_hex_bytesinstead of reimplementing ad-hoc parsers. - Clean cutover over shims: Do not re-add deprecated wildcard re-exports; update callers directly to canonical domain paths.
- Integration fixtures vs. unit tests: Keep focused unit tests inline under
#[cfg(test)] mod tests; place multi-module integration and large binary/JSON fixture tests undertests/protocol_*.rs.
ADR-0003: Tauri v2 Feature-Based TypeScript UI Architecture
- Status: Accepted (Superseded in workspace layout by ADR-0004)
- Date: 2026-11-08
- Author: ngxc
- Deciders: Alolite Core Engineering
1. Context
CoreEngine (src/core/) owns the single live Session, WebSocket push loop, long-poll loop, SQLite persistence, and image/sticker decoding without any GUI framework dependency. To deliver a full-featured native WebView UI alongside the lightweight egui binary and headless --mcp server, the Tauri v2 UI must share CoreEngine directly without duplicating Zalo protocol, crypto, or SQLite logic in TypeScript.
2. Decision
-
Tauri Host (
crates/alolite-desktop/):crates/alolite-desktop/Cargo.tomldepends exclusively onalolite-coreinside the root Cargo workspace, keeping headless CLI/MCP builds free ofwebkit2gtk-4.1.TauriEventSink(crates/alolite-desktop/src/events.rs) implementsCoreEventSinkand forwardsCoreEventDtoover"core-event";crates/alolite-desktop/src/commands.rsexposes 47 thin#[tauri::command]wrappers delegating directly toCoreEngine.
-
WebView-Friendly Core Projections (
src/core/ipc.rs,settings.rs,stickers.rs):CoreImageData::to_png_data_url()encodes decoded RGBA8 buffers into compactdata:image/png;base64,...URLs before crossing IPC.CoreBootstrapSnapshothydrates initial logged-in state, threads,AppSettings, saved accounts, built-in sticker packs, and embedded PNG reaction/logo assets in one round trip.
-
Feature-Based TypeScript Frontend (
apps/desktop/src/):src/app/styles/globals.css: single-source-of-truth Tailwind CSS v4 (@tailwindcss/vite)@theme inlinetoken stylesheet with 3 layers (--rail/--sidebar/--canvasshell,shadcn/uisemantic tokens, and--bubble-in/--bubble-out/--online/--warningchat tokens) for Light (Zalo Slate) and Dark (Zinc Dark) modes.src/app/store/: pureappReducer.tsstate transitions backed byuseAppStore.ts(zustandv5 selector store).src/shared/ui/: centralizedshadcn/uicomponent library built on@radix-ui/*+class-variance-authority+clsx+tailwind-merge(button,input,badge,dialog,dropdown-menu,context-menu,popover,tabs,switch,scroll-area,tooltip,separator,Avatar,ImageViewerModal).src/features/: domain-sliced UI & logic forauth,navigation,threads(virtualized via@tanstack/react-virtual),chat,contacts,sync,settings, anddevtools.- Built with Vite 8, React 19, Tailwind CSS v4, Radix UI /
shadcn/ui, Zustand 5, TanStack Virtual 3, Lucide vector icons, and TypeScript6.0.x(>=6.0.3 <7.0.0).
-
Linux Runtime Packaging Note:
- Tauri v2 (
wry) links dynamically towebkit2gtk-4.1(2.54.xon Arch Linux, GTK3 + libsoup3). Linux distributions should ship.deb/.rpm/PKGBUILDwithwebkit2gtk-4.1declared as a package dependency (or.AppImagebundling WebKit libs), whilealolite(egui/--mcp) remains available for zero-WebKit portable.tar.gztargets.
- Tauri v2 (
ADR-0004: Unified Cargo Workspace (alolite-core, alolite-cli, apps/desktop)
- Status: Accepted (Branch
ui/tauri) - Date: 2026-11-08
- Author: ngxc
- Deciders: Alolite Core Engineering
1. Context
During initial Tauri integration, the repository carried two separate Rust graphs (Cargo.toml at root bundling eframe/egui together with core protocol/storage, plus an isolated ui/tauri/src-tauri/Cargo.toml depending back up on root). That caused:
- Duplicate
Cargo.lockand duplicate multi-gigabytetarget/directories. alolite-tauritransitively compilingeframe,egui,glutin, andwinitdespite running WebKitGTK (~442 MB debug binary).- Three competing
src/trees (src/,ui/tauri/src/,ui/tauri/src-tauri/src/), leftoversrc/bin/probe binaries, and root-level documentation clutter.
2. Decision
- Single Root Cargo Workspace (
Cargo.toml):members = ["crates/alolite-core", "crates/alolite-cli", "crates/alolite-desktop"]so all three Rust crates share a singleCargo.lockandtarget/directory.
- UI-Free Core (
crates/alolite-core/):- Owns
core/,protocol/,storage/,mcp/,services/,common/, andassets/with zeroeframe/eguior WebKit dependencies.
- Owns
- Dual Focused Binaries & Pure TypeScript App:
crates/alolite-cli/(alolite): lightweight headless CLI,--mcpstdio server,--api-onlyREST server,--qrterminal login, and desktop launcher.crates/alolite-desktop/(alolite-desktop): Tauri v2 Rust host embedding../../apps/desktop/dist.apps/desktop/: 100% pure feature-based TypeScript (src/{app,shared,features}/) with zero Rust files insideapps/.
- Root Hygiene:
- Remove legacy
src/gui/(egui, preserved onmainatce798e6), legacysrc/bin/probes, andegui-only fonts (BeVietnamPro,lucide.ttf). - Move
book.toml,DESIGN.md,ROADMAP.md, andLEGAL.mdunderdocs/.
- Remove legacy
3. Measured Release Binary & RAM Benchmark (Arch Linux x86_64, 32 Threads / 961 Messages)
| Mode / Architecture | Release Binary | Processes / Threads (t=10s) | Total PSS (t=10s) | Total Private_Dirty (t=10s) | Total VmRSS (t=10s) |
|---|---|---|---|---|---|
Headless MCP (alolite --mcp) | 8.9 MiB | 1 proc / 13 threads | 7.87 MiB | 1.90 MiB | 10.36 MiB |
Legacy egui (main @ ce798e6) | 16.1 MiB | 1 proc / 43 threads | 85.20 MiB | 47.00 MiB | 118.40 MiB |
Tauri Desktop (alolite-desktop, total 3 procs) | 17.0 MiB | 3 procs / 113 threads | 373.96 MiB | 228.15 MiB | 571.51 MiB |
↳ alolite-desktop (Rust CoreEngine + GTK3 host) | — | 44 threads | 107.99 MiB | 66.30 MiB | 189.70 MiB |
↳ WebKitNetworkProcess (HTTP/TLS cache) | — | 18 threads | 48.73 MiB | 33.56 MiB | 84.90 MiB |
↳ WebKitWebProcess (DOM/CSS/JS + GPU tiles) | — | 51 threads | 217.24 MiB | 128.30 MiB | 296.91 MiB |
API, IPC & Error Handling Standards
This project is a client, not a server. The “API” surface is three boundaries:
| Boundary | Direction | Module |
|---|---|---|
| Zalo HTTP API | outbound | protocol/session/, protocol/registry/, protocol/auth/, protocol/social/, protocol/messaging/ |
| Zalo WebSocket | bidirectional | protocol/socket.rs, protocol/registry/ws.rs |
| UI ↔ Core IPC | in-process | core/ (CoreEngine / CoreEvent) + gui/worker/ (WorkerCmd / GuiEvent) |
Plus local filesystem persistence (src/storage/, protocol/session/persistence.rs).
1. Outbound HTTP Conventions
- Hosts come from
src/protocol/endpoints.rsonly. No literal*.zalo.me/*.zaloapp.comURLs elsewhere. - Command IDs & paths belong in
src/protocol/registry/. Invoke viaSession::api_get/Session::api_post; reusesrc/protocol/wire.rsfor JSON unwrapping,group_stripping, and control flattening. - Every request goes through one path: build params →
ParamCipher v2(param_cipher.rs) →signkey(crypto.rs) → attach session cookies → send. - No ad-hoc
reqwest::Clientper call. Reuse the shared client so cookies and TLS config stay consistent. - Timeouts are explicit on every request; no unbounded awaits.
- Response parsing is strict: decode into
serdestructs, not ad-hocValuewalks on hot paths.
Response Envelope
Zalo responses use { error_code, error_message, data }. Parse once, then branch:
error_code | Meaning | Handling |
|---|---|---|
0 | Success | Return typed data. |
18012 | QR scanned, not yet confirmed | Keep long-polling; no user error. |
18022 | Invalid signature | Bug: wrong signkey parameter set. Do not retry; log and fix. |
18060 | Invalid encryption protocol | Bug: request bypassed ParamCipher v2. Do not retry. |
600 / -102 | zpw_sek missing or expired | Fail closed: clear session, restart QR login. |
114 | Invalid parameter type | Bug: malformed nested JSON. Do not retry. |
429 | Rate limited | Back off exponentially; surface a retry hint. |
Canonical table lives in docs/KHAC_PHUC_SU_CO.md; keep both in sync when a new code is observed.
2. Error Taxonomy
Use anyhow::Result at module boundaries. Add typed errors only where callers must branch on the cause.
| Category | Examples | Retry? | Surface |
|---|---|---|---|
Network | DNS, TLS, timeout, socket reset | Yes, with backoff | “Mất kết nối, đang thử lại…” |
Auth | expired zpw_sek, invalid credentials | No | Prompt re-login |
Protocol | bad signkey, cipher mismatch, decode failure | No (bug) | Log + generic error |
RateLimit | 429 | Yes, honoring delay | “Thao tác quá nhanh, thử lại sau” |
Io | SQLite, file, media read/write | Conditional | Context-specific |
Unsupported | missing ffmpeg, missing audio device | No | Actionable hint |
Rules:
- No
unwrap()/expect()on network, parse, file or user-input paths. Allowed in tests and in true compile-time invariants with a message. ?over manual matching; add.context("...")when the error crosses a module boundary.- Never swallow errors silently.
let _ = ...is only acceptable for best-effort cleanup, and requires a Tier 2 comment. - Never include secrets in error text — no cookies,
zpw_sek,zpw_enk, tokens or rawsession.jsonfragments. - User-facing messages are Vietnamese; log messages are English.
3. Retry & Backoff
- Retry only
NetworkandRateLimitcategories. - Exponential backoff with jitter:
250ms → 500ms → 1s → 2s, capped at 8s, max 4 attempts. - Honor
Retry-After/429delay when present. - Never retry:
- Auth failures (must re-authenticate instead).
- Protocol bugs (
18022,18060,114). - Non-idempotent operations without a stable idempotency key.
- Background polling (
POLL_SECS) is not a retry loop; failures must be logged and the next tick scheduled.
4. Idempotency
- Client-generated message IDs are created once per user action and reused across retries; never regenerate on retry.
- Local persistence is idempotent by
msg_id(INSERT OR IGNORE), so re-delivery cannot duplicate history (INV-4). - Optimistic UI rows reconcile by local message ID; a server echo updates the row, it does not insert a second one.
5. WebSocket Conventions
- Command IDs are constants in
src/protocol/registry/ws.rs; never inline magic numbers. - A push frame is acknowledged/parsed without blocking the read loop; heavy decoding moves to
spawn_blocking. - Reconnect uses jittered backoff and re-authenticates before resubscribing.
- Unknown frame types are logged and skipped, never fatal.
6. UI ↔ Worker IPC
- The UI thread sends
WorkerCmdand rendersWorkerEvent; it never performs I/O (INV-3). - One command variant = one user intent. Do not add a generic
Do(String)escape hatch. - Every command that can fail emits a terminal event (success or error); the UI must not hang on a dropped command.
- Long-running tasks report progress events rather than blocking the channel.
- Channels are unbounded today for UI responsiveness; any producer that can flood must rate-limit at the source.
7. Local Persistence Boundary
src/storage/(MessageStore,sync_ingest) returnsanyhow::Result; callers decide whether the failure is fatal.- A failed history write must never block message delivery or UI rendering.
- Schema and migration rules:
docs/standards/database-and-migrations.md.
8. Two-Tier Architecture & Code-as-SSOT
AloLite enforces a strict separation between upstream server wire responses and in-process frontend IPC:
Tier 1: Upstream Wire Protocol (protocol/)
- Audience: Core protocol engineers working in
crates/alolite-core/src/protocol/. - SSOT: Rust
serde::Deserializestructs (ZaloWireEnvelope,SendMessageReceipt,ActionAck,PhoneLookupResult,ChatMessage, etc.). - Documentation: Living documentation via
cargo doc --document-private-itemswith docstrings (///) and sanitized JSON payload fixtures. The consolidated HTTP/WebSocket wire reference lives inre-notes/14-http-rest-endpoint-catalog.md(index:re-notes/README.md). Upstream schemas are never exposed as public AloLite web documentation to preserve Clean-Room compliance (docs/standards/compliance-and-ip.md). - Isolation: The UI thread and frontend React code never see or parse raw Zalo wire payloads.
Tier 2: Frontend IPC & State Contracts (core/ipc.rs ↔ apps/desktop)
- Audience: Desktop frontend engineers working in
apps/desktop/(React + TypeScript). - SSOT: Rust IPC event projection
CoreEventDtoand snapshotCoreBootstrapSnapshot. - Automated Codegen: Generated via
spectadirectly from Rust structs toapps/desktop/src/shared/types/ipc.generated.ts. JSDoc comments written on Rust structs propagate directly to IDE tooltips. - Drift Prevention: Verified in CI by
cargo test -p alolite-core --test ipc_types_sync. Any modification to Rust IPC structs without matching TypeScript regeneration causes an immediate test failure.
Wire struct convention (Tier 1)
Every protocol function that reads an upstream JSON response names its payload with a typed
*WireData struct instead of walking serde_json::Value inline.
| Rule | Detail |
|---|---|
| Location | Same module as the endpoint function (e.g. social/friends.rs). |
| Name | <Thing>WireData (e.g. LastOnlineWireData, GroupProfileWireData). |
| Derives | #[derive(Debug, Clone, Default, Serialize, Deserialize)] + #[serde(default)]. |
| Field mapping | Mirror the raw Zalo keys with #[serde(rename = "...")] / #[serde(alias = "...")]. |
| Type-inconsistent fields | Keep the field as Option<serde_json::Value> and expose a typed accessor using the existing protocol::wire helpers (val_i64, val_u64, pick_str, unwrap_data). Never add new ad-hoc coercion. |
| Docstring | Four blocks: summary line, # Wire Response Example (sanitized JSON), # Core Transformation, and # Errors on the consuming function. |
| Constructor | pub fn from_value(v: &Value) -> Self { serde_json::from_value(v.clone()).unwrap_or_default() }; the parse must never fail, so an unexpected scalar cannot silently turn a payload into Default. |
| Envelope head | Use wire::ErrorEnvelopeWireData instead of reading error_code / error_message inline. code() treats a missing code as success (0); use code_opt() when “absent” must stay distinct from 0. |
| Shared coercion | Multi-alias lookups keep wire::pick_str; an already-selected field uses wire::field_str so alias order lives in the accessor. |
| Behaviour | Behaviour-preserving: no public signature change, no change to emitted values. |
Reference implementations: protocol/social/friends.rs (FriendWireData,
PhoneProfileWireData), protocol/messaging/polling/parse.rs (ChatMessageWireData,
QuoteWireData), protocol/messaging/unread/mute.rs (MuteSnapshotWireData).
9. Review Checklist
- No hardcoded host outside
endpoints.rs. - New request uses the standard cipher/sign path.
- Error branch added for any new
error_code. - Retries limited to idempotent / transient failures.
- No secret in logs, errors or issue reports.
- New
WorkerCmdhas a matching completion event. - Rust IPC changes re-generate and pass
cargo test -p alolite-core --test ipc_types_sync.
Code Comment Taxonomy & Standards
Core Philosophy
Code tells you HOW. Comments tell you WHY. Expressive naming beats explanatory comments. A comment that restates the code is a defect.
1. The 4-Tier Taxonomy
| Tier | Form | Scope | Mandatory |
|---|---|---|---|
| 1. Contract | /// rustdoc, //! module docs | Public items, shared helpers, non-obvious domain rules | Yes for every pub item |
| 2. Rationale | // prose, // SAFETY: | Non-obvious decisions, protocol quirks, failure modes | Yes where the “why” is not inferable |
| 3. Tracked debt | // TODO(owner-or-issue): | Known gaps | Only when tracked |
| 4. Prohibited | — | Echoes, dead code, changelog tags, non-English prose | Never |
2. Tier 1 — Rustdoc Contracts
Every pub item in lib.rs/modules and every shared test helper carries rustdoc:
#![allow(unused)]
fn main() {
/// Decode a Base64 AES-CBC payload using a 16- or 32-byte key.
///
/// # Errors
/// Returns an error when the Base64 is malformed, the key length is not 16/32,
/// or the PKCS#7 padding is invalid.
///
/// # Invariants
/// - INV-1: callers must pass a key derived from `zpw_enk`, never a raw password.
pub fn decode_aes(key: &[u8], b64: &str) -> anyhow::Result<String> { ... }
}
Required rustdoc sections when applicable:
| Section | Use |
|---|---|
# Errors | Any function returning Result. |
# Panics | Any panic!, unwrap, expect, index or slice that can panic. |
# Safety | Every pub unsafe fn. |
# Invariants | Every INV-N the function enforces (see GLOSSARY.md). |
Module docs explain the module’s role and the protocol surface it implements, in 1–4 lines:
#![allow(unused)]
fn main() {
//! WebSocket transport for Zalo push/pull frames.
//!
//! Frame layout and command IDs are documented in `docs/GIAO_THUC_ZALO.md`.
}
3. Tier 2 — Rationale Comments
Write concise, professional English prose. Explain the constraint, the observed server behaviour, or the failure the code prevents.
#![allow(unused)]
fn main() {
// PC bundle ships a stale service map; the web/QR session returns *.chat.zalo.me hosts.
let host = service("chat").unwrap_or(MSG_CHAT);
}
Rules:
- No artificial prefix such as
// WHY:— the prose itself must be clear. - Put the comment next to the decision, not at the top of a 200-line function.
- Reference the evidence when it is protocol-derived:
// Observed 2026-10-21, error_code 0 (re-notes/...). // SAFETY:is mandatory immediately above everyunsafeblock, naming the invariant that makes it sound.
4. Tier 3 — Tracked Debt
#![allow(unused)]
fn main() {
// TODO(#142): drop this fallback once password login supports 2FA.
// TODO(protocol): revisit when Zalo bumps zpw_ver past 694.
}
- A bare
// TODO: fix thisis banned. - Use an issue number when one exists; otherwise a stable context token (
protocol,perf,ui). - TODOs that outlive a release without an issue must be converted into one.
5. Tier 4 — Prohibited
| Banned | Why | Do instead |
|---|---|---|
// increment counter | Echoes code. | Delete it. |
// get user by id above get_user_by_id() | Noise. | Delete it. |
| Commented-out code | Git preserves history. | Delete it. |
// added by X on 2026-01-01 | Git blame exists. | Delete it. |
// v2 rewrite | Changelog in source. | Put it in the PR/ADR. |
| Non-English prose in source | Mixed-language drift. | English comment; Vietnamese in user-facing strings. |
Banner art (///// ===== /////) | Decoration, not information. | Module docs or plain comments. |
6. Language Policy
- Rust source comments and doc comments: English only.
- User-facing strings: Vietnamese (UI labels, error toasts, CLI help).
- Log messages: English keys/structure, Vietnamese values only when quoting server text.
- Legacy Vietnamese comments are grandfathered, but any file you touch must convert the comments in the region you modify.
7. Review Checklist
- Every new
pubitem has Tier 1 docs with# Errors/# Panicswhere applicable. - Every
unsafeblock has a// SAFETY:justification. - Every non-obvious branch has a Tier 2 rationale or a clearer name.
- Every
TODOnames an issue or a context token. - No commented-out code, banners, author tags or non-English comments added.
Compliance, Intellectual Property & Clean-Room Standards
This document establishes the mandatory intellectual property and legal compliance standards for all human engineers and AI agents contributing to alolite.
1. Core Invariants
1.1 Clean-Room Re-implementation
- Specification-Only Implementation: Analyze only wire formats, parameter schemas, cryptographic handshakes, and public network protocols.
- FORBIDDEN: Committing verbatim decompiled code (from Ghidra, Hopper, IDA, or Wakaru), decompiled C/C++ fragments, or minified JavaScript extracted from
app.asar. - FORBIDDEN: Distributing or vendoring proprietary binary blobs, dynamic libraries (
.dll,.so,.dylib), or compiled helper executables.
1.2 Zero Copyrighted Media Assets in Git
- No Bundled Third-Party Artwork: Never commit proprietary graphic assets to the Git tree:
- Official brand logos, favicons, or application icons.
- Proprietary sticker packs (e.g., Ami Fat Cat, Onion, or artist-copyrighted sticker sets).
- Proprietary audio assets (ring tones, call alerts, notification sounds).
- Dynamic Fetching Requirement: Any user-facing stickers, avatars, or media must be retrieved dynamically over HTTPS into the user’s private cache directory (
~/.cache/alolite/) using active session credentials.
1.3 Trademark & Naming Discipline
- Public Surface: Use the brand display name AloLite exclusively for user-facing surfaces (UI window titles, notifications, desktop entry names, documentation). Technical identifiers (binary names, packages, data directories) strictly use lowercase alolite or alolite-desktop. Do not use trademarked third-party names.
- Internal Structure: Keep protocol logic organized under neutral technical namespaces (
src/protocol/). - Nominative Fair Use: References to the target service are permitted only in technical comments and interoperability notes where necessary to describe protocol compatibility.
1.4 Secret & Session Isolation
session.json, SQLite databases (*.db), authentication cookies, device IMEIs, and session encryption keys (zpw_sek,zpw_enk) are personal user secrets.- They must remain in
.gitignoreand must never be committed to Git under any circumstances.
2. Pull Request Review Checklist
Every pull request must pass this compliance audit before merging:
| Check | Requirement | Violation Action |
|---|---|---|
| Binaries | No .exe, .dll, .so, .asar, or proprietary blobs added. | Immediate rejection. |
| Media Assets | No proprietary stickers, brand logos, or copyrighted audio files added. | Immediate rejection; require dynamic CDN retrieval. |
| Naming | No public-facing branding conflicts or misleading trademark usages. | Require renaming to neutral technical identifiers. |
| Legal Notices | Disclaimers, copyright notices, and license headers remain intact. | Require re-addition before merge. |
Concurrency & Locking Standards
Runtime model: one UI thread (egui), one Tokio runtime owned by CoreEngine (src/core/), blocking work on spawn_blocking, SQLite accessed via CoreEngine/spawn_blocking.
1. Thread Ownership Matrix
| Resource | Owner | Access rule |
|---|---|---|
UI state (egui context, widget state) | UI thread | Never mutated off-thread. |
| Tokio runtime, HTTP client, WebSocket | Worker | UI only sends WorkerCmd. |
SQLite MessageStore | Worker | One connection, no cross-thread sharing. |
session.json / Session | Worker | UI receives snapshots, not handles. |
| Media/sticker caches | Worker (write), UI (read snapshot) | No shared &mut. |
INV-3: the UI thread never blocks on network, disk, crypto or SQLite.
2. Channel Rules
| Channel | Type | Direction | Rule |
|---|---|---|---|
| Commands | tokio::sync::mpsc::UnboundedSender<WorkerCmd> | UI → Worker | One variant per user intent; no generic escape hatch. |
| Events | std::sync::mpsc (UI polled via try_recv) | Worker → UI | Terminal event required for every fallible command. |
| WebSocket | Tokio task | Worker internal | Read loop never blocks on decoding. |
- Sending must never block the UI; use
send/try_sendappropriately and handle a closed channel. - A producer that can flood must rate-limit at the source (polling cadence, coalescing) rather than buffering unboundedly.
- Dropping the receiver must not panic the worker; log and shut down cleanly.
3. Blocking Work
spawn_blockingfor: SQLite, image decode, ZIP/sticker unpack, file hashing.- Never call
block_oninside async context. - Never hold a
MutexGuardacross.await. - File and DB handles stay inside the blocking closure.
4. Shared State
| Tier | Mechanism | When |
|---|---|---|
| Tier 1 — message passing | mpsc channels | Default. Prefer over shared state. |
| Tier 2 — single-writer | worker-owned struct | Mutable state only the worker touches. |
| Tier 3 — shared read | Arc<T> immutable snapshot | UI needs data the worker produced. |
| Tier 4 — lock | std::sync::Mutex / RwLock (short critical sections) | Rare, and only when tiers 1–3 do not fit. |
If a lock is unavoidable:
- Document why in a Tier 2 comment.
- Keep the critical section free of I/O, logging and allocation-heavy work.
- Never acquire a second lock while holding one unless an ordering rule is documented.
5. Lock Ordering & Deadlock Prevention
When multiple resources must be locked:
- Define a global order once (e.g.
session → store → cache). - Acquire in that order everywhere; never invert.
- Prefer try-lock with timeout over indefinite blocking on user-visible paths.
- If ordering cannot be guaranteed, restructure to message passing instead of adding a lock.
6. Failure Policy
| Operation | Policy | Rationale |
|---|---|---|
| UI refresh | Fail-open | Stale view beats a frozen window. |
| Message send | Fail-closed | Never show “sent” when the server rejected it. |
| History write | Fail-open | Local cache loss must not drop a message. |
| Session/auth | Fail-closed | Never continue with an expired credential. |
7. Timeouts & Cancellation
- Every network await has a timeout; no unbounded
await. - Long operations check a cancellation token / channel-closed state between units of work.
- On app shutdown: signal cancellation, drain the command channel, join with a bounded wait, then exit.
- Background tasks that outlive their owner are a leak — tie them to the worker lifetime.
8. Race Checklist
- No shared mutable state without a documented owner.
- No
.awaitwhile holding a lock. - No
block_onin async code; no blocking call on the UI thread. - Every channel send handles a closed receiver.
- Every spawned task has an owner and a termination path.
- Polling loops have a fixed cadence and cannot overlap themselves.
Database & Migration Standards (SQLite)
Persistence is local SQLite via rusqlite (bundled), owned by src/storage/ (MessageStore, threads, messages, importer, sync_ingest, thread_cache). There is no server database and src/protocol/ never imports rusqlite.
1. Schema Conventions
| Rule | Detail |
|---|---|
| Naming | snake_case for tables, columns, indexes. |
| Table names | Plural (messages, threads). |
| Primary keys | Natural stable IDs: msg_id TEXT PRIMARY KEY, thread_id TEXT PRIMARY KEY. No autoincrement surrogate unless justified. |
| Timestamps | INTEGER Unix epoch milliseconds in a ts / last_ts column; name them consistently. |
| Booleans | INTEGER 0/1, column prefixed with is_ (is_outgoing, is_group). |
| Nullability | Explicit. Prefer NOT NULL for identity/lookup columns. |
| Raw payloads | Keep raw_json TEXT for forward-compatible replay; never parse it on the hot path. |
| Foreign keys | PRAGMA foreign_keys = ON per connection when relations are added. |
Current tables: messages (msg_id, thread_id, sender_id, sender_name, text, msg_type, ts, is_outgoing, raw_json), threads (thread_id, name, is_group, last_ts). Extend with new tables, do not overload existing columns.
2. Connection Setup
Every opened connection MUST apply:
PRAGMA journal_mode = WAL; -- concurrent reads while the worker writes
PRAGMA synchronous = NORMAL; -- durability/throughput balance for chat history
PRAGMA busy_timeout = 5000; -- bounded wait instead of instant SQLITE_BUSY
PRAGMA foreign_keys = ON;
Rules:
MessageStoreis not shared across threads. The worker owns the connection; UI never touches SQLite directly (INV-3).- Open
:memory:for tests and fixtures. - Do not hold a
Connectionacross.await; run DB work insidespawn_blockingor a dedicated task.
3. Indexing Strategy
| Index | Purpose |
|---|---|
PRIMARY KEY (msg_id) | Idempotent upsert. |
idx_thread_ts (thread_id, ts) | Thread history pagination (high-selectivity thread_id first). |
| Partial index | For sparse states, e.g. WHERE is_outgoing = 1, when a query proves it. |
- Add an index only with a query that needs it (YAGNI); record the query in the migration comment.
EXPLAIN QUERY PLANbefore merging any index or query that touches history pagination.
4. Query Rules
- No
SELECT *on hot paths. Project only required columns. - Always parameterize (
params![...]); never interpolate values into SQL. - Batch writes inside one transaction (
conn.transaction()), especially history sync. - Upserts are idempotent:
INSERT OR IGNOREthen targetedUPDATE, keyed bymsg_id. - Bounded reads: always
LIMIT; never load an unbounded thread into memory. - Escape/quote identifiers defensively when building any dynamic SQL.
5. Transactions
- Wrap interdependent mutations in one transaction; history insert + thread
last_tsupdate is one unit. - Keep transactions short — no network, crypto or
awaitinside. - On failure, return the error; do not partially commit and log “best effort”.
6. Migration Policy
Schema evolves through versioned, forward-only migrations tracked by PRAGMA user_version.
schema version N = PRAGMA user_version
migrate path: N -> N+1 -> ... -> target
Rules:
| Rule | Detail |
|---|---|
| Single source | Migration list lives in src/storage/ (mod.rs / models.rs); no ad-hoc CREATE TABLE at call sites. |
| Idempotent bootstrap | Fresh DB runs every migration from 0; existing DB runs only missing steps. |
| Forward-only | No down-migrations; ship a compensating migration instead. |
| Atomic step | Each step runs in a transaction and bumps user_version in the same transaction. |
| Startup safety | Migration failure aborts startup with a clear error; never run on a corrupted/unknown newer version. |
| Backup | Before a destructive migration, copy the DB file to <name>.bak-<user_version> when feasible. |
Expand & Contract (SQLite adaptation)
SQLite has limited ALTER TABLE; use the rebuild pattern:
- Expand: create the new table/column (nullable or defaulted); code writes both old and new shapes.
- Backfill: copy/transform rows in a migration transaction.
- Contract: switch reads to the new shape; drop the old table/column in a later release.
Never rename or drop a column in the same release that stops writing to it.
Unsupported-version Guard
If user_version > CURRENT_SCHEMA_VERSION, refuse to open the store and tell the user to upgrade the app — do not silently write into a newer schema.
7. Data Retention & Privacy
- Local history is user data: deletion must be real (
DELETE), not soft-deleted unless the UI exposes restore. session.jsonis never stored in SQLite.- No raw credentials, cookies or tokens in any column.
- Tests use
:memory:or temp files; never the user’s real database.
8. Review Checklist
- New column is
snake_case, typed, and nullable only when justified. - Migration bumps
user_versionatomically and handles fresh + existing DBs. - Hot-path query has explicit projections +
LIMIT+ an index if needed. - Writes are parameterized and idempotent.
- No blocking DB call on the UI thread.
Domain Documentation Standards
Single-context repository: one glossary, one ADR log.
1. Files
| File | Purpose |
|---|---|
GLOSSARY.md | Ubiquitous language: session, protocol, chat, runtime terms + INV-N invariants. |
docs/adr/NNNN-<kebab-name>.md | One architectural decision per file, numbered from 0001. |
docs/adr/README.md | ADR template + index table. |
Do not create GLOSSARY-MAP.md or per-module glossaries; this repo is a single context.
2. Consumption Rules (for agents)
Before exploring or changing the codebase:
- Read
GLOSSARY.md. Use its terms verbatim in issue titles, ADR text, test names and identifiers. - Read the ADRs touching the area you are about to modify.
- If a file is missing, proceed silently — do not flag its absence or propose creating it.
/domain-modelingcreates entries lazily when a term or decision is actually resolved.
If your proposal contradicts an accepted ADR, surface it explicitly:
Contradicts ADR-0003 (single worker owns all network I/O) — reopening because…
3. Glossary Rules
- One term, one definition. Add a row only for domain concepts with a precise meaning in this repo.
- Record avoided synonyms in the
Avoidcolumn — that is what prevents drift. - Every term is testable or observable. Protocol constants, storage fields and runtime roles qualify; generic programming words do not.
- English only, matching the standards language. Everything under
docs/is English; Vietnamese remains only for user-facing UI strings in the application.
4. Invariant Traceability (INV-N)
Invariants are declared once in GLOSSARY.md, then referenced from code and tests.
GLOSSARY.md (INV-N SSOT)
↕
Rustdoc `# Invariants` section on the enforcing function
↕
Test name / assertion tagged "(INV-N)"
Rules:
- Declaration:
INV-Nlives only inGLOSSARY.md; IDs are never reused after removal. - Enforcement: the public function that enforces an invariant documents it under
# Invariantsin rustdoc. - Verification: at least one test names the invariant, e.g.
fn upsert_is_idempotent_by_msg_id_inv4()or an assertion comment// (INV-4). - Changing an invariant requires an ADR when it alters externally observable behaviour.
5. ADR Rules
| Status | Meaning |
|---|---|
proposed | Under discussion; not binding. |
accepted | Binding; code must comply or explicitly supersede. |
superseded by ADR-NNNN | Historical only; do not edit the decision body. |
deprecated | No longer relevant; kept for history. |
- ADRs are append-only: correct with a new ADR, never rewrite an accepted one.
- One ADR per decision. Bundle only tightly coupled choices.
- Include the evidence that justified the decision (capture date, server
error_code, upstream observation) — protocol work is not self-evident. - Link the ADR from the issue and the PR (
docs/adr/0007-...).
6. Project & Package Naming Conventions
See GLOSSARY.md (Product & Workspace Naming) for canonical terms and avoided synonyms:
- Product Display Name:
AloLite(UI headers, window title, desktop entry name, notifications, documentation headers). - Binaries:
alolite(CLI/launcher) andalolite-desktop(GUI desktop host). - Crates & Packages:
alolite-core,alolite-cli,alolite-desktop(Rust workspace) andalolite-desktop(UI packageapps/desktop/package.json).
Git Flow & Pull Request Standards
1. Branch Naming
| Prefix | Use |
|---|---|
feature/<kebab-name> | New capability. |
fix/<kebab-name> | Bug fix. |
hotfix/<kebab-name> | Production patch, branched from the release tag. |
core/<kebab-name> | Architecture, schema, protocol or crypto refactor (Tier 3). |
docs/<kebab-name> | Documentation only. |
chore/<kebab-name> | Tooling, deps, CI. |
- Branch from
main; keep branches short-lived. - One logical change per branch. Do not mix formatting sweeps with behaviour changes.
- Rebase on
mainbefore opening the PR; no merge commits inside a feature branch.
2. Conventional Commits
Format: <type>(<scope>): <summary> — header ≤ 72 characters, imperative mood, no trailing period.
| Type | Use |
|---|---|
feat | New user-visible capability. |
fix | Bug fix. |
refactor | Behaviour-preserving restructure. |
perf | Performance. |
test | Tests only. |
docs | Documentation. |
chore | Build, deps, tooling. |
ci | Workflows, packaging. |
style | Formatting only. |
Scopes (lowercase, module-aligned): auth, core, net, chat, media, mcp, ui, store, crypto, session, ci, docs, harness.
feat(chat): add quote-reply rendering
fix(session): clear expired zpw_sek before QR re-login
refactor(store): move schema bootstrap into versioned migrations
Rules:
- Body explains why, not a file list; use concise
-bullets. - One commit = one atomic, buildable change.
- Breaking protocol/schema changes use
!and an ADR link in the body:feat(store)!: ....
3. Adaptive 3-Tier PR Matrix
| Tier | Scope & risk | Requirements |
|---|---|---|
| Tier 1 — Patch | Typo, comment, docs, dependency bump with no API change. | One-sentence summary, CI green. |
| Tier 2 — Standard | Feature, bugfix, refactor, test. | Conventional Commits, 5-section PR body, tests pass, no new clippy warnings. |
| Tier 3 — Enterprise | Protocol/cipher/schema change, breaking change, release packaging. | Atomic commits, ADR/RFC link, protocol evidence, human audit, manual verification steps. |
Standard PR Body Schema (.github/PULL_REQUEST_TEMPLATE.md)
Every PR opened against main must adhere to the 5-section schema defined in .github/PULL_REQUEST_TEMPLATE.md:
## Summary
<!-- Concise explanation of what this PR changes and the technical rationale -->
## Context
- Resolves: # <!-- If closing an issue, e.g. Resolves: #123 -->
- Relates to: # <!-- If referencing an issue without closing -->
- None <!-- If standalone change -->
## Type
- [ ] feat: New feature
- [ ] fix: Bug fix
- [ ] refactor: Code refactoring
- [ ] perf: Performance improvement
- [ ] test: Testing updates
- [ ] docs: Documentation update
- [ ] ci: CI/CD or workflow update
- [ ] chore: Maintenance or dependencies
## Verification & Evidence
- **Platform(s) Tested**:
- Architecture: [ ] x86_64 [ ] aarch64
- Display Server: [ ] Wayland [ ] X11
- Distribution: <!-- e.g. Arch, Ubuntu 24.04, Fedora 40 -->
- **Evidence**:
- Output / Screenshots / Test logs: <!-- Attach screenshots for UI changes, or paste cargo test output -->
## Checklist
- [ ] `cargo test` passes locally.
- [ ] No proprietary binaries, secrets, or generated files (`target/`, `dist/`, `session*.json`) are committed.
- [ ] No RE code violates the Clean-Room & IP guidelines in `LEGAL.md` and `docs/standards/compliance-and-ip.md`.
- [ ] Documentation updated if introducing new features, flags, or configuration options.
Tier 3 additionally requires: ADR link in ## Summary, protocol capture/evidence reference (re-notes/...), and a rollback note for schema or protocol changes under ## Verification & Evidence.
4. Human Audit & Verification Protocol
- Inspection & proposal only: before committing, run
git statusandgit diff; propose the atomic commit slicing plan and show the formatted Conventional Commit messages. - No secrets in the diff: verify
session.json,*.db,dump/,qr.pngand logs are untracked. - Explicit confirmation required: never run
git commit/git pushuntil a human approves. - Commit bodies use short bullet points, not paragraphs.
5. Review Checklist
- Branch name matches the prefix table.
- Commits are atomic and conventional; header ≤ 72 chars.
-
cargo fmt --allandcargo clippyclean for touched code. -
cargo test --lockedpasses. - Docs/standards updated when behaviour or conventions change.
- ADR added or referenced for Tier 3 decisions.
- No secrets, logs, databases or capture dumps committed.
- PR body follows the tier requirement.
6. Releases
- Release tags follow
v<major>.<minor>.<patch>;v*triggers.github/workflows/release.yml. - A release PR must list the artifact matrix and the tested platforms.
- Never tag from a dirty worktree or an unsigned-off CI run.
Issue Tracking & Triage Standards
Issues, specs and tickets live in GitHub Issues for ngxccc/alolite. Use the gh CLI for every operation.
Source of truth for ticket state. Local markdown notes under
re-notes/are evidence, never tickets.
1. CLI Command Conventions
| Operation | Command | Notes |
|---|---|---|
| Create issue | gh issue create --title "..." --body "..." | Use a heredoc for structured bodies. |
| View issue | gh issue view <number> --comments | Description, labels and discussion. |
| List issues | gh issue list --state open --label "<label>" | Filter by lifecycle, type or area. |
| Comment | gh issue comment <number> --body "..." | Post updates, link PRs, attach evidence. |
| Apply labels | gh issue edit <number> --add-label "<label>" | Update type/area/priority. |
| Close issue | gh issue close <number> --comment "..." | Always close with a resolution summary. |
2. Label Taxonomy
A. Lifecycle (exceptions only)
State lives in the issue itself (open/closed), PR links (Fixes #<id>) and GitHub Projects. Do not maintain in-progress / needs-review labels.
| Label | Meaning |
|---|---|
status:blocked | Waiting on an external dependency, credentials, upstream protocol evidence or another issue. |
wontfix | Closed as out of scope, superseded or rejected. |
B. Type (Conventional Commits alignment)
type:feat, type:fix, type:refactor, type:perf, type:test, type:docs, type:chore, type:ci, type:style, type:task.
C. Area (domain scopes)
| Label | Scope |
|---|---|
area:core | Core engine, background runtime, common utilities and services (crates/alolite-core/src/{core,common,services}). |
area:protocol | Zalo network protocol, wire codecs, cryptographic handshakes, and message sync (crates/alolite-core/src/protocol/). |
area:auth | QR/password login, session.json, zpw_sek / zpw_enk, and trusted device pairing. |
area:net | HTTP endpoints, candidate failover, WebSocket framing, ParamCipher v2, and signkey. |
area:chat | Threads, message identity, reactions, recall, forwarding, and history sync. |
area:store | SQLite schema, migrations, queries, and local offline cache (crates/alolite-core/src/storage/). |
area:mcp | MCP JSON-RPC protocol over stdio/HTTP, local REST daemon, and autoreply rules (crates/alolite-core/src/mcp/). |
area:ui | Native Tauri v2 host and React desktop frontend (apps/desktop/, crates/alolite-desktop/). |
area:cli | Command-line interface, terminal QR login, and desktop launcher (crates/alolite-cli/). |
area:packaging | Linux distribution packages (.deb, .rpm, .AppImage, .tar.gz) under packaging/. |
area:assets | Desktop icons, SVG branding assets, and reaction graphics under assets/ and .github/assets/. |
area:docs | Documentation book (docs/), ADRs, standards, README, and user guides. |
area:ci | GitHub Actions workflows and CI/CD automation (.github/workflows/). |
area:harness | AGENTS.md, AI agent tooling, .omp/, helper scripts, and Makefile. |
D. Priority
| Label | Meaning |
|---|---|
priority:p0 | Critical: data loss, credential exposure, complete outage. |
priority:p1 | Blocks the next release milestone. |
priority:p2 | Normal (default). |
3. Triage Label Vocabulary
Canonical vocabulary consumed by /triage. Do not introduce synonyms.
| Role | Repo representation |
|---|---|
needs-triage | Default: open issue with no type:* / area:* label. |
needs-info | status:blocked + a comment naming the missing evidence. |
ready-for-agent | type:* + area:* set, acceptance criteria present, no open blocker. |
ready-for-human | priority:p0 / priority:p1, or requires protocol evidence / physical device testing. |
wontfix | wontfix label + closing comment. |
4. Native Sub-Issues Protocol
-
Create the child with canonical body format:
gh issue create --title "task(<area>): <summary>" --label "type:task,area:<area>" --body "$(cat <<'EOF' ### Outcome <One-sentence observable behaviour or state when complete.> ### Context <Child task context or sub-problem specification.> ### Acceptance Criteria - [ ] <Specific verifiable condition> ### Non-goals - <Explicit boundaries> EOF )" -
Link it to the parent:
CHILD_ID=$(gh api repos/ngxccc/alolite/issues/<child_number> --jq .id) gh api --method POST repos/ngxccc/alolite/issues/<parent_number>/sub_issues -F sub_issue_id=$CHILD_ID -
Query children:
gh api repos/ngxccc/alolite/issues/<parent_number>/sub_issues \ --jq '.[] | "#\(.number): \(.title)"'
5. Wayfinding
- Map ticket: one issue labeled
wayfinder:map, holding decisions and the fog tracker. - Child tickets: labeled
wayfinder:<research|prototype|grilling|task>and linked as native sub-issues. - Blocking: use native issue dependencies; a ticket is unblocked when every blocker is closed.
6. Ticket Quality Bar
A ticket is actionable only when it adheres to the canonical issue body structure (enforced across .github/ISSUE_TEMPLATE/ and CLI usage):
A. Canonical Body Structure
### Outcome
<One-sentence observable behaviour or state when complete, not file inventory.>
### Context
<Current limitation, background, discrepancy, or reproduction steps.>
### Acceptance Criteria
- [ ] <Specific verifiable condition>
- [ ] <Verification command or test pass criteria>
### Non-goals
- <Explicit non-goal to prevent scope creep.>
B. Checklist Requirements
- One-sentence outcome (observable behaviour, not file inventory).
- Reproduction or acceptance checklist (
- [ ]). - Affected area label (
area:*) and type label (type:*). - Evidence for protocol changes (capture path,
re-notes/reference, servererror_code). - Explicit non-goals when scope is easy to over-read.
C. CLI Heredoc Creation Template
gh issue create \
--title "<type>(<area>): <summary>" \
--label "type:<type>,area:<area>" \
--body "$(cat <<'EOF'
### Outcome
...
### Context
...
### Acceptance Criteria
- [ ] ...
### Non-goals
- ...
EOF
)"
7. Security Rule
Never paste session.json, zpw_sek, zpw_enk, cookies, IMEI or raw captures containing them into an issue. Redact to zpw_sek=<redacted> and attach only sanitized excerpts.
Security & Cryptography Standards
Threat model: local desktop client holding a live Zalo session. The main risks are credential leakage, session theft, and protocol misuse.
1. Secret Inventory
| Secret | Location | Rule |
|---|---|---|
zpw_sek (session cookie) | session.json | Never log, never commit, never send anywhere except Zalo hosts. |
zpw_enk (encryption key) | session.json | Same; derive AES key in memory only. |
| Cookies / IMEI | session.json | Same; IMEI is a hardware identifier. |
| Password | memory only | Never persist, never log. |
| Raw captures | re-notes/, dump/ | Must be sanitized before commit; dump/ is gitignored. |
session.json and *.db are gitignored and documented in SESSION_SECURITY.md. Both rules are non-negotiable.
2. Secret Handling in Code
- Never format a secret into an error, log line, panic message or UI toast.
#![allow(unused)] fn main() { // Bad anyhow!("login failed with cookie {cookie}") // Good anyhow!("login failed: session cookie rejected (error_code 600)") } - Never
Debug-print a session struct; give it a manualDebugthat redacts fields. - Zeroize derived key material after use where practical (
zeroizecrate) or keep its scope minimal. - Compare MACs, hashes and tokens with a constant-time comparison; never
==on secret bytes. - Do not add a dependency that phones home; audit new crates for network behaviour.
3. session.json Lifecycle
- Write atomically (temp file + rename) with restrictive permissions (
0600on Unix). - On read failure/corruption, treat as logged out; never fall back to a default key.
- On expiry (
600/-102), delete the file and restart QR login. - On explicit logout, delete the file.
- Never copy it into logs, crash reports, backups under the repo, or issue trackers.
4. Cryptography Rules
| Primitive | Usage | Rule |
|---|---|---|
| AES-CBC + PKCS#7, zero IV | Zalo params compatibility | Must match the observed server contract; do not “improve” it (INV-1). |
| AES-GCM | Local at-rest payloads where applicable | Fresh random nonce per message; never reuse a nonce. |
| MD5 | signkey only | Protocol compatibility only; never for password or integrity decisions. |
| Random | IDs, salts, nonces | Use OsRng / rand CSPRNG; never time-seeded PRNGs. |
- Crypto changes require an ADR (
docs/adr/) and a known-answer test. - Constant-time comparison is mandatory for any secret comparison.
- Do not invent a new cipher flow; the server rejects it (
18060).
5. Input & Content Safety
- Untrusted content: message text, names, sticker payloads, link previews, file names, raw JSON.
- Render as text; never interpret remote content as markup, commands or paths.
- Validate and bound: lengths, counts, nesting depth, archive entry paths (no path traversal when unpacking stickers/attachments).
- Treat URLs from messages as untrusted: parse and restrict schemes before opening.
- File writes go to app-owned directories with sanitized names; never to an attacker-chosen absolute path.
6. Logging Rules
- Log identifiers (
thread_id,msg_id) anderror_code; never cookies, tokens, passwords, phone numbers or message bodies of others. - Truncate raw payloads (
truncate(&text, 200)) and redact known secret fields before logging. - Logs are local only; do not add remote telemetry without an ADR and explicit user consent.
7. Dependencies & Supply Chain
cargo auditbefore a release; no known-vulnerable dependency ships.- Prefer
rustls(already used) over native TLS for reproducibility. - Pin versions in
Cargo.lock; review lockfile diffs in PRs. - New crypto, network or parsing crates need a one-line justification in the PR.
8. Release & Distribution
- Release artifacts are built by CI from tagged commits; no local unsigned binary is published.
- Do not embed credentials, dev tokens or debug endpoints in release builds.
- Keep
dump/,qr.png,call_relay.json,session*.jsonout of packaging and artifacts.
9. Incident Response
If a secret leaks (commit, issue, screenshot, log):
- Revoke the session from the Zalo mobile app (Login History / Active Sessions).
- Delete the exposed file/comment.
- Rotate anything derived from it.
- Record the incident and the prevention step in an ADR or issue.
10. Review Checklist
- No new secret in code, logs, errors or tests.
- New file writes are atomic and permission-restricted.
- Secret comparisons are constant-time.
- No nonce reuse; randomness from a CSPRNG.
- Untrusted content is bounded and never interpreted as code/paths.
-
cargo auditclean for the change set.
Testing & Fixture Standards
Runner: cargo test --locked (CI runs it on Linux, Windows and macOS). Tests live in the crate they cover.
1. Test Hierarchy
| Level | Location | Naming |
|---|---|---|
| Unit | #[cfg(test)] mod tests at the bottom of the module | mod tests + descriptive fn names |
| Module integration | tests/ directory when multiple modules must cooperate | tests/<area>_integration.rs |
| Protocol fixture | tests/ + re-notes/ fixtures | tests/protocol_<topic>.rs |
Naming pattern: fn <behaviour>_when_<condition>().
#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn upsert_is_idempotent_for_same_msg_id() { /* INV-4 */ }
}
}
Rules:
- One behaviour per test; a failure must name the broken behaviour.
- Tests must not touch the network. Zalo responses are fixtures, never live calls.
- Tests must not read or write the user’s real
session.jsonor database. - Tag assertions that verify a domain invariant with
// (INV-N).
2. Fixtures & Builders
There is no DB-backed factory system; use small builders and static fixtures.
| Pattern | Location | Rule |
|---|---|---|
| Static JSON fixture | tests/fixtures/<name>.json | Sanitized capture; never contains cookies, zpw_sek, zpw_enk, IMEI or phone numbers. |
| Builder | tests/common/mod.rs or inline fn sample_message() | Defaults are valid; override only the field under test. |
| Object mother | fn standard_thread(), fn group_thread() | Named domain presets for readability. |
| In-memory store | MessageStore::open(":memory:") | Mandatory for store tests. |
Rules:
- Fixture files are committed only after redaction; state the source date and
error_codein a companion comment or filename (get_last_msgs_2026-10-21.json). - No fixture may contain real user data.
- Builders return plain structs; no hidden global state.
3. SUT Isolation
- Test the module under test directly; do not route through GUI or worker unless the boundary is the SUT.
- GUI/worker tests assert on emitted
WorkerEvents, not rendered pixels. - Crypto tests are known-answer tests: fixed key + fixed plaintext → fixed ciphertext.
- Network-dependent behaviour is tested by parsing recorded frames, not by calling Zalo.
4. What Must Be Tested
| Area | Minimum coverage |
|---|---|
protocol/crypto.rs | AES roundtrip, known-answer vectors, md5_hex_bytes vector, sign_key parameter set. |
protocol/param_cipher.rs | Encode/decode roundtrip + known-answer vector. |
protocol/registry/ | Strict ID sorting/uniqueness (437 entries), domain fallback coverage, Session candidate resolution, ws::cmd_name. |
storage/ | Upsert idempotency, delete-for-me, thread ordering, ZDB4.0/BinNet archive ingest (INV-4). |
protocol/socket.rs | Frame encode/decode, unknown-frame survival, inflate path. |
protocol/session/ | session.json / device.json roundtrip, cookie attachment, Domains healing/failover, Privacy Guard, expiry handling. |
protocol/messaging/{threads,polling}.rs | ChatMessage wire parsing, PollState, merge_previews/merge_group_history, MessageIdentityIndex (INV-4). |
protocol/endpoints.rs | Service lookup for every key in SERVICE_MAP_V3 and EXTENDED_FALLBACK_MAP. |
Protocol parsing changes require a fixture-backed test. If a case cannot be tested automatically, document manual verification steps in the PR (device, flow, observed error_code). |
5. Test Data & Secrets
- Never use a live session in tests.
- Never commit captured traffic that still contains credentials.
- Use obviously fake identifiers (
user-1,thread-1,msg-0001). - If real data is needed for reproduction, keep it out of Git and describe how to obtain it in
re-notes/.
6. Running Tests
cargo test --locked # full suite
cargo test crypto # filter by module/name
cargo test -- --nocapture # show logs for a failing test
- A PR must not reduce coverage of the module it touches.
- Flaky tests are bugs: fix or quarantine with a tracked
// TODO(#id)and an issue.
7. Benchmarks & Performance Checks
- Any change to the polling loop, media cache or history pagination must include a measurement (before/after) in the PR.
- Benchmark output is a deterministic table or JSON:
task,iterations,min_ms,avg_ms,p50_ms,p95_ms,p99_ms. - No emojis or decorative banners in benchmark output.
- Report the hardware/OS and the dataset size alongside the numbers.
8. Review Checklist
- New behaviour has a test that fails before the change.
- Fixtures are sanitized and dated.
- Store tests use
:memory:. - Invariant assertions are tagged
(INV-N). - No network, no real
session.json, no real user database in tests.