diff --git a/.github/workflows/README.md b/.github/workflows/README.md index ae7dd90e2..b1089ece1 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -9,7 +9,8 @@ means a chain: run the steps in order, or one step calls the next. `Test+` marks | Name in Actions | File | When it runs | What it changes | |---|---|---|---| | App+Play: 1. send candidate to Play Console | `app-play-1-candidate.yml` | Manual, from `main` | Sends the Play AAB to Google review, tags `vX.Y.Z-rc.N`, archives the AAB to R2 | -| App+Play: 2. publish release | `app-play-2-release.yml` | Manual, after Google approves the candidate | Final AAB to the Play beta track, final tag, GitHub Release, website APKs on R2, OTA `update.json` | +| App+Play: 2. publish release | `app-play-2-release.yml` | Manual, after Google approves the candidate | Final AAB to the Play beta track, final tag, GitHub Release, website APKs on R2, OTA `update.json`; then calls `app-fdroid-repo.yml` | +| App: publish F-Droid repo | `app-fdroid-repo.yml` | Called by App+Play step 2; manual (staging by default) | F-Droid repo on R2: `fdroid/` (live) or `fdroid-staging/` | | App: Firebase distribution | `app-firebase.yml` | Each push to `main` or to a branch with a ticket key | Tester build on Firebase | | Bins: 1. build static (PRoot) | `bins-1-build.yml` | Weekly (Sunday) and manual | New `binaries-*` release; then calls step 2 | | Bins: 2. archive + retention | `bins-2-archive.yml` | Called by step 1, or manual (dry run option) | Archives binaries to R2, prunes old releases | diff --git a/.github/workflows/app-fdroid-repo.yml b/.github/workflows/app-fdroid-repo.yml new file mode 100644 index 000000000..44ee9ba01 --- /dev/null +++ b/.github/workflows/app-fdroid-repo.yml @@ -0,0 +1,81 @@ +name: "App: publish F-Droid repo" + +# K2GO-421: the self-hosted F-Droid repository on R2 (k2go-apk-repo, prefix fdroid/). +# Design: controller/docs/ADR-K2GO-421-self-hosted-fdroid-repo.md. Tool: tools/fdroid-repo/. +# +# - Called by "App+Play: 2. publish release" after the release APKs are on R2 (staging false). +# - Manual: publish a release that is on R2 already. Staging (default) writes fdroid-staging/, +# a separate repo with its own URL, so the live repo does not change. +# The repo index is signed with the app signing key (the same secrets as the APK). + +on: + workflow_call: + inputs: + tag: + type: string + required: true + staging: + type: boolean + default: false + workflow_dispatch: + inputs: + tag: + description: "Release tag whose fdroid APK is on R2, for example v1.2.0" + required: true + staging: + description: "Publish to fdroid-staging/ instead of the live fdroid/" + type: boolean + default: true + +permissions: + contents: read + +jobs: + publish: + name: Publish the F-Droid repository + runs-on: ubuntu-latest + # Two runs at once would race on the same index. + concurrency: + group: fdroid-repo + cancel-in-progress: false + env: + TAG: ${{ inputs.tag }} + PREFIX: ${{ inputs.staging && 'fdroid-staging' || 'fdroid' }} + BASE_URL: https://k2go-download.appdevforall.org + BUCKET_NAME: k2go-apk-repo + steps: + - name: Checkout Code + uses: actions/checkout@v5 + + - name: Require a release tag + run: | + if ! printf '%s' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then + echo "::error::'$TAG' is not a release tag (vX.Y.Z). Release candidates do not go to the F-Droid repo." + exit 1 + fi + + - name: Unit tests (fdroid-repo) + working-directory: tools/fdroid-repo + run: python3 -m unittest -v test_fdroid_repo + + - name: Decode Keystore + env: + ENCODED_STRING: ${{ secrets.KEYSTORE_BASE64 }} + run: echo "$ENCODED_STRING" | base64 -d > "$RUNNER_TEMP/keystore.jks" + + - name: Publish + env: + AWS_ACCESS_KEY_ID: ${{ vars.CLOUDFLARE_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: auto + R2_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + KEYSTORE_FILE: ${{ runner.temp }}/keystore.jks + KEY_ALIAS: ${{ secrets.KEY_ALIAS }} + KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} + KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }} + WORK: ${{ runner.temp }}/fdroid-work + run: bash tools/fdroid-repo/publish.sh + + - name: Cleanup Keystore + if: always() + run: rm -rf "$RUNNER_TEMP/keystore.jks" "$RUNNER_TEMP/fdroid-work/keystore.jks" diff --git a/.github/workflows/app-play-2-release.yml b/.github/workflows/app-play-2-release.yml index 087a4b502..82d4eb7d9 100644 --- a/.github/workflows/app-play-2-release.yml +++ b/.github/workflows/app-play-2-release.yml @@ -4,7 +4,7 @@ name: "App+Play: 2. publish release" # Run this from main after Google approved a candidate and main says versionName "vX.Y.Z" (the final # commit: same code, only the version line changed). It sends the final AAB to the Play beta track # (Open testing), and only when Play accepts the upload it tags the commit and runs the release build: -# GitHub Release, website APKs, R2 and the OTA update.json. An rc build is never released as final +# GitHub Release, website APKs, R2, the OTA update.json and the F-Droid repo (K2GO-421). An rc build is never released as final # (check-release). Google gives its verdict by email and in Play Console (the API cannot read it). on: @@ -387,3 +387,15 @@ jobs: - name: Cleanup Keystore if: always() run: rm -f keystore.jks + + # K2GO-421: the self-hosted F-Droid repository, from the fdroid APK that the release job put on R2. + fdroid-repo: + name: F-Droid repository + needs: [tag, release] + permissions: + contents: read + uses: ./.github/workflows/app-fdroid-repo.yml + with: + tag: ${{ needs.tag.outputs.tag }} + staging: false + secrets: inherit diff --git a/controller/docs/ADR-K2GO-421-self-hosted-fdroid-repo.md b/controller/docs/ADR-K2GO-421-self-hosted-fdroid-repo.md new file mode 100644 index 000000000..f536c2f26 --- /dev/null +++ b/controller/docs/ADR-K2GO-421-self-hosted-fdroid-repo.md @@ -0,0 +1,108 @@ +# ADR-K2GO-421 : Self-hosted F-Droid repository + +- Status: Accepted (decisions of the maintainer, 2026-11-21) +- Date: 2026-09-24 (draft), 2026-11-21 (decisions and implementation) +- Ticket: K2GO-421 (relates to K2GO-399, "Acceptable to F-Droid?") +- Author: AppDevForAll + +## Decision in one line + +Publish a fdroidserver-generated F-Droid repository of the `fdroid` flavor on the Cloudflare R2 +bucket `k2go-apk-repo` under the prefix `fdroid/`, signed with the app signing key, as an update +channel that we control while the official f-droid.org inclusion (K2GO-399) goes on in parallel. + +## Context (facts, verified 2026-11-21) + +- The release job of `app-play-2-release.yml` builds `standard` and `fdroid` and uploads both + APKs to the root of `k2go-apk-repo` (`K2Go--release.apk`, `K2Go--fdroid-release.apk`). + Public host: `https://k2go-download.appdevforall.org`. +- The `fdroid` flavor has no Firebase and no in-app OTA updater. Crash reports (GlitchTip) start + only after the user turns them on (`CrashReportConsent`, default off, K2GO-579). +- The `standard` APK and the `fdroid` APK have the same signer (apksigner, v1.2.0): + `3a11e9f345e8b4ef79ccb8c819ca0d5392dd8f3febe26abb089c5e2e022fefb5`. A website install and a + repository install can update each other. A Play install cannot: Google signs it with another key. +- An F-Droid repository is static files. The client reads `repo/entry.jar`, then the index that + entry.jar names with its SHA-256 (`index-v2.json`, or `index-v1.jar` for old clients), then + APKs and icons at fixed paths. It never asks for a directory listing. So R2 is sufficient. +- R2 has no directory listing and no implicit `index.html`. Only a person in a browser needs one. + A generated landing page closes that gap, the same as the add-ons gallery + (`appdevforall/plugin-examples`, `tools/addons`). +- Without the previous index, `fdroid update` sets the "added" date of every old version to the + date of the run (tested with fdroidserver 2.4.2). +- `static/` is not a public web root (box nginx, LAN only). It is not used here. + +## Decisions + +- D1. URL. Bucket `k2go-apk-repo`, prefix `fdroid/`: + repository `https://k2go-download.appdevforall.org/fdroid/repo`, landing page + `https://k2go-download.appdevforall.org/fdroid/index.html`. Manual test runs write + `fdroid-staging/`, a separate repository with its own URL. + The QR code of fdroidserver holds the repository address (`.../fdroid/repo?fingerprint=...`). + The F-Droid app reads it, but a phone camera opens it in a browser, and R2 has no object at that + key. So the landing page is also uploaded at the key `fdroid/repo` (no slash). R2 keys are flat: + that key and the `fdroid/repo/...` keys exist side by side, and the F-Droid app never asks for it. + The "Add to F-Droid" button and the QR code on the landing page use + `https://fdroid.link/#?fingerprint=`. The F-Droid app claims + `fdroid.link` as a verified App Link, so Android opens the app directly. Without the app, the + browser shows fdroid.link. The repo address is in the fragment: the browser does not send it to + fdroid.link. (The app claims `fdroidrepos://` for HTTPS repos, but no longer `fdroidrepo://` for + HTTP repos, so a scheme link fails in a local HTTP test.) +- D2. Flavor. The repository ships the `fdroid` flavor. The F-Droid client does the updates, and + this flavor has no in-app updater, so two updaters never compete. (The draft said `standard`.) +- D3. One key. The repository index is signed with the app signing key: the same keystore and the + same GitHub secrets (`KEYSTORE_BASE64`, `KEY_ALIAS`, `KEYSTORE_PASSWORD`, `KEY_PASSWORD`). The + repository fingerprint is then the fingerprint of the app certificate: one fingerprint to check. + - Consequence: a change of this key changes the repository fingerprint. Each user must then + remove the repository and add it again with the new fingerprint. The config change is one line. + - The run checks that the release APK is signed by the key that signs the index, so an APK + signed by another key is never published. +- D4. R2 holds the state. CI keeps nothing between runs. Each run pulls `fdroid/repo/` and + `fdroid/archive/` (indexes and APKs), adds the release APK, runs `fdroid update`, and uploads. + The localized images (`repo//`) are not pulled: they come from `metadata/` on each run. +- D5. Upload order. APKs and images, then the indexes, then `entry.jar`, then the landing page. + Deletions come last. The same rule as `update.json` (ADFA-4984): a published file never names a + file that is not in R2 yet. Before the upload, the run also checks that each file that the new + index names is in the upload. +- D6. History. `archive_older: 3`: the three newest versions in `repo/`, older ones in `archive/` + (also published). +- D7. Cache. `Cache-Control: public, max-age=60` on indexes, `entry.jar` and pages; + one year, immutable, on APKs (the name carries the version) and hashed icons. +- D7b. Look. The landing page uses the look of the add-ons site (`addons.appdevforall.org`, + also static files on R2): the same `styles.css`, logo, header and footer, copied from + `appdevforall/plugin-examples` `site/` into `tools/fdroid-repo/site/`. As on the add-ons site, + the page links its CSS and SVG under `assets/` with a content hash in the name, because the zone + can keep these file types in a browser for hours. The app icon on the page is an SVG that each + run makes from the adaptive icon of the app (`res/drawable/ic_launcher_*.xml`), so the icon has + one source and stays sharp on a phone. The F-Droid index keeps the PNG icon. +- D8. Metadata. `tools/fdroid-repo/metadata/org.appdevforall.k2go.yml`: license + `GPL-3.0-or-later`, source `https://github.com/appdevforall/KnowledgeToGo`, no anti-feature (no analytics, crash reports are opt-in). +- D9. Workflow. `app-fdroid-repo.yml`: called by `app-play-2-release.yml` after the release job + (live `fdroid/`), and manual (`staging` on by default) for a tag whose APK is on R2. + Release candidates never go to the repository. `fdroid update` runs in `debian:trixie` with + fdroidserver from apt. One run at a time (concurrency group `fdroid-repo`). + +## Before the first live publish + +- Run the workflow by hand with `staging` on, add the staging repository in the F-Droid app on a + phone, install, and check the fingerprint. +- Cloudflare: the zone can keep `.jar` files in its cache longer than `Cache-Control` says (the + add-ons work found that the Browser Cache TTL of the zone wins for file types that Cloudflare + caches by default). Add a cache rule for `/fdroid/repo/entry.jar`, `/fdroid/repo/index*` and the + same paths under `/fdroid/archive/` that respects the origin headers. Check `cf-cache-status` + and `age` after the first publish. +- Optional: a URL rewrite so that `/fdroid/` serves `/fdroid/index.html`. + +## Out of scope + +- Official f-droid.org submission and reproducible builds (K2GO-399). Note: an f-droid.org source + build needs the prebuilt native binaries that Gradle fetches from a GitHub Release + (`syncNativeArtifacts`). That is a concern for the official path, not for this repository. +- Removal or change of the OTA updater of the `standard` flavor. + +## References + +- Tool and local test: `tools/fdroid-repo/README.md`. +- Workflows: `.github/workflows/app-fdroid-repo.yml`, `.github/workflows/app-play-2-release.yml`. +- Pattern for a static site on R2: `appdevforall/plugin-examples`, `tools/addons`, + `.github/workflows/publish-addons.yml`. +- F-Droid umbrella: K2GO-399. diff --git a/tools/fdroid-repo/README.md b/tools/fdroid-repo/README.md new file mode 100644 index 000000000..f5d56388f --- /dev/null +++ b/tools/fdroid-repo/README.md @@ -0,0 +1,56 @@ +# fdroid-repo: the self-hosted F-Droid repository (K2GO-421) + +The F-Droid repository of Knowledge to Go is static files on Cloudflare R2: + +| What | URL | +|---|---| +| Repository (add it in the F-Droid app) | `https://k2go-download.appdevforall.org/fdroid/repo` | +| Landing page (for a person in a browser) | `https://k2go-download.appdevforall.org/fdroid/index.html` | +| Staging copy (manual runs) | `https://k2go-download.appdevforall.org/fdroid-staging/...` | + +Design: `controller/docs/ADR-K2GO-421-self-hosted-fdroid-repo.md`. +Workflow: `.github/workflows/app-fdroid-repo.yml`. + +## Files + +| File | Use | +|---|---| +| `publish.sh` | The publish run: pull from R2, `fdroid update`, verify, page, upload. | +| `fdroid_repo.py` | `config`, `qr`, `verify`, `page` and `plan` steps (Python stdlib; `qr` runs in the container with python3-qrcode). | +| `test_fdroid_repo.py` | Unit tests: `python -m unittest -v test_fdroid_repo` | +| `metadata/org.appdevforall.k2go.yml` | App text for the F-Droid client. The version, permissions and signer come from the APK. | +| `site/` | The landing page: `page.template.html`, and the look of the add-ons site (`styles.css` and `adfa-logo.svg` copied from `appdevforall/plugin-examples` `site/`; `fdroid.css` for this page only). | +| `r2_mock_server.py` | Local test: serves a folder the way R2 does (no listing, no implicit index). | + +## Rules that the run keeps + +- R2 holds the state. Each run pulls `fdroid/repo/` and `fdroid/archive/`. Without the old index, + `fdroid update` sets the "added" date of each old version to the date of the run. +- The repo index is signed with the app signing key (the same GitHub secrets as the APK). + So the repo fingerprint is the fingerprint of the app certificate. +- `verify` stops the run before the upload when the release APK is not in the index, when another + key signed it, or when the index names a file that is not there. +- Upload order: APKs and images, then the indexes, then `entry.jar`, then the landing page. + Deletions come last. A published file never names a file that is not in R2 yet. + +## Local test + +Needs Docker and Python 3. Use a test keystore and an APK signed with it: the release key stays +in CI. + +```sh +# A local folder is the bucket. Put the APK at its root, as the release job puts it on R2. +mkdir -p /tmp/bucket && cp K2Go-v1.2.0-fdroid-release.apk /tmp/bucket/ +export KEY_ALIAS=... KEYSTORE_PASSWORD=... KEY_PASSWORD=... +TAG=v1.2.0 PREFIX=fdroid BASE_URL=http://localhost:8080 KEYSTORE_FILE=test.jks \ + LOCAL_BUCKET=/tmp/bucket bash tools/fdroid-repo/publish.sh +python tools/fdroid-repo/r2_mock_server.py --root /tmp/bucket --port 8080 +# Open http://localhost:8080/fdroid/index.html +``` + +To test from a phone on the same Wi-Fi: set `BASE_URL=http://:8080` +in the publish run (the index, the QR code and the "Add to F-Droid" link carry this address), +then start the server with `--bind 0.0.0.0`. The firewall of the computer must let the port in. + +`FDROID_IMAGE` selects the Docker image for `fdroid update` (default `debian:trixie`, which installs +`fdroidserver` from apt on each run). diff --git a/tools/fdroid-repo/fdroid_repo.py b/tools/fdroid-repo/fdroid_repo.py new file mode 100644 index 000000000..4e9ab0b5e --- /dev/null +++ b/tools/fdroid-repo/fdroid_repo.py @@ -0,0 +1,502 @@ +"""Self-hosted F-Droid repository of Knowledge to Go on Cloudflare R2 (K2GO-421). + +Design: controller/docs/ADR-K2GO-421-self-hosted-fdroid-repo.md. + +R2 has no server code and no directory listing. The F-Droid client does not +need them: it reads repo/entry.jar, then the index that entry.jar names, then +APKs and icons, at fixed paths. A person in a browser gets index.html, which +this script makes from the signed index. + +The workflow app-fdroid-repo.yml runs the steps. Each one is a subcommand: + + config write config.yml for fdroid update. It holds no secret: the keystore + passwords and the key alias come from environment variables. + qr write the QR code of the "add this repository" link (in the container). + verify stop when the release APK is not in the index, or another key signed it. + page write the landing page /index.html from repo/index-v2.json. + plan print the upload order (and the deletions) for the R2 copy. + +Python stdlib only. Tests: python -m unittest -v test_fdroid_repo +""" + +import argparse +import datetime as dt +import hashlib +import html +import json +import re +import sys +from pathlib import Path, PurePosixPath + +APP_ID = "org.appdevforall.k2go" +HERE = Path(__file__).resolve().parent +# The QR code of the add_repo_link(), next to the landing page (publish.sh makes it). +ADD_REPO_QR = "add-repo-qr.png" +# The look of the add-ons site (appdevforall/plugin-examples, site/): the page links these files +# under assets/ with a content hash in the name. Cloudflare can keep a .css or .svg in a browser +# for hours whatever Cache-Control says, so new bytes get a new name (the add-ons site does the same). +SITE = HERE / "site" +SITE_ASSETS = ("styles.css", "fdroid.css", "adfa-logo.svg") +# The app icon on the page is an SVG made from the adaptive icon of the app (one source for the +# icon: these vector drawables). A PNG of 512 px goes soft on a phone screen at 3x density. +APP_RES = HERE.parent.parent / "controller" / "app" / "src" / "main" / "res" / "drawable" +ICON_LAYERS = (APP_RES / "ic_launcher_background.xml", APP_RES / "ic_launcher_foreground.xml") +ICON_ASSET = "k2go-icon.svg" + +# The repo folders that fdroid update writes and that go to R2. status/ is the +# run log of fdroidserver: it stays local. +REPO_DIRS = ("repo", "archive") +LOCAL_ONLY = ("status/",) + +TYPES = { + ".apk": "application/vnd.android.package-archive", + ".jar": "application/java-archive", + ".json": "application/json", + ".xml": "application/xml", + ".html": "text/html; charset=utf-8", + ".css": "text/css", + ".png": "image/png", + ".jpg": "image/jpeg", + ".svg": "image/svg+xml", +} +SHORT = "public, max-age=60" +LONG = "public, max-age=31536000, immutable" + +# minSdk -> the Android version that a person knows. +ANDROID = {21: "5.0", 22: "5.1", 23: "6.0", 24: "7.0", 25: "7.1", 26: "8.0", + 27: "8.1", 28: "9", 29: "10", 30: "11", 31: "12", 32: "12L", + 33: "13", 34: "14", 35: "15", 36: "16"} + + +# --- config -------------------------------------------------------------------------------- + +def config_yml(repo_url: str, keystore: str) -> str: + """config.yml for fdroid update. + + The repo index is signed with the app signing key (decision of the + maintainer, K2GO-421): the same keystore and the same GitHub secrets that + sign the APK. fdroidserver reads {env: NAME} values from the environment, + so no secret is in the file. + """ + url = repo_url.rstrip("/") + if not url.endswith("/repo"): + raise ValueError(f"repo URL must end with /repo: {repo_url}") + archive = url[: -len("/repo")] + "/archive" + return "\n".join([ + "# Written by tools/fdroid-repo/fdroid_repo.py config. Do not edit.", + f"repo_url: {json.dumps(url)}", + 'repo_name: "Knowledge to Go (App Dev for All)"', + 'repo_description: "The F-Droid repository of Knowledge to Go, self-hosted by ' + 'App Dev for All. It ships the F-Droid flavor of the app, signed with the same key ' + 'as the downloads on the website."', + "repo_icon: k2go.png", + f"archive_url: {json.dumps(archive)}", + 'archive_name: "Knowledge to Go (App Dev for All) archive"', + 'archive_description: "Older versions of Knowledge to Go."', + "archive_icon: k2go.png", + # Keep the three newest versions in repo/; older ones move to archive/. + "archive_older: 3", + f"keystore: {json.dumps(keystore)}", + "repo_keyalias: {env: KEY_ALIAS}", + "keystorepass: {env: KEYSTORE_PASSWORD}", + "keypass: {env: KEY_PASSWORD}", + "", + ]) + + +# --- page ---------------------------------------------------------------------------------- + +def esc(value) -> str: + return html.escape(str(value), quote=True) + + +def en(localized) -> str: + """The en-US value of a localized field, else the first value.""" + if not localized: + return "" + return localized.get("en-US") or next(iter(localized.values())) + + +def size(n: int) -> str: + return f"{n / 1048576:.1f} MB" + + +def day(ms: int) -> str: + return dt.datetime.fromtimestamp(ms / 1000, dt.timezone.utc).strftime("%Y-%m-%d") + + +def spaced(hex_value: str) -> str: + h = hex_value.replace(":", "").replace(" ", "").upper() + return " ".join(h[i:i + 2] for i in range(0, len(h), 2)) + + +def add_repo_link(address: str, fingerprint: str) -> str: + """The link that opens the "add repository" screen of the F-Droid app. + + The F-Droid app claims https://fdroid.link as a verified App Link, so Android + opens the app directly. Without the app, the browser shows fdroid.link, which + explains how to get F-Droid. The repo address is in the fragment (after "#"), + so the browser does not send it to fdroid.link. The app no longer claims the + fdroidrepo:// scheme of plain-HTTP repos; this link works for HTTP and HTTPS. + """ + fp = fingerprint.replace(":", "").replace(" ", "").upper() + return f"https://fdroid.link/#{address.rstrip('/')}?fingerprint={fp}" + + +def hashed_name(name: str, data: bytes) -> str: + """styles.css -> styles.<8 hex of sha256>.css""" + stem, _, suffix = name.rpartition(".") + return f"{stem}.{hashlib.sha256(data).hexdigest()[:8]}.{suffix}" + + +ANDROID_NS = "{http://schemas.android.com/apk/res/android}" +# Adaptive icon: a 108 dp canvas; every launcher mask shows at least its central 66 dp. +CANVAS_DP, SAFE_DP = 108, 66 +# The only attributes the converter knows. Anything else stops the run: a half-drawn icon on +# the public page is worse than a failed publish. +VECTOR_ATTRS = {"width", "height", "viewportWidth", "viewportHeight"} +GROUP_ATTRS = {"scaleX", "scaleY", "translateX", "translateY", "pivotX", "pivotY", "rotation"} +PATH_ATTRS = {"pathData", "fillColor", "fillAlpha"} + + +def _num(value) -> str: + v = float(value) + return f"{0.0 if v == 0 else v:g}" # no "-0" in the SVG + + +def _color(value: str) -> tuple: + """#RGB, #RRGGBB or #AARRGGBB -> (#RRGGBB, opacity).""" + if not re.fullmatch(r"#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})", value): + raise ValueError(f"color {value!r}: only #RGB, #RRGGBB and #AARRGGBB are known") + h = value[1:] + if len(h) == 3: + h = "".join(c * 2 for c in h) + if len(h) == 8: + return "#" + h[2:], int(h[:2], 16) / 255 + return "#" + h, 1.0 + + +def _check(node, known: set) -> dict: + attrs = {} + for key, value in node.attrib.items(): + if not key.startswith(ANDROID_NS): + continue + name = key[len(ANDROID_NS):] + if name not in known: + raise ValueError(f"<{node.tag} android:{name}> is not known to the SVG converter") + attrs[name] = value + return attrs + + +def _svg_children(node) -> list: + out = [] + for child in node: + if child.tag == "group": + a = _check(child, GROUP_ATTRS) + px, py = float(a.get("pivotX", 0)), float(a.get("pivotY", 0)) + tx, ty = float(a.get("translateX", 0)), float(a.get("translateY", 0)) + # Android: scale and rotate about the pivot, then translate. + transform = (f"translate({_num(tx + px)} {_num(ty + py)}) " + f"rotate({_num(a.get('rotation', 0))}) " + f"scale({_num(a.get('scaleX', 1))} {_num(a.get('scaleY', 1))}) " + f"translate({_num(-px)} {_num(-py)})") + out.append(f'' + "".join(_svg_children(child)) + "") + elif child.tag == "path": + a = _check(child, PATH_ATTRS) + if "fillColor" not in a: + # Android draws no fill when fillColor is missing (SVG would draw black). + out.append(f'') + continue + fill, opacity = _color(a["fillColor"]) + opacity *= float(a.get("fillAlpha", 1)) + extra = "" if opacity == 1 else f' fill-opacity="{_num(opacity)}"' + out.append(f'') + else: + raise ValueError(f"<{child.tag}> is not known to the SVG converter") + return out + + +def launcher_svg(background: Path, foreground: Path) -> str: + """The adaptive launcher icon of the app (two vector drawables) as one square SVG. + + The SVG shows the central 66 dp of the 108 dp canvas: the area that every launcher mask + shows. The rest of the canvas is a margin for masks, and with it the icon looks small. + """ + import xml.etree.ElementTree as ET + fg = ET.parse(foreground).getroot() + bg = ET.parse(background).getroot() + fa, ba = _check(fg, VECTOR_ATTRS), _check(bg, VECTOR_ATTRS) + w, h = float(fa["viewportWidth"]), float(fa["viewportHeight"]) + sx, sy = w / float(ba["viewportWidth"]), h / float(ba["viewportHeight"]) + vw, vh = w * SAFE_DP / CANVAS_DP, h * SAFE_DP / CANVAS_DP + box = f"{_num((w - vw) / 2)} {_num((h - vh) / 2)} {_num(vw)} {_num(vh)}" + return (f'' + f'' + "".join(_svg_children(bg)) + "" + + "".join(_svg_children(fg)) + "\n") + + +def write_assets(work: Path, site: Path = SITE, icon_layers: tuple = ICON_LAYERS) -> dict: + """Write the site assets to /assets/ under hashed names. Returns name -> URL path.""" + out = work / "assets" + out.mkdir(parents=True, exist_ok=True) + files = {name: (site / name).read_bytes() for name in SITE_ASSETS} + files[ICON_ASSET] = launcher_svg(*icon_layers).encode("ascii") + urls = {} + for name, data in files.items(): + target = out / hashed_name(name, data) + target.write_bytes(data) + urls[name] = f"assets/{target.name}" + return urls + + +def render(index: dict, fingerprint: str, template: str, assets: dict = None) -> str: + repo = index["repo"] + address = repo["address"].rstrip("/") + package = index["packages"][APP_ID] + meta = package["metadata"] + versions = sorted(package["versions"].values(), + key=lambda v: v["manifest"]["versionCode"], reverse=True) + latest = versions[0] + manifest = latest["manifest"] + min_sdk = manifest["usesSdk"]["minSdkVersion"] + + rows = "\n".join( + f'{esc(v["manifest"]["versionName"])}' + f'{esc(day(v["added"]))}' + f'{esc(size(v["file"]["size"]))}' + f'APK' + for v in versions) + + values = { + "repo_name": esc(en(repo["name"])), + "repo_description": esc(en(repo.get("description"))), + "address": esc(address), + "add_link": esc(add_repo_link(address, fingerprint)), + "fingerprint": esc(spaced(fingerprint)), + "app_name": esc(en(meta["name"])), + "summary": esc(en(meta.get("summary"))), + "version": esc(manifest["versionName"]), + "version_code": esc(manifest["versionCode"]), + "updated": esc(day(latest["added"])), + "apk_size": esc(size(latest["file"]["size"])), + "apk_sha256": esc(latest["file"]["sha256"]), + "android": esc(ANDROID.get(min_sdk, f"API {min_sdk}")), + "abis": esc(", ".join(manifest.get("nativecode", [])) or "all"), + "signer": esc(spaced(manifest["signer"]["sha256"][0])), + "source": esc(meta.get("sourceCode", "")), + "license": esc(meta.get("license", "")), + "rows": rows, + "generated": esc(day(repo["timestamp"])), + "asset_qr": esc(ADD_REPO_QR), + } + for name, url in (assets or {}).items(): + values[f"asset:{name}"] = esc(url) + out = template + for key, value in values.items(): + out = out.replace("{{" + key + "}}", value) + return out + + +# --- plan ---------------------------------------------------------------------------------- + +def stage(rel: str) -> int: + """Upload stage of a file in the work folder. Lower stages go first. + + The client trusts entry.jar, and entry.jar names the index, and the index + names APKs and icons. So upload in the other direction: a file is in R2 + before any published file names it (the same rule as update.json, ADFA-4984). + """ + name = PurePosixPath(rel).name + if name in ("entry.jar", "entry.json"): + return 3 + if name.startswith("index-v") or name in ("index.jar", "index.xml") or "/diff/" in rel: + return 2 + if rel == "index.html": # the landing page, at the top of the prefix + return 4 + return 1 # APKs, icons, screenshots, the QR image, index.html of fdroidserver + + +def cache_control(rel: str) -> str: + # An APK name carries its version; a localized icon or a site asset name carries its hash. + name = PurePosixPath(rel).name + if (name.endswith(".apk") or (name.startswith("icon_") and "/" in rel) + or rel.startswith("assets/")): + return LONG + return SHORT + + +def local_files(work: Path) -> list: + """Relative POSIX paths of the files to publish, from the work folder.""" + found = [] + for d in REPO_DIRS + ("assets",): + base = work / d + if not base.is_dir(): + continue + for p in base.rglob("*"): + if not p.is_file(): + continue + rel = p.relative_to(work).as_posix() + if any(rel[len(d) + 1:].startswith(x) for x in LOCAL_ONLY): + continue + found.append(rel) + for top in (ADD_REPO_QR, "index.html"): + if (work / top).is_file(): + found.append(top) + return found + + +def plan(files: list, prefix: str, remote: list) -> list: + """Upload lines, then delete lines, as tuples. + + ("put", key, rel, content_type, cache_control) and ("rm", key). + Deletions come last: an APK that moved from repo/ to archive/ stays at its + old key until the new index (that no longer names it) is up. A remote key + that is not under repo/ or archive/ is never deleted. + """ + prefix = prefix.strip("/") + remote = set(remote) + lines = [] + for rel in sorted(files, key=lambda r: (stage(r), r)): + key = f"{prefix}/{rel}" + # An APK key carries its version, so its bytes never change: an APK that + # is in R2 already is not sent again (each one is about 40 MB). + if rel.endswith(".apk") and key in remote: + continue + lines.append(("put", key, rel, + TYPES.get(PurePosixPath(rel).suffix, "application/octet-stream"), + cache_control(rel))) + # The repo address itself ("/repo", often with "?fingerprint=..."): a person can type + # or paste it in a browser, and the QR code on repo/index.html of fdroidserver holds it. R2 has + # no object there, so the landing page also goes to that key (no slash). Its relative links + # resolve the same from there. Do not remove it: the browser then shows "Object not found". + if "index.html" in files: + lines.append(("put", f"{prefix}/repo", "index.html", TYPES[".html"], SHORT)) + keep = {f"{prefix}/{rel}" for rel in files} + owned = tuple(f"{prefix}/{d}/" for d in REPO_DIRS) + for key in sorted(remote): + if key.startswith(owned) and key not in keep: + lines.append(("rm", key)) + return lines + + +# --- verify -------------------------------------------------------------------------------- + +def verify(index: dict, tag: str, fingerprint: str) -> None: + """Stop the publish when the new index is not what this release expects. + + The release APK must be in the index, and its signer must be the key that + signed the index: the repo and the app share one key (K2GO-421). So an APK + that the release key did not sign is never published. + """ + fp = fingerprint.replace(":", "").replace(" ", "").lower() + versions = index["packages"].get(APP_ID, {}).get("versions", {}).values() + found = [v for v in versions if v["manifest"]["versionName"] == tag] + if not found: + raise ValueError(f"{tag} is not in the index") + signers = found[0]["manifest"]["signer"]["sha256"] + if signers != [fp]: + raise ValueError(f"{tag} is signed by {signers}, the repo by {fp}") + + +def named_files(node) -> set: + """Every file that an index-v2 names: a dict with "name" and "sha256".""" + found = set() + if isinstance(node, dict): + if isinstance(node.get("name"), str) and "sha256" in node: + found.add(node["name"]) + for value in node.values(): + found |= named_files(value) + elif isinstance(node, list): + for value in node: + found |= named_files(value) + return found + + +def missing_files(index: dict, repo_dir: Path) -> list: + return sorted(n for n in named_files(index) if not (repo_dir / n.lstrip("/")).is_file()) + + +# --- CLI ----------------------------------------------------------------------------------- + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = parser.add_subparsers(dest="cmd", required=True) + + c = sub.add_parser("config", help="write /config.yml") + c.add_argument("--work", type=Path, required=True) + c.add_argument("--repo-url", required=True) + c.add_argument("--keystore", required=True, help="keystore path, seen from the work folder") + + p = sub.add_parser("page", help="write /index.html") + p.add_argument("--work", type=Path, required=True) + p.add_argument("--fingerprint", required=True, help="SHA-256 of the repo signing certificate") + p.add_argument("--template", type=Path, default=SITE / "page.template.html") + + q = sub.add_parser("qr", help="write /add-repo-qr.png (needs the qrcode module)") + q.add_argument("--work", type=Path, required=True) + q.add_argument("--repo-url", required=True) + q.add_argument("--fingerprint", required=True) + + v = sub.add_parser("verify", help="the release is in the index, signed by the repo key") + v.add_argument("--work", type=Path, required=True) + v.add_argument("--tag", required=True) + v.add_argument("--fingerprint", required=True) + + u = sub.add_parser("plan", help="print the upload and delete order, tab-separated") + u.add_argument("--work", type=Path, required=True) + u.add_argument("--prefix", required=True, help="R2 key prefix, for example fdroid") + u.add_argument("--remote", type=Path, help="file with the remote keys under the prefix, one per line") + + args = parser.parse_args(argv) + + if args.cmd == "config": + target = args.work / "config.yml" + target.write_text(config_yml(args.repo_url, args.keystore), encoding="utf-8", newline="\n") + # fdroidserver refuses a config with passwords that others can read. + target.chmod(0o600) + print(f"wrote {target}") + elif args.cmd == "page": + index = json.loads((args.work / "repo" / "index-v2.json").read_text(encoding="utf-8")) + assets = write_assets(args.work) + page = render(index, args.fingerprint, args.template.read_text(encoding="utf-8"), assets) + missing = sorted(set(re.findall(r"\{\{[^}]+\}\}", page))) + if missing: + print(f"page: the template has unknown placeholders: {missing}", file=sys.stderr) + return 1 + (args.work / "index.html").write_text(page, encoding="utf-8", newline="\n") + print(f"wrote {args.work / 'index.html'}") + elif args.cmd == "qr": + # Runs in the fdroidserver container (python3-qrcode). A phone camera opens the link, + # and Android gives it to the F-Droid app (see add_repo_link). + import qrcode + link = add_repo_link(args.repo_url, args.fingerprint) + qrcode.make(link).save(str(args.work / ADD_REPO_QR)) + print(f"wrote {args.work / ADD_REPO_QR}: {link}") + elif args.cmd == "verify": + index = json.loads((args.work / "repo" / "index-v2.json").read_text(encoding="utf-8")) + try: + verify(index, args.tag, args.fingerprint) + except ValueError as e: + print(f"verify: {e}", file=sys.stderr) + return 1 + # The index must not name a file that the upload does not send (an icon, an APK). + for d in REPO_DIRS: + path = args.work / d / "index-v2.json" + if not path.is_file(): + continue + missing = missing_files(json.loads(path.read_text(encoding="utf-8")), args.work / d) + if missing: + print(f"verify: {d}/index-v2.json names missing files: {missing}", file=sys.stderr) + return 1 + print(f"verify: {args.tag} is in the index, signed by the repo key; no file is missing") + elif args.cmd == "plan": + remote = [] + if args.remote and args.remote.is_file(): + remote = [k.strip() for k in args.remote.read_text(encoding="utf-8").splitlines() if k.strip()] + for line in plan(local_files(args.work), args.prefix, remote): + print("\t".join(line)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/fdroid-repo/metadata/org.appdevforall.k2go.yml b/tools/fdroid-repo/metadata/org.appdevforall.k2go.yml new file mode 100644 index 000000000..76db6a922 --- /dev/null +++ b/tools/fdroid-repo/metadata/org.appdevforall.k2go.yml @@ -0,0 +1,21 @@ +# F-Droid metadata of Knowledge to Go for the self-hosted repository (K2GO-421). +# fdroid update reads the version, the permissions and the signer from the APK itself. +Categories: + - Reading + - Science & Education +License: GPL-3.0-or-later +AuthorName: App Dev for All +WebSite: https://appdevforall.org/knowledgetogo/ +SourceCode: https://github.com/appdevforall/KnowledgeToGo +IssueTracker: https://github.com/appdevforall/KnowledgeToGo/issues + +AutoName: Knowledge to Go +Summary: Turn a phone into an offline library server +Description: |- + Knowledge to Go turns an Android phone into a small offline library server. + Other phones and computers on the same Wi-Fi open the library in a browser, + with no internet connection. + + This repository is self-hosted by App Dev for All. It ships the F-Droid flavor + of the app: no usage analytics, and no in-app updater. Crash reports are off + until you turn them on. diff --git a/tools/fdroid-repo/publish.sh b/tools/fdroid-repo/publish.sh new file mode 100644 index 000000000..7c2ca78ec --- /dev/null +++ b/tools/fdroid-repo/publish.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# Publish the self-hosted F-Droid repository (K2GO-421). Run by app-fdroid-repo.yml. +# +# R2 holds the state: each run pulls /repo and /archive, adds the +# release APK, runs fdroid update, and uploads in the order of fdroid_repo.py plan. +# +# Environment: +# TAG release tag, for example v1.2.0 (the APK is K2Go-$TAG-fdroid-release.apk) +# PREFIX key prefix: fdroid, or fdroid-staging +# BASE_URL public URL of the bucket, for example https://k2go-download.appdevforall.org +# KEYSTORE_FILE the app signing keystore (the repo index is signed with the same key) +# KEY_ALIAS, KEYSTORE_PASSWORD, KEY_PASSWORD the same secrets that sign the APK +# R2 backend: BUCKET_NAME, R2_ACCOUNT_ID, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY +# Local backend: LOCAL_BUCKET= uses a folder as the bucket (local test only) +# FDROID_IMAGE Docker image for fdroid update (default debian:trixie, fdroidserver from apt) +# WORK work folder (default: a new temporary folder) +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +: "${TAG:?}" "${PREFIX:?}" "${BASE_URL:?}" "${KEYSTORE_FILE:?}" +: "${KEY_ALIAS:?}" "${KEYSTORE_PASSWORD:?}" "${KEY_PASSWORD:?}" +FDROID_IMAGE="${FDROID_IMAGE:-debian:trixie}" +PREFIX="${PREFIX%/}" +apk_name="K2Go-${TAG}-fdroid-release.apk" +export REPO_URL="$BASE_URL/$PREFIX/repo" +work="${WORK:-$(mktemp -d)}" +py="$(command -v python3 || command -v python)" + +# --- storage backend: R2 (aws CLI) or a local folder ------------------------------------- +if [ -n "${LOCAL_BUCKET:-}" ]; then + s_list() { (cd "$LOCAL_BUCKET" && find "$PREFIX" -type f 2>/dev/null | sed 's#/\.r2-object$##') || true; } + s_pull() { if [ -d "$LOCAL_BUCKET/$1" ]; then cp -r "$LOCAL_BUCKET/$1/." "$2/"; rm -f "$2/.r2-object"; fi; } + s_get() { cp "$LOCAL_BUCKET/$1" "$2"; } + # R2 keys are flat: "fdroid/repo" and "fdroid/repo/entry.jar" can both exist. A folder cannot + # also be a file, so the local bucket keeps the object of a folder key in /.r2-object. + s_put() { local dest="$LOCAL_BUCKET/$2" + if [ -d "$dest" ]; then dest="$dest/.r2-object"; fi + mkdir -p "$(dirname "$dest")"; cp "$1" "$dest"; } + s_rm() { rm -f "$LOCAL_BUCKET/$1"; } +else + : "${BUCKET_NAME:?}" "${R2_ACCOUNT_ID:?}" + endpoint="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com" + # An empty prefix (the first publish) is not an error: list-objects-v2 prints "None". + s_list() { aws s3api list-objects-v2 --bucket "$BUCKET_NAME" --prefix "$PREFIX/" \ + --endpoint-url "$endpoint" --query 'Contents[].Key' --output text \ + | tr '\t' '\n' | grep -v '^None$' || true; } + s_pull() { aws s3 sync "s3://$BUCKET_NAME/$1/" "$2/" --endpoint-url "$endpoint" --only-show-errors; } + s_get() { aws s3 cp "s3://$BUCKET_NAME/$1" "$2" --endpoint-url "$endpoint" --only-show-errors; } + s_put() { aws s3 cp "$1" "s3://$BUCKET_NAME/$2" --endpoint-url "$endpoint" --only-show-errors \ + --content-type "$3" --cache-control "$4"; } + s_rm() { aws s3 rm "s3://$BUCKET_NAME/$1" --endpoint-url "$endpoint" --only-show-errors; } +fi + +# The keystore copy lives in the work folder only while fdroid update runs. +trap 'rm -f "$work/keystore.jks"' EXIT + +echo "== work folder: $work" +mkdir -p "$work/repo" "$work/archive" "$work/metadata" + +echo "== pull the published repo from $PREFIX/ (index and APKs: fdroid update keeps the added dates)" +s_pull "$PREFIX/repo" "$work/repo" +s_pull "$PREFIX/archive" "$work/archive" +s_list > "$work/remote-keys.txt" +# The localized images (repo//) come from metadata/ on each run. A pulled copy makes +# fdroid update drop the hashed icon file that its new index still names. +rm -rf "$work/repo/org.appdevforall.k2go" "$work/archive/org.appdevforall.k2go" + +echo "== add $apk_name" +if [ ! -f "$work/repo/$apk_name" ] && [ ! -f "$work/archive/$apk_name" ]; then + s_get "$apk_name" "$work/repo/$apk_name" +fi + +echo "== config, metadata, icons" +cp -r "$here/metadata/." "$work/metadata/" +mkdir -p "$work/metadata/org.appdevforall.k2go/en-US" +icon="$here/../../controller/app/src/main/ic_launcher-playstore.png" +cp "$icon" "$work/metadata/org.appdevforall.k2go/en-US/icon.png" +cp "$icon" "$work/k2go.png" +cp "$KEYSTORE_FILE" "$work/keystore.jks" +"$py" "$here/fdroid_repo.py" config --work "$work" \ + --repo-url "$REPO_URL" --keystore keystore.jks + +echo "== fdroid update ($FDROID_IMAGE)" +vol="$work"; tools="$here" +if command -v cygpath >/dev/null 2>&1; then vol="$(cygpath -w "$work")"; tools="$(cygpath -w "$here")"; fi +MSYS_NO_PATHCONV=1 docker run --rm -v "$vol:/work" -v "$tools:/tools:ro" -w /work \ + -e KEY_ALIAS -e KEYSTORE_PASSWORD -e KEY_PASSWORD -e REPO_URL \ + "$FDROID_IMAGE" sh -c ' + set -e + if ! command -v fdroid >/dev/null; then + apt-get update -qq + # python3-qrcode makes the QR codes: add-repo-qr.png (landing page) and repo/index.png. + apt-get install -y -qq --no-install-recommends fdroidserver python3-qrcode >/dev/null + fi + fdroid --version + fdroid update --pretty + # The repo fingerprint: SHA-256 of the certificate that signed entry.jar. + keytool -printcert -jarfile repo/entry.jar \ + | sed -n "s/^[[:space:]]*SHA256: //p" | head -n1 | tr -d ":" > fingerprint.txt + test -s fingerprint.txt + python3 /tools/fdroid_repo.py qr --work /work --repo-url "$REPO_URL" --fingerprint "$(cat fingerprint.txt)" + rm -f keystore.jks + # Let the host user read and remove what root wrote here (the keystore copy is gone). + chmod -R a+rwX /work + ' +fingerprint="$(cat "$work/fingerprint.txt")" +rm -f "$work/keystore.jks" + +echo "== verify, landing page, upload plan" +"$py" "$here/fdroid_repo.py" verify --work "$work" --tag "$TAG" --fingerprint "$fingerprint" +"$py" "$here/fdroid_repo.py" page --work "$work" --fingerprint "$fingerprint" +"$py" "$here/fdroid_repo.py" plan --work "$work" --prefix "$PREFIX" \ + --remote "$work/remote-keys.txt" > "$work/plan.tsv" + +echo "== upload ($(grep -c '^put' "$work/plan.tsv" || true) files, $(grep -c '^rm' "$work/plan.tsv" || true) deletions)" +while IFS=$'\t' read -r op key rel ctype cache; do + case "$op" in + put) echo "put $key"; s_put "$work/$rel" "$key" "$ctype" "$cache" ;; + rm) echo "rm $key"; s_rm "$key" ;; + esac +done < "$work/plan.tsv" + +echo "== done" +echo "repo: $BASE_URL/$PREFIX/repo" +echo "page: $BASE_URL/$PREFIX/index.html" +echo "fingerprint: $fingerprint" +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + { + echo "### F-Droid repository ($PREFIX)" + echo "- Repo: $BASE_URL/$PREFIX/repo" + echo "- Page: $BASE_URL/$PREFIX/index.html" + echo "- Fingerprint: \`$fingerprint\`" + } >> "$GITHUB_STEP_SUMMARY" +fi diff --git a/tools/fdroid-repo/r2_mock_server.py b/tools/fdroid-repo/r2_mock_server.py new file mode 100644 index 000000000..b661c757f --- /dev/null +++ b/tools/fdroid-repo/r2_mock_server.py @@ -0,0 +1,147 @@ +"""Serve a folder the way an R2 public bucket serves its objects. + +For a local test only. The differences from `python -m http.server`: + +- No directory listing. A path that is not an object gets 404. +- No implicit index. "/fdroid/" is 404; "/fdroid/index.html" is the object. + With --index-rewrite, "/x/" serves "/x/index.html", the same as a Cloudflare + URL rewrite rule would do. +- Byte ranges (206), ETag and Last-Modified, as the R2 public endpoint gives. +- The same Content-Type and Cache-Control that the publish step sets. + +Usage: python r2_mock_server.py --root bucket --port 8080 [--index-rewrite] +""" + +import argparse +import email.utils +import hashlib +import http.server +from pathlib import Path +from urllib.parse import unquote + +# The same types and cache rules as the publish step (fdroid_repo.py, in this folder). +from fdroid_repo import LONG, SHORT, TYPES # noqa: E402 + +OBJECT_FILE = ".r2-object" + + +def cache_control(key: str) -> str: + # fdroid_repo.cache_control takes a path under the prefix; a key starts with the prefix. + rel = key.split("/", 1)[1] if "/" in key else key + from fdroid_repo import cache_control as publish_rule + return publish_rule(rel) + + +class Handler(http.server.BaseHTTPRequestHandler): + root: Path + index_rewrite = False + server_version = "r2-mock" + sys_version = "" + + def resolve(self): + # R2 decodes the path: "icon_x%3D.png" is the object "icon_x=.png". + key = unquote(self.path.split("?", 1)[0].split("#", 1)[0]).lstrip("/") + if self.index_rewrite and (key == "" or key.endswith("/")): + key += "index.html" + target = (self.root / key).resolve() + if self.root not in target.parents: + return key, None + # R2 keys are flat: "fdroid/repo" can be an object beside "fdroid/repo/...". publish.sh + # (local backend) keeps such an object in /.r2-object. It is always a page. + if target.is_dir() and (target / OBJECT_FILE).is_file(): + return key + ".html", target / OBJECT_FILE + if not target.is_file(): + return key, None + return key, target + + def do_HEAD(self): + self.respond(body=False) + + def do_GET(self): + self.respond(body=True) + + def respond(self, body: bool): + key, target = self.resolve() + if target is None: + data = b"Object not found\n" + self.send_response(404) + self.send_header("Content-Type", "text/plain;charset=UTF-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + if body: + self.wfile.write(data) + return + + stat = target.stat() + etag = '"' + hashlib.md5(f"{stat.st_size}-{stat.st_mtime_ns}".encode()).hexdigest() + '"' + modified = email.utils.formatdate(stat.st_mtime, usegmt=True) + if self.headers.get("If-None-Match") == etag: + self.send_response(304) + self.send_header("ETag", etag) + self.end_headers() + return + + start, end = 0, stat.st_size - 1 + status = 200 + wanted = self.headers.get("Range", "") + if wanted.startswith("bytes=") and "," not in wanted: + first, _, last = wanted[6:].partition("-") + try: + if first: + start = int(first) + end = min(int(last), end) if last else end + else: + start = max(0, stat.st_size - int(last)) + if start > end: + raise ValueError + status = 206 + except ValueError: + self.send_response(416) + self.send_header("Content-Range", f"bytes */{stat.st_size}") + self.end_headers() + return + + self.send_response(status) + self.send_header("Content-Type", TYPES.get(Path(key).suffix, "application/octet-stream")) + self.send_header("Cache-Control", cache_control(key)) + self.send_header("Content-Length", str(end - start + 1)) + self.send_header("Accept-Ranges", "bytes") + self.send_header("ETag", etag) + self.send_header("Last-Modified", modified) + if status == 206: + self.send_header("Content-Range", f"bytes {start}-{end}/{stat.st_size}") + self.end_headers() + if not body: + return + with target.open("rb") as f: + f.seek(start) + left = end - start + 1 + while left > 0: + chunk = f.read(min(1 << 20, left)) + if not chunk: + break + try: + self.wfile.write(chunk) + except (BrokenPipeError, ConnectionResetError): + return + left -= len(chunk) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--port", type=int, default=8080) + parser.add_argument("--bind", default="127.0.0.1") + parser.add_argument("--index-rewrite", action="store_true") + args = parser.parse_args() + + Handler.root = args.root.resolve() + Handler.index_rewrite = args.index_rewrite + server = http.server.ThreadingHTTPServer((args.bind, args.port), Handler) + print(f"serving {Handler.root} on http://{args.bind}:{args.port}/ " + f"(index rewrite {'on' if args.index_rewrite else 'off'})", flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/tools/fdroid-repo/site/adfa-logo.svg b/tools/fdroid-repo/site/adfa-logo.svg new file mode 100644 index 000000000..0bbcec88f --- /dev/null +++ b/tools/fdroid-repo/site/adfa-logo.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tools/fdroid-repo/site/fdroid.css b/tools/fdroid-repo/site/fdroid.css new file mode 100644 index 000000000..e8749c6cc --- /dev/null +++ b/tools/fdroid-repo/site/fdroid.css @@ -0,0 +1,40 @@ +/* The F-Droid repository page. It adds to styles.css (the add-ons site) and uses + only its variables, so light and dark follow that file. */ + +/* The app icon is as tall as the text beside it (name to "Source code", about 13.5rem on a + wide screen). On a phone the icon goes on top, and the text gets the full width below it, + the same as the QR code and the button. */ +.app-card { display:grid; grid-template-columns:clamp(9rem,24vw,13.5rem) 1fr; gap:28px; + align-items:center; + padding:24px; margin:0 0 8px; + background:var(--card); border:1px solid var(--rule); border-radius:12px; + box-shadow:0 1px 2px rgba(35,52,144,.05); } +.app-card .icon { width:100%; height:auto; aspect-ratio:1; border-radius:22%; } +@media (max-width:640px) { + .app-card { grid-template-columns:1fr; gap:20px; padding:20px; } + .app-card .icon { width:min(60vw,13.5rem); justify-self:center; } +} +.app-card h2 { font-size:1.25rem; margin:0 0 4px; padding:0; border:0; + display:flex; align-items:center; gap:8px; flex-wrap:wrap; } +.app-card .summary { margin:0 0 10px; } +.app-card dl { display:grid; grid-template-columns:max-content 1fr; gap:2px 16px; + margin:0; font-size:.9rem; } +.app-card dt { color:var(--dim); } +.app-card dd { margin:0; overflow-wrap:anywhere; } + +.add-repo { display:flex; gap:20px; align-items:center; flex-wrap:wrap; margin:12px 0; } +.add-repo .qr { width:168px; height:168px; padding:8px; border-radius:8px; + background:#ffffff; border:1px solid var(--rule); } +.add-repo p { margin:0 0 10px; } +.button { display:inline-block; background:var(--brand); color:var(--on-brand); + border-radius:999px; padding:11px 24px; font-weight:600; } +.button:hover { background:var(--brand-light); color:var(--on-brand); text-decoration:none; } +@media (prefers-color-scheme: dark) { + /* --brand goes near-black in dark (styles.css), so use the link color */ + .button { background:var(--link); color:#0f1424; } + .button:hover { background:var(--link-hover); color:#0f1424; } +} + +.fingerprint { font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; + font-size:.85rem; overflow-wrap:anywhere; } +.page ol li, .page ul li { margin-bottom:8px; } diff --git a/tools/fdroid-repo/site/page.template.html b/tools/fdroid-repo/site/page.template.html new file mode 100644 index 000000000..adeb2d254 --- /dev/null +++ b/tools/fdroid-repo/site/page.template.html @@ -0,0 +1,133 @@ + + + + + +{{app_name}} for F-Droid — App Dev for All + + + + + + + + + + + +
+
+

