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
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
| **[`docs/adr/`](docs/adr/)** | Architecture Decision Records: [`ADR 0001`](docs/adr/0001-password-hash-versioning.md) (Password Hashing), [`ADR 0002`](docs/adr/0002-ios-open-source-literature-focus-and-manga-feature-flag.md) (Manga Feature Flag), [`ADR 0003`](docs/adr/0003-comprehensive-catalog-seeding-and-chapter-1-continuity.md) (Catalog Seeding), [`ADR 0004`](docs/adr/0004-render-neon-postgres-deployment.md) (Render + Neon) |
| **[`docs/final_milestone/MASTER_PROGRESS_LOG.md`](docs/final_milestone/MASTER_PROGRESS_LOG.md)** | Chronological engineering progress log across all phases and PRs |
| **[`docs/MAC_LAB_RUNBOOK.md`](docs/MAC_LAB_RUNBOOK.md)** | Step-by-step computer lab setup, grading demo runbook, and troubleshooting |
| **[`docs/WIRELESS_IPHONE_AND_LINUX_SETUP.md`](docs/WIRELESS_IPHONE_AND_LINUX_SETUP.md)** | One-command wireless backend launcher (`start_wireless_server.sh`), Fedora Linux setup, and in-app server switcher |

---

Expand Down Expand Up @@ -149,12 +150,12 @@ Fable is architected around **Feature-Driven Vertical Slices** combined with **M
```
*(All 100 tests must pass, verifying health checks, serialization contracts, Chapter 1 continuity, rate limits, auth hashing, and shelf sync logic).*

5. **Start the FastAPI Development Server:**
5. **Start the FastAPI Development Server (Single-Command Wireless Mode for Mac & Fedora Linux):**
```bash
cd backend
FABLE_ENV=development ../.venv/bin/uvicorn main:app --reload --host 127.0.0.1 --port 8001
./scripts/start_wireless_server.sh
```
* **API Base URL:** `http://127.0.0.1:8001/api/v1`
*(This one command starts Uvicorn on `0.0.0.0:8001` in `development` mode, prints your Home Wi-Fi / Hotspot URL `http://<LAN_IP>:8001/api/v1`, and opens a live HTTPS Cloudflare tunnel `https://<id>.trycloudflare.com/api/v1` for campus/mobile networks. Use `./scripts/start_wireless_server.sh --no-tunnel` for LAN/Simulator-only runs.)*
* **Local API Base URL:** `http://127.0.0.1:8001/api/v1`
* **Interactive Swagger UI:** Open your browser and navigate to `http://127.0.0.1:8001/docs`
* **Health Check:** `curl http://127.0.0.1:8001/api/v1/health`

Expand All @@ -173,9 +174,11 @@ Fable is architected around **Feature-Driven Vertical Slices** combined with **M
* Select an iOS Simulator running **iOS 17.0+** (e.g., **iPhone 16 Pro** or **iPhone 15 Pro**).

