Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions docs/01-ecosystem.md
Original file line number Diff line number Diff line change
@@ -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.
83 changes: 83 additions & 0 deletions docs/02-app-architecture.md
Original file line number Diff line number Diff line change
@@ -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 <token>` **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.
123 changes: 123 additions & 0 deletions docs/03-cloudflare.md
Original file line number Diff line number Diff line change
@@ -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 <NAME>` 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.
67 changes: 67 additions & 0 deletions docs/04-build-and-release.md
Original file line number Diff line number Diff line change
@@ -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<version>-Release.apk` | sideload / direct download |
| `BansifyMail-v<version>-PlayStore.aab` | Play Console upload |
| `BansifyMail-v<version>-Debug.apk` | debugging a reported issue |
| `BansifyMail-v<version>-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
Loading
Loading