{{app_name}} for F-Droid

+

{{repo_description}}

+
+
+ +
+
+ +
+

{{app_name}} F-Droid

+

{{summary}}

+
+
Version
{{version}} (code {{version_code}}), {{updated}}
+
Needs
Android {{android}} or newer
+
Processors
{{abis}}
+
Size
{{apk_size}}
+
License
{{license}}
+
Source code
{{source}}
+
+
+
+ +

Add this repository to F-Droid

+
+ QR code that adds this repository to F-Droid +
+

Add to F-Droid

+

On a phone with F-Droid, push the button.
+ On a computer, scan the QR code with the phone camera.

+
+
+

To add it by hand:

+
    +
  1. Install the F-Droid app from f-droid.org.
  2. +
  3. In F-Droid, open Settings, then Repositories, then push "+".
  4. +
  5. Type this address: {{address}}
  6. +
  7. Make sure that F-Droid shows this fingerprint of the repository key:
    + {{fingerprint}}
  8. +
+ +

Before you install

+
    +
  • Do you have {{app_name}} from Google Play? Then this repository cannot update it. + Google Play signs the app with a different key. To change, back up your library, + remove the app, and install it again from here.
  • +
  • The app from the App Dev for All website and the app from this repository have the + same signing key. Each one can update the other.
  • +
  • Signing key of the app (SHA-256):
    {{signer}}
  • +
