diff --git a/docs/01-ecosystem.md b/docs/01-ecosystem.md new file mode 100644 index 0000000..3f4898e --- /dev/null +++ b/docs/01-ecosystem.md @@ -0,0 +1,62 @@ +# 01 · Ecosystem + +Bansify is a small ecosystem of products that share **one identity**. A user signs in once +at `accounts.bansify.com` and every other product trusts that session. + +## Products and domains + +| Product | Web | Android | Status | +|---|---|---|---| +| Accounts (identity) | `accounts.bansify.com` | `Bansify Accounts` | live | +| Mail | `mail.bansify.com` | `Bansify Mail` (this repo) | live | +| Drive | `drive.bansify.com` | `Bansify Drive` | live (web), app pending | +| Meet | `meet.bansify.com` | — | live | +| Pay (billing) | `pay.bansify.com` | — | live (mock provider) | +| AI | `ai.bansify.com` | `Bansify AI` | live | +| Store | `store.bansify.com` | `Kiwi Store` | live | +| Store admin | `storeadmin.bansify.com` | — | live, admin-only | +| Store console | `storeconsole.bansify.com` | — | live, public developer console | +| GitPlus | `gitplus.bansify.com` | — | live | +| Browser / Launcher / Manager / Computer / Chat / Indogram / Notes / Contacts / Education / PrepMate / PW Parent | — | respective repos | live, APK only | +| Official website | `bansify.com`, `www.bansify.com` | — | live | + +## The identity layer + +``` + ┌────────────────────────────┐ + │ accounts.bansify.com │ sign-in UI + │ api.bansify.com │ OAuth 2.0 + PKCE, sessions, userinfo + └─────────────┬──────────────┘ + │ access token (scoped) + ┌──────────────────┼──────────────────┬─────────────────┐ + ▼ ▼ ▼ ▼ + Mail Worker Drive Worker Store Worker Pay Worker + (scope: mail) (drive.read) (store) (pay) +``` + +- **Clients** are registered in the accounts D1 (`ecosystem_apps`) with their package name, + signing-certificate SHA-256 and allowed scopes. +- **Scopes** are enforced per client. Mail needs + `profile, email, offline_access, mail, account.read, account.profile.write`. + If a scope is missing from the client record, the sign-in fails with + *"requested scope is not permitted"* — fix the client row, not the app. +- **Cookies** are set on `.bansify.com`, so a session started at `accounts.bansify.com` + is visible to every sibling subdomain. `isTrustedOrigin()` in the accounts Worker lists + exactly which origins may make credentialled cross-origin calls (apex, `www`, and the + named first-party subdomains). An origin missing from that list silently looks + "signed out". +- **Native Android sign-in** uses the same OAuth flow through the shared SDK. The + `gothwadRedirectScheme` manifest placeholder must match the application id + (`com.bansify.mail`) or the callback never returns. + +## Naming + +The product is **Bansify**. Older code, database rows and docs may still say +`Gothwad` / `gothwadtech.com` — those are historical. Anything user-visible must say +Bansify and use `*.bansify.com`. + +## What the app must never do + +- Talk to any host other than `mail.bansify.com` (see `MailApiClient.GothwadMailHost`). +- Store tokens outside the SDK's encrypted store. +- Assume the user has only one account — the ecosystem supports up to six slots. diff --git a/docs/02-app-architecture.md b/docs/02-app-architecture.md new file mode 100644 index 0000000..3e937dd --- /dev/null +++ b/docs/02-app-architecture.md @@ -0,0 +1,83 @@ +# 02 · App architecture + +## Shape of the app + +``` +com.bansify.mail +├── MailApplication app startup; initialises the shared Accounts SDK *before* any auth read +├── auth/ MailAuth facade over the SDK, endpoint constants, native auth models +│ └── broker/ peer-to-peer silent sign-in (Binder IPC) for sibling apps +├── data/ +│ ├── local/ Room: entities, DAOs, database +│ ├── model/ MailFolder, ServerFolder, UI models +│ ├── remote/ MailApiClient (OkHttp), API DTOs, error mapping +│ └── repository/ MailRepository — the only thing that touches both sides +└── ui/ + ├── components/ drawer, account switcher, shared widgets + ├── navigation/ MailNavGraph, routes + ├── screens/ inbox, message, compose, settings, signed-out, native auth + └── viewmodel/ MailViewModel + UI state +``` + +## Startup order (this order matters) + +1. `MailApplication.onCreate()` → `GothwadAccounts.init(...)` +2. then `MailAuth` is touched for the first time +3. `MailViewModel` starts, calls `repository.ensureInitialized()`, then observes + `auth.state` and `activeAccountFlow` +4. on `SignedIn`, accounts are copied into Room (`syncAccountsToCache`), then the first + folder refresh runs + +Reading the SDK before `init` throws a `lateinit` crash on launch. This has happened once +(v1.0.42); do not reorder these calls. + +## Data flow + +``` +UI → MailViewModel → MailRepository → MailApiClient (HTTPS + Bearer token) + │ │ + └── Room cache ◄─┘ +``` + +- **Reads** always render from Room first, then refresh from the API. +- **Writes** (send, star, move, delete) go to the API first; the cache is updated from the + response so a failed call never leaves a phantom row. +- **Refresh** replaces only the slice that mirrors the server folder; *Starred* is a + cross-folder view and upserts without deleting. + +## Folders + +The Worker exposes four listable mailboxes: `inbox`, `starred`, `sent`, `drafts`, `trash`. +The UI has more (Primary, Promotions, Social, Updates, Important, All mail, Snoozed, Spam); +`ServerFolder.forMailFolder()` maps each UI folder onto exactly one server folder. + +## Authentication + +`MailAuth` is a thin facade — the app no longer ships its own PKCE client, token store or +callback activity. It exposes: + +| Member | Purpose | +|---|---| +| `state` | `SignedIn` / `SignedOut` / `Initializing` with accounts | +| `accessToken()` | current token, refreshed by the SDK | +| `events` | sign-in / sign-out notifications | +| `signIn()`, `signOut()` | delegated to the SDK | + +The API client attaches `Authorization: Bearer ` **only** to the mail host, and +refuses to send it anywhere else. + +## Error surfacing + +`MailViewModel` records `syncError`; `MailNavGraph` renders it as a banner with a Retry +button. Before this existed a failed fetch looked exactly like an empty mailbox — keep the +banner when changing the shell. + +## Offline behaviour + +Room holds threads, messages and settings. Opening the app offline shows the last synced +state; sending is not queued (the user sees the API error instead of a false "sent"). + +## Instrumentation + +`CrashReporter` records the last fatal error to prefs so the next launch can show it instead +of a blank screen. diff --git a/docs/03-cloudflare.md b/docs/03-cloudflare.md new file mode 100644 index 0000000..5fe8282 --- /dev/null +++ b/docs/03-cloudflare.md @@ -0,0 +1,123 @@ +# 03 · Cloudflare + +Everything Mail runs on Cloudflare: one Worker, one D1 database, one Pages project, plus +DNS, Email Routing and secrets. + +## Components + +| Piece | Name | Purpose | +|---|---|---| +| Worker | `mail` | API at `mail.bansify.com/api/*`; also the `email()` handler for inbound mail | +| D1 | `mail` (`87854cea-7feb-46f3-ab99-2a2137f31105`) | `mail_messages`, `mail_settings` | +| Pages | `bansifymail` | the webmail SPA at `mail.bansify.com` | +| Route | `mail.bansify.com/api/*` → `mail` | API traffic; the rest of the host is Pages | +| Email Routing | catch-all `*@bansify.com` → Worker `mail` | inbound delivery | + +## Worker configuration (`worker/wrangler.toml`) + +``` +name = "mail" +main = "src/index.ts" +route = mail.bansify.com/api/* +D1 = mail + +APP_DOMAIN = "bansify.com" +AUTH_HUB_URL = "https://api.bansify.com" +AUTH_SIGNIN_URL = "https://accounts.bansify.com" +MAIL_URL = "https://mail.bansify.com" +ENVIRONMENT = "production" +DAILY_SEND_LIMIT = "30" # outbound mails per account per day +MAX_INBOUND_BYTES = "10485760" # 10 MB inbound cap +``` + +`ALLOWED_ORIGINS` stays empty in production — the trusted-origin list comes from the +accounts Worker policy, not from a comma-separated override. + +## Secrets (Cloudflare secret store only — never in the repo) + +| Secret | Used for | +|---|---| +| `RESEND_API_KEY` | outbound mail through Resend | +| `ACCOUNTS_INTERNAL_TOKEN` | server-to-server calls to the accounts API | + +Set with `wrangler secret put ` or through the dashboard. Rotating a secret requires +a redeploy of the Worker version that references it. + +## Email: inbound and outbound + +**Inbound** + +1. MX records for `bansify.com` point at `route1/2/3.mx.cloudflare.net` +2. Email Routing's catch-all sends `*@bansify.com` to the Worker +3. the Worker's `email()` handler stores the message in D1 (`folder = 'inbox'`) keyed by + the local part (`to_username`) + +**Outbound** + +- Sent through **Resend** with DKIM on `bansify.com` +- `send_email` binding is intentionally absent — Cloudflare Email Sending requires the + Workers Paid plan +- SPF: `v=spf1 include:_spf.mx.cloudflare.net ~all` +- DKIM: `resend._domainkey.bansify.com`, `resend._domainkey.noreply.bansify.com` +- DMARC: `_dmarc.bansify.com` → `v=DMARC1; p=none; rua=mailto:dmarc@bansify.com; fo=1` + +Deliverability notes: a brand-new domain lands in spam regardless of perfect +authentication. Warm up slowly, ask recipients to mark *not spam*, and move DMARC to +`p=quarantine` after a month of clean reports. + +## Database + +`mail_messages` columns that matter: + +| Column | Notes | +|---|---| +| `id`, `to_username` | `to_username` is the local part of the recipient address | +| `from_email`, `from_name`, `to_email`, `cc_emails`, `bcc_emails` | envelope | +| `subject`, `snippet`, `body_text`, `body_html`, `body_gzip` | body; large bodies are gzipped | +| `folder` | `inbox` \| `sent` \| `drafts` \| `trash` | +| `is_read`, `is_starred`, `provider_id`, `received_at` | state and ordering | + +Indexes exist on `(to_username, folder, received_at)` and starred rows; a full scan here +would burn the D1 read quota quickly. + +## Free-tier limits worth knowing + +| Limit | Free | Paid ($5/mo) | +|---|---|---| +| Databases | 10 | 1,00,000 included | +| Size per database | 500 MB | 10 GB | +| Rows read | 5 M/day | 25 B/month included | +| Rows written | 1,00,000/day | 5 crore/month included | +| Queries per Worker invocation | 50 | 1,000 | + +Attachments and large bodies must not live in D1 — use object storage and keep metadata +here. + +## Deploying + +``` +cd worker +npm install +npx wrangler deploy # uses worker/wrangler.toml +``` + +Then verify: + +``` +curl https://mail.bansify.com/api/health +``` + +The health payload reports which bindings are wired (`d1`, `emailBinding`, `provider`). +A missing binding shows up here before users notice. + +## Hard-won rules + +1. **Always pass explicit `vars` when deploying.** Inheriting bindings has silently + restored stale dashboard values (once pointing at `gothwadtech.com`). +2. **Pages custom domains are one-per-project.** A hostname attached to another project + fails with `8000018 already added`. +3. **A CNAME must point at the project that owns the domain**, otherwise the site 522s. +4. **Zone DNS edits need `Zone:DNS:Edit`** — an account-scoped token returns + `9106 Authentication failed` on DNS and Workers endpoints. +5. **The repo wins.** If you change something in the dashboard, copy it back into + `wrangler.toml` the same day. diff --git a/docs/04-build-and-release.md b/docs/04-build-and-release.md new file mode 100644 index 0000000..dfd9f9a --- /dev/null +++ b/docs/04-build-and-release.md @@ -0,0 +1,67 @@ +# 04 · Build & release + +## Local build + +``` +./gradlew :app:assembleDebug +``` + +The app id is `com.bansify.mail` (debug builds get the `.debug` suffix), `minSdk 26`, +`targetSdk 36`. Version is injected by CI through `-PversionCode` / `-PversionName`. + +## Shared SDK + +The app depends on the published Bansify Accounts SDK: + +``` +com.github.Bansify.accountsapp:core:v1.0.11 +com.github.Bansify.accountsapp:ui:v1.0.11 +``` + +Published from `Bansify/accountsapp` tags via JitPack. Bumping the SDK version is a normal +PR; the manifest placeholder `gothwadRedirectScheme` must stay equal to the application id. + +## CI workflows + +| Workflow | Trigger | What it does | +|---|---|---| +| `android-ci.yml` | push / PR | compiles, runs unit tests, runs the static checkers | +| `release.yml` | tag `v*` | builds, signs, publishes the GitHub Release | +| `planning.yml` | schedule | keeps the planning docs in check | + +## Release artefacts + +Every release publishes: + +| File | Use | +|---|---| +| `BansifyMail-v-Release.apk` | sideload / direct download | +| `BansifyMail-v-PlayStore.aab` | Play Console upload | +| `BansifyMail-v-Debug.apk` | debugging a reported issue | +| `BansifyMail-v-Release.apk.idsig` | Android 11+ incremental install | +| `SHA256SUMS.txt` | integrity check | + +**Downloads in the hub do not use these names.** The website links +`https://store.bansify.com/api/dl/mailapp`, which resolves the newest release and redirects +to its APK. That keeps the link valid across versions — do not put a versioned asset name +into any public page. + +## Signing + +The release keystore is supplied to CI as repository secrets. Nothing signing-related is +committed. If the keystore is lost, Play Store updates are impossible — keep an offline +copy. + +## Versioning + +- `versionCode` increments on every release +- `versionName` follows `MAJOR.MINOR.PATCH` +- the release workflow fails if the tag and `versionName` disagree + +## Checklist before tagging + +1. `tools/check_android_scaffold.py` and `tools/check_docs.py` pass +2. `./gradlew :app:lintDebug` is clean +3. CI green on `main` +4. changelog entry written +5. tag pushed → release workflow publishes diff --git a/docs/05-operations-troubleshooting.md b/docs/05-operations-troubleshooting.md new file mode 100644 index 0000000..6c857e5 --- /dev/null +++ b/docs/05-operations-troubleshooting.md @@ -0,0 +1,77 @@ +# 05 · Operations & troubleshooting + +Symptom → cause → fix, for the failures this project has actually hit. + +## The inbox is empty but webmail shows mail + +**Cause (found once):** `MailViewModel` recorded `syncError` but nothing rendered it, so an +API failure looked identical to an empty mailbox. + +**Check:** open the app, look for the red banner at the top of the canvas. +- *"Your Bansify Account session expired"* → token problem, sign in again +- *"Could not sync Bansify Mail: HTTP 403 …"* → scope problem, see below +- *"Could not sync Bansify Mail: HTTP 500 …"* → Worker error, check `wrangler tail` +- timeout → network + +## Sign-in fails with "requested scope is not permitted" + +The client record in the accounts D1 (`ecosystem_apps`) is missing a scope. +Mail needs `profile, email, offline_access, mail, account.read, account.profile.write`. +Fix the row, then sign in again — existing tokens keep their old scopes. + +## App shows "Sign in" although the user is signed in (web) + +The session probe must hit a real endpoint. A relative `/api/me` on a host without a Worker +returns the SPA's `index.html` with a 200, which used to be read as "signed out". Use +`api.bansify.com/api/auth/me`, and treat only a parsed JSON body with +`authenticated: false` as anonymous. + +Also confirm the calling origin is in the accounts Worker's trusted list — `www.` +was missing once and produced exactly this symptom. + +## Launch crash immediately after install + +The Accounts SDK was read before `GothwadAccounts.init()`. Initialise first, in +`MailApplication.onCreate()`. + +## Keyboard covers the composer / black screen behind it + +`windowBackground` plus a `Surface` wrapper around the content — already applied in +v1.0.46. Do not remove them. + +## Inbound mail never arrives + +1. Email Routing → **Activity** — did Cloudflare accept the message? +2. If it was forwarded instead of delivered, the catch-all still points at an email + address, not the Worker +3. Check the D1 row: `SELECT to_username, subject, received_at FROM mail_messages ORDER BY received_at DESC LIMIT 5` +4. If `to_username` has no matching account, the mail is stored but the app never lists it + — send to the real username + +## Outbound mail lands in spam + +Authentication is not the problem if SPF, DKIM and DMARC all pass. It is domain age and +reputation. Warm up slowly, keep volume low, ask recipients to mark *not spam*, and keep +`DMARC p=none` until reports look clean. + +## Store download links break after a release + +They should not: they point at `store.bansify.com/api/dl/`. If a link 404s, the repo +has no release with an `.apk` asset, or the asset name contains `UNSIGNED`/`Debug` (those +are skipped on purpose). + +## Admin API returns 401 / 403 + +- `401` → no valid session; sign in +- `403 Admin access required` → the username is not in `ADMIN_USERNAMES` (currently + `pawan`), which is a Worker secret + +## Where to look + +| Question | Where | +|---|---| +| Is the Worker healthy? | `GET https://mail.bansify.com/api/health` | +| Did the Worker throw? | `npx wrangler tail mail` | +| Did mail arrive? | Email Routing → Activity | +| Is the token valid? | `GET https://api.bansify.com/api/auth/me` in the browser | +| What did the app send? | `adb logcat -s MailApiClient` | diff --git a/docs/06-development-setup.md b/docs/06-development-setup.md new file mode 100644 index 0000000..b627249 --- /dev/null +++ b/docs/06-development-setup.md @@ -0,0 +1,71 @@ +# 06 · Development setup + +## Requirements + +| Tool | Version | +|---|---| +| JDK | 17 | +| Android SDK | API 36 (target), API 26 (minimum) | +| Gradle | via the wrapper (`./gradlew`) | +| Node | not required for the app; only for the Worker in `Bansify/mail` | + +## First run + +``` +git clone https://github.com/Bansify/mailapp.git +cd mailapp +./gradlew :app:assembleDebug +``` + +JitPack builds the shared SDK on first resolve — the first build is slow, later ones are +cached. + +## Static checkers + +Both must pass before a PR is opened: + +``` +python3 tools/check_android_scaffold.py # manifest, resources, workflow wiring +python3 tools/check_docs.py # required docs and README sections +``` + +They do not compile the app — CI does that. + +## Repository rules + +1. **One change per PR.** Unrelated edits make review and rollback harder. +2. **Never leave a fix only in the Cloudflare dashboard** — commit it, or the next deploy + silently reverts it. +3. **Secrets never enter the repo.** Cloudflare secret store for Workers, GitHub secrets + for CI. +4. **Supplied artwork is copied byte-for-byte.** Verify with `sha256sum`; never redraw. +5. **`TASK.md` is at its size ceiling** — do not append to it; add a new file instead. + +## Branch and merge + +- branch from `main` +- PR title in the imperative: `fix: …`, `feat: …`, `docs: …` +- wait for CI, then squash-merge +- after merging a release-relevant change, tag a version so the APK exists + +## Talking to the API by hand + +``` +# session +curl -i https://api.bansify.com/api/auth/me + +# mail list (needs a bearer token) +curl -H "Authorization: Bearer " \ + "https://mail.bansify.com/api/mail/messages?folder=inbox&limit=10" +``` + +## Where the app's behaviour is decided + +| Behaviour | File | +|---|---| +| Startup order | `MailApplication.kt` | +| Token handling | `auth/MailAuth.kt` | +| Endpoints | `data/remote/MailApiClient.kt` | +| Folder mapping | `data/model/MailModels.kt` (`ServerFolder`) | +| Sync + errors | `ui/viewmodel/MailViewModel.kt` | +| Shell, banner, panes | `ui/navigation/MailNavGraph.kt` | diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..1378d84 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,39 @@ +# Bansify Mail — documentation + +Everything about the Mail Android app, the product it belongs to, and the Cloudflare +infrastructure behind it. + +| Document | What it covers | +|---|---| +| [01 · Ecosystem](01-ecosystem.md) | The Bansify products, domains, the shared Accounts identity and how the apps relate | +| [02 · App architecture](02-app-architecture.md) | Modules, data flow, offline cache, authentication, key classes | +| [03 · Cloudflare](03-cloudflare.md) | The Mail Worker, D1 database, Pages site, DNS, Email Routing and secrets | +| [04 · Build & release](04-build-and-release.md) | CI workflows, signing, versioning, APK/AAB naming, Play Store | +| [05 · Operations & troubleshooting](05-operations-troubleshooting.md) | Symptom → cause → fix for the failures we have actually hit | +| [06 · Development setup](06-development-setup.md) | Local setup, the shared SDK from JitPack, checkers, PR rules | + +## The app in one paragraph + +`Bansify Mail` (`com.bansify.mail`) is a Kotlin/Compose Android client for the Bansify +mail service. It talks only to `https://mail.bansify.com/api`, signs users in through the +shared **Bansify Accounts** SDK, and keeps a Room cache so the inbox opens instantly and +works offline. Inbound mail reaches the Cloudflare Worker through Email Routing, is stored +in the `mail` D1 database, and is fetched by the app over the same API the webmail uses. + +## Repositories in play + +| Repository | Role | +|---|---| +| `Bansify/mailapp` | This app | +| `Bansify/mail` | The Worker API and the webmail at `mail.bansify.com` | +| `Bansify/accounts` | The Accounts Worker — OAuth 2.0 + PKCE, sessions, user directory | +| `Bansify/accountsapp` | The shared Android SDK (`:core`, `:ui`) published to JitPack | +| `Bansify/bansify` | The official website (hub) at `bansify.com` | + +## Ground rules + +1. **The repo is the source of truth.** Never leave a fix only in the Cloudflare + dashboard — commit it, or the next deploy will silently undo it. +2. **Never hard-code secrets.** They live in the Cloudflare secret store only. +3. **Supplied artwork is copied byte-for-byte.** Icons are never redrawn. +4. **Every change ships through a PR** with the static checkers passing.