mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
feat(cloudflare): serve app-link files on kjbox.cc/.well-known (#1209)
## Summary Mobile Phase 5 "Tonight": the printed venue QR (`HTTP://KJBOX.CC/<code>`) should open the Nomad Karaoke app when installed (Android App Links now; iOS universal links once the team-signed build exists in Phase 6). - New Pulumi-managed Worker `kjbox-cc-well-known` on `kjbox.cc/.well-known/*` and `www.kjbox.cc/.well-known/*` serving `assetlinks.json` (fingerprints from config `kjboxcc_android_sha256_fingerprints`, `[]` until set) and `apple-app-site-association` (team 55B76HN73D, `com.nomadkaraoke.mobile`). - The kjbox.cc `/<code>` redirect rule now skips `/.well-known/`; everything else unchanged. **Already applied** (`pulumi up`, +3 created, ~1 ruleset). Verified: both hosts' `assetlinks.json` 200 JSON with no redirect, AASA 200 `application/json`, `http://kjbox.cc/2121` still 302 → `sing.nomadkaraoke.com/?t=2121`, `/` still 302. ## Testing `infrastructure/cloudflare/tests`: 11 passed (Worker script exercised under node). CodeRabbit CLI: no findings. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_013Bkasn6trBadg1Zb39vSVR --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
032ac11a45
commit
5f72e618cc
6 files changed
+163
-3
No files matched your search
@@ -18,7 +18,7 @@ only app-specific stacks (e.g. karaoke-decide's Cloud Run + its API-proxy Worker
|
||||
| `email_routing.py` | Gmail destination address; Email Routing enablement (**protected**), catch-all and `google@` rules for nomadkaraoke.com, nomadkaroke.com, karaokehunt.com |
|
||||
| `tunnels.py` | `nomad-kjbox` (NomadPC: sing, kjbox, kjssh, kjvnc) and `nomad-hf2` (fiverrbot) tunnels (**protected**) + ingress |
|
||||
| `access.py` | Zero Trust org (**protected**), one-time-PIN + Google IdPs (Google OAuth client in GCP `nomadkaraoke`, secret in Pulumi config `googleOauthClientSecret`), `claude-code-kjbox` service token, reusable policies and the KJ Controller / FiverrBot noVNC apps |
|
||||
| `pages_workers.py` | Pages projects `karaoke-gen` + `karaoke-gen-tenant`, `gen.nomadkaraoke.com` Pages domain, nomadkaraoke.com/www Worker custom domains, `create.karaokehunt.com/*` and `requests.nomadkaraoke.com/*` routes |
|
||||
| `pages_workers.py` | Pages projects `karaoke-gen` + `karaoke-gen-tenant`, `gen.nomadkaraoke.com` Pages domain, nomadkaraoke.com/www Worker custom domains, `create.karaokehunt.com/*` and `requests.nomadkaraoke.com/*` routes, plus the `kjbox-cc-well-known` Worker script (`kjbox-cc-well-known/worker.js`, built by `well_known.py`) and its `kjbox.cc/.well-known/*` route |
|
||||
|
||||
All resource IDs (`ids.py`) are non-secret. Removing a non-protected resource from code deletes it
|
||||
on the next `pulumi up`, and `pulumi preview` always shows that first.
|
||||
@@ -36,6 +36,19 @@ on the next `pulumi up`, and `pulumi preview` always shows that first.
|
||||
| Tunnel connector tokens / cloudflared processes | NomadPC systemd `cloudflared-nomad`, hf2 `~/nomad-tunnel` compose |
|
||||
| Registrar, billing, API tokens, account members | Dashboard (admin@nomadkaraoke.com) |
|
||||
|
||||
## kjbox.cc app-link files
|
||||
|
||||
`kjbox.cc/.well-known/assetlinks.json` (Android App Links) and `apple-app-site-association` (iOS universal
|
||||
links) are served by the `kjbox-cc-well-known` Worker, routes `kjbox.cc/.well-known/*` and `www.kjbox.cc/.well-known/*` (scheme-agnostic, so
|
||||
http and https). The JSON mirrors what the kjbox box serves on `sing.nomadkaraoke.com`. The
|
||||
`kjbox.cc/<code>` redirect rule excludes `/.well-known/` so the Worker answers instead of redirecting.
|
||||
Android SHA-256 cert fingerprints come from Pulumi config, baked into the script at deploy time
|
||||
(empty list = `assetlinks.json` is `[]`):
|
||||
|
||||
```bash
|
||||
pulumi config set --path 'kjboxcc_android_sha256_fingerprints[0]' 'AA:BB:...' # then pulumi up
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
@@ -47,7 +60,7 @@ pulumi preview # must be clean (0 changes) before you start
|
||||
pulumi up
|
||||
```
|
||||
|
||||
Unit tests for the import-list builder: `venv/bin/pip install pytest && venv/bin/python -m pytest tests -c /dev/null`
|
||||
Unit tests (import-list builder, kjbox.cc well-known Worker; the Worker tests need `node`): `venv/bin/pip install pytest && venv/bin/python -m pytest tests -c /dev/null`
|
||||
(`-c /dev/null` skips the repo-root pytest config, which needs the backend's plugins).
|
||||
|
||||
As with the GCP project, **CI does not run Pulumi**. Apply locally, then merge the PR.
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// kjbox.cc/.well-known/* : app-link association files for the Nomad Karaoke app.
|
||||
// Must match what the kjbox box serves on sing.nomadkaraoke.com/.well-known/.
|
||||
// The fingerprint list is substituted at deploy time by ../well_known.py from Pulumi config
|
||||
// `kjboxcc_android_sha256_fingerprints`.
|
||||
const ANDROID_SHA256_FINGERPRINTS = /*FINGERPRINTS*/[]/*END*/;
|
||||
|
||||
const ASSETLINKS = ANDROID_SHA256_FINGERPRINTS.length === 0 ? [] : [{
|
||||
relation: ["delegate_permission/common.handle_all_urls"],
|
||||
target: {
|
||||
namespace: "android_app",
|
||||
package_name: "com.nomadkaraoke.mobile",
|
||||
sha256_cert_fingerprints: ANDROID_SHA256_FINGERPRINTS,
|
||||
},
|
||||
}];
|
||||
|
||||
const AASA = {
|
||||
applinks: {
|
||||
details: [{
|
||||
appIDs: ["55B76HN73D.com.nomadkaraoke.mobile"],
|
||||
components: [{ "/": "/", "?": { t: "?*" } }, { "/": "/*" }],
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
const FILES = {
|
||||
"/.well-known/assetlinks.json": ASSETLINKS,
|
||||
"/.well-known/apple-app-site-association": AASA,
|
||||
};
|
||||
|
||||
export default {
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url);
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
return new Response("Method Not Allowed", { status: 405, headers: { Allow: "GET, HEAD" } });
|
||||
}
|
||||
const body = FILES[url.pathname];
|
||||
if (body === undefined) return new Response("Not Found", { status: 404 });
|
||||
return new Response(request.method === "HEAD" ? null : JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json", "Cache-Control": "public, max-age=300" },
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -7,6 +7,7 @@ import pulumi
|
||||
import pulumi_cloudflare as cloudflare
|
||||
|
||||
from ids import ACCOUNT_ID, ZONE_IDS
|
||||
from well_known import ROUTE_PATTERNS, build_worker_script
|
||||
|
||||
worker_route_create_karaokehunt_com = cloudflare.WorkersRoute("worker-route-create-karaokehunt-com",
|
||||
pattern="create.karaokehunt.com/*",
|
||||
@@ -75,3 +76,20 @@ worker_domain_www_nomadkaraoke_com = cloudflare.WorkersCustomDomain("worker-doma
|
||||
service="nomadkaraoke-com-static",
|
||||
zone_id=ZONE_IDS["nomadkaraoke.com"],
|
||||
zone_name="nomadkaraoke.com")
|
||||
|
||||
# kjbox.cc/.well-known/*: Android App Links (assetlinks.json) + iOS universal links (AASA) for the
|
||||
# Nomad Karaoke app, so the venue QR (kjbox.cc/<code>) can open the app. The script is deployed by
|
||||
# Pulumi (fingerprints come from config `kjboxcc_android_sha256_fingerprints`, empty by default);
|
||||
# the kjbox.cc/<code> redirect rule in rulesets.py excludes /.well-known/ so this route answers.
|
||||
_kjbox_fingerprints = pulumi.Config().get_object("kjboxcc_android_sha256_fingerprints") or []
|
||||
worker_script_kjbox_cc_well_known = cloudflare.WorkersScript("worker-script-kjbox-cc-well-known",
|
||||
account_id=ACCOUNT_ID,
|
||||
script_name="kjbox-cc-well-known",
|
||||
content=build_worker_script(_kjbox_fingerprints),
|
||||
main_module="worker.js",
|
||||
compatibility_date="2026-09-01")
|
||||
for _name, _pattern in ROUTE_PATTERNS.items():
|
||||
cloudflare.WorkersRoute(f"worker-route-{_name}-well-known",
|
||||
pattern=_pattern,
|
||||
script=worker_script_kjbox_cc_well_known.script_name,
|
||||
zone_id=ZONE_IDS["kjbox.cc"])
|
||||
@@ -11,6 +11,7 @@ import pulumi
|
||||
import pulumi_cloudflare as cloudflare
|
||||
|
||||
from ids import ACCOUNT_ID, ZONE_IDS
|
||||
from well_known import WELL_KNOWN_EXCLUSION
|
||||
|
||||
ruleset_karaokehunt_com_request_dynamic_redirect = cloudflare.Ruleset("ruleset-karaokehunt-com-request-dynamic-redirect",
|
||||
kind="zone",
|
||||
@@ -95,7 +96,7 @@ ruleset_kjbox_cc_request_dynamic_redirect = cloudflare.Ruleset("ruleset-kjbox-cc
|
||||
},
|
||||
"description": "kjbox.cc/<code> -> sing.nomadkaraoke.com/?t=<code>",
|
||||
"enabled": True,
|
||||
"expression": "(http.host in {\"kjbox.cc\" \"www.kjbox.cc\"} and http.request.uri.path ne \"/\")",
|
||||
"expression": "(http.host in {\"kjbox.cc\" \"www.kjbox.cc\"} and http.request.uri.path ne \"/\"" + WELL_KNOWN_EXCLUSION + ")",
|
||||
"ref": "1f2e8fb05f844449ae29e7c1237ffc5c",
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""kjbox.cc/.well-known/*: the Worker serves the app-link files and the redirect rule excludes the path."""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
import well_known
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
FP = "AA:BB:CC:DD"
|
||||
|
||||
|
||||
def test_redirect_rule_excludes_well_known_and_is_otherwise_unchanged():
|
||||
src = (ROOT / "rulesets.py").read_text()
|
||||
assert "WELL_KNOWN_EXCLUSION" in src
|
||||
assert 'starts_with(http.request.uri.path, "/.well-known/")' in well_known.WELL_KNOWN_EXCLUSION
|
||||
# The code-entry rule (path eq "/") is untouched.
|
||||
assert '"(http.host in {\\"kjbox.cc\\" \\"www.kjbox.cc\\"} and http.request.uri.path eq \\"/\\")"' in src
|
||||
assert 'http.request.uri.path ne \\"/\\"" + WELL_KNOWN_EXCLUSION + ")"' in src
|
||||
|
||||
|
||||
def test_build_worker_script_bakes_fingerprints():
|
||||
assert "ANDROID_SHA256_FINGERPRINTS = []" in well_known.build_worker_script([])
|
||||
assert f'ANDROID_SHA256_FINGERPRINTS = ["{FP}"]' in well_known.build_worker_script([FP])
|
||||
|
||||
|
||||
def _run_worker(fps, path, method="GET"):
|
||||
script = well_known.build_worker_script(fps)
|
||||
js = script.replace("export default", "const worker =") + f"""
|
||||
worker.fetch(new Request("https://kjbox.cc{path}", {{method: "{method}"}})).then(async r =>
|
||||
console.log(JSON.stringify({{status: r.status, ct: r.headers.get("content-type"), body: await r.text()}})));
|
||||
"""
|
||||
out = subprocess.run(["node", "-e", js], capture_output=True, text=True, check=True).stdout
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
@pytest.mark.skipif(shutil.which("node") is None, reason="node not installed")
|
||||
class TestWorker:
|
||||
def test_assetlinks_with_fingerprint(self):
|
||||
r = _run_worker([FP], "/.well-known/assetlinks.json")
|
||||
assert r["status"] == 200 and r["ct"] == "application/json"
|
||||
assert json.loads(r["body"]) == [{
|
||||
"relation": ["delegate_permission/common.handle_all_urls"],
|
||||
"target": {"namespace": "android_app", "package_name": "com.nomadkaraoke.mobile",
|
||||
"sha256_cert_fingerprints": [FP]}}]
|
||||
|
||||
def test_assetlinks_empty_when_no_fingerprints(self):
|
||||
assert json.loads(_run_worker([], "/.well-known/assetlinks.json")["body"]) == []
|
||||
|
||||
def test_aasa(self):
|
||||
r = _run_worker([], "/.well-known/apple-app-site-association")
|
||||
assert r["status"] == 200 and r["ct"] == "application/json"
|
||||
assert json.loads(r["body"]) == {"applinks": {"details": [{
|
||||
"appIDs": ["55B76HN73D.com.nomadkaraoke.mobile"],
|
||||
"components": [{"/": "/", "?": {"t": "?*"}}, {"/": "/*"}]}]}}
|
||||
|
||||
def test_unknown_path_404_and_post_405(self):
|
||||
assert _run_worker([], "/.well-known/other")["status"] == 404
|
||||
assert _run_worker([], "/.well-known/assetlinks.json", "POST")["status"] == 405
|
||||
|
||||
|
||||
def test_routes_cover_apex_and_www():
|
||||
# The redirect exclusion matches both hosts, so both need the Worker route.
|
||||
assert sorted(well_known.ROUTE_PATTERNS.values()) == ["kjbox.cc/.well-known/*", "www.kjbox.cc/.well-known/*"]
|
||||
src = (ROOT / "pages_workers.py").read_text()
|
||||
assert "for _name, _pattern in ROUTE_PATTERNS.items()" in src
|
||||
@@ -0,0 +1,16 @@
|
||||
"""kjbox.cc/.well-known/* Worker: script builder + the redirect-rule exclusion (no pulumi imports, unit-testable)."""
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
WORKER_JS = pathlib.Path(__file__).parent / "kjbox-cc-well-known" / "worker.js"
|
||||
PLACEHOLDER = "/*FINGERPRINTS*/[]/*END*/"
|
||||
ROUTE_PATTERNS = {"kjbox-cc": "kjbox.cc/.well-known/*", "www-kjbox-cc": "www.kjbox.cc/.well-known/*"}
|
||||
|
||||
# Appended to the kjbox.cc/<code> redirect rule so the Worker route (not the redirect) answers.
|
||||
WELL_KNOWN_EXCLUSION = ' and not starts_with(http.request.uri.path, "/.well-known/")'
|
||||
|
||||
|
||||
def build_worker_script(fingerprints):
|
||||
src = WORKER_JS.read_text()
|
||||
assert src.count(PLACEHOLDER) == 1, "worker.js placeholder missing"
|
||||
return src.replace(PLACEHOLDER, json.dumps(list(fingerprints)))
|
||||
Reference in new issue
Block a user