+ +

Versions

+ + + +{{rows}} + +
VersionAddedSizeFile
+

SHA-256 of the newest APK: {{apk_sha256}}
+ Repository index: index-v2.json. Updated {{generated}}.

+
+ + + diff --git a/tools/fdroid-repo/site/styles.css b/tools/fdroid-repo/site/styles.css new file mode 100644 index 000000000..7a9c1b449 --- /dev/null +++ b/tools/fdroid-repo/site/styles.css @@ -0,0 +1,202 @@ +/* Copied from appdevforall/plugin-examples site/styles.css (2026-09-08), the add-ons site. + Keep it the same as that file: both sites share one look. Changes for this page: fdroid.css. */ +/* App Dev For All brand system, taken from appdevforall.org: + Poppins, indigo #233490, body text #333, mint #cce5e2. */ +:root { + --brand:#233490; + --brand-deep:#1b2870; + --brand-light:#4564df; + --mint:#cce5e2; + --ink:#333333; + --dim:#69727d; + --rule:#e2e6f0; + --ground:#ffffff; + --card:#ffffff; + --card-alt:#f6f7fb; + --link:#233490; + --link-hover:#4564df; + --on-brand:#ffffff; + --font:"Poppins",-apple-system,system-ui,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif; +} +@media (prefers-color-scheme: dark) { + :root { + --ink:#e9ecf6; --dim:#a8b0c6; --rule:#2b3350; + --ground:#0f1424; --card:#171d33; --card-alt:#131829; + --link:#9db4ff; --link-hover:#c6d4ff; + --brand:#1b2870; + } +} +* { box-sizing:border-box; } +html { -webkit-text-size-adjust:100%; } +body { + margin:0; background:var(--ground); color:var(--ink); + font-family:var(--font); font-size:16px; line-height:1.65; +} +h1,h2,h3 { font-weight:700; line-height:1.2; margin:0; } +a { color:var(--link); text-decoration:none; } +a:hover { color:var(--link-hover); text-decoration:underline; } +:focus-visible { outline:3px solid var(--brand-light); outline-offset:2px; } +/* the brand ring disappears on the indigo bars, so use white there */ +.site-header :focus-visible, .site-footer :focus-visible { + outline-color:#fff; outline-offset:3px; +} + +/* ---------- site header ---------- */ +.site-header { background:var(--brand); } +.site-header .bar { + max-width:74rem; margin:0 auto; padding:14px 20px; + display:flex; align-items:center; gap:24px; flex-wrap:wrap; +} +.site-header .logo { display:flex; align-items:center; } +.site-header .logo img { width:74px; height:58px; display:block; } +.site-nav { margin-left:auto; display:flex; align-items:center; gap:26px; flex-wrap:wrap; } +.site-nav a { + color:var(--on-brand); font-size:.82rem; font-weight:500; + letter-spacing:.06em; text-transform:uppercase; text-decoration:none; +} +.site-nav a:hover { color:var(--mint); text-decoration:none; } +.site-nav a[aria-current="page"] { color:var(--mint); } +.site-nav .cta { + background:#fff; color:var(--brand); border-radius:999px; + padding:11px 22px; font-weight:600; +} +.site-nav .cta:hover { background:var(--mint); color:var(--brand); } + +/* ---------- page masthead ---------- */ +.masthead { background:var(--card-alt); border-bottom:1px solid var(--rule); } +.masthead .bar { max-width:74rem; margin:0 auto; padding:34px 20px 30px; } +.masthead h1 { font-size:clamp(1.7rem,4vw,2.4rem); color:var(--ink); } +.masthead p { margin:8px 0 0; color:var(--dim); max-width:52ch; } + +main { max-width:74rem; margin:0 auto; padding:26px 20px 56px; } + +/* ---------- controls ---------- */ +.controls { display:flex; gap:10px; flex-wrap:wrap; margin-bottom:18px; } +.controls input { flex:1 1 14rem; } +.controls input, .controls select { + padding:11px 14px; border:1px solid var(--rule); border-radius:8px; + background:var(--card); color:var(--ink); font:inherit; font-size:.95rem; +} +.controls input:focus, .controls select:focus { border-color:var(--brand-light); } + +#active[hidden] { display:none; } +#active { display:flex; flex-wrap:wrap; align-items:center; gap:8px; + margin:0 0 16px; color:var(--dim); font-size:.88rem; } +.clear { font:inherit; font-size:.8rem; cursor:pointer; background:none; border:0; + color:var(--brand); text-decoration:underline; padding:2px 4px; } +@media (prefers-color-scheme: dark) { .clear { color:var(--link); } } + +/* ---------- cards ---------- */ +#cards { list-style:none; padding:0; margin:0; display:grid; gap:16px; + grid-template-columns:repeat(auto-fill,minmax(min(19rem,100%),1fr)); } +.card { display:flex; gap:14px; padding:16px; background:var(--card); + border:1px solid var(--rule); border-radius:12px; + box-shadow:0 1px 2px rgba(35,52,144,.05); } +.card:hover { border-color:var(--brand-light); } +.icon { flex:none; width:56px; height:56px; border-radius:12px; } +.card h2 { font-size:1.02rem; margin:0 0 5px; display:flex; align-items:center; + gap:8px; flex-wrap:wrap; } +.card p { margin:0 0 8px; } +.card .summary { font-size:.92rem; } +.badge { font-size:.63rem; font-weight:600; letter-spacing:.08em; text-transform:uppercase; + color:var(--brand); background:var(--mint); border-radius:4px; padding:2px 7px; } +@media (prefers-color-scheme: dark) { .badge { background:#22305e; color:#cfe0ff; } } +.meta { color:var(--dim); font-size:.8rem; } +/* R20: the shape cue beside the word, so neither badge relies on colour */ +.glyph { margin-right:.35em; } +.tags { display:flex; flex-wrap:wrap; gap:6px; } +.tag { font:inherit; font-size:.72rem; cursor:pointer; padding:3px 9px; border-radius:999px; + border:1px solid var(--rule); background:transparent; color:var(--dim); } +.tag:hover { border-color:var(--brand); color:var(--brand); } +@media (prefers-color-scheme: dark) { .tag:hover { border-color:var(--link); color:var(--link); } } +.tag.on { background:var(--brand); border-color:var(--brand); color:#fff; } +@media (prefers-color-scheme: dark) { + /* --brand goes near-black in dark, so the "on" state vanished */ + .tag.on { background:var(--link); border-color:var(--link); color:#0f1424; } + .tag { border-color:#3b4568; } +} +.links { display:flex; gap:16px; font-size:.9rem; font-weight:500; } + +/* ---------- description pages ---------- */ +.page { max-width:52rem; margin:0 auto; padding:30px 20px 56px; } +/* The way back to the gallery, above and below the addon's own content. The + second one matters most: these pages run long, and the header scrolls away. */ +.back { display:inline-block; font-size:.9rem; font-weight:500; margin:0 0 18px; } +.back-end { margin:34px 0 0; padding-top:18px; border-top:1px solid var(--rule); + width:100%; } +.page h1 { font-size:clamp(1.6rem,4vw,2.1rem); margin:0 0 14px; } +.page h2 { font-size:1.25rem; margin:32px 0 10px; padding-bottom:6px; + border-bottom:1px solid var(--rule); } +.page h3 { font-size:1.02rem; margin:22px 0 6px; } +.page table { border-collapse:collapse; width:100%; margin:12px 0; font-size:.92rem; } +/* wide content scrolls inside itself, never the document */ +.page .table-scroll { overflow-x:auto; margin:12px 0; } +.page table { display:block; overflow-x:auto; max-width:100%; } +.page code { overflow-wrap:anywhere; word-break:break-word; } +.page pre code { overflow-wrap:normal; word-break:normal; } +.page th, .page td { border:1px solid var(--rule); padding:8px 11px; text-align:left; vertical-align:top; } +.page th { background:var(--card-alt); } +.page code { background:var(--card-alt); border:1px solid var(--rule); border-radius:4px; + padding:.1em .35em; font-size:.9em; } +.page pre { background:var(--card-alt); border:1px solid var(--rule); border-radius:8px; + padding:14px; overflow-x:auto; } +.page pre code { border:0; background:none; padding:0; } + +/* ---------- site footer ---------- */ +.site-footer { background:var(--brand); color:#fff; margin-top:48px; } +.site-footer a { color:#fff; } +.site-footer a:hover { color:var(--mint); text-decoration:none; } +.site-footer .cols { + max-width:74rem; margin:0 auto; padding:44px 20px 20px; + display:grid; gap:28px; grid-template-columns:repeat(auto-fit,minmax(13rem,1fr)); +} +.site-footer h2 { font-size:1.15rem; margin:0 0 14px; } +.site-footer .about p { margin:0; max-width:30ch; font-size:.92rem; opacity:.9; } +.site-footer ul { list-style:none; margin:0; padding:0; display:grid; gap:9px; font-size:.94rem; } +.social { display:flex; gap:14px; margin-top:18px; } +.social a { display:inline-flex; } +.social svg { width:20px; height:20px; fill:currentColor; opacity:.9; } +.social a:hover svg { opacity:1; } +.legal { max-width:74rem; margin:0 auto; padding:14px 20px 30px; + text-align:right; font-size:.83rem; opacity:.85; } +@media (max-width:640px) { + .legal { text-align:left; } + .site-header .bar { gap:14px; } + .site-nav { gap:16px; } +} + +/* Classes the addon description pages use. Their own