Spaces:
Running

Nrighton233j commited on
Commit
8e177d6
·
1 Parent(s): 56d4096

Persist OTA manifests in Hugging Face dataset

Browse files
Files changed (1) hide show
  1. expoUpdates.py +108 -56
expoUpdates.py CHANGED
@@ -1,68 +1,90 @@
 
 
 
 
1
  import uuid
 
 
2
  from datetime import datetime, timezone
3
- from flask import Blueprint, request, jsonify, Response
4
- import os
5
 
6
- # ---------------------------------------------------------------------------
7
- # Self-hosted Expo Updates (OTA JS-bundle) manifest server, no code signing.
8
- # In-memory PUBLISHED dict on purpose, matching ota.py's pattern - published
9
- # via POST /publish after running `expo export` (see publish_ota_update.py).
10
- #
11
- # NOTE: in-memory means a Render restart/sleep wipes the published manifest
12
- # until you republish. Fine for now, matching the rest of this service's
13
- # storage approach - swap for a JSON file on persistent disk or a DB row
14
- # later if that becomes a real problem.
15
- # ---------------------------------------------------------------------------
16
 
17
  expo_updates_bp = Blueprint("expo_updates", __name__)
18
 
19
- PUBLISHED = {
20
- # "b24music": { "runtimeVersion": "1.0.1", "id": "...", "createdAt": "...",
21
- # "launchAsset": {...}, "assets": [...] }
22
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
 
25
  def _no_update_response():
26
- # Per the Expo Updates v1 spec, a content-type: application/json
27
- # response can ONLY carry a manifest, never a directive - sending
28
- # {"type": "noUpdateAvailable"} that way made the native client fail
29
- # to parse it (expected manifest fields, got a directive shape),
30
- # which surfaced as "Failed to check for update" with no real reason
31
- # shown. A multipart response with zero parts is a spec-legal no-op,
32
- # expressible as a plain 204 with no body - simplest fix that's
33
- # actually conformant.
34
  resp = Response(status=204)
35
  resp.headers["expo-protocol-version"] = "1"
36
  resp.headers["expo-sfv-version"] = "0"
37
- resp.headers["cache-control"] = "private, max-age=0"
38
  return resp
39
 
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  @expo_updates_bp.route("/manifest", methods=["GET"])
42
  def manifest():
43
  app_id = request.args.get("app_id", "b24music")
44
- runtime_version = request.headers.get("expo-runtime-version")
45
  platform = request.headers.get("expo-platform")
46
 
47
- if platform != "android":
48
  return _no_update_response()
49
 
50
- entry = PUBLISHED.get(app_id)
51
- if not entry:
52
  return _no_update_response()
53
 
54
- if runtime_version and entry["runtimeVersion"] != runtime_version:
55
- # A published update only applies to the runtimeVersion it was
56
- # built against - Expo Updates never cross-applies JS bundles
57
- # across mismatched native runtime versions.
 
58
  return _no_update_response()
 
 
 
59
 
60
  manifest_body = {
61
  "id": entry["id"],
62
  "createdAt": entry["createdAt"],
63
  "runtimeVersion": entry["runtimeVersion"],
64
  "launchAsset": entry["launchAsset"],
65
- "assets": entry["assets"],
66
  "metadata": {},
67
  "extra": {},
68
  }
@@ -70,38 +92,68 @@ def manifest():
70
  resp = jsonify(manifest_body)
71
  resp.headers["expo-protocol-version"] = "1"
72
  resp.headers["expo-sfv-version"] = "0"
73
- resp.headers["cache-control"] = "private, no-cache"
74
  return resp
75
 
76
 
77
  @expo_updates_bp.route("/publish", methods=["POST"])
78
  def publish():
79
- """Registers a freshly exported+uploaded bundle as the current update
80
- for an app. This route is listed in app.py's OPEN_PATHS (bypasses the
81
- normal user-JWT auth) since it's called by a standalone publish script,
82
- not the app itself - gated by its own shared admin key instead, same
83
- pattern as the old native-APK OTA system's X-Admin-Key. Body: { app_id,
84
- runtimeVersion, launchAsset: {url, contentType, hash, key,
85
- fileExtension}, assets: [ same shape, ... ] }"""
86
- # Admin-key check temporarily disabled - the HF Space secret wasn't
87
- # taking effect reliably (secret update vs restart timing issue).
88
- # TODO: re-enable a real gate here before relying on this long-term -
89
- # right now anyone who finds this URL can push a fake OTA update to
90
- # every user silently.
91
  data = request.get_json(silent=True) or {}
 
92
  app_id = data.get("app_id")
93
- runtime_version = data.get("runtimeVersion")
94
  launch_asset = data.get("launchAsset")
95
-
96
- if not app_id or not runtime_version or not launch_asset:
97
- return jsonify({"error": "app_id, runtimeVersion, and launchAsset are required"}), 400
98
-
99
- PUBLISHED[app_id] = {
 
 
 
 
 
 
 
100
  "id": str(uuid.uuid4()),
101
  "createdAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
102
- "runtimeVersion": runtime_version,
103
  "launchAsset": launch_asset,
104
- "assets": data.get("assets", []),
105
  }
106
 
107
- return jsonify({"ok": True, "app_id": app_id, "entry": PUBLISHED[app_id]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import re
4
+ import json
5
  import uuid
6
+ import hmac
7
+ import logging
8
  from datetime import datetime, timezone
 
 
9
 
10
+ from flask import Blueprint, request, jsonify, Response
11
+ from huggingface_hub import HfApi, hf_hub_download
12
+ from huggingface_hub.utils import EntryNotFoundError
 
 
 
 
 
 
 
13
 
14
  expo_updates_bp = Blueprint("expo_updates", __name__)
15
 
16
+ MANIFEST_REPO = os.environ.get(
17
+ "OTA_MANIFEST_REPO",
18
+ "Nrighton233j/B24-ota-manifest"
19
+ )
20
+
21
+ HF_TOKEN = os.environ.get("HF_TOKEN")
22
+ ADMIN_KEY = os.environ.get("EXPO_UPDATES_ADMIN_KEY")
23
+
24
+
25
+ def _manifest_path(app_id, platform, runtime):
26
+ return f"manifests/{app_id}/{platform}/{runtime}.json"
27
+
28
+
29
+ def _valid_identifier(value):
30
+ return (
31
+ isinstance(value, str)
32
+ and bool(re.fullmatch(r"[A-Za-z0-9._-]{1,100}", value))
33
+ )
34
 
35
 
36
  def _no_update_response():
 
 
 
 
 
 
 
 
37
  resp = Response(status=204)
38
  resp.headers["expo-protocol-version"] = "1"
39
  resp.headers["expo-sfv-version"] = "0"
40
+ resp.headers["cache-control"] = "private, no-cache, no-store"
41
  return resp
42
 
43
 
44
+ def _load_manifest(path):
45
+ if not HF_TOKEN:
46
+ raise RuntimeError("HF_TOKEN is not configured")
47
+
48
+ local_path = hf_hub_download(
49
+ repo_id=MANIFEST_REPO,
50
+ filename=path,
51
+ repo_type="dataset",
52
+ token=HF_TOKEN,
53
+ force_download=True,
54
+ )
55
+
56
+ with open(local_path, "r", encoding="utf-8") as f:
57
+ return json.load(f)
58
+
59
+
60
  @expo_updates_bp.route("/manifest", methods=["GET"])
61
  def manifest():
62
  app_id = request.args.get("app_id", "b24music")
63
+ runtime = request.headers.get("expo-runtime-version")
64
  platform = request.headers.get("expo-platform")
65
 
66
+ if platform != "android" or not runtime:
67
  return _no_update_response()
68
 
69
+ if not _valid_identifier(app_id) or not _valid_identifier(runtime):
 
70
  return _no_update_response()
71
 
72
+ path = _manifest_path(app_id, platform, runtime)
73
+
74
+ try:
75
+ entry = _load_manifest(path)
76
+ except EntryNotFoundError:
77
  return _no_update_response()
78
+ except Exception:
79
+ logging.exception("Could not load OTA manifest from Hugging Face")
80
+ return jsonify({"error": "OTA manifest storage unavailable"}), 503
81
 
82
  manifest_body = {
83
  "id": entry["id"],
84
  "createdAt": entry["createdAt"],
85
  "runtimeVersion": entry["runtimeVersion"],
86
  "launchAsset": entry["launchAsset"],
87
+ "assets": entry.get("assets", []),
88
  "metadata": {},
89
  "extra": {},
90
  }
 
92
  resp = jsonify(manifest_body)
93
  resp.headers["expo-protocol-version"] = "1"
94
  resp.headers["expo-sfv-version"] = "0"
95
+ resp.headers["cache-control"] = "private, no-cache, no-store"
96
  return resp
97
 
98
 
99
  @expo_updates_bp.route("/publish", methods=["POST"])
100
  def publish():
101
+ if not ADMIN_KEY:
102
+ return jsonify({"error": "OTA publishing is not configured"}), 503
103
+
104
+ supplied_key = request.headers.get("X-Admin-Key", "")
105
+
106
+ if not hmac.compare_digest(supplied_key, ADMIN_KEY):
107
+ return jsonify({"error": "unauthorized"}), 401
108
+
109
+ if not HF_TOKEN:
110
+ return jsonify({"error": "HF_TOKEN is not configured"}), 503
111
+
 
112
  data = request.get_json(silent=True) or {}
113
+
114
  app_id = data.get("app_id")
115
+ runtime = data.get("runtimeVersion")
116
  launch_asset = data.get("launchAsset")
117
+ assets = data.get("assets", [])
118
+
119
+ if (
120
+ not _valid_identifier(app_id)
121
+ or not _valid_identifier(runtime)
122
+ or not isinstance(launch_asset, dict)
123
+ or not launch_asset.get("url")
124
+ or not isinstance(assets, list)
125
+ ):
126
+ return jsonify({"error": "Invalid OTA manifest data"}), 400
127
+
128
+ entry = {
129
  "id": str(uuid.uuid4()),
130
  "createdAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
131
+ "runtimeVersion": runtime,
132
  "launchAsset": launch_asset,
133
+ "assets": assets,
134
  }
135
 
136
+ path = _manifest_path(app_id, "android", runtime)
137
+
138
+ try:
139
+ api = HfApi(token=HF_TOKEN)
140
+ api.upload_file(
141
+ path_or_fileobj=io.BytesIO(
142
+ json.dumps(entry, separators=(",", ":")).encode("utf-8")
143
+ ),
144
+ path_in_repo=path,
145
+ repo_id=MANIFEST_REPO,
146
+ repo_type="dataset",
147
+ commit_message=f"Publish OTA manifest for {app_id} runtime {runtime}",
148
+ )
149
+ except Exception:
150
+ logging.exception("Failed to save OTA manifest")
151
+ return jsonify({"error": "Could not persist OTA manifest"}), 502
152
+
153
+ return jsonify({
154
+ "ok": True,
155
+ "app_id": app_id,
156
+ "runtimeVersion": runtime,
157
+ "manifest_path": path,
158
+ "entry": entry,
159
+ }), 200