Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Android AR through the relay: the model goes encrypted via link.sculptforge.app

islandmed8d5b2488b6cc
diff --git a/services/link-worker/src/index.js b/services/link-worker/src/index.js
index 6639eea7..c1bf8304 100644
--- a/services/link-worker/src/index.js
+++ b/services/link-worker/src/index.js
@@ -15,6 +15,8 @@ export const TOPIC_PATTERN = /^sculptforge-[0-9a-f]{24}$/;
export const MAX_MESSAGE_BYTES = 8192;
export const MAX_MESSAGES = 4; // per topic: the answer, and a few retries
export const TTL_MS = 10 * 60 * 1000;
+export const MAX_BLOB_BYTES = 48 * 1024 * 1024; // an AR model (encrypted GLB), usually a few MB
+const BLOB_CHUNK = 1024 * 1024; // Durable Object storage values are limited to 2 MB
const MESSAGE_PATTERN = /^[A-Za-z0-9_-]+$/; // base64url: the relay carries opaque ciphertext only
export class Topic {
@@ -46,6 +48,32 @@ export class Topic {
return messages.filter((m) => m.time >= since && m.time >= fresh);
}
+ // The AR model for Android Chrome, which can't reach the computer on the home network: the desktop posts it
+ // encrypted (AES-GCM, key only in the AR page's #fragment), the page polls the version and downloads it. A newer
+ // version replaces an older one; posting keeps the topic alive for another TTL.
+ async putBlob(version, bytes) {
+ const meta = await this.ctx.storage.get("blob");
+ if (meta && meta.version >= version) return { version: meta.version, stale: true };
+ const chunks = Math.ceil(bytes.byteLength / BLOB_CHUNK);
+ for (let i = 0; i < chunks; ++i) await this.ctx.storage.put(`blob:${i}`, bytes.slice(i * BLOB_CHUNK, (i + 1) * BLOB_CHUNK));
+ await this.ctx.storage.put("blob", { version, bytes: bytes.byteLength, chunks });
+ await this.ctx.storage.setAlarm(Date.now() + TTL_MS);
+ return { version };
+ }
+
+ async getBlob(withData) {
+ const meta = await this.ctx.storage.get("blob");
+ if (!meta) return null;
+ if (!withData) return { meta };
+ const data = new Uint8Array(meta.bytes);
+ for (let i = 0, at = 0; i < meta.chunks; ++i) {
+ const chunk = new Uint8Array(await this.ctx.storage.get(`blob:${i}`));
+ data.set(chunk, at);
+ at += chunk.byteLength;
+ }
+ return { meta, data };
+ }
+
async alarm() {
await this.ctx.storage.deleteAll();
}
@@ -54,6 +82,14 @@ export class Topic {
// "cloudflare:workers", which plain Node can't import, and the tests run this file under plain Node.
async fetch(request) {
const url = new URL(request.url);
+ if (url.pathname === "/blob") {
+ if (request.method === "POST")
+ return Response.json(await this.putBlob(Number(url.searchParams.get("v")), await request.arrayBuffer()));
+ const blob = await this.getBlob(url.searchParams.has("data"));
+ if (!blob) return Response.json({ error: "no model yet" }, { status: 404 });
+ if (!blob.data) return Response.json(blob.meta);
+ return new Response(blob.data, { headers: { "X-Version": String(blob.meta.version) } });
+ }
if (request.method === "POST") return Response.json(await this.post(url.searchParams.get("topic"), await request.text()));
return Response.json(await this.poll(Number(url.searchParams.get("since"))));
}
@@ -84,6 +120,7 @@ function respond(body, status, origin, type = "application/json") {
if (origin) {
headers["Access-Control-Allow-Origin"] = origin;
headers["Access-Control-Allow-Methods"] = "GET, POST";
+ headers["Access-Control-Expose-Headers"] = "X-Version";
headers["Access-Control-Max-Age"] = "86400";
headers["Vary"] = "Origin";
}
@@ -101,6 +138,32 @@ export default {
if (url.pathname === "/" || url.pathname === "/relay" || url.pathname === "/relay/")
return respond(HOME_PAGE, 200, origin, "text/html; charset=utf-8");
+ const blobMatch = url.pathname.match(/^\/blob\/([^/]+)$/);
+ if (blobMatch) {
+ const topic = blobMatch[1];
+ if (!TOPIC_PATTERN.test(topic)) return json({ error: "bad topic" }, 400, origin);
+ const stub = env.TOPICS.get(env.TOPICS.idFromName(topic));
+ if (request.method === "POST") {
+ if (origin) return json({ error: "only SculptForge posts models" }, 403, origin); // not from a page
+ const version = Number(url.searchParams.get("v"));
+ if (!Number.isSafeInteger(version) || version < 1) return json({ error: "bad version" }, 400, origin);
+ if (Number(request.headers.get("Content-Length") ?? "0") > MAX_BLOB_BYTES) return json({ error: "too large" }, 413, origin);
+ const body = await request.arrayBuffer();
+ if (body.byteLength > MAX_BLOB_BYTES) return json({ error: "too large" }, 413, origin);
+ if (body.byteLength < 12 + 16) return json({ error: "not an encrypted model" }, 400, origin);
+ const r = await stub.fetch(new Request(`https://topic/blob?v=${version}`, { method: "POST", body }));
+ return json(await r.json(), 200, origin);
+ }
+ if (request.method !== "GET") return json({ error: "method not allowed" }, 405, origin);
+ const data = url.searchParams.has("data");
+ const r = await stub.fetch(new Request(`https://topic/blob${data ? "?data=1" : ""}`));
+ if (r.status === 404) return json({ error: "no model yet" }, 404, origin);
+ if (!data) return respond(await r.text(), 200, origin);
+ const out = respond(await r.arrayBuffer(), 200, origin, "application/octet-stream");
+ out.headers.set("X-Version", r.headers.get("X-Version"));
+ return out;
+ }
+
const match = url.pathname.match(/^\/relay\/([^/]+)(\/json)?$/);
if (!match) return json({ error: "not found" }, 404, origin);
const [, topic, poll] = match;
diff --git a/services/link-worker/test/relay.test.mjs b/services/link-worker/test/relay.test.mjs
index 847234e5..8f7751a6 100644
--- a/services/link-worker/test/relay.test.mjs
+++ b/services/link-worker/test/relay.test.mjs
@@ -67,3 +67,26 @@ test("messages are deleted ten minutes after the first", async () => {
assert.equal((await lines(await poll(env, TOPIC))).length, 0);
assert.equal((await post(env, TOPIC, "again")).status, 200); // the topic works again (a new alarm)
});
+
+test("an encrypted AR model: SculptForge posts it, the page reads the version and downloads it", async () => {
+ const env = fakeEnv();
+ const blob = (query = "", init = {}) => worker.fetch(new Request(`${BASE}/blob/${TOPIC}${query}`, init), env);
+ assert.equal((await blob("", { headers: { Origin: PAGE } })).status, 404); // nothing yet
+ const model = new Uint8Array(2.5 * 1024 * 1024).map((_, i) => (i * 131) % 251); // spans three chunks
+ assert.equal((await blob("?v=2", { method: "POST", body: model })).status, 200);
+ // A page may not post; an older version doesn't replace a newer one; tiny or unversioned bodies are refused.
+ assert.equal((await blob("?v=3", { method: "POST", body: model, headers: { Origin: PAGE } })).status, 403);
+ assert.equal(await (await blob("?v=1", { method: "POST", body: new Uint8Array(100) })).json().then((j) => j.stale), true);
+ assert.equal((await blob("?v=4", { method: "POST", body: new Uint8Array(10) })).status, 400);
+ assert.equal((await blob("", { method: "POST", body: model })).status, 400);
+ const meta = await blob("", { headers: { Origin: PAGE } });
+ assert.equal(meta.status, 200);
+ assert.equal(meta.headers.get("Access-Control-Allow-Origin"), PAGE);
+ assert.deepEqual(await meta.json(), { version: 2, bytes: model.byteLength, chunks: 3 });
+ const got = await blob("?data=1", { headers: { Origin: PAGE } });
+ assert.equal(got.headers.get("X-Version"), "2");
+ assert.deepEqual(new Uint8Array(await got.arrayBuffer()), model);
+ // Gone after the TTL.
+ await env.fireAlarms(Date.now() + TTL_MS + 1000);
+ assert.equal((await blob("", { headers: { Origin: PAGE } })).status, 404);
+});
diff --git a/src/link/PhoneLink.cpp b/src/link/PhoneLink.cpp
index d2bd796e..af1dc89f 100644
--- a/src/link/PhoneLink.cpp
+++ b/src/link/PhoneLink.cpp
@@ -830,6 +830,26 @@ void PhoneLink::publishArModel(std::string glb, std::string usdz, std::string su
}
}
sendArModelToPage();
+ uploadArModel();
+}
+
+void PhoneLink::uploadArModel() {
+ std::string url, key, glb;
+ uint64_t version;
+ {
+ std::lock_guard lock(mutex_);
+ if (arBlobUrl_.empty() || arGlb_.empty() || arVersion_ == arBlobVersion_ || Clock::now() > arBlobUntil_) return;
+ url = arBlobUrl_;
+ key = arBlobKey_;
+ glb = arGlb_;
+ version = arBlobVersion_ = arVersion_;
+ }
+ std::thread([url, key, glb = std::move(glb), version] {
+ std::string packed, bytes, error;
+ if (!aesGcmEncrypt(key, glb, packed, error) || !base64UrlDecode(packed, bytes)) return;
+ // The relay keeps the newest version; an older upload finishing late is ignored there.
+ ai::httpRequest("POST", url + "?v=" + std::to_string(version), {"Content-Type: application/octet-stream"}, bytes, 120);
+ }).detach();
}
void PhoneLink::setArError(std::string error) {
@@ -1065,12 +1085,35 @@ bool PhoneLink::createFaceLink(std::string& faceUrl, std::string& error, bool ar
// Everything after '#' stays on the phone: the website never sees the offer, the token or the key.
std::string page = options_.siteUrl;
if (ar) page = page.substr(0, page.rfind('/') + 1) + "ar.html";
+ // AR: the model also goes through our relay (its /blob/ path), for phones whose browser can't reach this computer.
+ std::string blobUrl;
+ if (ar)
+ for (const std::string& relay : relays)
+ if (const size_t at = relay.rfind("/relay/"); at != std::string::npos && at + 7 == relay.size()) {
+ blobUrl = relay.substr(0, at) + "/blob/" + topic;
+ break;
+ }
faceUrl = page + "#v=1&k=" + token + "&d=" + percentEncode(desktop) + "&o=" + base64UrlEncode(sdp) +
"&n=" + percentEncode(options_.desktopName) + "&x=" + base64UrlEncode(key);
if (ar) {
char size[32];
std::snprintf(size, sizeof size, "%g", double(arSizeCm));
faceUrl += std::string("&m=ar&s=") + (arScope == "scene" ? "scene" : "subtool") + "&z=" + size;
+ std::lock_guard lock(mutex_);
+ arBlobUrl_ = blobUrl;
+ arBlobKey_ = key;
+ arBlobVersion_ = 0;
+ if (!blobUrl.empty()) {
+ faceUrl += "&b=" + percentEncode(blobUrl);
+ // A fresh model for the relay now (over the direct link the page asks for one itself once connected).
+ PhoneEvent e = PhoneEvent::make(PhoneEvent::Type::ArRequested);
+ e.wholeScene = arScope == "scene";
+ e.sizeCm = arSizeCm;
+ pushEvent(e);
+ arBlobUntil_ = Clock::now() + std::chrono::minutes(10);
+ arViewed_ = Clock::now();
+ arViewedEver_ = true;
+ }
}
for (const std::string& relay : relays) faceUrl += "&r=" + percentEncode(relay + topic); // the page tries them in order
if (!relays.empty()) {
diff --git a/src/link/PhoneLink.h b/src/link/PhoneLink.h
index 6125b44e..896d0be3 100644
--- a/src/link/PhoneLink.h
+++ b/src/link/PhoneLink.h
@@ -222,6 +222,7 @@ private:
HttpResponse serveArModel(bool usdz);
HttpResponse faceLink(const HttpRequest& request);
void sendArModelToPage(); // the latest model (or error) to the AR page, if one is connected
+ void uploadArModel(); // the latest model, encrypted, to the relay for the AR page (Android Chrome)
HttpResponse directAnswer(const HttpRequest& request);
void relayLoop(std::string topic, std::string key, int64_t sinceUnix);
std::vector<std::string> relayUrls() const;
@@ -257,6 +258,11 @@ private:
std::mutex faceLinkMutex_; // createFaceLink
std::mutex rtcMutex_; // rtc_: creating / answering the peer connection
uint64_t arSentVersion_ = 0; // the model version the AR page has (rtcMutex_)
+ // The AR page's copy on the relay (mutex_): Android Chrome can't reach this computer at all, so the model goes
+ // through the internet, encrypted with a key only the page has.
+ std::string arBlobUrl_, arBlobKey_;
+ uint64_t arBlobVersion_ = 0;
+ Clock::time_point arBlobUntil_{};
std::string faceTransport_;
bool faceConnected_ = false;
FaceFrame face_;
diff --git a/tests/test_phone_link.cpp b/tests/test_phone_link.cpp
index 09fed305..4c8cf2c1 100644
--- a/tests/test_phone_link.cpp
+++ b/tests/test_phone_link.cpp
@@ -654,6 +654,58 @@ TEST(ar_link_sends_the_model_over_webrtc) {
link.stop();
}
+// Android Chrome may not reach the computer at all: the AR link also carries a relay URL, and each model goes
+// there encrypted with the link's key (only the page can read it).
+TEST(ar_link_uploads_the_model_encrypted_to_the_relay) {
+ if (!webrtcAvailable()) return;
+ std::mutex m;
+ std::vector<std::pair<std::string, std::string>> posted; // query, body
+ HttpServer relay;
+ HttpServer::Options ro;
+ ro.port = 0;
+ ro.bindAddress = "127.0.0.1";
+ std::string err;
+ CHECK(relay.start(ro, [&](const HttpRequest& r) {
+ std::lock_guard lock(m);
+ if (r.method == "POST" && r.path.rfind("/blob/sculptforge-", 0) == 0) posted.emplace_back(r.query, r.body);
+ return HttpResponse::json(200, "{}");
+ }, err));
+ if (ai::httpRequest("GET", "http://127.0.0.1:" + std::to_string(relay.port()) + "/blob/x", {}, {}, 5).status != 200) {
+ relay.stop(); // no HTTP client in this build
+ return;
+ }
+ const fs::path inbox = freshDir("sf_phone_ar_blob");
+ PhoneLinkOptions o = testOptions(inbox);
+ o.relayUrl = "http://127.0.0.1:" + std::to_string(relay.port()) + "/relay/";
+ PhoneLink link;
+ CHECK(link.start(o, err));
+ std::string url;
+ CHECK(link.createFaceLink(url, err, true, "subtool", 20.0f));
+ const std::string fragment = url.substr(url.find('#') + 1);
+ const std::string blobUrl = percentDecode(queryParameter(fragment, "b"));
+ CHECK(blobUrl.rfind("http://127.0.0.1:" + std::to_string(relay.port()) + "/blob/sculptforge-", 0) == 0);
+ std::string key;
+ CHECK(base64UrlDecode(queryParameter(fragment, "x"), key));
+ bool asked = false;
+ for (const PhoneEvent& e : link.takeEvents()) asked = asked || e.type == PhoneEvent::Type::ArRequested;
+ CHECK(asked); // the app makes a fresh model for the page
+ std::string glb = "glTF";
+ for (int i = 0; glb.size() < 200000; ++i) glb += char(i * 37 % 253);
+ link.publishArModel(glb, "usdz", "summary");
+ std::string query, body;
+ for (int i = 0; i < 200 && body.empty(); ++i) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(25));
+ std::lock_guard lock(m);
+ if (!posted.empty()) std::tie(query, body) = posted.front();
+ }
+ CHECK(query == "v=1");
+ std::string plain;
+ CHECK(aesGcmDecrypt(key, base64UrlEncode(body), plain, err));
+ CHECK(plain == glb);
+ link.stop();
+ relay.stop();
+}
+
// The phone's answer through the relays (services/link-worker's protocol, which ntfy.sh also speaks): the first
// relay is down, the second, a fake one here, carries the message; the desktop polls both and connects.
TEST(face_link_answer_through_the_relays) {
diff --git a/website/link/ar.html b/website/link/ar.html
index 212769da..f31e5bfd 100644
--- a/website/link/ar.html
+++ b/website/link/ar.html
@@ -95,6 +95,7 @@ const token = frag.get("k"), desktop = frag.get("d");
const desktopName = frag.get("n") || "your computer";
const scope = frag.get("s") === "scene" ? "scene" : "subtool";
const sizeCm = Number(frag.get("z")) || 20;
+const blobUrl = frag.get("b"); // the model through our relay, encrypted (for browsers that can't reach the computer)
history.replaceState(null, "", location.pathname); // keep the secrets out of history
if (desktop && token) {
$("back").href = `${desktop}/?k=${encodeURIComponent(token)}`;
@@ -216,16 +217,45 @@ function receive(data) {
incoming = { version: msg.version, bytes: msg.bytes, summary: msg.summary || "", parts: [], got: 0 };
if (!shownVersion) { $("waitText").textContent = "Receiving the model..."; $("bar").classList.remove("hidden"); }
} else if (msg.type === "end" && incoming && incoming.version === msg.version) {
- const blob = new Blob(incoming.parts, { type: "model/gltf-binary" });
- const first = !shownVersion;
- shownVersion = incoming.version;
- const summary = incoming.summary;
+ showModel(new Blob(incoming.parts, { type: "model/gltf-binary" }), incoming.version, incoming.summary);
incoming = null;
- if (modelUrl) URL.revokeObjectURL(modelUrl);
- modelUrl = URL.createObjectURL(blob);
- $("mv").src = modelUrl;
- $("wait").classList.add("hidden");
- note($("liveMsg"), first ? (summary ? "Ready: " + esc(summary) : "") : "Updated from your sculpt.", first ? "" : "ok");
+ }
+}
+function showModel(blob, version, summary) {
+ const first = !shownVersion;
+ shownVersion = version;
+ if (modelUrl) URL.revokeObjectURL(modelUrl);
+ modelUrl = URL.createObjectURL(blob);
+ $("mv").src = modelUrl;
+ $("wait").classList.add("hidden");
+ note($("liveMsg"), first ? (summary ? "Ready: " + esc(summary) : "") : "Updated from your sculpt.", first ? "" : "ok");
+}
+
+// Through the relay: SculptForge uploads each version encrypted (AES-GCM, iv | ciphertext | tag) with the key from
+// this link; the page checks for a newer one every few seconds. Works whatever network the phone is on.
+async function followRelay() {
+ const key = await crypto.subtle.importKey("raw", b64u.dec(frag.get("x")), "AES-GCM", false, ["decrypt"]);
+ setConn("ok", "Via the internet");
+ $("waitText").textContent = "Preparing the model on your computer...";
+ let failures = 0;
+ for (;;) {
+ try {
+ const r = await fetch(blobUrl, { cache: "no-store" });
+ if (r.ok) {
+ const meta = await r.json();
+ if (meta.version > shownVersion) {
+ if (!shownVersion) { $("waitText").textContent = "Receiving the model..."; }
+ const data = await (await fetch(blobUrl + "?data=1", { cache: "no-store" })).arrayBuffer();
+ const bytes = new Uint8Array(data);
+ const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, key, bytes.slice(12));
+ showModel(new Blob([plain], { type: "model/gltf-binary" }), meta.version, "");
+ }
+ } else if (r.status !== 404) throw new Error("HTTP " + r.status);
+ failures = 0;
+ } catch (e) {
+ if (++failures >= 3 && !shownVersion) return false; // no internet: try the direct link
+ }
+ await new Promise((resolve) => setTimeout(resolve, document.hidden ? 8000 : 2500));
}
}
@@ -262,6 +292,8 @@ if (!token || !frag.get("o")) {
try { await navigator.clipboard.writeText(fullUrl); $("copy").textContent = "Copied"; }
catch (e) { prompt("Copy this link:", fullUrl); }
};
+} else if (blobUrl && await followRelay().catch(() => false) !== false) {
+ // (followRelay runs for as long as the page is open)
} else {
// The camera first, as on the face page: until a page may use it, Chrome hides this phone's network address
// behind a random name the computer can't look up, and a firewall on the computer then keeps the phone's own