3. **Configure the API URL:**
* The `FABLE_API_BASE_URL` Xcode build setting is exposed through the generated Info.plist. It defaults to `http://127.0.0.1:8001/api/v1`, matching the Docker Compose host port.
* For a physical device, set it to the development machine's LAN address, such as `http://192.168.1.20:8001/api/v1`, and bind FastAPI to `0.0.0.0`. For release builds, use the deployed HTTPS API URL.
* ATS allows local networking for development and keeps arbitrary HTTP loads disabled.
* The `FABLE_API_BASE_URL` Xcode build setting is exposed through `frontend/FableApp-Info.plist`. It defaults to `http://127.0.0.1:8001/api/v1`, matching the local Uvicorn and Docker Compose host port.
* **In-App Backend Server URL Switcher (No Rebuild Needed):** Both `WelcomeView` (**"Server: … • Change"**) and `SettingsView` (**"Backend Server URL"**) let you change the active backend URL at runtime (`StoryAPIService.setCustomBaseURL`), automatically appending `/api/v1` if omitted, or switch with one tap to Render Cloud (`https://fable-api-cbo8.onrender.com/api/v1`).
* **Physical iPhone on Home Wi-Fi / Personal Hotspot (Mac or Fedora Linux):** Bind FastAPI to `0.0.0.0` (`uvicorn main:app --reload --host 0.0.0.0 --port 8001`) and enter your computer's LAN address (e.g., `http://192.168.1.20:8001/api/v1`) in the in-app **Backend Server URL** switcher.
* **Physical iPhone on Campus / Isolated Wi-Fi (Wireless Local Backend):** When campus Wi-Fi AP Client Isolation blocks peer-to-peer LAN traffic, expose your local FastAPI server over an instant SSH HTTPS tunnel (`ssh -T -R 80:127.0.0.1:8001 nokey@localhost.run`) and enter the generated `https://<id>.app.lhr.life/api/v1` URL in the in-app **Backend Server URL** switcher—or tap **Use Render Cloud**.
* ATS (`NSAppTransportSecurity` in `frontend/FableApp-Info.plist`) allows local networking for development while keeping arbitrary HTTP loads disabled. `StoryAPIService.iso8601DateDecodingStrategy` supports both fractional-microsecond ISO-8601 timestamps from FastAPI and standard ISO-8601 timestamps.

4. **Build & Launch:**
* Press `Cmd + R` (or click the **Play** button).
Expand Down Expand Up @@ -251,6 +254,8 @@ Fable-IOS/
| **Simulator fails to connect to `127.0.0.1:8001`** | The API container is stopped or the app URL uses a different host port | Start it with `docker compose up -d --build` and verify `curl http://127.0.0.1:8001/api/v1/health`. Keep the Xcode Debug URL on port 8001. |
| **Old cached build artifacts fail** | Previous user left stale build cache | Press `Shift + Cmd + K` (**Product** ➔ **Clean Build Folder**), then press `Cmd + B` to rebuild. |
| **Offline Lab Network (No Internet)** | Campus Wi-Fi blocked or offline computer | Fable reads previously cached stories, chapters, images, and per-account shelf data. A first launch without network has no catalog to display. |
| **Physical iPhone "Untrusted Developer" / "Internet connection required"** | Free Apple ID Personal Team certificate requires one-time verification with `ppq.apple.com` | On the iPhone, temporarily enable **Mobile Data** (if campus Wi-Fi blocks Apple verification), go to **Settings ➔ General ➔ VPN & Device Management**, tap your Developer App profile, and tap **Trust**. |
| **Physical iPhone cannot reach Mac's local IP (`172.x.x.x:8001`) on campus Wi-Fi** | Campus Wi-Fi AP Client Isolation blocks peer-to-peer traffic between wireless clients | Run `ssh -T -R 80:127.0.0.1:8001 nokey@localhost.run` on the Mac and pass `FABLE_API_BASE_URL="https://<id>.app.lhr.life/api/v1"` (or use the deployed Render URL `https://fable-api-cbo8.onrender.com/api/v1`). |

---

Expand Down
32 changes: 20 additions & 12 deletions backend/api/v1/endpoints/auth.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Request, Response, status
from core.rate_limit import extract_client_ip
from schemas import (
Expand Down Expand Up @@ -41,27 +42,34 @@ def request_password_reset(
request: Request,
background_tasks: BackgroundTasks,
):
is_dev_env = os.environ.get("FABLE_ENV", "").strip().lower() == "development"
smtp_settings = None
try:
smtp_settings = load_smtp_settings()
except EmailDeliveryConfigurationError as error:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Password recovery is temporarily unavailable.",
) from error
if not is_dev_env:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Password recovery is temporarily unavailable.",
) from error

