otaship 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
otaship/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Self-hosted update server for Expo apps (expo-updates protocol)."""
2
+
3
+ __version__ = "0.1.0"
otaship/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
otaship/admin.py ADDED
@@ -0,0 +1,319 @@
1
+ """Admin API (bearer token) and dashboard routes (session cookie + CSRF token)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import os
9
+ import time
10
+ from typing import TYPE_CHECKING, Any
11
+ from urllib.parse import urlsplit
12
+
13
+ from fastapi import FastAPI, Request
14
+ from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
15
+
16
+ from .bodies import BodyTooLarge, read_form, read_limited
17
+ from .storage import StorageError
18
+ from .store import StoreError
19
+ from .validation import valid_blob_name, valid_channel, valid_runtime
20
+
21
+ if TYPE_CHECKING:
22
+ from .app import Context
23
+
24
+ MIN_TOKEN_LEN = 16
25
+ SESSION_COOKIE = "otaship_session"
26
+ SESSION_TTL = 12 * 3600
27
+
28
+
29
+ class AdminError(Exception):
30
+ def __init__(self, status: int, message: str, code: str = "error", extra: dict[str, Any] | None = None):
31
+ super().__init__(message)
32
+ self.status, self.message, self.code, self.extra = status, message, code, extra or {}
33
+
34
+
35
+ def _token_ok(ctx: Context, presented: str) -> bool:
36
+ expected = ctx.settings.admin_token
37
+ if len(expected) < MIN_TOKEN_LEN or not presented:
38
+ return False
39
+ return hmac.compare_digest(expected.encode(), presented.encode())
40
+
41
+
42
+ def _require_bearer(ctx: Context, request: Request) -> None:
43
+ if len(ctx.settings.admin_token) < MIN_TOKEN_LEN:
44
+ raise AdminError(503, f"admin API disabled: set OTASHIP_ADMIN_TOKEN (>= {MIN_TOKEN_LEN} chars)")
45
+ auth = request.headers.get("authorization", "")
46
+ scheme, _, presented = auth.partition(" ")
47
+ if scheme.lower() != "bearer" or not _token_ok(ctx, presented.strip()):
48
+ raise AdminError(401, "invalid or missing admin token", "unauthorized")
49
+
50
+
51
+ async def _json_body(request: Request, limit: int) -> dict[str, Any]:
52
+ try:
53
+ raw = await read_limited(request, limit)
54
+ except BodyTooLarge as exc:
55
+ raise AdminError(413, str(exc)) from exc
56
+ try:
57
+ data = json.loads(raw or b"{}")
58
+ except ValueError as exc:
59
+ raise AdminError(400, "body must be JSON") from exc
60
+ if not isinstance(data, dict):
61
+ raise AdminError(400, "body must be a JSON object")
62
+ return data
63
+
64
+
65
+ def _channel_args(runtime: str, channel: str) -> None:
66
+ if not (valid_runtime(runtime) and valid_channel(channel)):
67
+ raise AdminError(400, "invalid runtime or channel")
68
+
69
+
70
+ def _opt_str(data: dict[str, Any], key: str) -> str | None:
71
+ value = data.get(key)
72
+ if value is not None and not isinstance(value, str):
73
+ raise AdminError(400, f"{key} must be a string")
74
+ return value
75
+
76
+
77
+ # ---- session (dashboard) ---------------------------------------------------------
78
+ def _session_key(ctx: Context) -> bytes:
79
+ return hashlib.sha256(b"otaship-session|" + ctx.settings.admin_token.encode()).digest()
80
+
81
+
82
+ def make_session(ctx: Context, now: float | None = None) -> str:
83
+ exp = str(int((now if now is not None else time.time()) + SESSION_TTL))
84
+ nonce = os.urandom(12).hex()
85
+ sig = hmac.new(_session_key(ctx), f"{exp}.{nonce}".encode(), hashlib.sha256).hexdigest()
86
+ return f"{exp}.{nonce}.{sig}"
87
+
88
+
89
+ def session_ok(ctx: Context, cookie: str | None, now: float | None = None) -> bool:
90
+ if not cookie or len(ctx.settings.admin_token) < MIN_TOKEN_LEN:
91
+ return False
92
+ parts = cookie.split(".")
93
+ if len(parts) != 3 or not parts[0].isdigit():
94
+ return False
95
+ exp, nonce, sig = parts
96
+ good = hmac.new(_session_key(ctx), f"{exp}.{nonce}".encode(), hashlib.sha256).hexdigest()
97
+ return hmac.compare_digest(good, sig) and int(exp) > (now if now is not None else time.time())
98
+
99
+
100
+ def csrf_token(ctx: Context, cookie: str) -> str:
101
+ return hmac.new(_session_key(ctx), b"csrf|" + cookie.encode(), hashlib.sha256).hexdigest()
102
+
103
+
104
+ async def _form_or_empty(request: Request) -> dict[str, str]:
105
+ try:
106
+ return await read_form(request)
107
+ except BodyTooLarge:
108
+ return {}
109
+
110
+
111
+ def _same_origin(request: Request) -> bool:
112
+ origin = request.headers.get("origin") or request.headers.get("referer")
113
+ if not origin:
114
+ return True # non-browser client; the CSRF token still has to match
115
+ host = request.headers.get("host", "")
116
+ return urlsplit(origin).netloc == host
117
+
118
+
119
+ # ---- routes -------------------------------------------------------------------------
120
+ def register_admin(app: FastAPI, ctx: Context) -> None: # noqa: C901 - route table
121
+ store, s = ctx.store, ctx.settings
122
+
123
+ @app.exception_handler(AdminError)
124
+ async def _admin_error(_request: Request, exc: AdminError) -> JSONResponse:
125
+ return JSONResponse({"error": exc.message, "code": exc.code, **exc.extra}, status_code=exc.status,
126
+ headers={"cache-control": "no-store"})
127
+
128
+ @app.exception_handler(StoreError)
129
+ async def _store_error(_request: Request, exc: StoreError) -> JSONResponse:
130
+ body: dict[str, Any] = {"error": str(exc), "code": exc.code}
131
+ if exc.index is not None:
132
+ body["state"] = {k: exc.index.get(k) for k in ("active", "previous", "candidate", "directive")}
133
+ return JSONResponse(body, status_code=exc.status, headers={"cache-control": "no-store"})
134
+
135
+ @app.exception_handler(StorageError)
136
+ async def _storage_error(_request: Request, exc: StorageError) -> JSONResponse:
137
+ # Unreadable metadata: refuse to act rather than rebuild state from scratch.
138
+ return JSONResponse({"error": "storage read failed; nothing was changed", "code": "storage_error"},
139
+ status_code=500, headers={"cache-control": "no-store"})
140
+
141
+ @app.exception_handler(BodyTooLarge)
142
+ async def _too_large(_request: Request, exc: BodyTooLarge) -> JSONResponse:
143
+ return JSONResponse({"error": str(exc), "code": "too_large"}, status_code=413)
144
+
145
+ # -- blobs --
146
+ @app.post("/admin/api/blobs/missing")
147
+ async def blobs_missing(request: Request) -> dict[str, Any]:
148
+ _require_bearer(ctx, request)
149
+ data = await _json_body(request, 1024 * 1024)
150
+ names = data.get("names")
151
+ if not isinstance(names, list) or len(names) > 20000 or not all(valid_blob_name(n) for n in names):
152
+ raise AdminError(400, "names must be a list of valid blob names")
153
+ return {"missing": sorted({n for n in names if not ctx.storage.has_blob(n)})}
154
+
155
+ @app.put("/admin/api/blobs/{name}")
156
+ async def blob_upload(name: str, request: Request) -> dict[str, Any]:
157
+ _require_bearer(ctx, request)
158
+ if not valid_blob_name(name):
159
+ raise AdminError(400, "invalid blob name (expected <md5><.ext>)")
160
+ expected_sha = request.query_params.get("sha256", "")
161
+ if ctx.storage.has_blob(name):
162
+ return {"name": name, "status": "exists"}
163
+ declared = request.headers.get("content-length")
164
+ if declared and declared.isdigit() and int(declared) > s.max_blob_bytes:
165
+ raise AdminError(413, f"blob larger than {s.max_blob_bytes} bytes")
166
+ md5, sha, size = hashlib.md5(), hashlib.sha256(), 0 # noqa: S324 - md5 is the expo asset key
167
+ tmp_path, fh = ctx.storage.new_upload_file()
168
+ try:
169
+ async for chunk in request.stream():
170
+ size += len(chunk)
171
+ if size > s.max_blob_bytes:
172
+ raise AdminError(413, f"blob larger than {s.max_blob_bytes} bytes")
173
+ md5.update(chunk)
174
+ sha.update(chunk)
175
+ fh.write(chunk)
176
+ if md5.hexdigest() != name[:32]:
177
+ raise AdminError(400, "content md5 does not match the blob name")
178
+ import base64
179
+
180
+ sha_b64 = base64.urlsafe_b64encode(sha.digest()).decode().rstrip("=")
181
+ if expected_sha and not hmac.compare_digest(expected_sha, sha_b64):
182
+ raise AdminError(400, "content sha256 does not match ?sha256=")
183
+ ctx.storage.put_blob(name, fh)
184
+ finally:
185
+ if not fh.closed:
186
+ fh.close()
187
+ if tmp_path.exists():
188
+ tmp_path.unlink()
189
+ return {"name": name, "status": "stored", "size": size, "hash": sha_b64}
190
+
191
+ # -- updates --
192
+ @app.post("/admin/api/updates")
193
+ async def register_update(request: Request) -> dict[str, Any]:
194
+ _require_bearer(ctx, request)
195
+ doc = await _json_body(request, s.max_update_doc_bytes)
196
+ actor = _opt_str(doc, "actor") or "api"
197
+ doc.pop("actor", None)
198
+ return {"update": store.register(doc, actor=actor)}
199
+
200
+ @app.get("/admin/api/channels")
201
+ def list_channels(request: Request) -> dict[str, Any]:
202
+ _require_bearer(ctx, request)
203
+ return {"channels": [store.channel_view(rt, ch, history=10) for rt, ch in store.channels()]}
204
+
205
+ @app.get("/admin/api/channels/{runtime}/{channel}")
206
+ def get_channel(runtime: str, channel: str, request: Request) -> dict[str, Any]:
207
+ _require_bearer(ctx, request)
208
+ _channel_args(runtime, channel)
209
+ view = store.channel_view(runtime, channel, history=int(request.query_params.get("history", "50") or 50))
210
+ health = ctx.guard.candidate_health(runtime, channel)
211
+ if health is not None:
212
+ view["candidate_health"] = {"served": health.served, "observed": health.matured,
213
+ "confirmed": health.confirmed, "ratio": health.ratio}
214
+ return view
215
+
216
+ @app.post("/admin/api/channels/{runtime}/{channel}/{action}")
217
+ async def channel_action(runtime: str, channel: str, action: str, request: Request) -> dict[str, Any]:
218
+ _require_bearer(ctx, request)
219
+ _channel_args(runtime, channel)
220
+ data = await _json_body(request, 64 * 1024)
221
+ actor = _opt_str(data, "actor") or "api"
222
+ reason = _opt_str(data, "reason") or ""
223
+ return {"index": _dispatch(ctx, runtime, channel, action, data, actor, reason)}
224
+
225
+ # -- dashboard --
226
+ from .dashboard import render_dashboard, render_login
227
+
228
+ def _session(request: Request) -> str | None:
229
+ cookie = request.cookies.get(SESSION_COOKIE)
230
+ return cookie if session_ok(ctx, cookie) else None
231
+
232
+ page_headers = {"cache-control": "no-store", "x-frame-options": "DENY",
233
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; "
234
+ "form-action 'self'; frame-ancestors 'none'",
235
+ "referrer-policy": "same-origin", "x-content-type-options": "nosniff"}
236
+
237
+ @app.get("/admin", response_class=HTMLResponse)
238
+ def dashboard(request: Request) -> Response:
239
+ cookie = _session(request)
240
+ if cookie is None:
241
+ enabled = len(s.admin_token) >= MIN_TOKEN_LEN
242
+ return HTMLResponse(render_login(enabled=enabled, error=request.query_params.get("e") == "1"),
243
+ headers=page_headers)
244
+ return HTMLResponse(render_dashboard(ctx, csrf_token(ctx, cookie),
245
+ notice=request.query_params.get("msg", "")[:200]),
246
+ headers=page_headers)
247
+
248
+ @app.post("/admin/login")
249
+ async def login(request: Request) -> Response:
250
+ form = await _form_or_empty(request)
251
+ if not _same_origin(request) or not _token_ok(ctx, str(form.get("token") or "")):
252
+ return RedirectResponse("/admin?e=1", status_code=303)
253
+ resp = RedirectResponse("/admin", status_code=303)
254
+ resp.set_cookie(SESSION_COOKIE, make_session(ctx), max_age=SESSION_TTL, httponly=True,
255
+ secure=s.secure_cookies, samesite="strict", path="/admin")
256
+ return resp
257
+
258
+ @app.post("/admin/logout")
259
+ async def logout(request: Request) -> Response:
260
+ resp = RedirectResponse("/admin", status_code=303)
261
+ resp.delete_cookie(SESSION_COOKIE, path="/admin")
262
+ return resp
263
+
264
+ @app.post("/admin/action")
265
+ async def dashboard_action(request: Request) -> Response:
266
+ cookie = _session(request)
267
+ form = await _form_or_empty(request)
268
+ if cookie is None or not _same_origin(request) or not hmac.compare_digest(
269
+ csrf_token(ctx, cookie), str(form.get("csrf") or "")):
270
+ return Response("forbidden", status_code=403, headers=page_headers)
271
+ runtime, channel = str(form.get("runtime") or ""), str(form.get("channel") or "")
272
+ data: dict[str, Any] = {k: str(v) for k, v in form.items() if k in ("group", "to", "expected_active")}
273
+ if form.get("percent"):
274
+ try:
275
+ data["percent"] = int(str(form.get("percent")))
276
+ except ValueError:
277
+ data["percent"] = -1
278
+ data["auto_rollback"] = form.get("auto_rollback") == "on"
279
+ try:
280
+ _channel_args(runtime, channel)
281
+ _dispatch(ctx, runtime, channel, str(form.get("action") or ""), data, "dashboard", "")
282
+ msg = "done"
283
+ except (AdminError, StoreError) as exc:
284
+ msg = f"error: {exc}"
285
+ from urllib.parse import quote
286
+
287
+ return RedirectResponse(f"/admin?msg={quote(msg[:200])}", status_code=303)
288
+
289
+
290
+ def _dispatch(ctx: Context, runtime: str, channel: str, action: str, data: dict[str, Any],
291
+ actor: str, reason: str) -> dict[str, Any]:
292
+ store = ctx.store
293
+ group = _opt_str(data, "group") or ""
294
+ expected = _opt_str(data, "expected_active")
295
+ if action == "activate":
296
+ return store.activate(runtime, channel, group, actor=actor, reason=reason, expected_active=expected)
297
+ if action == "rollback":
298
+ to = data.get("to", "previous")
299
+ if to == "embedded":
300
+ return store.rollback_to_embedded(runtime, channel, actor=actor, reason=reason, expected_active=expected)
301
+ if to != "previous":
302
+ raise AdminError(400, "to must be 'previous' or 'embedded'")
303
+ return store.rollback(runtime, channel, actor=actor, reason=reason, expected_active=expected)
304
+ if action == "stage":
305
+ percent = data.get("percent")
306
+ auto = data.get("auto_rollback")
307
+ if auto is None:
308
+ auto = ctx.settings.auto_rollback.enabled
309
+ if not isinstance(percent, int) or not isinstance(auto, bool):
310
+ raise AdminError(400, "percent must be an integer and auto_rollback a boolean")
311
+ return store.stage(runtime, channel, group, percent, actor=actor, reason=reason,
312
+ expected_active=expected, auto_rollback=auto)
313
+ if action == "promote":
314
+ return store.promote(runtime, channel, group, actor=actor, reason=reason)
315
+ if action == "abort":
316
+ return store.abort(runtime, channel, group, actor=actor, reason=reason)
317
+ raise AdminError(404, f"unknown action {action!r}")
318
+
319
+
otaship/app.py ADDED
@@ -0,0 +1,271 @@
1
+ """FastAPI application: public update endpoints (manifest, assets, health).
2
+
3
+ The admin API and dashboard live in admin.py and dashboard.py.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import logging
10
+ import mimetypes
11
+ import os
12
+ import secrets
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+ from fastapi import FastAPI, Request
17
+ from fastapi.responses import FileResponse, JSONResponse, Response
18
+
19
+ from . import __version__
20
+ from .bodies import BodyTooLarge, read_limited
21
+ from .config import Settings
22
+ from .guard import RolloutGuard
23
+ from .protocol import Signer, build_manifest, dumps, multipart
24
+ from .storage import LocalStorage, Storage, StorageError
25
+ from .store import UpdateStore
26
+ from .telemetry import Telemetry
27
+ from .validation import PLATFORMS, UUID_RE, valid_blob_name, valid_channel, valid_runtime
28
+ from .webhooks import WebhookDispatcher
29
+
30
+ log = logging.getLogger("otaship")
31
+
32
+ NO_STORE = "private, no-store, max-age=0"
33
+ IMMUTABLE = "public, max-age=31536000, immutable"
34
+ # Assets share the origin with /admin: never let an uploaded HTML/SVG file run script there.
35
+ ASSET_HEADERS = {"cache-control": IMMUTABLE, "content-security-policy": "sandbox; default-src 'none'",
36
+ "x-content-type-options": "nosniff"}
37
+ _TOKEN_CHARS = frozenset("0123456789abcdef")
38
+
39
+
40
+ @dataclass
41
+ class Context:
42
+ settings: Settings
43
+ storage: Storage
44
+ store: UpdateStore
45
+ telemetry: Telemetry
46
+ guard: RolloutGuard
47
+ signer: Signer
48
+ webhooks: WebhookDispatcher
49
+
50
+
51
+ def _load_secret(path: os.PathLike[str]) -> bytes:
52
+ """Per-installation secret used to pseudonymize device ids (created on first start)."""
53
+ try:
54
+ with open(path, "rb") as fh:
55
+ data = fh.read().strip()
56
+ if len(data) >= 32:
57
+ return data
58
+ except FileNotFoundError:
59
+ pass
60
+ data = secrets.token_hex(32).encode()
61
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
62
+ with os.fdopen(fd, "wb") as fh:
63
+ fh.write(data)
64
+ return data
65
+
66
+
67
+ def build_context(settings: Settings) -> Context:
68
+ storage = LocalStorage(settings.data_dir)
69
+ webhooks = WebhookDispatcher(settings.webhook_urls, settings.webhook_secret)
70
+ store = UpdateStore(storage, history_max=settings.history_max, on_event=webhooks)
71
+ telemetry = Telemetry(settings.data_dir / "telemetry.sqlite3", _load_secret(settings.data_dir / "telemetry.secret"))
72
+ guard = RolloutGuard(store, telemetry, settings.auto_rollback)
73
+ signer = Signer(settings.signing_key_path, settings.signing_keyid)
74
+ return Context(settings, storage, store, telemetry, guard, signer, webhooks)
75
+
76
+
77
+ def _proto(request: Request) -> int:
78
+ try:
79
+ return 1 if int(request.headers.get("expo-protocol-version", "0")) >= 1 else 0
80
+ except ValueError:
81
+ return 0
82
+
83
+
84
+ def _error(status: int, message: str, proto: int) -> JSONResponse:
85
+ return JSONResponse({"error": message}, status_code=status,
86
+ headers={"expo-protocol-version": str(proto), "cache-control": NO_STORE})
87
+
88
+
89
+ def _multipart_response(name: str, obj: dict[str, Any], ctx: Context, extra_headers: dict[str, str]) -> Response:
90
+ body = dumps(obj)
91
+ part_headers = ctx.signer.headers_for(body)
92
+ payload, boundary = multipart([(name, body, part_headers)])
93
+ headers = {"expo-protocol-version": "1", "expo-sfv-version": "0", "cache-control": NO_STORE, **extra_headers}
94
+ return Response(payload, media_type=f"multipart/mixed; boundary={boundary}", headers=headers)
95
+
96
+
97
+ def _json_response(obj: dict[str, Any], proto: int, ctx: Context, media: str,
98
+ extra_headers: dict[str, str]) -> Response:
99
+ body = dumps(obj)
100
+ headers = {"expo-protocol-version": str(proto), "expo-sfv-version": "0", "cache-control": NO_STORE,
101
+ **ctx.signer.headers_for(body), **extra_headers}
102
+ return Response(body, media_type=media, headers=headers)
103
+
104
+
105
+ _MULTIPART = "multipart/mixed"
106
+ _JSON_TYPES = ("application/expo+json", "application/json")
107
+
108
+
109
+ def accept_weights(accept: str) -> dict[str, float]:
110
+ """q-value of each media type we can produce, using the most specific matching Accept range."""
111
+ if not accept.strip():
112
+ return {_MULTIPART: 1.0, _JSON_TYPES[0]: 0.5, _JSON_TYPES[1]: 0.5}
113
+ ranges: list[tuple[str, float]] = []
114
+ for item in accept.split(","):
115
+ media, *params = (p.strip() for p in item.split(";"))
116
+ q = 1.0
117
+ for param in params:
118
+ if param.lower().startswith("q="):
119
+ try:
120
+ q = float(param[2:])
121
+ except ValueError:
122
+ q = 0.0
123
+ if not 0.0 <= q <= 1.0: # also rejects NaN
124
+ q = 0.0
125
+ if media:
126
+ ranges.append((media.lower(), q))
127
+ weights = {}
128
+ for concrete in (_MULTIPART, *_JSON_TYPES):
129
+ kind = concrete.split("/")[0] + "/*"
130
+ best = None
131
+ for rank, pattern in enumerate((concrete, kind, "*/*")):
132
+ matches = [q for media, q in ranges if media == pattern]
133
+ if matches:
134
+ best = (rank, max(matches))
135
+ break
136
+ weights[concrete] = best[1] if best else 0.0
137
+ return weights
138
+
139
+
140
+ def negotiate(accept: str) -> str | None:
141
+ """Pick the response media type: multipart/mixed, a JSON type, or None (406). Ties prefer multipart."""
142
+ weights = accept_weights(accept)
143
+ best = max(weights, key=lambda m: (weights[m], m == _MULTIPART, m == _JSON_TYPES[0]))
144
+ return best if weights[best] > 0 else None
145
+
146
+
147
+ def _no_update(proto: int, expect_signature: bool, ctx: Context, multipart_ok: bool = True) -> Response:
148
+ # 204 is the cheapest "no update". A client that expects a signature rejects an empty
149
+ # body, so protocol 1 clients with code signing get a signed noUpdateAvailable directive.
150
+ if proto >= 1 and expect_signature and ctx.signer.enabled and multipart_ok:
151
+ return _multipart_response("directive", {"type": "noUpdateAvailable"}, ctx, {})
152
+ return Response(status_code=204, headers={"expo-protocol-version": str(proto), "expo-sfv-version": "0",
153
+ "cache-control": NO_STORE})
154
+
155
+
156
+ def _asset_base(ctx: Context, request: Request) -> str:
157
+ s = ctx.settings
158
+ if s.asset_base_url:
159
+ return s.asset_base_url
160
+ if s.public_url:
161
+ return f"{s.public_url}/assets"
162
+ return str(request.base_url).rstrip("/") + "/assets"
163
+
164
+
165
+ def create_app(settings: Settings | None = None) -> FastAPI:
166
+ settings = settings or Settings.from_env()
167
+ ctx = build_context(settings)
168
+ app = FastAPI(title="otaship", version=__version__, docs_url=None, redoc_url=None, openapi_url=None)
169
+ app.state.ctx = ctx
170
+
171
+ @app.get("/healthz")
172
+ def healthz() -> dict[str, Any]:
173
+ return {"ok": True, "version": __version__, "signing": ctx.signer.enabled}
174
+
175
+ @app.get("/manifest")
176
+ def manifest(request: Request) -> Response:
177
+ h, q = request.headers, request.query_params
178
+ proto = _proto(request)
179
+ platform = (h.get("expo-platform") or q.get("platform") or "").lower()
180
+ runtime = h.get("expo-runtime-version") or q.get("runtime-version") or ""
181
+ channel = (h.get("expo-channel-name") or q.get("channel") or settings.default_channel).lower()
182
+ current = (h.get("expo-current-update-id") or "").lower()
183
+ embedded = (h.get("expo-embedded-update-id") or "").lower()
184
+ expect_signature = bool(h.get("expo-expect-signature"))
185
+ accept = ",".join(h.getlist("accept"))
186
+ fmt = negotiate(accept) if proto >= 1 else "application/json"
187
+ multipart_ok = proto >= 1 and accept_weights(accept)[_MULTIPART] > 0
188
+ if fmt is None:
189
+ return _error(406, "Accept must allow multipart/mixed or application/expo+json", proto)
190
+
191
+ if platform not in PLATFORMS:
192
+ return _error(400, "expo-platform must be 'android' or 'ios'", proto)
193
+ if not valid_runtime(runtime):
194
+ return _error(400, "expo-runtime-version is missing or invalid", proto)
195
+ if not valid_channel(channel):
196
+ return _error(400, "expo-channel-name is invalid", proto)
197
+
198
+ client = ctx.telemetry.client_marker(h.get("eas-client-id") or "")
199
+ if client and current:
200
+ ctx.telemetry.record_check(client=client, runtime=runtime, channel=channel, platform=platform,
201
+ current=current)
202
+ try:
203
+ idx = ctx.store.read_index(runtime, channel)
204
+ if idx is not None and (idx.get("candidate") or {}).get("auto_rollback"):
205
+ ctx.guard.maybe_evaluate(runtime, channel)
206
+ idx = ctx.store.read_index(runtime, channel) or idx
207
+ group = ctx.store.pick_group(idx, h.get("eas-client-id") or "") if idx else None
208
+ doc = ctx.store.read_update(runtime, channel, group) if group else None
209
+ except StorageError:
210
+ return _error(503, "update metadata is temporarily unreadable", proto)
211
+ if idx is None:
212
+ return _no_update(proto, expect_signature, ctx, multipart_ok)
213
+
214
+ directive = idx.get("directive") or {}
215
+ if directive.get("type") == "rollBackToEmbedded":
216
+ # Protocol 0 has no directives. A device already running its embedded update
217
+ # has nothing to roll back.
218
+ if proto < 1 or (current and embedded and current == embedded):
219
+ return _no_update(proto, expect_signature, ctx, multipart_ok)
220
+ if not multipart_ok:
221
+ return _error(406, "directives require Accept: multipart/mixed", proto)
222
+ return _multipart_response("directive", {
223
+ "type": "rollBackToEmbedded",
224
+ "parameters": {"commitTime": directive.get("commitTime")},
225
+ }, ctx, {})
226
+
227
+ pdata = ((doc or {}).get("platforms") or {}).get(platform)
228
+ if not doc or not pdata or (current and current == pdata["id"]):
229
+ return _no_update(proto, expect_signature, ctx, multipart_ok)
230
+
231
+ extra = {"expoOtaServer": {"healthToken": client}} if client else None
232
+ body = build_manifest(doc, platform, channel, _asset_base(ctx, request), extra)
233
+ if client:
234
+ ctx.telemetry.record_served(client=client, update_id=pdata["id"], group=doc["group"])
235
+ headers = {"expo-manifest-filters": f'branchname="{channel}"'}
236
+ if fmt == _MULTIPART:
237
+ return _multipart_response("manifest", body, ctx, headers)
238
+ return _json_response(body, proto, ctx, fmt, headers)
239
+
240
+ @app.get("/assets/{name}")
241
+ def asset(name: str) -> Response:
242
+ if not valid_blob_name(name):
243
+ return JSONResponse({"error": "not found"}, status_code=404)
244
+ path = ctx.storage.blob_path(name)
245
+ if path is None:
246
+ return JSONResponse({"error": "not found"}, status_code=404)
247
+ media = "application/javascript" if name.endswith(".js") else (
248
+ mimetypes.guess_type(name)[0] or "application/octet-stream")
249
+ return FileResponse(path, media_type=media, headers=ASSET_HEADERS)
250
+
251
+ @app.post("/health", status_code=204)
252
+ async def launch_health(request: Request) -> Response:
253
+ """Explicit launch confirmation sent by the app (see README, "Auto-rollback")."""
254
+ try:
255
+ raw = await read_limited(request, 4096)
256
+ except BodyTooLarge:
257
+ return Response(status_code=413)
258
+ try:
259
+ data = json.loads(raw or b"{}")
260
+ except ValueError:
261
+ return Response(status_code=400)
262
+ update_id = str(data.get("updateId") or "").lower() if isinstance(data, dict) else ""
263
+ token = str(data.get("token") or "") if isinstance(data, dict) else ""
264
+ if UUID_RE.match(update_id) and len(token) == 32 and set(token) <= _TOKEN_CHARS:
265
+ ctx.telemetry.record_confirmation(client=token, update_id=update_id)
266
+ return Response(status_code=204)
267
+
268
+ from .admin import register_admin
269
+
270
+ register_admin(app, ctx)
271
+ return app
otaship/bodies.py ADDED
@@ -0,0 +1,39 @@
1
+ """Bounded request-body reading for unauthenticated or form endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from urllib.parse import parse_qs
6
+
7
+ from fastapi import Request
8
+
9
+
10
+ class BodyTooLarge(ValueError):
11
+ pass
12
+
13
+
14
+ async def read_limited(request: Request, limit: int) -> bytes:
15
+ """Read the body but stop as soon as it exceeds `limit` bytes (with or without Content-Length)."""
16
+ declared = request.headers.get("content-length", "")
17
+ if declared.isdigit() and int(declared) > limit:
18
+ raise BodyTooLarge(f"request body larger than {limit} bytes")
19
+ chunks: list[bytes] = []
20
+ size = 0
21
+ async for chunk in request.stream():
22
+ size += len(chunk)
23
+ if size > limit:
24
+ raise BodyTooLarge(f"request body larger than {limit} bytes")
25
+ chunks.append(chunk)
26
+ return b"".join(chunks)
27
+
28
+
29
+ async def read_form(request: Request, limit: int = 16 * 1024) -> dict[str, str]:
30
+ """Parse a small application/x-www-form-urlencoded body (first value per field)."""
31
+ ctype = request.headers.get("content-type", "").split(";")[0].strip().lower()
32
+ if ctype != "application/x-www-form-urlencoded":
33
+ return {}
34
+ raw = await read_limited(request, limit)
35
+ try:
36
+ parsed = parse_qs(raw.decode("utf-8", "replace"), keep_blank_values=True, max_num_fields=50)
37
+ except ValueError:
38
+ return {}
39
+ return {k: v[0] for k, v in parsed.items()}