Files
qurani/docs/architecture.md
T
2026-11-11 20:25:21 +01:00

207 lines
11 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Architecture
## Stack
| Part | Choice |
| --- | --- |
| Website | Next.js (TypeScript), server-side rendering for reading pages |
| API | NestJS (TypeScript) |
| Database | PostgreSQL with full-text search |
| Deployment | Docker Compose on the owner's server behind Traefik |
| Domain | `quran.diyaa.de` (website and API on one host; API under `/api`) |
Package manager is not chosen yet (see `decisions.md`).
## Two data zones
```text
Quran Foundation Content Sync --> qf_* tables --> website pages (server-side only)
Open licensed sources ----------> open_* tables --> website fallback + public API
```
- `qf_*`: content synced from Quran Foundation. Used only by the website's own server-side rendering. Never returned by the public API.
- `open_*`: content from sources whose license allows redistribution with attribution. Used by the public API and as a fallback for the website.
- The two zones have separate tables, separate import code and separate modules. `api/src/public/` must never reference `qf_*`. `scripts/check-invariants.sh` checks this.
- T-002 terms check, 2026-11-11: [Quran Foundation developer terms](https://api-docs.quran.com/legal/developer-terms/) permit display to end users within the application, subject to their conditions, including via a private backend. Redistribution as data through another public API requires a separate signed commercial license. This is a terms review, not a verification of the project's account or access.
## Quran Foundation access
- OAuth2 `client_credentials`. Token URLs: `https://prelive-oauth2.quran.foundation/oauth2/token` and `https://oauth2.quran.foundation/oauth2/token`. Token lifetime 3600 s.
- API hosts: `https://apis-prelive.quran.foundation` and `https://apis.quran.foundation`, path prefix `/content/api/v4`. Headers `x-auth-token` and `x-client-id`.
- Prelive has only surahs 1 and 2. Production has the full dataset. Never mix prelive and production tokens or caches.
- Offline data comes only from Content Sync (`GET /resources/sync`, bootstrap, snapshots, sync tokens, mutation types). Sync at least every 7 days. The Quran text must not be modified.
- The [terms](https://api-docs.quran.com/legal/developer-terms/) limit storage of content not covered by Content Sync to one week, subject to the stated font and Mushaf image exceptions; if connectivity is unavailable for more than seven days, sync promptly when it returns.
- Tafsir rows may cover verse ranges (`start_verse_id` / `end_verse_id`). Verse recitation ids and chapter recitation ids are separate namespaces.
- Credentials live only in the server `.env`. Browser code never sees them.
- Findings from the public Quran.com API are not verified against the Content API: no Arabic translation; tafsir only in Arabic, English, Russian, Bengali, Urdu, Kurdish; none in German, Spanish, Turkish. Verify in T-002.
## Data model (proposed)
Content tables exist once per zone (`qf_` or `open_` prefix):
| Table | Main fields |
| --- | --- |
| chapters | id, names (per language), revelation place, verses count |
| verses | verse_key (`2:255`), chapter id, verse number, text_arabic (exact), text_search (normalized, separate column) |
| translations_meta | resource id, language, author, source, license |
| translations | resource id, verse_key, text |
| tafsirs_meta | resource id, language, author, source, license |
| tafsirs | resource id, start_verse_key, end_verse_key, text |
| reciters | id, name, style, source, license |
| audio_files | reciter id, kind (verse or chapter), verse_key or chapter id, url, duration |
API tables:
| Table | Main fields |
| --- | --- |
| api_clients | id, owner email, created_at, status |
| api_keys | id, client id, key prefix, key hash, created_at, last_used_at, revoked_at, plan |
| usage_counters | key id, day, request count |
Reader data (favorites, bookmarks, notes, folders, last read) is stored in the browser (IndexedDB or localStorage), not in PostgreSQL. Each record has a UUID and an updatedAt so a later account sync stays possible.
## Search
- Arabic: a separate normalized column (marks and tatweel removed; alef variants folded). Display always uses the original text. Decide whether to fold ى/ي and ة/ه (open question).
- Translations: PostgreSQL full-text search with the right language configuration per language.
- Surah names: a small table of names and spellings per language.
## Public API (proposed)
Base: `https://quran.diyaa.de/api/v1`. Auth: header `X-API-Key: <key>`. JSON only. Every translation or tafsir response carries `author`, `source` and `license`.
| Method and path | Returns |
| --- | --- |
| `GET /chapters` | list of chapters |
| `GET /chapters/{id}` | one chapter |
| `GET /verses/{verse_key}` | one verse with optional `translations` |
| `GET /chapters/{id}/verses` | verses of a chapter, paged |
| `GET /translations` | available translations with author and license |
| `GET /tafsirs` | available tafsirs |
| `GET /tafsirs/{id}/{verse_key}` | tafsir entry covering the verse |
| `GET /reciters` | reciters |
| `GET /audio/{reciter_id}/{chapter_id}` | audio file info |
| `GET /search?q=&lang=` | search results |
- Rate limits per key (placeholder: 60 requests per minute and 10,000 per day; to decide).
- Keys are random and high entropy; only a hash (with a server pepper) is stored; the key is shown once.
- Errors use a stable JSON shape with a code. Responses include rate-limit headers.
- OpenAPI document is generated and published on the developer page.
## Website pages
`/` home, `/surah/{n}` reader, `/search`, `/library` (favorites, bookmarks, notes, from the browser), `/reciters`, `/settings`, `/developers` (API docs and key request), `/about` (sources and authors).
## Server (verify before use)
Verification on 2026-11-11: connected via the existing `d-server` SSH alias and queried DNS. The provider firewall is still unverified, so T-001 remains in progress. Results are a snapshot and must be checked again before deployment.
| Item | Observed result |
| --- | --- |
| Host | `ubuntu`, Ubuntu 24.04.5 LTS; `d-server` connects as root to `194.164.60.161` on port 22 |
| DNS | `diyaa.de` resolves to `194.164.60.161`; `quran.diyaa.de` returned NOERROR with no A or AAAA answer. The previous claim that it resolves through a wildcard is not currently true. |
| Host firewall | `ufw` is inactive. TCP ports 22, 80, 443 and 2222 were listening on all IPv4 and IPv6 addresses; Docker rules forward 2222 to a container. Listening does not establish provider-side reachability. |
| Provider firewall | Not checked; provider account access is needed. |
| Reverse proxy | Running container `traefik`, image `traefik:v3.6.25`; its configuration and data are mounted from `/srv/traefik/config` and `/srv/traefik/data`. |
| Docker network | `traefik-public` is a bridge network and Traefik is connected to it; `traefik-net` was absent. |
| Entrypoints | `web` on :80 redirects to HTTPS; `websecure` on :443. |
| Certificate resolver | `le`, HTTP challenge through `web`; storage `/letsencrypt/acme.json`, mounted from `/srv/traefik/data`. |
| Capacity | Root filesystem: 232G total, 212G available; memory: 7.7 GiB total, 5.9 GiB available; no swap. |
Differences from the August 2026 assumptions below: hostname and OS, DNS, host firewall and extra listening port, Traefik paths, network name, and resolver name/storage. The proxy version family and entrypoints match. The deployment example below is a historical template: update its network and resolver references during T-007 after rechecking the server.
Previous assumptions (August 2026):
| Item | Value |
| --- | --- |
| Host | `diya-server`, Debian 12, SSH alias `d-server` |
| Public IP | 194.164.60.161 |
| DNS | `*.diyaa.de` points to the IP; `quran.diyaa.de` resolves via the wildcard |
| Firewall | ufw: 22, 80, 443 only (also check the provider's firewall) |
| Reverse proxy | Traefik v3.6 in `/opt/traefik/` |
| Docker network | `traefik-net` (external, bridge) |
| Entrypoints | `web` (:80, redirects to https), `websecure` (:443) |
| Certificate resolver | `myresolver` (Let's Encrypt HTTP challenge, `/opt/traefik/acme.json`) |
Verify with:
```bash
dig +short quran.diyaa.de
docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'
docker network ls | grep traefik-net
docker inspect traefik --format '{{.Config.Image}}'
ls /opt
ufw status
```
## Deployment layout
| Field | Value |
| --- | --- |
| Folder | `/opt/quran-web` |
| Website container and router | `quran-web`, internal port 3000 |
| API container and router | `quran-api`, internal port 8080 |
| Database container | `quran-db`, private network `quran-internal`, not on `traefik-net` |
| Networks | web and API join `traefik-net` and `quran-internal`; the database only `quran-internal` |
| Ports | no `ports:` on any service |
| Env | `.env` only on the server; `.env.example` in git |
Traefik labels (template; router and service names must be unique on the whole server):
```yaml
services:
quran-web:
build: ./web
container_name: quran-web
restart: unless-stopped
env_file: .env
networks: [traefik-net, quran-internal]
labels:
- "traefik.enable=true"
- "traefik.http.routers.quran-web.rule=Host(`quran.diyaa.de`)"
- "traefik.http.routers.quran-web.entrypoints=websecure"
- "traefik.http.routers.quran-web.tls.certresolver=myresolver"
- "traefik.http.services.quran-web.loadbalancer.server.port=3000"
quran-api:
build: ./api
container_name: quran-api
restart: unless-stopped
env_file: .env
networks: [traefik-net, quran-internal]
labels:
- "traefik.enable=true"
- "traefik.http.routers.quran-api.rule=Host(`quran.diyaa.de`) && PathPrefix(`/api`)"
- "traefik.http.routers.quran-api.priority=100"
- "traefik.http.routers.quran-api.entrypoints=websecure"
- "traefik.http.routers.quran-api.tls.certresolver=myresolver"
- "traefik.http.services.quran-api.loadbalancer.server.port=8080"
quran-db:
image: postgres:16
container_name: quran-db
restart: unless-stopped
env_file: .env
networks: [quran-internal]
volumes:
- quran-pgdata:/var/lib/postgresql/data
networks:
traefik-net:
external: true
quran-internal:
volumes:
quran-pgdata:
```
The API uses the global prefix `/api`, so no path stripping is needed. A "Cannot GET /" or 404 with a valid certificate means Traefik works and the app has no such route: debug the app.
## Security
- Secrets only in the server `.env`.
- Security headers and a strict Content Security Policy; no third-party scripts, fonts or CDNs.
- CORS: the public API allows cross-origin reads only for GET.
- Rate limiting at the API; request size limits; no reader activity in logs.
- Database backups with a tested restore (T-029).