client_host = extract_client_ip(request)
enforce_auth_rate_limit("password_reset", client_host, payload.email)
token = auth_service.issue_password_reset_token(payload.email)
if token is not None:
background_tasks.add_task(
deliver_password_reset_email,
smtp_settings,
payload.email,
token,
)
return {
response_body = {
"message": "If an account uses this address, recovery instructions will arrive shortly."
}
if token is not None:
if smtp_settings is not None:
background_tasks.add_task(
deliver_password_reset_email,
smtp_settings,
payload.email,
token,
)
elif is_dev_env:
response_body["recoveryToken"] = token
return response_body


@router.post("/auth/password-reset/confirm", status_code=status.HTTP_204_NO_CONTENT)
Expand Down
7 changes: 6 additions & 1 deletion docs/AGENT_HANDOFF_CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,12 @@ Below is the original file-and-line audit baseline gathered prior to executing *

## 5. Known Gotchas & Compiler Notes from This Session

1. **Swift Closure Type Inference in `StoryStore.swift`:**
1. **ISO-8601 Fractional Microseconds Decoding (`StoryAPIService.iso8601DateDecodingStrategy`):**
- FastAPI/Pydantic serializes UTC timestamps with fractional microseconds (e.g., `"2026-11-16T04:25:03.094537Z"`), whereas Swift's built-in `JSONDecoder.DateDecodingStrategy.iso8601` does not enable `.withFractionalSeconds` and throws `DecodingError.dataCorrupted`. Always use `StoryAPIService.iso8601DateDecodingStrategy` in `frontend/FableApp/Features/Library/Services/StoryAPIService.swift`, which supports both `.withFractionalSeconds` and standard `.withInternetDateTime`.
2. **Physical iPhone `Info.plist` Keys (`FABLE_API_BASE_URL` & `NSAppTransportSecurity`) & Runtime Server URL Override:**
- Xcode's `GENERATE_INFOPLIST_FILE = YES` ignores custom `INFOPLIST_KEY_FABLE_API_BASE_URL` and nested `INFOPLIST_KEY_NSAppTransportSecurity_*` settings unless `<key>FABLE_API_BASE_URL</key><string>$(FABLE_API_BASE_URL)</string>` and `<key>NSAppTransportSecurity</key>` are explicitly declared in `frontend/FableApp-Info.plist`.
- `StoryAPIService.resolvedBaseURL()` dynamically checks `UserDefaults.standard.string(forKey: StoryAPIService.customBaseURLDefaultsKey)` (`"fable_custom_api_base_url"`) before falling back to `FABLE_API_BASE_URL`. Both `WelcomeView` and `SettingsView` expose an in-app **Backend Server URL** switcher (`StoryAPIService.setCustomBaseURL`) so a physical iPhone can switch between a Fedora/Mac LAN backend, an SSH tunnel, and Render Cloud without rebuilding in Xcode.
3. **Swift Closure Type Inference in `StoryStore.swift`:**
- Around line 880 in `StoryStore.swift` (`availableGenres`), keep `let candidates: [(name: String, matcher: (String) -> Bool)] = [...]` as a single typed array literal and filter inside the `for (name, matcher) in candidates` loop (`if !Self.isMangaEnabled && name == "Manga" { continue }`). Splitting it into `candidates.append(contentsOf: [...])` causes Swift compiler error `Cannot infer type of closure parameter '$0' without a type annotation`.
2. **`ReaderTheme` Enum Cases:**
- The dark themes in `ReaderTheme` (`frontend/FableApp/Core/Models/Models.swift`) are `.parchment`, `.sepia`, `.midnight`, and `.oled` (there is **no** `.night` case).
Expand Down
51 changes: 51 additions & 0 deletions docs/MAC_LAB_RUNBOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,57 @@ Before running, clear any potential cache conflicts from previous students:
- Press `Cmd + R` (**Product ➔ Run**).
- The Simulator will launch and display the Library. The catalog loads live Gutenberg metadata and official covers; full text is fetched from the chapter endpoint when a book is opened. Without network access, expect a previously cached library or an empty state.

### Step 5b: Running on a Physical iPhone (USB & Wireless Local Backend)
1. **Connect iPhone via Lightning / USB-C** and verify Xcode/CoreDevice sees it:
```bash
xcrun devicectl list devices
```
2. **Choose how your iPhone will reach the Backend API:**
- **Option A — Home Wi-Fi or iPhone Personal Hotspot (Direct LAN):**
Start FastAPI bound to `0.0.0.0`:
```bash
cd backend
FABLE_ENV=development ../.venv/bin/uvicorn main:app --reload --host 0.0.0.0 --port 8001
```
Use your Mac's Wi-Fi IP (`http://<mac-lan-ip>:8001/api/v1`) as `FABLE_API_BASE_URL`.
- **Option B — Campus Lab Wi-Fi with AP Client Isolation (Wireless Tunnel to Local Backend):**
Campus Wi-Fi routers (`172.22.x.x`) isolate wireless clients from connecting directly to each other's local IP. To use your Mac's local FastAPI server wirelessly from your iPhone, start a free SSH HTTPS tunnel in a second terminal:
```bash
ssh -T -o ServerAliveInterval=30 -R 80:127.0.0.1:8001 nokey@localhost.run
```
Copy the printed `https://<id>.app.lhr.life` address and set `FABLE_API_BASE_URL="https://<id>.app.lhr.life/api/v1"`.
- **Option C — Deployed Cloud Backend (Render + Neon):**
Set `FABLE_API_BASE_URL="https://fable-api-cbo8.onrender.com/api/v1"`.
3. **Build, Sign & Install to the iPhone:**
```bash
xcodebuild -project frontend/FableApp.xcodeproj -scheme FableApp \
-destination 'id=<DEVICE_UDID>' \
DEVELOPMENT_TEAM=<YOUR_TEAM_ID> \
FABLE_API_BASE_URL="https://<id>.app.lhr.life/api/v1" \
-allowProvisioningUpdates build

xcrun devicectl device install app --device <DEVICE_IDENTIFIER> \
~/Library/Developer/Xcode/DerivedData/FableApp-*/Build/Products/Debug-iphoneos/FableApp.app
```
*(If macOS prompts for the Keychain password during `codesign`, enter the current Mac login password and click **Always Allow**).*
4. **Trust the Developer Certificate on Your iPhone (One-Time for Personal Teams):**
- On your iPhone, open **Settings ➔ General ➔ VPN & Device Management**, tap your **Developer App** profile, and tap **Trust**.
- If campus Wi-Fi blocks Apple's certificate verification server (`ppq.apple.com`) and shows *"An internet connection is required"*, temporarily switch your iPhone to **Mobile Data** for 5 seconds, tap **Trust**, and then re-enable Wi-Fi.
5. **Unplug & Use Wirelessly (Including from a Fedora Linux Laptop):**
- Once installed, you can change the backend server URL at any time **directly inside the iPhone app** without Xcode:
- On the **Welcome Screen** (before signing in), tap **"Server: … • Change"** at the bottom.
- Or inside the app, open **Shelf ➔ Settings ➔ Backend Server URL**.
- **Using Your Fedora Linux Laptop (or Mac) as the Wireless Backend in One Command:**
1. Run the unified launcher script from the repository root:
```bash
./scripts/start_wireless_server.sh
```
*(Creates `.venv` if missing, starts FastAPI on `0.0.0.0:8001` with `FABLE_ENV=development`, and prints both your **Home Wi-Fi / Hotspot URL** `http://<lan-ip>:8001/api/v1` and a **Public HTTPS Tunnel URL** `https://<id>.trycloudflare.com/api/v1`.)*
2. On Fedora, if using Home Wi-Fi / Hotspot directly, open port `8001` once: `sudo firewall-cmd --add-port=8001/tcp`.
3. On your iPhone, tap **Server: … • Change** (or **Settings ➔ Backend Server URL**), paste either URL, and tap **Save**.
- **Re-signing / Refreshing the iOS App from Fedora Linux (7-Day Personal Team Expiry):**
- Free Apple ID ("Personal Team") provisioning profiles expire after 7 days. Without a physical Mac, build the `.ipa` on GitHub Actions (`macos-latest` runner) and sideload/refresh it on Fedora using **SideStore** or **`altserver-linux`** (`sudo dnf install usbmuxd libimobiledevice`).

---

## 3. Final Capstone Grading & Demonstration Runbook ("The Hero Path")
Expand Down
Loading
Loading